From fecb717f99fa829f815b3ce4f741e30ff3a0cefe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 04:08:41 -0800 Subject: [PATCH 01/99] Metafiles: read WMF, EMF and EMF+ with craft-metafile (#6636) crates/metafile is deleted. formats, layout, render and pdf take their WMF, EMF and EMF+ reader from craft-metafile (craft-libs 9dcbd90c, the rev craft-docx is already pinned at), so EMF+ records are read: an EMF+ only file's DrawImage of a 32bppPARGB bitmap draws its pixels. render and pdf draw what the shared model adds: pattern and hatch fills, clip regions and clip paths, pen caps, joins, miter limits and dashes, turned, skewed or mirrored bitmaps, and the opaque background behind text. The text layout and the default font for a file that names none (Arial, a 16-unit cell) move to layout, next to metafile_text_run. layout/src/metafile.rs holds the rules both outputs follow: a negative crop side draws as no crop, as before; a cosmetic pen's shortest dash or gap is one output pixel; a dash pattern whose period is under a pixel, or that would split a path into more than 100,000 pieces, draws solid; and an invalid miter limit is 10. On screen, a pattern tile whose sides are both under 1.5 device pixels fills with its average color, computed once a tile, and the vector cache counts each item's clip region, clip list and dash pattern. Fixes #6636 --- Cargo.lock | 16 +- Cargo.toml | 3 +- crates/formats/Cargo.toml | 2 +- crates/formats/src/odt/body/drawing.rs | 6 +- crates/layout/Cargo.toml | 2 +- crates/layout/src/contour.rs | 2 +- crates/layout/src/lib.rs | 6 +- crates/layout/src/metafile.rs | 75 ++ crates/layout/src/missing.rs | 100 +- crates/layout/src/strict.rs | 2 +- crates/layout/src/tests/missing_glyphs.rs | 59 + crates/metafile/Cargo.toml | 13 - crates/metafile/src/bytes.rs | 59 - crates/metafile/src/canvas.rs | 812 -------------- crates/metafile/src/dib.rs | 719 ------------- crates/metafile/src/emf.rs | 370 ------- crates/metafile/src/geom.rs | 128 --- crates/metafile/src/lib.rs | 284 ----- crates/metafile/src/place.rs | 217 ---- crates/metafile/src/size.rs | 98 -- crates/metafile/src/tests.rs | 1187 --------------------- crates/metafile/src/wmf.rs | 272 ----- crates/pdf/Cargo.toml | 2 +- crates/pdf/src/exporter.rs | 2 +- crates/pdf/src/exporter/draw.rs | 2 +- crates/pdf/src/exporter/text.rs | 19 +- crates/pdf/src/lib.rs | 2 +- crates/pdf/src/picture.rs | 172 ++- crates/pdf/src/tests.rs | 122 +++ crates/render/Cargo.toml | 2 +- crates/render/src/lib.rs | 4 +- crates/render/src/media.rs | 239 ++++- crates/render/src/tests.rs | 293 +++++ docs/architecture.md | 2 +- docs/file-format-parity.md | 2 +- xtask/src/layers.rs | 1 - 36 files changed, 1024 insertions(+), 4272 deletions(-) create mode 100644 crates/layout/src/metafile.rs delete mode 100644 crates/metafile/Cargo.toml delete mode 100644 crates/metafile/src/bytes.rs delete mode 100644 crates/metafile/src/canvas.rs delete mode 100644 crates/metafile/src/dib.rs delete mode 100644 crates/metafile/src/emf.rs delete mode 100644 crates/metafile/src/geom.rs delete mode 100644 crates/metafile/src/lib.rs delete mode 100644 crates/metafile/src/place.rs delete mode 100644 crates/metafile/src/size.rs delete mode 100644 crates/metafile/src/tests.rs delete mode 100644 crates/metafile/src/wmf.rs diff --git a/Cargo.lock b/Cargo.lock index 5a89245b0d..d077d28f18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7128,6 +7128,7 @@ dependencies = [ "cfb", "chardetng", "chrono", + "craft-metafile", "craft-rtf", "encoding_rs", "getrandom 0.3.4", @@ -7143,7 +7144,6 @@ dependencies = [ "wordcraft-doc", "wordcraft-docx", "wordcraft-geom", - "wordcraft-metafile", "zeroize", "zip 3.0.0", ] @@ -7160,6 +7160,7 @@ dependencies = [ name = "wordcraft-layout" version = "0.18.1" dependencies = [ + "craft-metafile", "craft-proof", "image", "js-sys", @@ -7173,7 +7174,6 @@ dependencies = [ "wordcraft-doc", "wordcraft-fonts", "wordcraft-geom", - "wordcraft-metafile", ] [[package]] @@ -7188,19 +7188,12 @@ dependencies = [ "wordcraft-render", ] -[[package]] -name = "wordcraft-metafile" -version = "0.18.1" -dependencies = [ - "kurbo", - "thiserror 2.0.21", -] - [[package]] name = "wordcraft-pdf" version = "0.18.1" dependencies = [ "chrono", + "craft-metafile", "craft-pdf", "hayro-cmap", "hayro-interpret", @@ -7214,13 +7207,13 @@ dependencies = [ "wordcraft-fonts", "wordcraft-geom", "wordcraft-layout", - "wordcraft-metafile", ] [[package]] name = "wordcraft-render" version = "0.18.1" dependencies = [ + "craft-metafile", "image", "log", "vello_cpu", @@ -7228,7 +7221,6 @@ dependencies = [ "wordcraft-fonts", "wordcraft-geom", "wordcraft-layout", - "wordcraft-metafile", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1ff4830208..6c4c1fc586 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,6 @@ wordcraft-mcp = { path = "crates/mcp" } wordcraft-zotero = { path = "crates/zotero" } wordcraft-control-key = { path = "crates/control-key" } wordcraft-ui-egui = { path = "crates/ui-egui" } -wordcraft-metafile = { path = "crates/metafile" } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -74,6 +73,8 @@ craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "9dcb craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0" } craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0", features = ["doc"] } craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0" } +# WMF, EMF and EMF+ reader. +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0" } quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } # zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates. diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 995a4eb630..08c6abdeb8 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-doc = { workspace = true } wordcraft-docx = { workspace = true } craft-rtf = { workspace = true } wordcraft-geom = { workspace = true, features = ["image"] } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } base64 = { workspace = true } image = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/formats/src/odt/body/drawing.rs b/crates/formats/src/odt/body/drawing.rs index 3e5065b5f0..e8b8daa6b4 100644 --- a/crates/formats/src/odt/body/drawing.rs +++ b/crates/formats/src/odt/body/drawing.rs @@ -402,7 +402,7 @@ impl Body<'_> { /// Whether WordCraft can show these bytes as a picture (see the function below). pub(in crate::odt) fn readable_picture(data: &[u8]) -> bool { - wordcraft_metafile::is_metafile(data) || model::sniff_image(data).is_some() + craft_metafile::is_metafile(data) || model::sniff_image(data).is_some() } /// A picture from a package's bytes: a raster image, or a Windows metafile (WMF, EMF: LibreOffice @@ -411,7 +411,7 @@ pub(in crate::odt) fn picture(data: Vec, w: Option, h: Option, alt // What the frame states, if it could be a size (far past any page, kept from overflowing). let stated = |v: Option| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| v.min(1e6)); let (w, h) = (stated(w), stated(h)); - let mut img = if wordcraft_metafile::is_metafile(&data) { + let mut img = if craft_metafile::is_metafile(&data) { // An EMF starts with its header record, type 1. let ext = if data.get(..4) == Some(&[1, 0, 0, 0]) { "emf" } else { "wmf" }; // Its own size, when the frame gives none: a placeable WMF's or an EMF's frame, points. @@ -450,7 +450,7 @@ fn fit_to(img: &mut model::Img, room: Option) { /// A picture's height for each point of its width, by its own size, before anything caps it (1 /// when it doesn't say). fn height_per_width(data: &[u8]) -> f32 { - let own = if wordcraft_metafile::is_metafile(data) { metafile_size(data) } else { model::image_px(data).map(|(w, h)| (w as f32, h as f32)) }; + let own = if craft_metafile::is_metafile(data) { metafile_size(data) } else { model::image_px(data).map(|(w, h)| (w as f32, h as f32)) }; own.filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0).map_or(1.0, |(w, h)| h / w) } diff --git a/crates/layout/Cargo.toml b/crates/layout/Cargo.toml index 21762d5039..7cf71a1bf3 100644 --- a/crates/layout/Cargo.toml +++ b/crates/layout/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } wordcraft-proof = { workspace = true } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } kurbo = { workspace = true } unicode-bidi = { workspace = true } unicode-linebreak = { workspace = true } diff --git a/crates/layout/src/contour.rs b/crates/layout/src/contour.rs index 9b92cb6e82..9f5d90b56b 100644 --- a/crates/layout/src/contour.rs +++ b/crates/layout/src/contour.rs @@ -307,7 +307,7 @@ fn decode_alpha(bytes: &[u8], decoded: &mut u64) -> Result, OverBu fn alpha_in_crop(img: &Alpha, crop: [f32; 4]) -> Option> { let (iw, ih) = (img.w, img.h); // The part the renderers draw (#1899): a sliver keeps its partly covered pixels. - let [cl, ct, vw, vh] = wordcraft_metafile::crop_window(crop); + let [cl, ct, vw, vh] = crate::crop_window(crop); let (fw, fh) = (f64::from(iw), f64::from(ih)); let x0 = ((fw * cl) as u32).min(iw); let y0 = ((fh * ct) as u32).min(ih); diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 86e2664285..edc60026cd 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -58,6 +58,7 @@ mod ctx; mod floats; mod flow; mod headers; +mod metafile; mod missing; mod notes; mod page; @@ -84,7 +85,10 @@ use headers::MAX_HEADER_ITEMS; #[cfg(test)] use headers::placed_cost; use headers::placed_cost_by; -pub use missing::{MAX_MISSING_GLYPHS, MissingGlyphs, metafile_text_run, missing_watermark_glyphs, watermark_run}; +pub use metafile::{MAX_METAFILE_DASHES, crop_sides, crop_window, metafile_average_color, metafile_dashes, metafile_miter_limit}; +pub use missing::{ + MAX_MISSING_GLYPHS, MetafileTextLayout, MissingGlyphs, metafile_text_layout, metafile_text_run, missing_watermark_glyphs, watermark_run, +}; pub use notes::DECOR_STORY; pub(crate) use notes::NOTE_SEP_W; use notes::{MAX_NOTE_PASSES, footnote_pages}; diff --git a/crates/layout/src/metafile.rs b/crates/layout/src/metafile.rs new file mode 100644 index 0000000000..a562550e88 --- /dev/null +++ b/crates/layout/src/metafile.rs @@ -0,0 +1,75 @@ +//! Drawing rules the page renderer and the PDF export share for metafile pictures and picture +//! crops, so the two outputs draw the same file the same way. + +/// Most dashes and gaps one metafile stroke is split into. A path that a pen's pattern would split +/// into more draws solid. +pub const MAX_METAFILE_DASHES: f64 = 100_000.0; + +/// The crop sides a picture is drawn with: each side of `crop` (left, top, right, bottom fractions +/// of the source) at least 0. A negative side draws as no crop, not as padding around the source. +pub fn crop_sides(crop: [f32; 4]) -> [f32; 4] { + crop.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 }) +} + +/// The part of a picture's source that `crop` keeps, as fractions of the source: [left, top, +/// width, height] (`craft_metafile::crop_window` of [`crop_sides`]). +pub fn crop_window(crop: [f32; 4]) -> [f64; 4] { + craft_metafile::crop_window(crop_sides(crop)) +} + +/// The miter limit a metafile pen is drawn with: its own when it is finite and at least 1, +/// otherwise 10. +pub fn metafile_miter_limit(limit: f32) -> f32 { + if limit.is_finite() && limit >= 1.0 { limit } else { 10.0 } +} + +/// The dash lengths (page points) a metafile pen draws a path `length` points long with, or None +/// for a solid line. `dash` is the placed pen's pattern (`craft_metafile::LineStyle::dash`, page +/// points) and `pixel` is one output pixel in points. +/// +/// A cosmetic pen (`cosmetic`: width 0) has its pattern scaled so that its shortest dash or gap is +/// one pixel, at any zoom. A pattern with a negative or non-finite length draws solid, and so does +/// one whose period is shorter than a pixel or that would split the path into more than +/// [`MAX_METAFILE_DASHES`] dashes and gaps. +pub fn metafile_dashes(dash: &[f32], cosmetic: bool, pixel: f64, length: f64) -> Option> { + if dash.is_empty() || !pixel.is_finite() || pixel <= 0.0 { + return None; + } + let mut out: Vec = dash.iter().map(|d| f64::from(*d)).collect(); + if !out.iter().all(|d| d.is_finite() && *d >= 0.0) { + return None; + } + if cosmetic { + let shortest = out.iter().copied().filter(|d| *d > 0.0).fold(f64::INFINITY, f64::min); + if !shortest.is_finite() { + return None; + } + let k = pixel / shortest; + out.iter_mut().for_each(|d| *d *= k); + } + let period: f64 = out.iter().sum(); + if !period.is_finite() || period < pixel { + return None; + } + // Each length of the pattern starts a new dash or gap. + let pieces = out.len() as f64 * if length.is_finite() { length.max(0.0) / period } else { f64::INFINITY }; + (pieces <= MAX_METAFILE_DASHES).then_some(out) +} + +/// The alpha-weighted average color of straight RGBA pixels (transparent when there are none): a +/// metafile pattern fill whose tile is too small to show is filled with it. +pub fn metafile_average_color(px: &[u8]) -> [u8; 4] { + let (mut r, mut g, mut b, mut a, mut n) = (0u64, 0u64, 0u64, 0u64, 0u64); + for p in px.as_chunks::<4>().0 { + let w = u64::from(p[3]); + r += u64::from(p[0]) * w; + g += u64::from(p[1]) * w; + b += u64::from(p[2]) * w; + a += w; + n += 1; + } + if a == 0 || n == 0 { + return [0; 4]; + } + [(r / a) as u8, (g / a) as u8, (b / a) as u8, (a / n) as u8] +} diff --git a/crates/layout/src/missing.rs b/crates/layout/src/missing.rs index 6ea5c3bc20..8425362685 100644 --- a/crates/layout/src/missing.rs +++ b/crates/layout/src/missing.rs @@ -151,12 +151,100 @@ pub fn watermark_run(wm: &wordcraft_doc::Watermark, max_chars: usize) -> Option< /// in the face its font name resolves to (no fallback face), so a character that face lacks shapes /// to glyph id 0. Strict export checks these same glyphs, so the check and the exporters can't /// drift. -pub fn metafile_text_run(t: &wordcraft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec) { - let face = wordcraft_fonts::word::resolve(&t.font, t.bold, t.italic).face; +pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec) { + let family = t.font.family.trim(); + let family = if family.is_empty() { METAFILE_DEFAULT_FONT } else { family }; + let face = wordcraft_fonts::word::resolve(family, t.font.weight >= 600, t.font.italic).face; let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c); (face, shaped) } +/// The face a metafile font with no face name is drawn in. +const METAFILE_DEFAULT_FONT: &str = "Arial"; +/// The cell height (text units) of a metafile font whose height is 0, the file's default size. +const METAFILE_DEFAULT_HEIGHT: f64 = 16.0; + +/// A metafile text run laid out with a font's metrics: the em size (text units), the baseline's y +/// and each glyph's (x, y), alignment included, in the run's text space (see +/// `craft_metafile::Text::transform`). +pub struct MetafileTextLayout { + pub em: f64, + pub baseline: f64, + pub glyphs: Vec<(f64, f64)>, + /// The rectangle of the character cells (x0, y0, x1, y1): from the leftmost to the rightmost + /// pen position of the run, the font's ascent above the baseline and its descent below. An + /// opaque background fills it. + pub cell: [f64; 4], +} + +/// Lays out the shaped glyphs of `t`, given as (cluster byte offset, x advance, x offset, y offset) +/// in font units of a font with `upem` units per em, `ascent` above and `descent` below the +/// baseline. The font height is the em size when negative and the cell height (ascent plus +/// descent) when positive. The per-character advances `dx` place each cluster when there is one +/// per character. None when the size is not finite and positive. +pub fn metafile_text_layout( + t: &craft_metafile::Text, + upem: f64, + ascent: f64, + descent: f64, + glyphs: &[(usize, f64, f64, f64)], +) -> Option { + let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 }; + let height = if t.font.height == 0.0 { METAFILE_DEFAULT_HEIGHT } else { f64::from(t.font.height) }; + let cell = ascent + descent; + let em = if height > 0.0 && cell.is_finite() && cell > 0.0 { height * upem / cell } else { height.abs() }; + if !em.is_finite() || em <= 0.0 { + return None; + } + let k = em / upem; + let starts: Vec = t.text.char_indices().map(|(i, _)| i).collect(); + let dx = (t.dx.len() == starts.len() && !starts.is_empty()).then(|| { + let mut cum = Vec::with_capacity(t.dx.len() + 1); + let mut x = 0.0; + cum.push(x); + for d in &t.dx { + x += f64::from(*d); + cum.push(x); + } + cum + }); + let mut out = Vec::with_capacity(glyphs.len()); + let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None); + // The leftmost and rightmost pen positions: advances can move backward. + let (mut lo, mut hi) = (0.0f64, 0.0f64); + for &(cluster, adv, xo, yo) in glyphs { + let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1); + if last != Some(ci) { + cluster_pen = pen; + last = Some(ci); + } + let x = match &dx { + Some(cum) => cum.get(ci).copied().unwrap_or(0.0) + pen - cluster_pen, + None => pen, + }; + out.push((x + xo * k, -yo * k)); + pen += adv * k; + (lo, hi) = (lo.min(pen), hi.max(pen)); + } + if let Some(cum) = &dx { + (lo, hi) = cum.iter().fold((0.0f64, 0.0f64), |(l, h), x| (l.min(*x), h.max(*x))); + } + let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen); + let hoff = match t.h_align { + craft_metafile::HAlign::Left => 0.0, + craft_metafile::HAlign::Center => -width / 2.0, + craft_metafile::HAlign::Right => -width, + }; + let baseline = match t.v_align { + craft_metafile::VAlign::Top => ascent * k, + craft_metafile::VAlign::Baseline => 0.0, + craft_metafile::VAlign::Bottom => -descent * k, + }; + let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect(); + let cell = [hoff + lo, baseline - ascent * k, hoff + hi, baseline + descent * k]; + Some(MetafileTextLayout { em, baseline, glyphs, cell }) +} + /// The characters of the watermark that draw as an empty box (glyph id 0), counted as /// [`DocLayout::missing_glyphs`] counts them; sorted by code point. The watermark is on every /// page, so it counts once. @@ -265,19 +353,19 @@ impl Found { /// The text runs of a metafile picture that the exporters draw (a run whose layout fails is not). fn meta_runs(bytes: &[u8]) -> Vec { - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return Vec::new(); } - let Ok(pic) = wordcraft_metafile::parse(bytes) else { return Vec::new() }; + let Ok(pic) = craft_metafile::parse(bytes) else { return Vec::new() }; if !pic.has_size() { return Vec::new(); } let mut out = Vec::new(); for item in &pic.items { - let wordcraft_metafile::Item::Text(t) = item else { continue }; + let craft_metafile::Item::Text(t) = item else { continue }; let (face, shaped) = metafile_text_run(t); let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect(); - if t.layout(face.upem, face.ascent, face.descent, &glyphs).is_none() { + if metafile_text_layout(t, face.upem, face.ascent, face.descent, &glyphs).is_none() { continue; } let ranges = cluster_ranges(&t.text, &shaped); diff --git a/crates/layout/src/strict.rs b/crates/layout/src/strict.rs index c9dcfec389..e089f711cd 100644 --- a/crates/layout/src/strict.rs +++ b/crates/layout/src/strict.rs @@ -40,7 +40,7 @@ impl StrictOutput { /// decodes within the decode budget. The same decision `wordcraft-pdf` and `wordcraft-render` /// take, so a picture that fails here is drawn as a grey box (or not at all) by that output. pub fn media_check(bytes: &[u8], output: StrictOutput) -> Result<(), DrawFailure> { - if wordcraft_metafile::is_metafile(bytes) && wordcraft_metafile::parse(bytes).is_ok_and(|p| p.has_size()) { + if craft_metafile::is_metafile(bytes) && craft_metafile::parse(bytes).is_ok_and(|p| p.has_size()) { return Ok(()); } wordcraft_geom::picture::check_for_drawing(bytes, output.max_picture_side()) diff --git a/crates/layout/src/tests/missing_glyphs.rs b/crates/layout/src/tests/missing_glyphs.rs index 1a9444f346..e105797f8b 100644 --- a/crates/layout/src/tests/missing_glyphs.rs +++ b/crates/layout/src/tests/missing_glyphs.rs @@ -242,3 +242,62 @@ fn an_equation_run_names_each_glyphs_characters() { assert!(found.iter().any(|(t, g, _)| (t.contains('\u{1D44E}') || t == "ab") && *g == 2), "{found:?}"); assert!(found.iter().all(|(_, g, r)| g == r), "{found:?}"); } + +/// A metafile text run with the given font height and advances, left-aligned at the baseline. +fn meta_text(height: f32, dx: Vec) -> craft_metafile::Text { + craft_metafile::Text { + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + text: "ab".into(), + dx, + font: craft_metafile::Font { family: "Arial".into(), height, ..Default::default() }, + color: [0, 0, 0, 255], + background: Some([255, 255, 255, 255]), + h_align: craft_metafile::HAlign::Left, + v_align: craft_metafile::VAlign::Baseline, + clip: None, + region: None, + clips: Vec::new(), + } +} + +/// A metafile font height of 0 is the file's default size: a 16-unit cell. A negative height is +/// the em size, and a positive one the cell (ascent plus descent, 1200 units of a 1000-unit em +/// here). +#[test] +fn metafile_text_heights() { + let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)]; + let em = |h| crate::metafile_text_layout(&meta_text(h, Vec::new()), 1000.0, 900.0, 300.0, &glyphs).map(|l| l.em); + let near = |a: Option, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-9); + assert!(near(em(0.0), 16.0 * 1000.0 / 1200.0), "{:?}", em(0.0)); + assert!(near(em(-10.0), 10.0), "{:?}", em(-10.0)); + assert!(near(em(24.0), 20.0), "a positive height is the cell: {:?}", em(24.0)); +} + +/// A cosmetic pen's dashes become whole output pixels (the shortest one pixel), a period under a +/// pixel draws solid, and so does a pattern that would split the path into too many pieces. +#[test] +fn metafile_dashes_follow_the_output_pixel() { + let cosmetic = crate::metafile_dashes(&[0.75, 0.25], true, 0.5, 100.0).unwrap_or_default(); + assert!(cosmetic.len() == 2 && (cosmetic[0] - 1.5).abs() < 1e-6 && (cosmetic[1] - 0.5).abs() < 1e-6, "{cosmetic:?}"); + assert_eq!(crate::metafile_dashes(&[3.0, 1.0], false, 0.5, 100.0), Some(vec![3.0, 1.0])); + assert_eq!(crate::metafile_dashes(&[0.2, 0.2], false, 0.5, 100.0), None, "a period under a pixel"); + assert_eq!(crate::metafile_dashes(&[1.0, 1.0], false, 0.5, 1e6), None, "a million pieces"); + assert_eq!(crate::metafile_dashes(&[1.0, -1.0], false, 0.5, 100.0), None, "a negative length"); + assert_eq!(crate::metafile_dashes(&[0.0, 0.0], true, 0.5, 100.0), None, "no length at all"); +} + +/// A negative crop side is no crop; the others stay as they are. +#[test] +fn negative_crop_sides_are_no_crop() { + assert_eq!(crate::crop_sides([-0.5, 0.25, f32::NAN, 1.5]), [0.0, 0.25, 0.0, 1.5]); + assert_eq!(crate::crop_window([-0.5, 0.0, 0.0, 0.0]), [0.0, 0.0, 1.0, 1.0]); +} + +/// The opaque background of a run whose advances move backward covers every pen position, not +/// only the run's total advance. +#[test] +fn metafile_text_cell_spans_backward_advances() { + let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)]; + let lay = crate::metafile_text_layout(&meta_text(-10.0, vec![50.0, -40.0]), 1000.0, 800.0, 200.0, &glyphs).expect("a layout"); + assert_eq!(lay.cell, [0.0, -8.0, 50.0, 2.0]); +} diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml deleted file mode 100644 index 55e76c98ce..0000000000 --- a/crates/metafile/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "wordcraft-metafile" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "WordCraft metafiles: parses Windows WMF and EMF records into a neutral vector model (paths and bitmaps)" - -[lints] -workspace = true - -[dependencies] -kurbo = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/metafile/src/bytes.rs b/crates/metafile/src/bytes.rs deleted file mode 100644 index 5584d6dff8..0000000000 --- a/crates/metafile/src/bytes.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Bounds-checked little-endian access to hostile input. Every read returns `None` past the end, so -//! a truncated or lying size field stops the parse instead of panicking. - -#[derive(Clone, Copy)] -pub(crate) struct Bytes<'a>(pub(crate) &'a [u8]); - -impl<'a> Bytes<'a> { - pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { - self.0.get(off..off.checked_add(len)?) - } - - pub fn tail(&self, off: usize) -> Option> { - self.0.get(off..).map(Bytes) - } - - fn arr(&self, off: usize) -> Option<[u8; N]> { - self.slice(off, N)?.try_into().ok() - } - - pub fn u16(&self, off: usize) -> Option { - Some(u16::from_le_bytes(self.arr(off)?)) - } - - pub fn i16(&self, off: usize) -> Option { - Some(i16::from_le_bytes(self.arr(off)?)) - } - - pub fn u32(&self, off: usize) -> Option { - Some(u32::from_le_bytes(self.arr(off)?)) - } - - pub fn i32(&self, off: usize) -> Option { - Some(i32::from_le_bytes(self.arr(off)?)) - } - - pub fn f32(&self, off: usize) -> Option { - Some(f32::from_le_bytes(self.arr(off)?)) - } - - /// `n` consecutive (x, y) pairs of 16- or 32-bit signed integers starting at `off`. - pub fn points(&self, off: usize, n: usize, wide: bool) -> Option> { - let sz = if wide { 8 } else { 4 }; - let raw = self.slice(off, n.checked_mul(sz)?)?; - let mut out = Vec::with_capacity(n); - for c in raw.chunks_exact(sz) { - let p = if wide { - let x = i32::from_le_bytes(c.get(0..4)?.try_into().ok()?); - let y = i32::from_le_bytes(c.get(4..8)?.try_into().ok()?); - (f64::from(x), f64::from(y)) - } else { - let x = i16::from_le_bytes(c.get(0..2)?.try_into().ok()?); - let y = i16::from_le_bytes(c.get(2..4)?.try_into().ok()?); - (f64::from(x), f64::from(y)) - }; - out.push(p); - } - Some(out) - } -} diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs deleted file mode 100644 index bb6ecd3167..0000000000 --- a/crates/metafile/src/canvas.rs +++ /dev/null @@ -1,812 +0,0 @@ -//! Drawing state shared by the WMF and EMF readers: window/viewport mapping and the EMF world -//! transform, pen and brush selection through an object table, the DC save stack and path brackets. -//! Output is device-space items; `lib.rs` maps them into the picture frame. - -use crate::dib::Rgba; -use crate::geom::{Op, P}; -use crate::{MAX_BYTES, MAX_ITEMS, MAX_OBJECTS, MAX_PATH_OPS, MAX_STACK}; - -pub(crate) const MM_TEXT: u32 = 1; -const MM_ISOTROPIC: u32 = 7; -const MM_ANISOTROPIC: u32 = 8; -const STOCK: u32 = 0x8000_0000; -pub(crate) const PS_NULL: u32 = 5; -/// Pen style bits; the rest of the style word holds end-cap, join and type flags. -pub(crate) const PS_STYLE_MASK: u32 = 0x0F; -const BS_SOLID: u32 = 0; -pub(crate) const BS_NULL: u32 = 1; -const WINDING: u32 = 2; -/// SETROP2 mix mode that leaves the destination alone: outlines and fills draw nothing. -const R2_NOP: u32 = 11; -const PATCOPY: u32 = 0x00F0_0021; -const BLACKNESS: u32 = 0x0000_0042; -const WHITENESS: u32 = 0x00FF_0062; -/// SETTEXTALIGN: draw at and update the current point. -const TA_UPDATECP: u32 = 1; -/// Font height (cell height, logical units) of the default font, used for a height of 0. -const DEFAULT_FONT_HEIGHT: f64 = 16.0; -/// Face used when a font names none. -const DEFAULT_FONT_FACE: &str = "Arial"; -/// Device pixels per millimetre assumed for WMF (96 dpi), and for EMF files without a device size. -const DEFAULT_PX_PER_MM: f64 = 96.0 / 25.4; - -/// Affine transform `[m11, m12, m21, m22, dx, dy]` in EMF XFORM order: `x' = x·m11 + y·m21 + dx`. -pub(crate) type Xform = [f64; 6]; -const IDENTITY: Xform = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; - -/// `a` then `b` in EMF row-vector convention: the matrix product `a × b`. -pub(crate) fn mul(a: Xform, b: Xform) -> Xform { - [ - a[0] * b[0] + a[1] * b[2], - a[0] * b[1] + a[1] * b[3], - a[2] * b[0] + a[3] * b[2], - a[2] * b[1] + a[3] * b[3], - a[4] * b[0] + a[5] * b[2] + b[4], - a[4] * b[1] + a[5] * b[3] + b[5], - ] -} - -#[derive(Clone, Copy, PartialEq, Debug)] -pub(crate) struct Pen { - pub style: u32, - /// Logical width; 0 means a cosmetic one-pixel hairline. - pub width: f64, - pub color: [u8; 4], -} - -#[derive(Clone, Copy, PartialEq, Debug)] -pub(crate) struct Brush { - pub style: u32, - pub color: [u8; 4], -} - -/// A logical font (EMF LogFont): height in logical units (negative = character height, positive = -/// cell height, 0 = default), escapement in tenths of a degree, face name as UTF-16 (NUL-padded). -#[derive(Clone, Copy, PartialEq, Debug)] -pub(crate) struct Font { - pub height: i32, - pub escapement: i32, - pub weight: i32, - pub italic: bool, - pub face: [u16; 32], -} - -#[derive(Clone, Copy, Debug)] -pub(crate) enum Obj { - Pen(Pen), - Brush(Brush), - Font(Font), - /// Palettes, pattern brushes and regions: they take a table slot but draw nothing. - Other, -} - -/// Converts a COLORREF (0x00BBGGRR) to opaque RGBA. -pub(crate) fn colorref(c: u32) -> [u8; 4] { - [(c & 0xFF) as u8, ((c >> 8) & 0xFF) as u8, ((c >> 16) & 0xFF) as u8, 255] -} - -/// Millimetres per logical unit of the metric map modes (LOMETRIC, HIMETRIC, LOENGLISH, HIENGLISH, TWIPS). -fn metric_mm(mode: u32) -> Option { - match mode { - 2 => Some(0.1), - 3 => Some(0.01), - 4 => Some(25.4 / 100.0), - 5 => Some(25.4 / 1000.0), - 6 => Some(25.4 / 1440.0), - _ => None, - } -} - -#[derive(Clone, Copy)] -pub(crate) struct Mapping { - wo: P, - we: P, - vo: P, - ve: P, - mode: u32, - world: Xform, - /// Device pixels per millimetre on each axis (EMF: from szlDevice and szlMillimeters). - px_mm: P, -} - -impl Mapping { - fn identity() -> Self { - Mapping { - wo: (0.0, 0.0), - we: (1.0, 1.0), - vo: (0.0, 0.0), - ve: (1.0, 1.0), - mode: MM_TEXT, - world: IDENTITY, - px_mm: (DEFAULT_PX_PER_MM, DEFAULT_PX_PER_MM), - } - } - - /// Logical point to device point: world transform, then window to viewport. - pub fn device(&self, p: P) -> P { - let w = self.world; - let (x, y) = (p.0 * w[0] + p.1 * w[2] + w[4], p.0 * w[1] + p.1 * w[3] + w[5]); - let (sx, sy) = self.ratios(); - ((x - self.wo.0) * sx + self.vo.0, (y - self.wo.1) * sy + self.vo.1) - } - - /// Window-to-viewport scale per axis. MM_TEXT fixes the scale at 1; the metric modes use a fixed - /// scale with y up; MM_ISOTROPIC uses one scale on both axes (the smaller magnitude, each axis's - /// sign kept); anisotropic and unknown modes use the extents as given. - fn ratios(&self) -> (f64, f64) { - if self.mode == MM_TEXT { - return (1.0, 1.0); - } - if let Some(mm) = metric_mm(self.mode) { - return (mm * self.px_mm.0, -mm * self.px_mm.1); - } - let (rx, ry) = (ratio(self.ve.0, self.we.0), ratio(self.ve.1, self.we.1)); - if self.mode == MM_ISOTROPIC { - let s = rx.abs().min(ry.abs()); - return (if rx < 0.0 { -s } else { s }, if ry < 0.0 { -s } else { s }); - } - (rx, ry) - } - - /// Approximate device length per logical length, for pen widths. - fn scale(&self) -> f64 { - let w = self.world; - let det = (w[0] * w[3] - w[1] * w[2]).abs().sqrt(); - let (sx, sy) = self.ratios(); - det * (sx.abs() + sy.abs()) / 2.0 - } - - /// True when the window-to-viewport extents set the scale (the isotropic and anisotropic modes). - pub fn uses_extents(&self) -> bool { - matches!(self.mode, MM_ISOTROPIC | MM_ANISOTROPIC) - } - - pub fn window_ext(&self) -> P { - self.we - } - - pub fn viewport_ext(&self) -> P { - self.ve - } - - /// The window in device units as `[x, y, w, h]` with positive extents, used as the picture frame - /// of a plain WMF. - pub fn window_rect(&self) -> [f64; 4] { - let a = self.device(self.wo); - let b = self.device((self.wo.0 + self.we.0, self.wo.1 + self.we.1)); - [a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()] - } -} - -fn ratio(num: f64, den: f64) -> f64 { - if den == 0.0 { 1.0 } else { num / den } -} - -/// Output of drawing, in device units. Path points are already mapped; `lib.rs` normalises them. -pub(crate) enum Raw { - Path { ops: Vec, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f64)>, even_odd: bool }, - Bitmap { rect: [f64; 4], img: Rgba }, - Text(RawText), -} - -/// A text run in device units: the reference point, the font height along the text's up direction, -/// the baseline angle (radians, clockwise in y-down space) and per-character advances. -pub(crate) struct RawText { - pub text: String, - pub origin: P, - pub size: f64, - pub cell: bool, - pub angle: f64, - pub dx: Vec, - pub font: String, - pub bold: bool, - pub italic: bool, - pub color: [u8; 4], - pub align: u32, -} - -#[derive(Clone)] -struct Saved { - map: Mapping, - pen: Pen, - brush: Brush, - even_odd: bool, - nop: bool, - font: Option, - text_color: [u8; 4], - text_align: u32, -} - -pub(crate) struct Canvas { - pub items: Vec, - pub map: Mapping, - /// True once SETWINDOWEXT was seen, so a plain WMF has a frame to use. - pub window_set: bool, - /// True once the file set the viewport extent itself (not the player, see [`Canvas::play_into`]). - pub viewport_set: bool, - saved: Vec, - /// Bytes held by the items so far (path ops and pixels), capped at [`MAX_BYTES`]. - used: usize, - objects: Vec>, - /// Indices below `objects.len()` that hold no object, so the WMF handle table finds its lowest - /// free slot without scanning. - free: std::collections::BTreeSet, - /// Table slots examined by `add_object(None, ..)`; the tests assert it stays constant per call. - #[cfg(test)] - pub slot_probes: usize, - pen: Pen, - brush: Brush, - even_odd: bool, - /// The mix mode is R2_NOP: shapes draw nothing. - nop: bool, - /// The selected font; None is the default font. - font: Option, - text_color: [u8; 4], - /// SETTEXTALIGN flags (TA_*). - text_align: u32, - pos: P, - in_path: bool, - path: Vec, - full: bool, -} - -impl Canvas { - pub fn new() -> Self { - Canvas { - items: Vec::new(), - map: Mapping::identity(), - window_set: false, - viewport_set: false, - saved: Vec::new(), - used: 0, - objects: Vec::new(), - free: std::collections::BTreeSet::new(), - #[cfg(test)] - slot_probes: 0, - pen: Pen { style: 0, width: 0.0, color: [0, 0, 0, 255] }, - brush: Brush { style: BS_SOLID, color: [255, 255, 255, 255] }, - even_odd: true, - nop: false, - font: None, - text_color: [0, 0, 0, 255], - text_align: 0, - pos: (0.0, 0.0), - in_path: false, - path: Vec::new(), - full: false, - } - } - - /// True once the item cap is hit; the readers stop there and keep what they have. - pub fn full(&self) -> bool { - self.full - } - - fn push(&mut self, raw: Raw) { - let cost = match &raw { - // What is held, capacity and all. - Raw::Path { ops, .. } => ops.capacity().saturating_mul(std::mem::size_of::()), - Raw::Bitmap { img, .. } => img.px.capacity(), - Raw::Text(t) => { - t.text.capacity().saturating_add(t.font.capacity()).saturating_add(t.dx.capacity().saturating_mul(std::mem::size_of::())) - } - }; - if self.items.len() >= MAX_ITEMS || self.used.saturating_add(cost) > MAX_BYTES { - self.full = true; - } else { - self.used += cost; - self.items.push(raw); - } - } - - pub fn set_window_org(&mut self, p: P) { - self.map.wo = p; - } - - pub fn set_window_ext(&mut self, e: P) { - self.map.we = e; - self.window_set = true; - } - - pub fn set_viewport_org(&mut self, p: P) { - self.map.vo = p; - } - - pub fn set_viewport_ext(&mut self, e: P) { - self.map.ve = e; - self.viewport_set = true; - } - - /// Sets up the mapping the way a player does before it plays a WMF into a target: anisotropic, - /// `window` (`[x, y, w, h]` in logical units) onto a viewport of `size` at the origin. The file's - /// own window records then replace the window; the viewport stays unless the file sets one. - /// Without a window (a plain WMF) only the viewport extent is set: the map mode and viewport - /// origin stay the file's. - pub fn play_into(&mut self, window: Option<[f64; 4]>, size: P) { - if let Some([x, y, w, h]) = window { - self.map.mode = MM_ANISOTROPIC; - self.map.wo = (x, y); - self.map.we = (w, h); - self.map.vo = (0.0, 0.0); - } - self.map.ve = size; - } - - pub fn set_map_mode(&mut self, mode: u32) { - self.map.mode = mode; - } - - /// Device pixels per millimetre (x, y) for the metric map modes. Ignored unless both are positive. - pub fn set_device_mm(&mut self, px_mm: P) { - if px_mm.0.is_finite() && px_mm.1.is_finite() && px_mm.0 > 0.0 && px_mm.1 > 0.0 { - self.map.px_mm = px_mm; - } - } - - pub fn set_polyfill(&mut self, mode: u32) { - self.even_odd = mode != WINDING; - } - - /// SETROP2: only R2_NOP changes what is drawn (nothing); the other mix modes draw as copy. - pub fn set_rop2(&mut self, mode: u32) { - self.nop = mode == R2_NOP; - } - - /// EMF SETWORLDTRANSFORM (`mode` 4) and MODIFYWORLDTRANSFORM (1 identity, 2 left, 3 right, 4 set). - /// An unknown mode leaves the world transform as it was. - pub fn modify_world(&mut self, x: Xform, mode: u32) { - match mode { - 1 => self.map.world = IDENTITY, - 2 => self.map.world = mul(x, self.map.world), - 3 => self.map.world = mul(self.map.world, x), - 4 => self.map.world = x, - _ => {} - } - } - - /// Pushes the drawing state. Past [`MAX_STACK`] levels the parse stops, since later restores - /// could no longer match the file. - pub fn save_dc(&mut self) { - if self.saved.len() < MAX_STACK { - self.saved.push(Saved { - map: self.map, - pen: self.pen, - brush: self.brush, - even_odd: self.even_odd, - nop: self.nop, - font: self.font, - text_color: self.text_color, - text_align: self.text_align, - }); - } else { - self.full = true; - } - } - - /// Negative `n` pops `-n` levels; positive `n` restores absolute level `n`. - pub fn restore_dc(&mut self, n: i32) { - let idx = if n < 0 { self.saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; - let Some(idx) = idx else { return }; - let Some(s) = self.saved.get(idx).cloned() else { return }; - self.saved.truncate(idx); - self.map = s.map; - self.pen = s.pen; - self.brush = s.brush; - self.even_odd = s.even_odd; - self.nop = s.nop; - self.font = s.font; - self.text_color = s.text_color; - self.text_align = s.text_align; - } - - /// Stores an object in `slot` (EMF index), or in the lowest free slot (WMF handle table). - pub fn add_object(&mut self, slot: Option, obj: Obj) { - match slot { - Some(i) if i < MAX_OBJECTS => { - // Growing the table leaves the slots between the old end and `i` free. - self.free.extend(self.objects.len()..i); - if self.objects.len() <= i { - self.objects.resize(i + 1, None); - } - self.free.remove(&i); - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - Some(_) => {} - None => match self.free.pop_first() { - Some(i) => { - #[cfg(test)] - { - self.slot_probes += 1; - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - None if self.objects.len() < MAX_OBJECTS => self.objects.push(Some(obj)), - None => {} - }, - } - } - - pub fn delete_object(&mut self, i: u32) { - let i = i as usize; - if let Some(s) = self.objects.get_mut(i) { - *s = None; - self.free.insert(i); - } - } - - /// Selects an object by index; indices with the high bit set are stock objects. - pub fn select(&mut self, i: u32) { - if i & STOCK != 0 { - return self.select_stock(i & !STOCK); - } - match self.objects.get(i as usize).copied().flatten() { - Some(Obj::Pen(p)) => self.pen = p, - Some(Obj::Brush(b)) => self.brush = b, - Some(Obj::Font(f)) => self.font = Some(f), - Some(Obj::Other) | None => {} - } - } - - fn select_stock(&mut self, i: u32) { - let white = [255, 255, 255, 255]; - let black = [0, 0, 0, 255]; - let gray = |v: u8| Brush { style: BS_SOLID, color: [v, v, v, 255] }; - match i { - 0 | 18 => self.brush = Brush { style: BS_SOLID, color: white }, - 1 => self.brush = gray(192), - 2 => self.brush = gray(128), - 3 => self.brush = gray(64), - 4 => self.brush = Brush { style: BS_SOLID, color: black }, - 5 => self.brush = Brush { style: BS_NULL, color: black }, - 6 => self.pen = Pen { style: 0, width: 0.0, color: white }, - 7 | 19 => self.pen = Pen { style: 0, width: 0.0, color: black }, - 8 => self.pen = Pen { style: PS_NULL, width: 0.0, color: black }, - // The stock fonts (OEM, ANSI, system, device default...): the default font. - 10..=17 => self.font = None, - _ => {} - } - } - - fn map_op(&self, op: Op) -> Op { - match op { - Op::M(p) => Op::M(self.map.device(p)), - Op::L(p) => Op::L(self.map.device(p)), - Op::C(a, b, c) => Op::C(self.map.device(a), self.map.device(b), self.map.device(c)), - Op::Z => Op::Z, - } - } - - fn fill_color(&self) -> Option<[u8; 4]> { - (self.brush.style == BS_SOLID).then_some(self.brush.color) - } - - fn stroke_pen(&self) -> Option<([u8; 4], f64)> { - if (self.pen.style & PS_STYLE_MASK) == PS_NULL { - return None; - } - // A cosmetic pen (width 0) stays 0: the renderers draw that as a hairline. - let w = if self.pen.width == 0.0 { 0.0 } else { self.pen.width.abs() * self.map.scale() }; - Some((self.pen.color, w)) - } - - fn push_path_ops(&mut self, ops: impl IntoIterator) { - for op in ops { - if self.path.len() >= MAX_PATH_OPS { - return; - } - self.path.push(op); - } - } - - /// Draws logical-space ops with the current pen (`stroke`) and brush (`fill`), or appends them to - /// the open path bracket, where fill and stroke wait for FILLPATH/STROKEPATH. - pub fn shape(&mut self, mut dev: Vec, fill: bool, stroke: bool) { - // Maps in place: the caller's vector becomes the device-space path, no second copy. - for op in &mut dev { - *op = self.map_op(*op); - } - if self.in_path { - return self.push_path_ops(dev); - } - if self.nop { - return; - } - let fill = if fill { self.fill_color() } else { None }; - let stroke = if stroke { self.stroke_pen() } else { None }; - if (fill.is_none() && stroke.is_none()) || dev.len() < 2 { - return; - } - let even_odd = self.even_odd; - self.push(Raw::Path { ops: dev, fill, stroke, even_odd }); - } - - pub fn move_to(&mut self, p: P) { - if self.in_path { - self.push_path_ops([Op::M(self.map.device(p))]); - } - self.pos = p; - } - - /// LINETO from the current point, then moves the current point to `p`. - pub fn line_to(&mut self, p: P) { - self.line_chain(&[p], false, true); - } - - /// Lines from the current point through `pts` (POLYLINETO), or a polyline from the current point. - pub fn line_chain(&mut self, pts: &[P], fill: bool, stroke: bool) { - // Inside an open bracket the path already ends at the current point, so no MoveTo is needed. - let mut ops = if self.in_path && !self.path.is_empty() { Vec::new() } else { vec![Op::M(self.pos)] }; - ops.extend(pts.iter().map(|p| Op::L(*p))); - if let Some(last) = pts.last() { - self.pos = *last; - } - self.shape(ops, fill, stroke); - } - - /// POLYBEZIER: cubic segments that start a new figure at `from`. The current point is unchanged. - pub fn bezier(&mut self, from: P, pts: &[P]) { - let mut ops = vec![Op::M(from)]; - ops.extend(cubics(pts)); - self.shape(ops, false, true); - } - - /// POLYBEZIERTO: cubic segments from the current point through groups of three control or end - /// points; the current point moves to the last point. Inside an open bracket the path already - /// ends at the current point, so no MoveTo is needed. - pub fn bezier_to(&mut self, pts: &[P]) { - let mut ops = if self.in_path && !self.path.is_empty() { Vec::new() } else { vec![Op::M(self.pos)] }; - ops.extend(cubics(pts)); - if let Some(last) = pts.last() { - self.pos = *last; - } - self.shape(ops, false, true); - } - - pub fn poly(&mut self, pts: &[P], close: bool, fill: bool, stroke: bool) { - let Some(first) = pts.first() else { return }; - let mut ops = vec![Op::M(*first)]; - ops.extend(pts.iter().skip(1).map(|p| Op::L(*p))); - if close { - ops.push(Op::Z); - } - self.shape(ops, fill, stroke); - } - - pub fn begin_path(&mut self) { - self.in_path = true; - self.path.clear(); - } - - pub fn end_path(&mut self) { - self.in_path = false; - } - - pub fn close_figure(&mut self) { - if self.in_path { - self.push_path_ops([Op::Z]); - } - } - - /// FILLPATH, STROKEPATH and STROKEANDFILLPATH: paints the bracketed path and empties it. - pub fn paint_path(&mut self, fill: bool, stroke: bool) { - let ops = std::mem::take(&mut self.path); - if self.nop { - return; - } - let fill = if fill { self.fill_color() } else { None }; - let stroke = if stroke { self.stroke_pen() } else { None }; - if ops.len() < 2 || (fill.is_none() && stroke.is_none()) { - return; - } - let even_odd = self.even_odd; - self.push(Raw::Path { ops, fill, stroke, even_odd }); - } - - /// Fills a logical rectangle `[l, t, r, b]` with the current brush (nothing when it is not solid). - pub fn fill_brush_rect(&mut self, rect: [f64; 4]) { - if let Some(color) = self.fill_color() { - self.fill_rect_with(rect, color); - } - } - - /// Fills a logical rectangle `[l, t, r, b]` with a solid colour (ROP fills such as BLACKNESS). - pub fn fill_rect_with(&mut self, [l, t, r, b]: [f64; 4], color: [u8; 4]) { - let dev: Vec = crate::geom::rect(l, t, r, b).iter().map(|o| self.map_op(*o)).collect(); - self.push(Raw::Path { ops: dev, fill: Some(color), stroke: None, even_odd: true }); - } - - /// Whether a raster operation draws without a source bitmap (PATCOPY, BLACKNESS, WHITENESS). - pub fn sourceless(rop: u32) -> bool { - matches!(rop, PATCOPY | BLACKNESS | WHITENESS) - } - - /// Fills a logical rectangle `[x, y, w, h]` for a source-less raster operation. PATCOPY uses the - /// brush (when solid); the others fill black or white. Other operations are not handled here. - pub fn fill_rop(&mut self, [x, y, w, h]: [f64; 4], rop: u32) { - let rect = [x, y, x + w, y + h]; - match rop { - PATCOPY => self.fill_brush_rect(rect), - BLACKNESS => self.fill_rect_with(rect, [0, 0, 0, 255]), - WHITENESS => self.fill_rect_with(rect, [255, 255, 255, 255]), - _ => {} - } - } - - pub fn set_text_color(&mut self, c: [u8; 4]) { - self.text_color = c; - } - - pub fn set_text_align(&mut self, a: u32) { - self.text_align = a; - } - - /// Draws `text` at the logical point `at` (the current point with TA_UPDATECP) with the selected - /// font, text colour and alignment. `dx` holds per-character logical advances (empty for the - /// font's own); with TA_UPDATECP the current point moves past them. - pub fn text(&mut self, at: P, text: String, dx: &[f64]) { - if text.is_empty() || self.in_path { - return; - } - let font = self.font.unwrap_or(Font { height: 0, escapement: 0, weight: 400, italic: false, face: [0; 32] }); - let at = if self.text_align & TA_UPDATECP != 0 { self.pos } else { at }; - if self.text_align & TA_UPDATECP != 0 { - self.pos = (at.0 + dx.iter().sum::(), at.1); - } - let height = if font.height == 0 { DEFAULT_FONT_HEIGHT } else { f64::from(font.height) }; - let origin = self.map.device(at); - let len = |v: P| { - let d = self.map.device((at.0 + v.0, at.1 + v.1)); - (d.0 - origin.0).hypot(d.1 - origin.1) - }; - let base = self.map.device((at.0 + 1.0, at.1)); - let escapement = f64::from(font.escapement) / 10.0; - let angle = (base.1 - origin.1).atan2(base.0 - origin.0) - escapement.to_radians(); - let size = len((0.0, height.abs())); - let dx = dx.iter().map(|d| len((*d, 0.0)).copysign(*d)).collect(); - let name = String::from_utf16_lossy(&font.face); - let name = name.trim_end_matches('\0').trim(); - let raw = RawText { - text, - origin, - size, - cell: height > 0.0, - angle: if angle.is_finite() { angle } else { 0.0 }, - dx, - font: if name.is_empty() { DEFAULT_FONT_FACE.to_string() } else { name.to_string() }, - bold: font.weight >= 600, - italic: font.italic, - color: self.text_color, - align: self.text_align, - }; - if raw.origin.0.is_finite() && raw.origin.1.is_finite() && raw.size.is_finite() && raw.size > 0.0 { - self.push(Raw::Text(raw)); - } - } - - /// A bitmap stretched into a logical rectangle `[x, y, w, h]`. A negative extent mirrors the - /// bitmap, as the mapping does. - pub fn bitmap(&mut self, rect: [f64; 4], mut img: Rgba) { - let [x, y, w, h] = rect; - let a = self.map.device((x, y)); - let b = self.map.device((x + w, y + h)); - crate::dib::flip(&mut img, a.0 > b.0, a.1 > b.1); - let dev = [a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()]; - self.push(Raw::Bitmap { rect: dev, img }); - } -} - -/// Cubic segments from groups of three points (control, control, end). A trailing partial group is -/// dropped. -fn cubics(pts: &[P]) -> Vec { - let mut ops = Vec::with_capacity(pts.len() / 3); - let mut it = pts.iter().copied(); - while let (Some(a), Some(b), Some(e)) = (it.next(), it.next(), it.next()) { - ops.push(Op::C(a, b, e)); - } - ops -} - -#[cfg(test)] -mod object_table_tests { - use super::*; - - fn pen(id: u32) -> Obj { - Obj::Pen(Pen { style: 0, width: 0.0, color: [id as u8, (id >> 8) as u8, 0, 255] }) - } - - fn id_of(o: &Option) -> Option { - match o { - Some(Obj::Pen(p)) => Some(u32::from(p.color[0]) | u32::from(p.color[1]) << 8), - _ => None, - } - } - - /// The table as it was before the free-slot set: a scan from index 0 for every handle-table create. - struct Naive(Vec>); - - impl Naive { - fn add(&mut self, slot: Option, id: u32) { - match slot { - Some(i) if i < MAX_OBJECTS => { - if self.0.len() <= i { - self.0.resize(i + 1, None); - } - self.0[i] = Some(id); - } - Some(_) => {} - None => match self.0.iter().position(Option::is_none) { - Some(i) => self.0[i] = Some(id), - None if self.0.len() < MAX_OBJECTS => self.0.push(Some(id)), - None => {} - }, - } - } - - fn delete(&mut self, i: u32) { - if let Some(s) = self.0.get_mut(i as usize) { - *s = None; - } - } - } - - #[test] - fn handle_table_picks_the_same_slots_as_the_first_free_scan() { - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - let mut rnd = move |n: u64| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - seed % n - }; - for round in 0..20 { - // Small tables exercise reuse; some rounds also run past the cap and use explicit EMF slots. - let span = if round % 2 == 0 { 12 } else { MAX_OBJECTS as u64 + 50 }; - let (mut cv, mut naive) = (Canvas::new(), Naive(Vec::new())); - for id in 0..20_000u32 { - match rnd(10) { - 0..=4 => { - cv.add_object(None, pen(id)); - naive.add(None, id); - } - 5 | 6 if round >= 10 => { - let slot = rnd(span + 20) as usize; - cv.add_object(Some(slot), pen(id)); - naive.add(Some(slot), id); - } - _ => { - let i = rnd(span + 5) as u32; - cv.delete_object(i); - naive.delete(i); - } - } - if id % 500 == 0 || id == 19_999 { - let got: Vec> = cv.objects.iter().map(id_of).collect(); - assert_eq!(got, naive.0, "round {round}, step {id}"); - } - } - } - } - - #[test] - fn creating_into_a_full_table_does_not_scan_it() { - let mut cv = Canvas::new(); - for i in 0..MAX_OBJECTS as u32 { - cv.add_object(None, pen(i)); - } - assert_eq!(cv.objects.len(), MAX_OBJECTS); - let before = cv.slot_probes; - for i in 0..10_000 { - cv.add_object(None, pen(i)); - } - // A scan from index 0 would examine 4096 slots per create; the free set examines none. - assert_eq!(cv.slot_probes, before); - cv.delete_object(7); - cv.add_object(None, pen(99)); - assert_eq!(cv.slot_probes, before + 1); - assert_eq!(cv.objects.get(7).map(id_of), Some(Some(99))); - } -} diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs deleted file mode 100644 index 15be8aa3c0..0000000000 --- a/crates/metafile/src/dib.rs +++ /dev/null @@ -1,719 +0,0 @@ -//! Device-independent bitmaps. BITMAPINFOHEADER DIBs at 1/4/8/16/24/32 bpp with BI_RGB or BI_BITFIELDS -//! decode to RGBA8 rows, top-down. Compressed (RLE, JPEG, PNG) and V4/V5-only features are not decoded. - -use crate::{MAX_BITMAP_SIDE, MAX_PIXELS, bytes::Bytes}; - -const BI_RGB: u32 = 0; -const BI_BITFIELDS: u32 = 3; -/// Most palette entries a DIB can carry (the colour table never exceeds 2^8). -const MAX_PALETTE: usize = 256; -const ROP_SRCAND: u32 = 0x0088_00C6; -const ROP_SRCPAINT: u32 = 0x00EE_0086; -const ROP_SRCINVERT: u32 = 0x0066_0046; - -/// A decoded picture, rows top-down. -pub(crate) struct Rgba { - pub w: usize, - pub h: usize, - pub px: Vec, -} - -/// How a decoded bitmap combines with the destination. -#[derive(Clone, Copy)] -pub(crate) enum Blend { - /// A raster operation (BITBLT, STRETCHDIB and friends). - Rop(u32), - /// EMR_ALPHABLEND: a constant alpha (0..=255), times the per-pixel alpha when `per_pixel` is set - /// (AC_SRC_ALPHA: the source colours are premultiplied by it). - Alpha { constant: u8, per_pixel: bool }, -} - -impl Blend { - /// Whether the decoder must keep the 32-bit alpha byte of each pixel. - pub fn per_pixel(self) -> bool { - matches!(self, Blend::Alpha { per_pixel: true, .. }) - } -} - -struct Header { - w: usize, - h: usize, - top_down: bool, - bpp: usize, - masks: [u32; 3], - pal_off: usize, - pal_n: usize, -} - -impl Header { - fn read(info: Bytes) -> Option
{ - let size = info.u32(0)? as usize; - let w = info.i32(4)?; - let h = info.i32(8)?; - let bpp = info.u16(14)? as usize; - let comp = info.u32(16)?; - let clr_used = info.u32(32)? as usize; - if size < 40 || w <= 0 || h == 0 || !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) || !matches!(comp, BI_RGB | BI_BITFIELDS) { - return None; - } - let masks = if comp == BI_BITFIELDS { - [info.u32(40)?, info.u32(44)?, info.u32(48)?] - } else if bpp == 16 { - [0x7C00, 0x03E0, 0x001F] - } else { - [0xFF_0000, 0xFF00, 0xFF] - }; - let masks_len = if comp == BI_BITFIELDS && size == 40 { 12 } else { 0 }; - let pal_off = size.checked_add(masks_len)?; - // Indexed formats take 2^bpp entries when clrUsed is 0. Deeper formats carry only the - // entries clrUsed names (WMF DIBs can have them), still capped. - let pal_n = match (bpp <= 8, clr_used) { - (true, 0) => 1usize << bpp, - (true, n) => n.min(1usize << bpp), - (false, n) => n.min(MAX_PALETTE), - }; - Some(Header { w: w as usize, h: h.unsigned_abs() as usize, top_down: h < 0, bpp, masks, pal_off, pal_n }) - } -} - -/// Byte length of the info part (header, masks, palette) of a DIB, so the pixel bits follow it. -pub(crate) fn info_len(dib: Bytes) -> Option { - let h = Header::read(dib)?; - h.pal_off.checked_add(h.pal_n.checked_mul(4)?) -} - -/// Decodes the part of a DIB that the source rectangle `src` = `[x, y, w, h]` selects and returns it -/// (top-down) with the part of the destination `dst` that it fills; see [`clip_rect`] for the -/// coordinates. `info` is the info part (header plus masks and palette) and `bits` the pixel bits. The -/// 32-bit alpha byte is kept only when `keep_alpha` is set (per-pixel alpha blends); otherwise pixels -/// are opaque. Only the clipped rows and columns are decoded, so the work and the memory follow the -/// crop, not the whole bitmap; the whole bitmap is still validated (size cap, palette, bits length). -/// None as well when the clipped width or height is over [`MAX_BITMAP_SIDE`], which no renderer draws. -pub(crate) fn decode_clip(info: Bytes, bits: Bytes, keep_alpha: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Rgba, [f64; 4])> { - let hd = Header::read(info)?; - let pixels = hd.w.checked_mul(hd.h)?; - if pixels == 0 || pixels > MAX_PIXELS { - return None; - } - let stride = hd.w.checked_mul(hd.bpp)?.checked_add(31)? / 32 * 4; - let data = bits.slice(0, stride.checked_mul(hd.h)?)?; - let pal = info.slice(hd.pal_off, hd.pal_n * 4)?; - let (clip, out) = clip_rect(hd.w, hd.h, !hd.top_down, src, dst)?; - // The renderers draw no bitmap with a side over the cap (`Item::take_pixels`); decoding one - // would only fill the parse's memory budget with pixels nobody draws. - let cap = MAX_BITMAP_SIDE as usize; - if clip.x1 - clip.x0 > cap || clip.r1 - clip.r0 > cap { - return None; - } - let (ow, oh) = (clip.x1 - clip.x0, clip.r1 - clip.r0); - let mut px = vec![0u8; ow.checked_mul(oh)?.checked_mul(4)?]; - #[cfg(test)] - DECODED.with(|d| d.set(d.get() + ow * oh)); - // The depth, palette and masks are the same for every pixel: pick the row decoder once. - let kind = RowKind::new(&hd, pal, keep_alpha); - for (y, line) in (clip.r0..clip.r1).zip(px.chunks_exact_mut(ow * 4)) { - let src_row = if hd.top_down { y } else { hd.h - 1 - y }; - let row = data.get(src_row * stride..(src_row + 1) * stride)?; - kind.decode_row(row, clip.x0..clip.x1, line.as_chunks_mut::<4>().0)?; - } - Some((Rgba { w: ow, h: oh, px }, out)) -} - -#[cfg(test)] -thread_local! { - /// Pixels asked of the decoder on this thread, so the tests can check that the work follows the crop. - static DECODED: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// One channel of a masked 16/32 bpp pixel, with the shift and scale worked out once per bitmap. -/// Channels of up to 8 bits (every common 16 bpp layout) go through a table of their values, so a -/// pixel costs no division. -#[derive(Clone)] -struct Channel { - mask: u32, - shift: u32, - max: u64, - table: [u8; 256], -} - -impl Channel { - fn new(mask: u32) -> Channel { - let shift = if mask == 0 { 0 } else { mask.trailing_zeros() }; - let max = u64::from(mask >> shift); - let mut table = [0u8; 256]; - if mask != 0 && max <= 255 { - for (val, t) in table.iter_mut().enumerate().take(max as usize + 1) { - *t = ((val as u64 * 255 + max / 2) / max) as u8; - } - } - Channel { mask, shift, max, table } - } - - /// The channel of `v` scaled to 8 bits; 0 when the mask is empty. - fn get(&self, v: u32) -> u8 { - if self.mask == 0 { - return 0; - } - let val = u64::from((v & self.mask) >> self.shift); - if self.max <= 255 { - return self.table[usize::from(val as u8)]; - } - ((val * 255 + self.max / 2) / self.max) as u8 - } -} - -/// How the pixels of one DIB turn into RGBA, decided once from its header. -enum RowKind { - /// 1, 4 or 8 bpp: `bpp` bits per index into a table of every possible index. - Indexed { bpp: usize, table: Box<[[u8; 4]; 256]> }, - /// 24 bpp: BGR triples. - Bgr24, - /// 32 bpp with the default masks: BGRA quads, alpha kept or forced opaque. - Bgra32 { keep_alpha: bool }, - /// 16 bpp, or 32 bpp with other masks. - Masked { bpp: usize, ch: Box<[Channel; 3]>, keep_alpha: bool }, -} - -impl RowKind { - fn new(hd: &Header, pal: &[u8], keep_alpha: bool) -> RowKind { - match hd.bpp { - 1 | 4 | 8 => { - // An index past the palette reads as black, as in `palette`. - let mut table = Box::new([[0u8, 0, 0, 255]; 256]); - for (i, t) in table.iter_mut().enumerate().take(1 << hd.bpp) { - let [r, g, b] = palette(pal, i); - *t = [r, g, b, 255]; - } - RowKind::Indexed { bpp: hd.bpp, table } - } - 24 => RowKind::Bgr24, - 32 if hd.masks == [0xFF_0000, 0xFF00, 0xFF] => RowKind::Bgra32 { keep_alpha }, - _ => RowKind::Masked { bpp: hd.bpp, ch: Box::new(hd.masks.map(Channel::new)), keep_alpha }, - } - } - - /// Decodes the columns `cols` of one source row `row` (all of its bytes) into `out`. `None` when - /// the row is shorter than the columns need. - fn decode_row(&self, row: &[u8], cols: std::ops::Range, out: &mut [[u8; 4]]) -> Option<()> { - match self { - RowKind::Indexed { bpp: 8, table } => { - for (d, s) in out.iter_mut().zip(row.get(cols)?) { - *d = table[usize::from(*s)]; - } - } - RowKind::Indexed { bpp: 4, table } => { - for (d, x) in out.iter_mut().zip(cols) { - let b = *row.get(x / 2)?; - *d = table[usize::from(if x.is_multiple_of(2) { b >> 4 } else { b & 0x0F })]; - } - } - RowKind::Indexed { table, .. } => { - for (d, x) in out.iter_mut().zip(cols) { - let b = *row.get(x / 8)?; - *d = table[usize::from((b >> (7 - x % 8)) & 1)]; - } - } - RowKind::Bgr24 => { - let src = row.get(cols.start.checked_mul(3)?..cols.end.checked_mul(3)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<3>().0) { - *d = [s[2], s[1], s[0], 255]; - } - } - RowKind::Bgra32 { keep_alpha } => { - let src = row.get(cols.start.checked_mul(4)?..cols.end.checked_mul(4)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<4>().0) { - *d = [s[2], s[1], s[0], if *keep_alpha { s[3] } else { 255 }]; - } - } - RowKind::Masked { bpp: 16, ch, .. } => { - let [r, g, b] = &**ch; - let src = row.get(cols.start.checked_mul(2)?..cols.end.checked_mul(2)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<2>().0) { - let v = u32::from(u16::from_le_bytes(*s)); - *d = [r.get(v), g.get(v), b.get(v), 255]; - } - } - RowKind::Masked { ch, keep_alpha, .. } => { - let [r, g, b] = &**ch; - let src = row.get(cols.start.checked_mul(4)?..cols.end.checked_mul(4)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<4>().0) { - let v = u32::from_le_bytes(*s); - *d = [r.get(v), g.get(v), b.get(v), if *keep_alpha { (v >> 24) as u8 } else { 255 }]; - } - } - } - Some(()) - } -} - -/// Palette entries are BGRX quads; an index past the table reads as black rather than failing the image. -fn palette(pal: &[u8], i: usize) -> [u8; 3] { - pal.get(i * 4..i * 4 + 4).and_then(|c| <[u8; 4]>::try_from(c).ok()).map_or([0, 0, 0], |c| [c[2], c[1], c[0]]) -} - -/// The columns `x0..x1` and top-down rows `r0..r1` of a bitmap that a clipped source rectangle covers. -struct Clip { - x0: usize, - x1: usize, - r0: usize, - r1: usize, -} - -/// Clips a source rectangle `src` = `[x, y, w, h]` to a `w` x `h` bitmap and returns the covered pixels -/// with the part of the destination `dst` that they fill. `src` is in DIB pixel coordinates (`y` counted -/// from the DIB's origin, so bottom-up images count from the bottom); a non-positive source size means the -/// whole bitmap. Clipping shrinks the destination by the same ratio and shifts it by the clipped-off part, -/// so the rest of the image keeps its place. A negative destination extent is kept (the caller mirrors). -/// `None` when nothing of the bitmap is covered. -fn clip_rect(w: usize, h: usize, bottom_up: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Clip, [f64; 4])> { - let (iw, ih) = (w as i64, h as i64); - let [sx, sy, sw, sh] = if src[2] > 0 && src[3] > 0 { src } else { [0, 0, iw, ih] }; - // The request's top row in top-down order. - let top = if bottom_up { ih.saturating_sub(sy).saturating_sub(sh) } else { sy }; - let (x0, x1) = (sx.max(0), sx.saturating_add(sw).min(iw)); - let (r0, r1) = (top.max(0), top.saturating_add(sh).min(ih)); - if x1 <= x0 || r1 <= r0 { - return None; - } - let (kx, ky) = (dst[2] / sw as f64, dst[3] / sh as f64); - let out = [dst[0] + (x0 - sx) as f64 * kx, dst[1] + (r0 - top) as f64 * ky, (x1 - x0) as f64 * kx, (r1 - r0) as f64 * ky]; - Some((Clip { x0: x0 as usize, x1: x1 as usize, r0: r0 as usize, r1: r1 as usize }, out)) -} - -/// Applies a blend to decoded pixels before they are drawn. The picture has no destination pixels, so -/// raster operations are drawn as they look over white paper: SRCAND (destination AND source) leaves -/// white source pixels out and draws the rest; SRCPAINT and SRCINVERT leave black ones out. Other -/// operations draw the source as copied. Constant alpha scales every pixel's alpha, after a -/// per-pixel (premultiplied) source is made straight. -pub(crate) fn prepare(img: &mut Rgba, blend: Blend) { - match blend { - Blend::Rop(ROP_SRCAND) => clear_where(img, [255, 255, 255]), - Blend::Rop(ROP_SRCPAINT | ROP_SRCINVERT) => clear_where(img, [0, 0, 0]), - Blend::Rop(_) => {} - Blend::Alpha { constant, per_pixel } => { - for p in img.px.as_chunks_mut::<4>().0 { - if per_pixel { - unpremultiply(p); - } - p[3] = (u16::from(p[3]) * u16::from(constant) / 255) as u8; - } - } - } -} - -/// Makes the pixels of colour `rgb` transparent: where a raster operation keeps the destination. -fn clear_where(img: &mut Rgba, rgb: [u8; 3]) { - for p in img.px.as_chunks_mut::<4>().0 { - if p[..3] == rgb { - p[3] = 0; - } - } -} - -/// AC_SRC_ALPHA sources are premultiplied; the model holds straight RGBA, so divide the colour by the -/// alpha (rounded, capped at 255). A transparent pixel keeps its colour bytes. -fn unpremultiply(p: &mut [u8; 4]) { - let a = u32::from(p[3]); - if a == 0 || a == 255 { - return; - } - for c in &mut p[..3] { - *c = ((u32::from(*c) * 255 + a / 2) / a).min(255) as u8; - } -} - -/// Mirrors a decoded image left-right and/or top-bottom. Rows come from the buffer as chunks, so a -/// short buffer flips only the rows it has. -pub(crate) fn flip(img: &mut Rgba, horizontal: bool, vertical: bool) { - let (w, h) = (img.w, img.h); - if w == 0 || h == 0 { - return; - } - let row = w * 4; - if horizontal { - for line in img.px.chunks_exact_mut(row) { - for x in 0..w / 2 { - for c in 0..4 { - line.swap(x * 4 + c, (w - 1 - x) * 4 + c); - } - } - } - } - if vertical { - // Rows the buffer actually holds: a short buffer flips only those. - let n = h.min(img.px.len() / row); - for y in 0..n / 2 { - swap_rows(&mut img.px, y * row, (n - 1 - y) * row, row); - } - } -} - -/// Swaps the `len` bytes at `a` with those at `b` (`a < b`); does nothing when either is out of range. -fn swap_rows(px: &mut [u8], a: usize, b: usize, len: usize) { - let Some((head, tail)) = px.split_at_mut_checked(b) else { return }; - if let (Some(top), Some(bottom)) = (head.get_mut(a..a.saturating_add(len)), tail.get_mut(..len)) { - top.swap_with_slice(bottom); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The pipeline before `decode_clip`: decode the whole bitmap, then copy the clipped part out. - fn decode_whole(info: Bytes, bits: Bytes, keep_alpha: bool) -> Option { - let hd = Header::read(info)?; - let pixels = hd.w.checked_mul(hd.h)?; - if pixels == 0 || pixels > MAX_PIXELS { - return None; - } - let stride = hd.w.checked_mul(hd.bpp)?.checked_add(31)? / 32 * 4; - let data = bits.slice(0, stride.checked_mul(hd.h)?)?; - let pal = info.slice(hd.pal_off, hd.pal_n * 4)?; - let mut px = vec![0u8; pixels * 4]; - for y in 0..hd.h { - let src_row = if hd.top_down { y } else { hd.h - 1 - y }; - let row = src_row * stride; - for x in 0..hd.w { - let p = pixel(data, row, x, &hd, pal, keep_alpha)?; - let o = (y * hd.w + x) * 4; - px.get_mut(o..o + 4)?.copy_from_slice(&p); - } - } - Some(Rgba { w: hd.w, h: hd.h, px }) - } - - fn clip_blit_whole(img: &Rgba, bottom_up: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Rgba, [f64; 4])> { - let (iw, ih) = (img.w as i64, img.h as i64); - let [sx, sy, sw, sh] = if src[2] > 0 && src[3] > 0 { src } else { [0, 0, iw, ih] }; - let top = if bottom_up { ih.saturating_sub(sy).saturating_sub(sh) } else { sy }; - let (x0, x1) = (sx.max(0), sx.saturating_add(sw).min(iw)); - let (r0, r1) = (top.max(0), top.saturating_add(sh).min(ih)); - if x1 <= x0 || r1 <= r0 { - return None; - } - let (kx, ky) = (dst[2] / sw as f64, dst[3] / sh as f64); - let out = [dst[0] + (x0 - sx) as f64 * kx, dst[1] + (r0 - top) as f64 * ky, (x1 - x0) as f64 * kx, (r1 - r0) as f64 * ky]; - let (x0, x1, r0, r1) = (x0 as usize, x1 as usize, r0 as usize, r1 as usize); - let (ow, oh) = (x1 - x0, r1 - r0); - let mut px = Vec::with_capacity(ow * oh * 4); - for row in r0..r1 { - let s = (row * img.w + x0) * 4; - px.extend_from_slice(img.px.get(s..s + ow * 4)?); - } - Some((Rgba { w: ow, h: oh, px }, out)) - } - - /// A BITMAPINFOHEADER DIB with a palette for indexed depths; returns (info, bits). - fn make_dib(w: usize, h: i32, bpp: usize, seed: &mut u64) -> (Vec, Vec) { - let mut rnd = || { - *seed ^= *seed << 13; - *seed ^= *seed >> 7; - *seed ^= *seed << 17; - *seed - }; - let mut info = Vec::new(); - info.extend(40u32.to_le_bytes()); - info.extend((w as i32).to_le_bytes()); - info.extend(h.to_le_bytes()); - info.extend(1u16.to_le_bytes()); - info.extend((bpp as u16).to_le_bytes()); - info.extend([0u8; 24]); - if bpp <= 8 { - for _ in 0..(1usize << bpp) * 4 { - info.push(rnd() as u8); - } - } - let stride = (w * bpp).div_ceil(32) * 4; - let bits = (0..stride * h.unsigned_abs() as usize).map(|_| rnd() as u8).collect(); - (info, bits) - } - - /// The per-pixel decoder `decode_clip` used before the depth was chosen once per bitmap. Kept as - /// the reference the fast decoder must match byte for byte. - fn pixel(data: &[u8], row: usize, x: usize, hd: &Header, pal: &[u8], keep_alpha: bool) -> Option<[u8; 4]> { - DECODED.with(|d| d.set(d.get() + 1)); - let [m_r, m_g, m_b] = hd.masks; - let [r, g, b] = match hd.bpp { - 1 => { - let b = *data.get(row + x / 8)?; - palette(pal, usize::from((b >> (7 - x % 8)) & 1)) - } - 4 => { - let b = *data.get(row + x / 2)?; - palette(pal, usize::from(if x.is_multiple_of(2) { b >> 4 } else { b & 0x0F })) - } - 8 => palette(pal, usize::from(*data.get(row + x)?)), - 24 => { - let [b, g, r] = data.get(row + x * 3..row + x * 3 + 3)?.try_into().ok()?; - [r, g, b] - } - 16 => { - let o = row + x * 2; - let v = u32::from(u16::from_le_bytes(data.get(o..o + 2)?.try_into().ok()?)); - [field(v, m_r), field(v, m_g), field(v, m_b)] - } - _ => { - let o = row + x * 4; - let v = u32::from_le_bytes(data.get(o..o + 4)?.try_into().ok()?); - let a = if keep_alpha { (v >> 24) as u8 } else { 255 }; - return Some([field(v, m_r), field(v, m_g), field(v, m_b), a]); - } - }; - Some([r, g, b, 255]) - } - - /// Extracts one channel from a masked pixel value and scales it to 8 bits. - fn field(v: u32, mask: u32) -> u8 { - if mask == 0 { - return 0; - } - let shift = mask.trailing_zeros(); - let max = u64::from(mask >> shift); - let val = u64::from((v & mask) >> shift); - ((val * 255 + max / 2) / max) as u8 - } - - /// `decode_clip` as it was: the same clip, then `pixel` for every output pixel. - fn decode_clip_reference(info: Bytes, bits: Bytes, keep_alpha: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Rgba, [f64; 4])> { - let hd = Header::read(info)?; - let pixels = hd.w.checked_mul(hd.h)?; - if pixels == 0 || pixels > MAX_PIXELS { - return None; - } - let stride = hd.w.checked_mul(hd.bpp)?.checked_add(31)? / 32 * 4; - let data = bits.slice(0, stride.checked_mul(hd.h)?)?; - let pal = info.slice(hd.pal_off, hd.pal_n * 4)?; - let (clip, out) = clip_rect(hd.w, hd.h, !hd.top_down, src, dst)?; - let (ow, oh) = (clip.x1 - clip.x0, clip.r1 - clip.r0); - let mut px = vec![0u8; ow.checked_mul(oh)?.checked_mul(4)?]; - for (y, line) in (clip.r0..clip.r1).zip(px.chunks_exact_mut(ow * 4)) { - let src_row = if hd.top_down { y } else { hd.h - 1 - y }; - let row = src_row * stride; - for (x, dst_px) in (clip.x0..clip.x1).zip(line.as_chunks_mut::<4>().0) { - *dst_px = pixel(data, row, x, &hd, pal, keep_alpha)?; - } - } - Some((Rgba { w: ow, h: oh, px }, out)) - } - - /// A DIB with chosen header fields: `masks` makes it BI_BITFIELDS (inline after a 40 byte - /// header, or inside a larger header), `clr_used` limits the palette, and the palette, when the - /// depth is indexed, has `pal_entries` entries (fewer than the depth names reads as black). - fn make_dib_with( - w: usize, - h: i32, - bpp: usize, - masks: Option<([u32; 3], usize)>, - clr_used: u32, - pal_entries: usize, - seed: &mut u64, - ) -> (Vec, Vec) { - let mut rnd = || { - *seed ^= *seed << 13; - *seed ^= *seed >> 7; - *seed ^= *seed << 17; - *seed - }; - let size = masks.map_or(40, |(_, s)| s); - let mut info = Vec::new(); - info.extend((size as u32).to_le_bytes()); - info.extend((w as i32).to_le_bytes()); - info.extend(h.to_le_bytes()); - info.extend(1u16.to_le_bytes()); - info.extend((bpp as u16).to_le_bytes()); - info.extend(if masks.is_some() { 3u32 } else { 0 }.to_le_bytes()); - info.extend([0u8; 12]); - info.extend(clr_used.to_le_bytes()); - info.extend([0u8; 4]); - info.resize(size.max(40), 0); - if let Some((m, _)) = masks { - for (i, v) in m.iter().enumerate() { - let at = 40 + i * 4; - if size == 40 { - info.extend(v.to_le_bytes()); - } else if let Some(dst) = info.get_mut(at..at + 4) { - dst.copy_from_slice(&v.to_le_bytes()); - } - } - } - for _ in 0..pal_entries * 4 { - info.push(rnd() as u8); - } - let stride = (w * bpp).div_ceil(32) * 4; - let bits = (0..stride * h.unsigned_abs() as usize).map(|_| rnd() as u8).collect(); - (info, bits) - } - - fn assert_same(info: &[u8], bits: &[u8], what: &str) { - for keep_alpha in [false, true] { - for src in [[0, 0, 0, 0], [3, 1, 20, 3], [-4, -4, 100, 100], [36, 4, 5, 5], [1, 0, 1, 5], [8, 2, 17, 2], [0, 3, 37, 1]] { - let dst = [1.0, 2.0, 30.0, 40.0]; - let old = decode_clip_reference(Bytes(info), Bytes(bits), keep_alpha, src, dst); - let new = decode_clip(Bytes(info), Bytes(bits), keep_alpha, src, dst); - match (old, new) { - (None, None) => {} - (Some((a, ad)), Some((b, bd))) => { - assert_eq!((a.w, a.h, &a.px), (b.w, b.h, &b.px), "{what} alpha={keep_alpha} {src:?}"); - assert_eq!(ad.map(f64::to_bits), bd.map(f64::to_bits), "{what} alpha={keep_alpha} {src:?}"); - } - _ => panic!("old and new disagree on None: {what} alpha={keep_alpha} {src:?}"), - } - } - } - } - - #[test] - fn decode_clip_matches_the_per_pixel_reference_at_every_depth_palette_and_mask() { - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - // Widths that leave padding bits in the row, so a row's last byte is only partly used. - for w in [1, 9, 37] { - for h in [6, -6] { - for bpp in [1usize, 4, 8] { - let n = 1usize << bpp; - // Full palette, clrUsed shorter than the depth (the rest reads black), a - // palette cut short of what clrUsed names, and none at all. - for (clr_used, entries) in [(0, n), (3, 3), (n as u32 + 50, n), (0, 1), (0, 0)] { - let (info, bits) = make_dib_with(w, h, bpp, None, clr_used, entries, &mut seed); - assert_same(&info, &bits, &format!("{bpp} bpp w={w} h={h} clrUsed={clr_used} palette={entries}")); - } - } - let (info, bits) = make_dib_with(w, h, 24, None, 0, 0, &mut seed); - assert_same(&info, &bits, &format!("24 bpp w={w} h={h}")); - // A colour table on a deep DIB is carried but unused. - let (info, bits) = make_dib_with(w, h, 24, None, 5, 5, &mut seed); - assert_same(&info, &bits, &format!("24 bpp with palette w={w} h={h}")); - // Masks on depths that ignore them still move the palette and the bits. - for bpp in [1usize, 8, 24] { - let n = if bpp == 24 { 0 } else { 1 << bpp }; - let (info, bits) = make_dib_with(w, h, bpp, Some(([0xF800, 0x07E0, 0x001F], 40)), 0, n, &mut seed); - assert_same(&info, &bits, &format!("{bpp} bpp with masks w={w} h={h}")); - } - let masks16: [Option<[u32; 3]>; 5] = [ - None, - Some([0xF800, 0x07E0, 0x001F]), - Some([0x7C00, 0x03E0, 0x001F]), - Some([0x0F00, 0x00F0, 0x000F]), - Some([0xF800, 0x0000, 0x001F]), - ]; - let masks32: [Option<[u32; 3]>; 6] = [ - None, - Some([0xFF_0000, 0xFF00, 0xFF]), - Some([0xFF, 0xFF00, 0xFF_0000]), - Some([0x3FF0_0000, 0x000F_FC00, 0x0000_03FF]), - Some([0xFFFF_FFFF, 0x0000_FF00, 0]), - Some([0x00FF_FF00, 0x00FF_FF00, 0x0000_00FF]), - ]; - for (bpp, sets) in [(16usize, masks16.as_slice()), (32, masks32.as_slice())] { - for m in sets { - // 40: the masks follow the header; 56 and 108: they are inside it. - for hsize in [40usize, 56, 108] { - let inline = m.map(|m| (m, hsize)); - let (info, bits) = make_dib_with(w, h, bpp, inline, 0, 0, &mut seed); - assert_same(&info, &bits, &format!("{bpp} bpp masks={m:x?} header={hsize} w={w} h={h}")); - } - } - } - } - } - } - - /// Timing of the per-pixel reference against `decode_clip` on a 40 MP bitmap: - /// `cargo test -p wordcraft-metafile --release -- --ignored --nocapture dib_decode_speed`. - #[test] - #[ignore = "timing only"] - fn dib_decode_speed() { - let mut seed = 6u64; - for bpp in [1usize, 4, 8, 16, 24, 32] { - let (info, bits) = make_dib(8000, -5000, bpp, &mut seed); - for round in 0..4 { - let t = std::time::Instant::now(); - let a = decode_clip_reference(Bytes(&info), Bytes(&bits), false, [0, 0, 8000, 5000], [0.0, 0.0, 1.0, 1.0]).map(|x| x.0.px); - let slow = t.elapsed().as_secs_f64() * 1e3; - let t = std::time::Instant::now(); - let b = decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 8000, 5000], [0.0, 0.0, 1.0, 1.0]).map(|x| x.0.px); - let fast = t.elapsed().as_secs_f64() * 1e3; - assert!(a == b); - eprintln!("{bpp:2} bpp round {round}: reference {slow:4.0} ms, decode_clip {fast:4.0} ms"); - } - } - } - - #[test] - fn decode_clip_matches_decode_then_clip_blit() { - let mut seed = 0x2545_F491_4F6C_DD1Du64; - let mut cases = 0; - for bpp in [1, 4, 8, 16, 24, 32] { - for h in [5, -5, 1, -1] { - let w = 7; - let (info, bits) = make_dib(w, h, bpp, &mut seed); - for keep_alpha in [false, true] { - // Source x/y from outside the bitmap on both sides; sizes include zero and negative. - for sx in [-9, -2, 0, 3, 6, 8, 20] { - for sy in [-9, -2, 0, 2, 4, 5, 20] { - for (sw, sh) in [(0, 0), (-3, 4), (4, -2), (1, 1), (3, 2), (7, 5), (30, 30), (2, 9)] { - let src = [sx, sy, sw, sh]; - let dst = [10.0, 20.0, 70.0, 50.0]; - let old = decode_whole(Bytes(&info), Bytes(&bits), keep_alpha).and_then(|img| clip_blit_whole(&img, h > 0, src, dst)); - let new = decode_clip(Bytes(&info), Bytes(&bits), keep_alpha, src, dst); - match (old, new) { - (None, None) => {} - (Some((a, ad)), Some((b, bd))) => { - assert_eq!((a.w, a.h, &a.px), (b.w, b.h, &b.px), "{bpp} bpp h={h} {src:?}"); - assert_eq!(ad.map(f64::to_bits), bd.map(f64::to_bits), "{bpp} bpp h={h} {src:?}"); - } - _ => panic!("old and new disagree on None: {bpp} bpp h={h} {src:?}"), - } - cases += 1; - } - } - } - } - } - } - assert!(cases > 10_000); - } - - #[test] - fn decode_clip_rejects_what_decode_rejected() { - let mut seed = 7; - let (info, bits) = make_dib(7, 5, 24, &mut seed); - let short = &bits[..bits.len() - 1]; - // A short bits buffer fails the whole image even when the crop lies in the rows that exist. - assert!(decode_clip(Bytes(&info), Bytes(short), false, [0, 0, 1, 1], [0.0, 0.0, 1.0, 1.0]).is_none()); - assert!(decode_whole(Bytes(&info), Bytes(short), false).is_none()); - } - - #[test] - fn decode_clip_decodes_only_the_cropped_pixels() { - let mut seed = 99; - let (info, bits) = make_dib(400, -300, 24, &mut seed); - DECODED.with(|d| d.set(0)); - let (img, _) = decode_clip(Bytes(&info), Bytes(&bits), false, [10, 20, 8, 4], [0.0, 0.0, 8.0, 4.0]).unwrap(); - assert_eq!((img.w, img.h), (8, 4)); - assert_eq!(DECODED.with(|d| d.get()), 8 * 4); - // The whole-bitmap path decodes all 400 x 300. - DECODED.with(|d| d.set(0)); - decode_whole(Bytes(&info), Bytes(&bits), false).unwrap(); - assert_eq!(DECODED.with(|d| d.get()), 400 * 300); - } - - #[test] - fn decode_clip_refuses_a_side_no_renderer_draws() { - let cap = MAX_BITMAP_SIDE as usize; - let mut seed = 11; - // 1 bpp, one row longer than the cap: 5 KB of bits, 120 KB of RGBA. - let (info, bits) = make_dib(cap + 1, 1, 1, &mut seed); - assert!(decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).is_none()); - // The same for the height. - let (info, bits) = make_dib(1, cap as i32 + 1, 1, &mut seed); - assert!(decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).is_none()); - // A crop of the wide bitmap within the cap still decodes, and so does the cap itself. - let (info, bits) = make_dib(cap + 1, 1, 1, &mut seed); - let (img, _) = decode_clip(Bytes(&info), Bytes(&bits), false, [10, 0, 100, 1], [0.0, 0.0, 1.0, 1.0]).unwrap(); - assert_eq!((img.w, img.h), (100, 1)); - let (info, bits) = make_dib(cap, 1, 1, &mut seed); - let (img, _) = decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).unwrap(); - assert_eq!((img.w, img.h), (cap, 1)); - } -} diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs deleted file mode 100644 index 195faa2a83..0000000000 --- a/crates/metafile/src/emf.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! EMF reader (MS-EMF). Records are (type, size in bytes) followed by a payload; offsets inside a -//! record (bitmap info and bits) are relative to the record start, so each handler reads the record slice. - -use crate::bytes::Bytes; -use crate::canvas::{BS_NULL, Brush, Canvas, Font, Obj, PS_NULL, PS_STYLE_MASK, Pen, Xform, colorref}; -use crate::dib::{self, Blend}; -use crate::geom::{self, ArcKind, P}; -use crate::{Error, Frame, MAX_PATH_OPS}; - -const EMF_SIGNATURE: u32 = 0x464D_4520; -/// Hundredths of a millimetre to points. -const HMM_TO_PT: f64 = 72.0 / 2540.0; -/// SRCCOPY, the plain copy of a bitmap. -const SRCCOPY: u32 = 0x00CC_0020; -/// LogPenEx pen type bits; PS_COSMETIC pens are one device pixel wide. -const PS_TYPE_MASK: u32 = 0x000F_0000; -const PS_COSMETIC: u32 = 0; -/// EXTTEXTOUT options: the string holds glyph indices, and the dx array holds (x, y) pairs. -const ETO_GLYPH_INDEX: u32 = 0x10; -const ETO_PDY: u32 = 0x2000; - -pub(crate) fn is_emf(b: Bytes) -> bool { - b.u32(0) == Some(1) && b.u32(40) == Some(EMF_SIGNATURE) -} - -/// The picture frame: `rclFrame` (0.01 mm) mapped to device units through `szlDevice` and -/// `szlMillimeters`, sized in points. Without a usable frame, the device bounds stand in (1 unit = 1 point). -pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { - if !is_emf(input) { - return Err(Error::BadHeader); - } - let hsize = input.u32(4).ok_or(Error::BadHeader)? as usize; - let bounds = rect32(input, 8).ok_or(Error::BadHeader)?; - let [l, t, r, b] = bounds; - let frame = frame_from_header(input).or_else(|| (r > l && b > t).then_some(Frame { rect: [l, t, r - l, b - t], size: None })); - let mut cv = Canvas::new(); - if let Some(px_mm) = device_px_per_mm(input) { - cv.set_device_mm(px_mm); - } - let mut parsed = 0usize; - let mut pos = hsize.max(88); - while !cv.full() { - let (Some(typ), Some(size)) = (input.u32(pos), pos.checked_add(4).and_then(|o| input.u32(o))) else { break }; - let size = size as usize; - if size < 8 || !size.is_multiple_of(4) { - break; - } - let Some(rec) = input.slice(pos, size) else { break }; - if typ == 14 { - break; - } - record(&mut cv, typ, Bytes(rec)); - parsed += 1; - let Some(next) = pos.checked_add(size) else { break }; - pos = next; - } - if parsed == 0 { - return Err(Error::NoRecords); - } - Ok((cv, frame)) -} - -/// Device pixels per millimetre on each axis, from `szlDevice` (72) and `szlMillimeters` (80). -fn device_px_per_mm(input: Bytes) -> Option<(f64, f64)> { - let (dw, dh) = (input.i32(72)?, input.i32(76)?); - let (mw, mh) = (input.i32(80)?, input.i32(84)?); - (dw > 0 && dh > 0 && mw > 0 && mh > 0).then(|| (f64::from(dw) / f64::from(mw), f64::from(dh) / f64::from(mh))) -} - -/// The frame from `rclFrame` (offset 24), `szlDevice` (72) and `szlMillimeters` (80) in the header. -pub(crate) fn frame_from_header(input: Bytes) -> Option { - let [fl, ft, fr, fb] = rect32(input, 24)?; - if fr <= fl || fb <= ft { - return None; - } - // Device units per hundredth of a millimetre. - let (px_mm_x, px_mm_y) = device_px_per_mm(input)?; - let (sx, sy) = (px_mm_x / 100.0, px_mm_y / 100.0); - let rect = [fl * sx, ft * sy, (fr - fl) * sx, (fb - ft) * sy]; - Some(Frame { rect, size: Some(((fr - fl) * HMM_TO_PT, (fb - ft) * HMM_TO_PT)) }) -} - -fn record(cv: &mut Canvas, typ: u32, r: Bytes) { - if cv.full() { - return; - } - let _ = match typ { - 9 => xy32(r, 8).map(|p| cv.set_window_ext(p)), - 10 => xy32(r, 8).map(|p| cv.set_window_org(p)), - 11 => xy32(r, 8).map(|p| cv.set_viewport_ext(p)), - 12 => xy32(r, 8).map(|p| cv.set_viewport_org(p)), - 17 => r.u32(8).map(|m| cv.set_map_mode(m)), - 19 => r.u32(8).map(|m| cv.set_polyfill(m)), - 20 => r.u32(8).map(|m| cv.set_rop2(m)), - 33 => { - cv.save_dc(); - Some(()) - } - 34 => r.i32(8).map(|n| cv.restore_dc(n)), - 35 => xform(r, 8).map(|x| cv.modify_world(x, 4)), - 36 => xform(r, 8).zip(r.u32(32)).map(|(x, m)| cv.modify_world(x, m)), - 37 => r.u32(8).map(|i| cv.select(i)), - 38 => create_pen(cv, r), - 95 => create_ext_pen(cv, r), - 39 => create_brush(cv, r), - 82 => create_font(cv, r), - 22 => r.u32(8).map(|a| cv.set_text_align(a)), - 24 => r.u32(8).map(|c| cv.set_text_color(colorref(c))), - 84 => ext_text_out_w(cv, r), - 40 => r.u32(8).map(|i| cv.delete_object(i)), - 27 => xy32(r, 8).map(|p| cv.move_to(p)), - 54 => xy32(r, 8).map(|p| cv.line_to(p)), - 42 => rect32(r, 8).map(|[l, t, rr, b]| cv.shape(geom::ellipse(l, t, rr, b), true, true)), - 43 => rect32(r, 8).map(|[l, t, rr, b]| cv.shape(geom::rect(l, t, rr, b), true, true)), - 44 => { - let (cw, ch) = (r.i32(24), r.i32(28)); - let (Some(cw), Some(ch)) = (cw, ch) else { return }; - rect32(r, 8).map(|[l, t, rr, b]| { - cv.shape(geom::round_rect(l, t, rr, b, f64::from(cw), f64::from(ch)), true, true); - }) - } - 45..=47 => arc32(r).map(|(bounds, s, e)| { - let kind = match typ { - 45 => ArcKind::Arc, - 46 => ArcKind::Chord, - _ => ArcKind::Pie, - }; - let [l, t, rr, b] = bounds; - cv.shape(geom::arc_shape(l, t, rr, b, s, e, kind), kind != ArcKind::Arc, true); - }), - 4 | 87 => counted(r, typ == 4).map(|pts| cv.poly(&pts, false, false, true)), - 3 | 86 => counted(r, typ == 3).map(|pts| cv.poly(&pts, true, true, true)), - 6 | 89 => counted(r, typ == 6).map(|pts| cv.line_chain(&pts, false, true)), - // POLYBEZIER starts its own figure at the first point and leaves the current point alone; - // POLYBEZIERTO continues from the current point. - 2 | 85 => counted(r, typ == 2).and_then(|pts| { - let from = *pts.first()?; - cv.bezier(from, pts.get(1..)?); - Some(()) - }), - 5 | 88 => counted(r, typ == 5).map(|pts| cv.bezier_to(&pts)), - 7 | 90 => poly_groups(r, typ == 7).map(|(counts, pts)| cv.shape(geom::subpaths(&pts, &counts, false), false, true)), - 8 | 91 => poly_groups(r, typ == 8).map(|(counts, pts)| cv.shape(geom::subpaths(&pts, &counts, true), true, true)), - 59 => { - cv.begin_path(); - Some(()) - } - 60 => { - cv.end_path(); - Some(()) - } - 61 => { - cv.close_figure(); - Some(()) - } - 62 => { - cv.paint_path(true, false); - Some(()) - } - 63 => { - cv.paint_path(true, true); - Some(()) - } - 64 => { - cv.paint_path(false, true); - Some(()) - } - 76 | 77 => bitblt(cv, r, typ == 77), - 80 => set_dibits(cv, r), - 81 => stretch_dibits(cv, r), - 114 => alphablend(cv, r), - _ => Some(()), - }; -} - -/// Two little-endian i32 values at `off`, as a point. -fn xy32(r: Bytes, off: usize) -> Option

{ - Some((f64::from(r.i32(off)?), f64::from(r.i32(off + 4)?))) -} - -/// RECTL (left, top, right, bottom) as i32 values widened to f64. -fn rect32(r: Bytes, off: usize) -> Option<[f64; 4]> { - Some([f64::from(r.i32(off)?), f64::from(r.i32(off + 4)?), f64::from(r.i32(off + 8)?), f64::from(r.i32(off + 12)?)]) -} - -/// An i32 field as f64; 0 past the end. -fn i32s(r: Bytes, off: usize) -> f64 { - r.i32(off).map_or(0.0, f64::from) -} - -/// XFORM: six f32 values in M11, M12, M21, M22, Dx, Dy order. -fn xform(r: Bytes, off: usize) -> Option { - let mut x = [0.0f64; 6]; - for (i, v) in x.iter_mut().enumerate() { - *v = f64::from(r.f32(off + i * 4)?); - } - Some(x) -} - -/// ARC, CHORD, PIE: bounds at 8, start point at 24, end point at 32. -fn arc32(r: Bytes) -> Option<([f64; 4], P, P)> { - Some((rect32(r, 8)?, xy32(r, 24)?, xy32(r, 32)?)) -} - -/// A point count from a record, rejected when it exceeds the path budget (before any allocation). -fn budget(n: u32) -> Option { - let n = n as usize; - (n <= MAX_PATH_OPS).then_some(n) -} - -/// Point count at 24, then the points (32-bit or 16-bit) at 28. -fn counted(r: Bytes, wide: bool) -> Option> { - let n = budget(r.u32(24)?)?; - r.tail(28)?.points(0, n, wide) -} - -/// Subpath count at 24, total point count at 28, per-subpath counts at 32, then the points. -fn poly_groups(r: Bytes, wide: bool) -> Option<(Vec, Vec

)> { - let n = budget(r.u32(24)?)?; - // The record must hold the n counts before anything is allocated for them. - let raw = r.slice(32, n.checked_mul(4)?)?; - let counts: Vec = raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as usize).collect(); - let total = counts.iter().try_fold(0usize, |a, c| a.checked_add(*c))?; - let total = budget(u32::try_from(total).ok()?)?; - let pts = r.tail(n.checked_mul(4)?.checked_add(32)?)?.points(0, total, wide)?; - Some((counts, pts)) -} - -/// EMR_CREATEPEN: handle, LogPen (style, width x/y, colour). -fn create_pen(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let style = r.u32(12)?; - let width = r.i32(16)?; - let color = r.u32(24)?; - cv.add_object(Some(slot), Obj::Pen(Pen { style, width: f64::from(width), color: colorref(color) })); - Some(()) -} - -/// EMR_EXTCREATEPEN: handle, bitmap offsets (unused), LogPenEx (style, width, brush style, colour). -/// A cosmetic pen's width is in device pixels (always 1), so it is a hairline; a BS_NULL brush draws -/// no line at all. -fn create_ext_pen(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let (style, width, brush, color) = (r.u32(28)?, r.u32(32)?, r.u32(36)?, r.u32(40)?); - let width = if style & PS_TYPE_MASK == PS_COSMETIC { 0.0 } else { f64::from(width) }; - let style = if brush == BS_NULL { PS_NULL } else { style & PS_STYLE_MASK }; - cv.add_object(Some(slot), Obj::Pen(Pen { style, width, color: colorref(color) })); - Some(()) -} - -/// EMR_CREATEBRUSHINDIRECT: handle, LogBrush32 (style, colour, hatch). -fn create_brush(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let style = r.u32(12)?; - let color = r.u32(16)?; - cv.add_object(Some(slot), Obj::Brush(Brush { style, color: colorref(color) })); - Some(()) -} - -/// EMR_EXTCREATEFONTINDIRECTW: handle, then a LogFont (height, width, escapement, orientation, weight, -/// italic, ..., face name of 32 UTF-16 units at 40). -fn create_font(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let mut face = [0u16; 32]; - for (i, u) in face.iter_mut().enumerate() { - *u = r.u16(40 + i * 2).unwrap_or(0); - } - let font = Font { height: r.i32(12)?, escapement: r.i32(20)?, weight: r.i32(28)?, italic: *r.0.get(32)? != 0, face }; - cv.add_object(Some(slot), Obj::Font(font)); - Some(()) -} - -/// EMR_EXTTEXTOUTW: an EmrText at 36 with the reference point, the character count at 44, the string -/// offset at 48, the options at 52 and the dx array offset at 72 (offsets from the record start). -/// Glyph-index strings are skipped: they cannot be mapped back to characters. -fn ext_text_out_w(cv: &mut Canvas, r: Bytes) -> Option<()> { - let at = xy32(r, 36)?; - let n = r.u32(44)? as usize; - let (off, options, off_dx) = (r.u32(48)? as usize, r.u32(52)?, r.u32(72)? as usize); - if options & ETO_GLYPH_INDEX != 0 || n == 0 { - return None; - } - let units: Vec = r.slice(off, n.checked_mul(2)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); - // dx has one entry per UTF-16 unit (two with ETO_PDY); a character takes the sum of its units. - let step = if options & ETO_PDY != 0 { 8 } else { 4 }; - let raw_dx: Vec = match r.slice(off_dx, n.checked_mul(step)?) { - Some(b) if off_dx != 0 => b.chunks_exact(step).filter_map(|c| Some(f64::from(i32::from_le_bytes(c.get(..4)?.try_into().ok()?)))).collect(), - _ => Vec::new(), - }; - let mut text = String::new(); - let mut dx = Vec::new(); - let mut i = 0; - for ch in char::decode_utf16(units.iter().copied()) { - let c = ch.unwrap_or(char::REPLACEMENT_CHARACTER); - // A replacement stands for one unpaired unit. - let w = if c == char::REPLACEMENT_CHARACTER { 1 } else { c.len_utf16() }; - if !raw_dx.is_empty() { - dx.push(raw_dx.get(i..i + w).map_or(0.0, |s| s.iter().sum())); - } - i += w; - text.push(c); - } - let text = text.trim_end_matches('\0').to_string(); - dx.truncate(text.chars().count()); - cv.text(at, text, &dx); - Some(()) -} - -/// BITBLT (76) and STRETCHBLT (77): dest at 24..40, rop at 40, source x/y at 44, bmi at 84, bits at -/// 92; STRETCHBLT adds the source w/h at 100. A source-less rop fills the destination instead. -fn bitblt(cv: &mut Canvas, r: Bytes, stretch: bool) -> Option<()> { - let dst = [i32s(r, 24), i32s(r, 28), i32s(r, 32), i32s(r, 36)]; - let rop = r.u32(40)?; - if Canvas::sourceless(rop) { - cv.fill_rop(dst, rop); - return Some(()); - } - let (sw, sh) = if stretch { (i32s(r, 100), i32s(r, 104)) } else { (dst[2], dst[3]) }; - let src = [i32s(r, 44), i32s(r, 48), sw, sh]; - blit(cv, r, dst, src, (84, 92), Blend::Rop(rop)) -} - -/// ALPHABLEND: laid out like STRETCHBLT, with a BLENDFUNCTION at 40. Constant alpha at 42 applies to -/// every pixel; AlphaFormat at 43 with AC_SRC_ALPHA (1) also uses the per-pixel alpha. -fn alphablend(cv: &mut Canvas, r: Bytes) -> Option<()> { - let dst = [i32s(r, 24), i32s(r, 28), i32s(r, 32), i32s(r, 36)]; - let constant = *r.0.get(42)?; - let per_pixel = (*r.0.get(43)? & 0x01) != 0; - let src = [i32s(r, 44), i32s(r, 48), i32s(r, 100), i32s(r, 104)]; - blit(cv, r, dst, src, (84, 92), Blend::Alpha { constant, per_pixel }) -} - -/// STRETCHDIBITS: dest x/y at 24, src x/y/w/h at 32..48, bmi offset/size at 48, bits at 56, rop at 68, -/// dest w/h at 72. -fn stretch_dibits(cv: &mut Canvas, r: Bytes) -> Option<()> { - let dst = [i32s(r, 24), i32s(r, 28), i32s(r, 72), i32s(r, 76)]; - let src = [i32s(r, 32), i32s(r, 36), i32s(r, 40), i32s(r, 44)]; - let rop = r.u32(68)?; - blit(cv, r, dst, src, (48, 56), Blend::Rop(rop)) -} - -/// SETDIBITSTODEVICE (MS-EMF 2.3.1.5): dest x/y at 24, src x/y at 32, size (cxSrc, cySrc) at 40, bmi -/// at 48, bits at 56, start scan at 68. The image keeps its own size; the bits begin at scan line -/// `iStartScan`, so the source y counts from there. -fn set_dibits(cv: &mut Canvas, r: Bytes) -> Option<()> { - let (cx, cy) = (i32s(r, 40), i32s(r, 44)); - if cx <= 0.0 || cy <= 0.0 { - return None; - } - let dst = [i32s(r, 24), i32s(r, 28), cx, cy]; - let src = [i32s(r, 32), i32s(r, 36) - f64::from(r.u32(68)?), cx, cy]; - blit(cv, r, dst, src, (48, 56), Blend::Rop(SRCCOPY)) -} - -/// Decodes the bitmap at `at` = (offset of the bmi offset/length pair, offset of the bits pair), both -/// inside the record, and stretches the source rectangle `src` into `dst`. Both are `[x, y, w, h]`; a -/// non-positive source size means the whole bitmap. `blend` decides how it combines. -fn blit(cv: &mut Canvas, r: Bytes, dst: [f64; 4], src: [f64; 4], at: (usize, usize), blend: Blend) -> Option<()> { - let (bo, bl) = (r.u32(at.0)? as usize, r.u32(at.0 + 4)? as usize); - let (po, pl) = (r.u32(at.1)? as usize, r.u32(at.1 + 4)? as usize); - if pl == 0 { - return None; - } - let info = Bytes(r.slice(bo, bl)?); - let pixels = Bytes(r.slice(po, pl)?); - let (mut img, dst) = dib::decode_clip(info, pixels, blend.per_pixel(), src.map(|v| v as i64), dst)?; - dib::prepare(&mut img, blend); - cv.bitmap(dst, img); - Some(()) -} diff --git a/crates/metafile/src/geom.rs b/crates/metafile/src/geom.rs deleted file mode 100644 index 0c2b772cf1..0000000000 --- a/crates/metafile/src/geom.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! Path operations in `f64` and the shape builders that turn WMF/EMF rectangles, ellipses and arcs -//! into cubic Béziers (the classic 4/3·tan(Δ/4) approximation, at most 90° per piece). - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -pub(crate) type P = (f64, f64); - -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Op { - M(P), - L(P), - C(P, P, P), - Z, -} - -pub(crate) fn rect(l: f64, t: f64, r: f64, b: f64) -> Vec { - vec![Op::M((l, t)), Op::L((r, t)), Op::L((r, b)), Op::L((l, b)), Op::Z] -} - -/// Corner radii are half the EMF/WMF corner ellipse size, clamped so the corners never overlap. -pub(crate) fn round_rect(l: f64, t: f64, r: f64, b: f64, ew: f64, eh: f64) -> Vec { - // Reversed corners (right < left, bottom < top) describe the same rectangle. - let (l, r) = (l.min(r), l.max(r)); - let (t, b) = (t.min(b), t.max(b)); - let rx = (ew / 2.0).abs().min((r - l) / 2.0); - let ry = (eh / 2.0).abs().min((b - t) / 2.0); - let mut ops = vec![Op::M((l + rx, t)), Op::L((r - rx, t))]; - ops.extend(arc(r - rx, t + ry, rx, ry, -FRAC_PI_2, FRAC_PI_2)); - ops.push(Op::L((r, b - ry))); - ops.extend(arc(r - rx, b - ry, rx, ry, 0.0, FRAC_PI_2)); - ops.push(Op::L((l + rx, b))); - ops.extend(arc(l + rx, b - ry, rx, ry, FRAC_PI_2, FRAC_PI_2)); - ops.push(Op::L((l, t + ry))); - ops.extend(arc(l + rx, t + ry, rx, ry, PI, FRAC_PI_2)); - ops.push(Op::Z); - ops -} - -pub(crate) fn ellipse(l: f64, t: f64, r: f64, b: f64) -> Vec { - let (cx, cy, rx, ry) = center(l, t, r, b); - let mut ops = vec![Op::M((cx + rx, cy))]; - ops.extend(arc(cx, cy, rx, ry, 0.0, TAU)); - ops.push(Op::Z); - ops -} - -/// Which closed or open shape an ARC/CHORD/PIE record draws. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ArcKind { - Arc, - Chord, - Pie, -} - -/// ARC, CHORD and PIE: the arc runs counter-clockwise on screen from the start point to the end point. -pub(crate) fn arc_shape(l: f64, t: f64, r: f64, b: f64, s: P, e: P, kind: ArcKind) -> Vec { - let (cx, cy, rx, ry) = center(l, t, r, b); - let ang = |p: P| ((p.1 - cy) / ry.max(f64::MIN_POSITIVE)).atan2((p.0 - cx) / rx.max(f64::MIN_POSITIVE)); - let (a0, a1) = (ang(s), ang(e)); - let mut d = (a0 - a1).rem_euclid(TAU); - if d < 1e-12 { - d = TAU; - } - let sweep = -d; - let start = (cx + rx * a0.cos(), cy + ry * a0.sin()); - let mut ops = if kind == ArcKind::Pie { vec![Op::M((cx, cy)), Op::L(start)] } else { vec![Op::M(start)] }; - ops.extend(arc(cx, cy, rx, ry, a0, sweep)); - match kind { - ArcKind::Arc => {} - ArcKind::Chord => ops.push(Op::Z), - ArcKind::Pie => ops.extend([Op::L((cx, cy)), Op::Z]), - } - ops -} - -fn center(l: f64, t: f64, r: f64, b: f64) -> (f64, f64, f64, f64) { - ((l + r) / 2.0, (t + b) / 2.0, (r - l).abs() / 2.0, (b - t).abs() / 2.0) -} - -/// Cubic pieces along an ellipse from parameter `a0` over signed `sweep` radians. The current point -/// must already be at `(cx + rx cos a0, cy + ry sin a0)`. -fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, sweep: f64) -> Vec { - let n = ((sweep.abs() / FRAC_PI_2).ceil() as usize).clamp(1, 8); - let step = sweep / n as f64; - let k = 4.0 / 3.0 * (step / 4.0).tan(); - let pt = |t: f64| (cx + rx * t.cos(), cy + ry * t.sin()); - let mut ops = Vec::with_capacity(n); - for i in 0..n { - let t0 = a0 + step * i as f64; - let t1 = t0 + step; - let (p0, p3) = (pt(t0), pt(t1)); - let c1 = (p0.0 - k * rx * t0.sin(), p0.1 + k * ry * t0.cos()); - let c2 = (p3.0 + k * rx * t1.sin(), p3.1 - k * ry * t1.cos()); - ops.push(Op::C(c1, c2, p3)); - } - ops -} - -/// Consecutive subpaths: `counts[i]` points each, taken in order from `pts`. Counts that run past the -/// point list are cut short rather than failing the whole record. -pub(crate) fn subpaths(pts: &[P], counts: &[usize], close: bool) -> Vec { - // The exact size first: empty groups add no ops, so a long count list of zeros (file data) - // mustn't reserve room the canvas budget never sees. - let (mut n, mut at) = (0usize, 0usize); - for &c in counts { - let end = at.saturating_add(c).min(pts.len()); - if end > at { - n = n.saturating_add(end - at + usize::from(close)); - } - at = end; - } - let mut ops = Vec::with_capacity(n); - let mut at = 0usize; - for &c in counts { - let end = at.saturating_add(c).min(pts.len()); - let Some((first, rest)) = pts.get(at..end).and_then(<[_]>::split_first) else { - at = end; - continue; - }; - ops.push(Op::M(*first)); - ops.extend(rest.iter().map(|p| Op::L(*p))); - if close { - ops.push(Op::Z); - } - at = end; - } - ops -} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs deleted file mode 100644 index 2797002e5f..0000000000 --- a/crates/metafile/src/lib.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! WordCraft metafiles: reads Windows Metafiles (WMF) and Enhanced Metafiles (EMF) into a neutral -//! vector model of filled and stroked paths, RGBA bitmaps and text runs, in a picture frame with y down. -//! -//! The reader is pure Rust over byte slices (no file system), so it builds for wasm. Every read is -//! bounds-checked and every count is capped; hostile input yields a shorter picture or an [`Error`], -//! never a panic. -//! -//! Records follow MS-WMF and MS-EMF. Records outside the supported set are skipped silently. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -#![forbid(unsafe_code)] - -mod bytes; -mod canvas; -mod dib; -mod emf; -mod geom; -mod place; -mod size; -mod wmf; - -#[cfg(test)] -mod tests; - -use bytes::Bytes; -use canvas::{Raw, RawText}; -use geom::{Op, P}; -pub use place::{MAX_BITMAP_SIDE, PlacedItem, TextLayout, crop_window}; -pub use size::size; - -/// Items kept from one file. Past the cap the parse stops and keeps what it has. -pub(crate) const MAX_ITEMS: usize = 200_000; -/// Object table slots (WMF handles, EMF object indices). -pub(crate) const MAX_OBJECTS: usize = 4096; -/// Largest bitmap in pixels (about 40 megapixels, 160 MB of RGBA). -pub(crate) const MAX_PIXELS: usize = 40_000_000; -/// DC save-stack depth. -pub(crate) const MAX_STACK: usize = 1024; -/// Points in one open path bracket. -pub(crate) const MAX_PATH_OPS: usize = 2_000_000; -/// Bytes of path ops and pixels kept from one file (about 256 MB). -pub(crate) const MAX_BYTES: usize = 256 * 1024 * 1024; - -/// A parsed metafile. Items use coordinates in `0..width` and `0..height`, y down. -#[derive(Debug, Clone, PartialEq)] -pub struct Picture { - /// Size of the drawing in its own units: points for placeable WMF and EMF (from the frame), device - /// or logical units otherwise. - pub width: f32, - pub height: f32, - pub items: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Item { - /// A filled and/or stroked path, in picture coordinates. - Path { - segs: Vec, - fill: Option<[u8; 4]>, - /// Colour and width in picture units. - stroke: Option<([u8; 4], f32)>, - even_odd: bool, - }, - /// A bitmap stretched into `rect` = `[x, y, w, h]` (picture units), RGBA8 rows top-down. - Bitmap { rect: [f32; 4], width: u32, height: u32, rgba: Vec }, - /// A run of text; the renderers shape it with the named font (see [`Text::layout`]). - Text(Text), -} - -/// A text run, in picture units. -#[derive(Debug, Clone, PartialEq)] -pub struct Text { - pub text: String, - /// The reference point that `halign` and `valign` refer to. - pub x: f32, - pub y: f32, - /// Font height: the em size, or the cell height (ascent + descent) when `cell` is set. - pub size: f32, - pub cell: bool, - pub font: String, - pub bold: bool, - pub italic: bool, - pub color: [u8; 4], - /// Baseline direction in radians, clockwise from +x (y down). - pub angle: f32, - pub halign: HAlign, - pub valign: VAlign, - /// Advance of each character along the baseline; empty when the font's own advances apply. - pub dx: Vec, -} - -/// Where the reference point sits along the run. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum HAlign { - Left, - Center, - Right, -} - -/// Where the reference point sits across the run. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VAlign { - Top, - Baseline, - Bottom, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Seg { - Move(f32, f32), - Line(f32, f32), - Cubic(f32, f32, f32, f32, f32, f32), - Close, -} - -#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] -pub enum Error { - #[error("not a WMF or EMF file")] - NotMetafile, - #[error("metafile header is truncated or invalid")] - BadHeader, - #[error("metafile has no readable records")] - NoRecords, -} - -/// The picture frame in device units (`rect` = `[x, y, w, h]`) and, when the file states one, its -/// size in picture units. -pub(crate) struct Frame { - pub rect: [f64; 4], - pub size: Option<(f64, f64)>, -} - -/// Parses a WMF (placeable or plain) or EMF file. -pub fn parse(bytes: &[u8]) -> Result { - let b = Bytes(bytes); - let (cv, frame) = if emf::is_emf(b) { - emf::parse(b)? - } else if wmf::is_wmf(b) { - wmf::parse(b)? - } else { - return Err(Error::NotMetafile); - }; - Ok(build(cv.items, frame)) -} - -/// True when the bytes start like a WMF (placeable or plain header) or an EMF. -pub fn is_metafile(bytes: &[u8]) -> bool { - let b = Bytes(bytes); - emf::is_emf(b) || wmf::is_wmf(b) -} - -/// Maps device-space output into the picture frame. Without a usable frame the frame is the bounding -/// box of the drawing, so the origin is still the top-left of what was drawn. -fn build(raw: Vec, frame: Option) -> Picture { - let frame = frame.filter(|f| f.rect.iter().all(|v| v.is_finite()) && f.rect[2] > 0.0 && f.rect[3] > 0.0); - let (rect, size) = match frame { - Some(f) => (f.rect, f.size.unwrap_or((f.rect[2], f.rect[3]))), - None => match bbox(&raw) { - Some([x0, y0, x1, y1]) => ([x0, y0, x1 - x0, y1 - y0], (x1 - x0, y1 - y0)), - None => return Picture { width: 0.0, height: 0.0, items: Vec::new() }, - }, - }; - let sx = if rect[2] > 0.0 { size.0 / rect[2] } else { 1.0 }; - let sy = if rect[3] > 0.0 { size.1 / rect[3] } else { 1.0 }; - let tf = move |p: P| ((p.0 - rect[0]) * sx, (p.1 - rect[1]) * sy); - let stroke_scale = (sx + sy) / 2.0; - // No stroke is wider than the picture's diagonal: anything wider is a mapping artefact. - let diag = size.0.hypot(size.1); - let items = raw.into_iter().filter_map(|r| match r { - Raw::Path { ops, fill, stroke, even_odd } => { - let segs = ops.iter().map(|op| seg(op, tf)).collect::>>()?; - if segs.len() < 2 { - return None; - } - let stroke = stroke.and_then(|(c, w)| Some((c, f((w * stroke_scale).min(diag))?))); - Some(Item::Path { segs, fill, stroke, even_odd }) - } - Raw::Bitmap { rect: r, img } => { - let (x, y) = tf((r[0], r[1])); - let rect = [f(x)?, f(y)?, f(r[2] * sx)?, f(r[3] * sy)?]; - Some(Item::Bitmap { rect, width: img.w as u32, height: img.h as u32, rgba: img.px }) - } - Raw::Text(t) => text_item(t, tf, sx, sy), - }); - let items = items.collect(); - Picture { width: f(size.0).unwrap_or(0.0), height: f(size.1).unwrap_or(0.0), items } -} - -/// A device-space text run mapped into the picture: the reference point through `tf`, lengths by the -/// frame scale. TA_* flags become the alignment. -fn text_item(t: RawText, tf: impl Fn(P) -> P, sx: f64, sy: f64) -> Option { - let (x, y) = tf(t.origin); - let halign = match t.align & 6 { - 2 => HAlign::Right, - 6 => HAlign::Center, - _ => HAlign::Left, - }; - let valign = match t.align & 24 { - 8 => VAlign::Bottom, - 24 => VAlign::Baseline, - _ => VAlign::Top, - }; - let dx = t.dx.iter().map(|d| f(d * sx.abs())).collect::>>()?; - let size = f(t.size * sy.abs()).filter(|s| *s > 0.0)?; - Some(Item::Text(Text { - text: t.text, - x: f(x)?, - y: f(y)?, - size, - cell: t.cell, - font: t.font, - bold: t.bold, - italic: t.italic, - color: t.color, - angle: f(t.angle).unwrap_or(0.0), - halign, - valign, - dx, - })) -} - -fn f(v: f64) -> Option { - let v = v as f32; - v.is_finite().then_some(v) -} - -fn seg(op: &Op, tf: impl Fn(P) -> P) -> Option { - let pt = |p: P| { - let (x, y) = tf(p); - Some((f(x)?, f(y)?)) - }; - Some(match *op { - Op::M(p) => { - let (x, y) = pt(p)?; - Seg::Move(x, y) - } - Op::L(p) => { - let (x, y) = pt(p)?; - Seg::Line(x, y) - } - Op::C(a, b, c) => { - let (x1, y1) = pt(a)?; - let (x2, y2) = pt(b)?; - let (x3, y3) = pt(c)?; - Seg::Cubic(x1, y1, x2, y2, x3, y3) - } - Op::Z => Seg::Close, - }) -} - -/// Bounding box `[x0, y0, x1, y1]` over the finite points of the output. -fn bbox(raw: &[Raw]) -> Option<[f64; 4]> { - let mut b: Option<[f64; 4]> = None; - let mut grow = |p: P| { - if p.0.is_finite() && p.1.is_finite() { - b = Some(match b { - None => [p.0, p.1, p.0, p.1], - Some([x0, y0, x1, y1]) => [x0.min(p.0), y0.min(p.1), x1.max(p.0), y1.max(p.1)], - }); - } - }; - for r in raw { - match r { - Raw::Path { ops, .. } => { - for op in ops { - match *op { - Op::M(p) | Op::L(p) => grow(p), - Op::C(a, c, d) => { - grow(a); - grow(c); - grow(d); - } - Op::Z => {} - } - } - } - Raw::Bitmap { rect, .. } => { - grow((rect[0], rect[1])); - grow((rect[0] + rect[2], rect[1] + rect[3])); - } - Raw::Text(t) => grow(t.origin), - } - } - b -} diff --git a/crates/metafile/src/place.rs b/crates/metafile/src/place.rs deleted file mode 100644 index 5a160c4edb..0000000000 --- a/crates/metafile/src/place.rs +++ /dev/null @@ -1,217 +0,0 @@ -//! Placing a picture on a target (a page or a device): the fitted transform, paths as kurbo paths in -//! target units and bitmaps as target rectangles. The rasteriser and the PDF writer only paint the result. - -use kurbo::{Affine, BezPath, Rect, Shape}; - -use crate::{HAlign, Item, Picture, Seg, Text, VAlign}; - -/// Largest bitmap side the renderers draw: within the PDF image limit and the rasteriser's 16-bit sides. -pub const MAX_BITMAP_SIDE: u32 = 30_000; -/// Placed coordinates past this (target units) are far off any page; such items are left out. -const MAX_COORD: f64 = 1e6; -/// Smallest placed bitmap side (target units), so the stretch onto it is never singular. -const MIN_BITMAP_SIDE: f64 = 1e-6; -/// The least of a source axis a crop keeps (0.5%). Files crop pictures to slivers (a header bar -/// that is 2.7% of a page-sized metafile, #1899). Layout makes a picture's frame at most 4000 pt -/// a side, so the whole source then spans at most 800,000 pt: what it covers stays inside -/// `MAX_COORD` and is never left out as far off the page. -const MIN_VISIBLE: f64 = 0.005; - -/// The part of a picture's source that `crop` (left, top, right, bottom fractions of the source) -/// keeps, as fractions of the source: [left, top, width, height], bitmap or metafile alike. Each -/// side is taken as 0–1 (junk as 0). When the two sides of an axis leave less than 0.5% of it, -/// the left (top) side stands and 0.5% shows. -pub fn crop_window(crop: [f32; 4]) -> [f64; 4] { - let [l, t, r, b] = crop.map(|v| if v.is_finite() { f64::from(v.clamp(0.0, 1.0)) } else { 0.0 }); - let axis = |lo: f64, hi: f64| { - let lo = lo.min(1.0 - MIN_VISIBLE); - (lo, (1.0 - lo - hi).max(MIN_VISIBLE)) - }; - let ((x, w), (y, h)) = (axis(l, r), axis(t, b)); - [x, y, w, h] -} - -/// One item of a placed picture, in target units. -pub enum PlacedItem { - /// A filled and/or stroked path. The stroke width is in target units; 0 is a cosmetic hairline that - /// the renderer draws at its minimum width. - Path { path: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f64)>, even_odd: bool }, - /// `Picture::items[index]`, a bitmap, stretched into `rect`. - Bitmap { index: usize, rect: Rect }, - /// `Picture::items[index]`, a text run. `tf` maps the run's own space (picture units, the - /// reference point at the origin, the baseline along +x, y down) to the target. - Text { index: usize, tf: Affine }, -} - -/// A text run laid out with a font's metrics: the em size (in the run's own units, see -/// [`PlacedItem::Text`]), the baseline's y and each glyph's (x, y), alignment included. -pub struct TextLayout { - pub em: f64, - pub baseline: f64, - pub glyphs: Vec<(f64, f64)>, -} - -impl Text { - /// Lays out shaped glyphs, given as (cluster byte offset, x advance, x offset, y offset) in font - /// units of a font with `upem` units per em, `ascent` above and `descent` below the baseline. - /// The per-character advances `dx` place each cluster when there is one per character. - pub fn layout(&self, upem: f64, ascent: f64, descent: f64, glyphs: &[(usize, f64, f64, f64)]) -> Option { - let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 }; - let cell = ascent + descent; - let size = f64::from(self.size); - let em = if self.cell && cell.is_finite() && cell > 0.0 { size * upem / cell } else { size }; - if !em.is_finite() || em <= 0.0 { - return None; - } - let k = em / upem; - let starts: Vec = self.text.char_indices().map(|(i, _)| i).collect(); - let dx = (self.dx.len() == starts.len() && !starts.is_empty()).then(|| { - let mut cum = Vec::with_capacity(self.dx.len() + 1); - let mut x = 0.0; - cum.push(x); - for d in &self.dx { - x += f64::from(*d); - cum.push(x); - } - cum - }); - let mut out = Vec::with_capacity(glyphs.len()); - let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None); - for &(cluster, adv, xo, yo) in glyphs { - let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1); - if last != Some(ci) { - cluster_pen = pen; - last = Some(ci); - } - let x = match &dx { - Some(cum) => cum.get(ci).copied().unwrap_or(0.0) + pen - cluster_pen, - None => pen, - }; - out.push((x + xo * k, -yo * k)); - pen += adv * k; - } - let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen); - let hoff = match self.halign { - HAlign::Left => 0.0, - HAlign::Center => -width / 2.0, - HAlign::Right => -width, - }; - let baseline = match self.valign { - VAlign::Top => ascent * k, - VAlign::Baseline => 0.0, - VAlign::Bottom => -descent * k, - }; - let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect(); - Some(TextLayout { em, baseline, glyphs }) - } -} - -impl Picture { - /// Whether the picture has a finite, positive size, so it can be fitted into a frame. - pub fn has_size(&self) -> bool { - self.width.is_finite() && self.height.is_finite() && self.width > 0.0 && self.height > 0.0 - } - - /// The transform that fits the picture into `r` with the crop fractions `crop` (left, top, right, - /// bottom) removed first: the visible part fills `r`. None for a degenerate size. - pub fn fit(&self, r: Rect, crop: [f32; 4]) -> Option { - let [cl, ct, vw, vh] = crop_window(crop); - let (w, h) = (f64::from(self.width), f64::from(self.height)); - let sx = r.width() / (w * vw); - let sy = r.height() / (h * vh); - (sx.is_finite() && sy.is_finite() && sx > 0.0 && sy > 0.0) - .then(|| Affine::translate((r.x0 - cl * w * sx, r.y0 - ct * h * sy)) * Affine::scale_non_uniform(sx, sy)) - } - - /// The items placed into `r` with `crop` applied. Items that are not finite or reach past ±1e6 - /// target units are left out (they are far off any page), as are bitmaps with no area. Stroke - /// widths are scaled to target units (along the mean axis scale, so a non-uniform fit keeps - /// strokes even). - pub fn place(&self, r: Rect, crop: [f32; 4]) -> Vec { - let Some(tf) = self.fit(r, crop) else { return Vec::new() }; - let c = tf.as_coeffs(); - let k = (c[0].abs() + c[3].abs()) / 2.0; - let mut out = Vec::with_capacity(self.items.len()); - for (index, item) in self.items.iter().enumerate() { - match item { - Item::Path { segs, fill, stroke, even_odd } => { - let path = tf * bez(segs); - if in_range(path.bounding_box()) { - let stroke = stroke.map(|(c, w)| (c, f64::from(w) * k)); - out.push(PlacedItem::Path { path, fill: *fill, stroke, even_odd: *even_odd }); - } - } - Item::Bitmap { rect: [x, y, w, h], .. } => { - let (x0, y0) = (f64::from(*x), f64::from(*y)); - let rect = tf.transform_rect_bbox(Rect::new(x0, y0, x0 + f64::from(*w), y0 + f64::from(*h))); - if in_range(rect) && rect.width() > MIN_BITMAP_SIDE && rect.height() > MIN_BITMAP_SIDE { - out.push(PlacedItem::Bitmap { index, rect }); - } - } - Item::Text(t) => { - let (x, y) = (f64::from(t.x), f64::from(t.y)); - let at = tf * kurbo::Point::new(x, y); - if in_range(Rect::new(at.x, at.y, at.x, at.y)) { - let tf = tf * Affine::translate((x, y)) * Affine::rotate(f64::from(t.angle)); - out.push(PlacedItem::Text { index, tf }); - } - } - } - } - out - } -} - -impl Item { - /// Takes a bitmap's pixels out of the item (its geometry stays) and returns them as (width, height, - /// RGBA) when a renderer can draw them: both sides in 1..=[`MAX_BITMAP_SIDE`] and exactly that many - /// pixels. None for paths and for bitmaps that cannot be drawn. - pub fn take_pixels(&mut self) -> Option<(u32, u32, Vec)> { - let Item::Bitmap { width, height, rgba, .. } = self else { return None }; - let (w, h, px) = (*width, *height, std::mem::take(rgba)); - let sides = (1..=MAX_BITMAP_SIDE).contains(&w) && (1..=MAX_BITMAP_SIDE).contains(&h); - (sides && px.len() == (w as usize).saturating_mul(h as usize).saturating_mul(4)).then_some((w, h, px)) - } -} - -/// Segments as a kurbo path. A segment after a close opens a new subpath at the last start point. -fn bez(segs: &[Seg]) -> BezPath { - let mut p = BezPath::new(); - let mut start = (0.0, 0.0); - let mut open = false; - for s in segs { - match *s { - Seg::Move(x, y) => { - start = (f64::from(x), f64::from(y)); - p.move_to(start); - open = true; - } - Seg::Line(x, y) => { - if !open { - p.move_to(start); - } - p.line_to((f64::from(x), f64::from(y))); - open = true; - } - Seg::Cubic(a, b, c, d, e, f) => { - if !open { - p.move_to(start); - } - p.curve_to((f64::from(a), f64::from(b)), (f64::from(c), f64::from(d)), (f64::from(e), f64::from(f))); - open = true; - } - Seg::Close => { - if open { - p.close_path(); - } - open = false; - } - } - } - p -} - -/// Whether a placed box is finite and within ±[`MAX_COORD`]. -fn in_range(b: Rect) -> bool { - [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() < MAX_COORD) -} diff --git a/crates/metafile/src/size.rs b/crates/metafile/src/size.rs deleted file mode 100644 index 8766b99626..0000000000 --- a/crates/metafile/src/size.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! The size of a metafile picture without playing its records. - -use crate::bytes::Bytes; -use crate::{Error, emf, f, parse, wmf}; - -/// A placeable WMF header is 22 bytes, followed by the 9-word standard header. -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; -const PLACEABLE_LEN: usize = 22; -const DEFAULT_INCH: f64 = 1440.0; - -/// The size of a WMF or EMF picture in points (device or logical units when the file states no -/// size), the same as `parse(bytes)` would put in the picture's `width` and `height`, or the error -/// `parse` would give. -/// -/// An EMF and a placeable WMF carry their frame in the header, so the size is read from there -/// without decoding a bitmap or building a path. Any other file (a plain WMF, an EMF without a -/// usable frame) takes the full parse. -pub fn size(bytes: &[u8]) -> Result<(f32, f32), Error> { - if let Some(size) = header_size(Bytes(bytes)) { - return Ok(size); - } - let pic = parse(bytes)?; - Ok((pic.width, pic.height)) -} - -/// The size when the header decides it and the file has a first record (otherwise `parse` fails -/// with `NoRecords`, so the header alone is not enough). None sends the caller to the full parse. -pub(crate) fn header_size(b: Bytes) -> Option<(f32, f32)> { - if emf::is_emf(b) { - return emf_size(b); - } - if wmf::is_wmf(b) && b.u32(0) == Some(PLACEABLE_KEY) { - return placeable_wmf_size(b); - } - None -} - -/// `rclFrame` mapped to points. The frame must pass the checks `build` applies to it. -fn emf_size(b: Bytes) -> Option<(f32, f32)> { - let hsize = b.u32(4)? as usize; - b.slice(8, 16)?; - let frame = emf::frame_from_header(b)?; - if !frame.rect.iter().all(|v| v.is_finite()) || frame.rect[2] <= 0.0 || frame.rect[3] <= 0.0 { - return None; - } - // The records start after the header; the parse needs one that is not the end record. - let pos = hsize.max(88); - let (typ, len) = (b.u32(pos)?, b.u32(pos.checked_add(4)?)? as usize); - if len < 8 || !len.is_multiple_of(4) || b.slice(pos, len).is_none() || typ == 14 { - return None; - } - let (w, h) = frame.size?; - Some((f(w).unwrap_or(0.0), f(h).unwrap_or(0.0))) -} - -/// The placeable header's size in points, for a file whose records leave the target mapping alone -/// (see [`sets_the_mapping`]); the full parse decides the others. -fn placeable_wmf_size(b: Bytes) -> Option<(f32, f32)> { - let [l, t, r, bt] = [6, 8, 10, 12].map(|o| b.i16(o).map(f64::from)); - let (l, t, r, bt) = (l?, t?, r?, bt?); - let inch = b.u16(14).filter(|v| *v > 0).map_or(DEFAULT_INCH, f64::from); - let (w, h) = (r - l, bt - t); - if w <= 0.0 || h <= 0.0 { - return None; - } - let hsize = b.u16(PLACEABLE_LEN + 2)? as usize; - if hsize < 9 { - return None; - } - let pos = PLACEABLE_LEN.checked_add(hsize.checked_mul(2)?)?; - let (words, func) = (b.u32(pos)? as usize, b.u16(pos.checked_add(4)?)?); - let len = words.checked_mul(2).filter(|l| *l >= 6)?; - if func == 0 || b.slice(pos, len).is_none() { - return None; - } - if sets_the_mapping(b, pos) { - return None; - } - Some((f(w * 72.0 / inch)?, f(h * 72.0 / inch)?)) -} - -/// Whether a record from `pos` on is SetMapMode (0x0103) or SetViewportExt (0x020E). Those can change -/// the frame the full parse ends with (a zero-size viewport leaves none), so the header size is not -/// enough. The records are only walked, not played, with the same stops as `wmf::parse`. -fn sets_the_mapping(b: Bytes, mut pos: usize) -> bool { - while let (Some(words), Some(func)) = (b.u32(pos), pos.checked_add(4).and_then(|o| b.u16(o))) { - let Some(len) = (words as usize).checked_mul(2).filter(|l| *l >= 6) else { return false }; - if func == 0 || b.slice(pos, len).is_none() { - return false; - } - if matches!(func, 0x0103 | 0x020E) { - return true; - } - let Some(next) = pos.checked_add(len) else { return false }; - pos = next; - } - false -} diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs deleted file mode 100644 index b006b90428..0000000000 --- a/crates/metafile/src/tests.rs +++ /dev/null @@ -1,1187 +0,0 @@ -//! Hand-built WMF and EMF buffers: each test writes the records it needs and checks the parsed model. - -use crate::canvas::Canvas; -use crate::dib::Rgba; -use crate::{Error, Item, MAX_BYTES, MAX_ITEMS, Seg, is_metafile, parse}; - -fn h16(v: i32) -> Vec { - (v as i16).to_le_bytes().to_vec() -} - -fn h32(v: u32) -> Vec { - v.to_le_bytes().to_vec() -} - -fn e32(v: i32) -> Vec { - v.to_le_bytes().to_vec() -} - -fn cat(parts: Vec>) -> Vec { - parts.concat() -} - -/// One WMF record: size in words, function, parameters (padded to a word boundary). -fn wrec(func: u16, params: &[u8]) -> Vec { - let mut p = params.to_vec(); - if !p.len().is_multiple_of(2) { - p.push(0); - } - let words = ((6 + p.len()) / 2) as u32; - let mut v = words.to_le_bytes().to_vec(); - v.extend(func.to_le_bytes()); - v.extend(p); - v -} - -/// A WMF file: optional placeable header (bbox left, top, right, bottom in logical units, 1440 per inch), -/// the standard header, the records and an end-of-file record. -fn wmf(records: &[Vec], placeable: Option<[i32; 4]>) -> Vec { - let body: Vec = records.concat(); - let eof = wrec(0, &[]); - let mut f = Vec::new(); - if let Some(bb) = placeable { - f.extend(0x9AC6_CDD7u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - for v in bb { - f.extend((v as i16).to_le_bytes()); - } - f.extend(1440u16.to_le_bytes()); - f.extend(0u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - } - let total = (f.len() + 18 + body.len() + eof.len()) / 2; - f.extend(1u16.to_le_bytes()); - f.extend(9u16.to_le_bytes()); - f.extend(0x300u16.to_le_bytes()); - f.extend((total as u32).to_le_bytes()); - f.extend(16u16.to_le_bytes()); - f.extend(0u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - f.extend(body); - f.extend(eof); - f -} - -/// One EMF record: type, size in bytes (payload padded to 4), payload. -fn erec(typ: u32, payload: &[u8]) -> Vec { - let mut p = payload.to_vec(); - while !p.len().is_multiple_of(4) { - p.push(0); - } - let mut v = typ.to_le_bytes().to_vec(); - v.extend(((8 + p.len()) as u32).to_le_bytes()); - v.extend(p); - v -} - -/// An EMF file with an 88-byte header (bounds and frame in 0.01 mm), the records and an EOF record. -fn emf(records: &[Vec], bounds: [i32; 4], frame: [i32; 4]) -> Vec { - let body: Vec = records.concat(); - let eof = erec(14, &[0; 12]); - let total = 88 + body.len() + eof.len(); - let mut h = vec![0u8; 88]; - h[0..4].copy_from_slice(&1u32.to_le_bytes()); - h[4..8].copy_from_slice(&88u32.to_le_bytes()); - h[8..24].copy_from_slice(&bounds.iter().flat_map(|v| v.to_le_bytes()).collect::>()); - h[24..40].copy_from_slice(&frame.iter().flat_map(|v| v.to_le_bytes()).collect::>()); - h[40..44].copy_from_slice(&0x464D_4520u32.to_le_bytes()); - h[44..48].copy_from_slice(&0x0001_0000u32.to_le_bytes()); - h[48..52].copy_from_slice(&(total as u32).to_le_bytes()); - h[52..56].copy_from_slice(&((records.len() + 1) as u32).to_le_bytes()); - h[56..58].copy_from_slice(&1u16.to_le_bytes()); - // 1000 x 500 device pixels for 250 x 125 mm: 0.04 device units per hundredth of a millimetre. - h[72..76].copy_from_slice(&1000i32.to_le_bytes()); - h[76..80].copy_from_slice(&500i32.to_le_bytes()); - h[80..84].copy_from_slice(&250i32.to_le_bytes()); - h[84..88].copy_from_slice(&125i32.to_le_bytes()); - let mut out = h; - out.extend(body); - out.extend(eof); - out -} - -/// A BITMAPINFOHEADER (40 bytes). -fn info_header(w: i32, h: i32, bpp: u16, size_image: u32) -> Vec { - cat(vec![h32(40), e32(w), e32(h), h16(1), h16(i32::from(bpp)), h32(0), h32(size_image), e32(0), e32(0), h32(0), h32(0)]) -} - -/// A 2x2 24-bit bottom-up DIB. File rows are stored bottom first: the bottom image row is blue, green; -/// the top row is red, white. Rows are padded to 4 bytes (8 bytes per row). -fn dib24_bottom_up() -> Vec { - let mut v = info_header(2, 2, 24, 16); - v.extend([255, 0, 0, 0, 255, 0, 0, 0]); - v.extend([0, 0, 255, 255, 255, 255, 0, 0]); - v -} - -/// Top-down RGBA of [`dib24_bottom_up`]: top-left red, top-right white, bottom-left blue, bottom-right green. -const DIB24_RGBA: [u8; 16] = [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]; - -fn path_segs(item: &Item) -> (&Vec, Option<[u8; 4]>, Option<([u8; 4], f32)>, bool) { - match item { - Item::Path { segs, fill, stroke, even_odd } => (segs, *fill, *stroke, *even_odd), - Item::Bitmap { .. } | Item::Text(_) => panic!("expected a path"), - } -} - -fn close(a: f32, b: f32) -> bool { - (a - b).abs() < 1e-3 -} - -#[test] -fn wmf_rectangle_with_solid_brush() { - let recs = [ - wrec(0x02FC, &cat(vec![h16(0), h32(0x0000_00FF), h16(0)])), - wrec(0x012D, &h16(0)), - wrec(0x041B, &cat(vec![h16(70), h16(110), h16(20), h16(10)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (100.0, 50.0)); - assert_eq!(p.items.len(), 1); - let (segs, fill, stroke, even_odd) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(100.0, 0.0), Seg::Line(100.0, 50.0), Seg::Line(0.0, 50.0), Seg::Close]); - assert_eq!(fill, Some([255, 0, 0, 255])); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); - assert!(even_odd); -} - -#[test] -fn wmf_polyline_with_pen() { - let recs = [ - wrec(0x02FA, &cat(vec![h16(0), h16(4), h16(0), h32(0x0000_FF00)])), - wrec(0x012D, &h16(0)), - wrec(0x0325, &cat(vec![h16(3), h16(0), h16(0), h16(50), h16(0), h16(50), h16(40)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (50.0, 40.0)); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(50.0, 0.0), Seg::Line(50.0, 40.0)]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 255, 0, 255], 4.0))); -} - -#[test] -fn wmf_polygon_fill_rule_follows_polyfillmode() { - let square = cat(vec![h16(4), h16(0), h16(0), h16(10), h16(0), h16(10), h16(10), h16(0), h16(10)]); - let winding = [wrec(0x0106, &h16(2)), wrec(0x0324, &square)]; - let p = parse(&wmf(&winding, None)).unwrap(); - assert!(!path_segs(&p.items[0]).3, "WINDING fills use the nonzero rule"); - let alternate = [wrec(0x0324, &square)]; - let p = parse(&wmf(&alternate, None)).unwrap(); - let (segs, fill, _, even_odd) = path_segs(&p.items[0]); - assert!(even_odd, "default ALTERNATE is even-odd"); - assert_eq!(fill, Some([255, 255, 255, 255])); - assert_eq!(segs.last(), Some(&Seg::Close)); -} - -#[test] -fn wmf_stretchdib_flips_bottom_up_rows() { - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0), dib24_bottom_up()]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - assert_eq!((p.width, p.height), (20.0, 10.0)); - let Item::Bitmap { rect, width, height, rgba } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 20.0, 10.0]); - assert_eq!((*width, *height), (2, 2)); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn wmf_mapping_window_and_viewport() { - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020B, &cat(vec![h16(100), h16(100)])), - wrec(0x020C, &cat(vec![h16(50), h16(50)])), - wrec(0x020E, &cat(vec![h16(100), h16(100)])), - wrec(0x0214, &cat(vec![h16(100), h16(100)])), - wrec(0x0213, &cat(vec![h16(150), h16(150)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (100.0, 100.0)); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(100.0, 100.0)]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn wmf_placeable_header_sets_frame_in_points() { - let p = parse(&wmf(&[wrec(0x041B, &cat(vec![h16(1440), h16(2880), h16(0), h16(0)]))], Some([0, 0, 2880, 1440]))).unwrap(); - assert_eq!((p.width, p.height), (144.0, 72.0)); -} - -#[test] -fn emf_stretchdibits_flips_and_fits_frame() { - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![ - e32(0), - e32(0), - e32(0), - e32(0), - e32(2), - e32(2), - e32(80), - e32(40), - e32(120), - e32(16), - e32(0), - e32(0x00CC_0020), - e32(100), - e32(50), - ])); - payload.extend(info_header(2, 2, 24, 16)); - payload.extend(dib24_bottom_up().get(40..).unwrap_or_default()); - let rec = erec(81, &payload); - // A 25 x 12.5 mm frame is 70.87 x 35.43 points; the bitmap fills the whole frame. - let file = emf(&[rec], [0, 0, 100, 50], [0, 0, 2500, 1250]); - let p = parse(&file).unwrap(); - let (w, h) = (2500.0 * 72.0 / 2540.0, 1250.0 * 72.0 / 2540.0); - assert!(close(p.width, w as f32) && close(p.height, h as f32)); - let Item::Bitmap { rect, width, height, rgba } = &p.items[0] else { panic!("expected a bitmap") }; - assert!(rect.iter().zip([0.0, 0.0, w, h]).all(|(a, b)| close(*a, b as f32))); - assert_eq!((*width, *height), (2, 2)); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_world_transform_scales_geometry() { - let xf = cat([2.0f32, 0.0, 0.0, 2.0, 0.0, 0.0].iter().map(|v| v.to_le_bytes().to_vec()).collect()); - let recs = [erec(35, &xf), erec(27, &cat(vec![e32(0), e32(0)])), erec(54, &cat(vec![e32(10), e32(5)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!((p.width, p.height), (20.0, 10.0)); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(20.0, 10.0)]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn emf_ellipse_is_four_cubics_back_to_start() { - let rect = cat(vec![e32(0), e32(0), e32(40), e32(20)]); - let p = parse(&emf(&[erec(42, &rect)], [0; 4], [0; 4])).unwrap(); - let (segs, fill, _, _) = path_segs(&p.items[0]); - assert_eq!(segs.len(), 6); - assert_eq!(segs[0], Seg::Move(40.0, 10.0)); - assert!(matches!(segs[4], Seg::Cubic(_, _, _, _, x, y) if close(x, 40.0) && close(y, 10.0))); - assert_eq!(segs[5], Seg::Close); - assert_eq!(fill, Some([255, 255, 255, 255])); -} - -#[test] -fn emf_path_bracket_strokeandfill_uses_stock_black_brush() { - let bounds = vec![0u8; 16]; - let recs = [ - erec(59, &[]), - erec(27, &cat(vec![e32(0), e32(0)])), - erec(54, &cat(vec![e32(10), e32(0)])), - erec(54, &cat(vec![e32(10), e32(10)])), - erec(61, &[]), - erec(60, &[]), - erec(37, &h32(0x8000_0004)), - erec(63, &bounds), - ]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 1); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(10.0, 0.0), Seg::Line(10.0, 10.0), Seg::Close]); - assert_eq!(fill, Some([0, 0, 0, 255])); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn item_cap_stops_the_parse_and_keeps_the_rest() { - let rect = wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)])); - let recs: Vec> = (0..MAX_ITEMS + 10).map(|_| rect.clone()).collect(); - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!(p.items.len(), MAX_ITEMS); -} - -#[test] -fn detection_and_garbage() { - let w = wmf(&[wrec(0x041B, &cat(vec![h16(1), h16(1), h16(0), h16(0)]))], None); - let e = emf(&[erec(42, &cat(vec![e32(0), e32(0), e32(4), e32(4)]))], [0; 4], [0; 4]); - assert!(is_metafile(&w)); - assert!(is_metafile(&e)); - assert!(!is_metafile(b"hello world, not a metafile")); - assert_eq!(parse(b"hello world, not a metafile").unwrap_err(), Error::NotMetafile); - assert!(parse(&[]).is_err()); -} - -/// Fixed-seed LCG (Knuth's constants): the fuzz inputs are reproducible. -struct Lcg(u64); - -impl Lcg { - fn rnd(&mut self) -> u32 { - self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); - (self.0 >> 33) as u32 - } -} - -#[test] -fn truncated_random_and_mutated_inputs_never_panic() { - let rect = wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)])); - let wfile = wmf( - &[ - wrec(0x02FC, &cat(vec![h16(0), h32(0xFF), h16(0)])), - wrec(0x012D, &h16(0)), - rect, - wrec(0x0325, &cat(vec![h16(2), h16(0), h16(0), h16(5), h16(5)])), - ], - Some([0, 0, 20, 10]), - ); - let mut dib_rec = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0)]); - dib_rec.extend(dib24_bottom_up()); - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![e32(0), e32(0), e32(0), e32(0), e32(2), e32(2), e32(80), e32(40), e32(120), e32(16), e32(0), e32(0), e32(20), e32(10)])); - payload.extend(info_header(2, 2, 24, 16)); - payload.extend(dib24_bottom_up().get(40..).unwrap_or_default()); - let efile = emf( - &[ - erec(59, &[]), - erec(27, &cat(vec![e32(0), e32(0)])), - erec(54, &cat(vec![e32(9), e32(9)])), - erec(61, &[]), - erec(60, &[]), - erec(63, &[0; 16]), - erec(81, &payload), - erec(86, &cat(vec![h32(4), h16(0), h16(0), h16(9), h16(9), h16(0), h16(9)])), - ], - [0, 0, 20, 10], - [0, 0, 2540, 1270], - ); - for file in [&wfile, &efile] { - for n in 0..=file.len() { - let prefix = &file[..n]; - let _ = parse(prefix); - let _ = is_metafile(prefix); - } - } - let mut rng = Lcg(0x2545_F491_4F6C_DD1D); - for _ in 0..3000 { - let len = (rng.rnd() % 400) as usize; - let buf: Vec = (0..len).map(|_| rng.rnd() as u8).collect(); - let _ = parse(&buf); - } - for i in 0..1500usize { - let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() }; - for _ in 0..8 { - let at = rng.rnd() as usize % buf.len(); - buf[at] = rng.rnd() as u8; - } - let _ = parse(&buf); - } - for i in 0..500usize { - let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() }; - let at = rng.rnd() as usize % buf.len(); - buf[at..].iter_mut().for_each(|b| *b = 0xFF); - let _ = parse(&buf); - } -} - -#[test] -fn wmf_stock_null_brush_by_16_bit_handle_has_no_fill() { - // SELECTOBJECT with 0x8005 is the NULL_BRUSH stock object (0x8000 | 5), so the rectangle is outline only. - let recs = [wrec(0x012D, &h16(0x8005u16 as i32)), wrec(0x041B, &cat(vec![h16(70), h16(110), h16(20), h16(10)]))]; - let p = parse(&wmf(&recs, None)).unwrap(); - let (_, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn emf_frame_comes_from_rclframe_not_device_bounds() { - // Bounds cover only the left half of the 25 x 12.5 mm frame (device units are 0.04 per 0.01 mm), so a - // rectangle from x = 0 to 50 px ends at half the picture width. - let rec = erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let p = parse(&emf(&[rec], [0, 0, 50, 25], [0, 0, 2500, 1250])).unwrap(); - let w = 2500.0 * 72.0 / 2540.0; - assert!(close(p.width, w as f32) && close(p.height, (1250.0 * 72.0 / 2540.0) as f32)); - let (segs, ..) = path_segs(&p.items[0]); - assert!(matches!(segs[1], Seg::Line(x, _) if close(x, (w / 2.0) as f32)), "{segs:?}"); -} - -#[test] -fn emf_bounds_stand_in_when_the_frame_is_empty() { - let rec = erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let p = parse(&emf(&[rec], [0, 0, 50, 25], [0; 4])).unwrap(); - assert_eq!((p.width, p.height), (50.0, 25.0)); -} - -#[test] -fn wmf_placeable_bounds_go_through_the_window_mapping() { - // Logical bounds 200 x 100 at 1440 per inch are 10 x 5 points; the window is 2:1 onto the viewport, so - // the frame is 100 x 50 device units and the rectangle fills it. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020C, &cat(vec![h16(100), h16(200)])), - wrec(0x020E, &cat(vec![h16(50), h16(100)])), - wrec(0x041B, &cat(vec![h16(100), h16(200), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, Some([0, 0, 200, 100]))).unwrap(); - assert_eq!((p.width, p.height), (10.0, 5.0)); - let (segs, ..) = path_segs(&p.items[0]); - assert!(segs.iter().any(|s| matches!(s, Seg::Line(x, y) if close(*x, 10.0) && close(*y, 5.0))), "{segs:?}"); -} - -#[test] -fn wmf_stretchdib_clipped_source_keeps_its_place() { - // Source x from -1 for 2 columns: only column 0 is in the bitmap, so it fills the right half of the - // destination and the picture keeps the original 20-unit width scale. - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(-1), h16(10), h16(20), h16(0), h16(0), dib24_bottom_up()]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], Some([0, 0, 20, 10]))).unwrap(); - let Item::Bitmap { rect, width, height, rgba } = &p.items[0] else { panic!("expected a bitmap") }; - // Placeable units are points: 20 units at 1440 per inch are 1 point, so the right column is 0.5 pt wide. - assert_eq!(rect, &[0.5, 0.0, 0.5, 0.5]); - assert_eq!((*width, *height), (1, 2)); - assert_eq!(rgba.as_slice(), [255, 0, 0, 255, 0, 0, 255, 255]); -} - -#[test] -fn wmf_negative_destination_width_mirrors_the_bitmap() { - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(-20), h16(0), h16(0), dib24_bottom_up()]); - // Frame from the placeable bounds (-20, 0)-(0, 10): the mirrored bitmap fills it. - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], Some([-20, 0, 0, 10]))).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 1.0, 0.5]); - assert_eq!(&rgba[..8], [255, 255, 255, 255, 255, 0, 0, 255]); -} - -#[test] -fn emf_blackness_bitblt_fills_black_without_a_source() { - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![e32(10), e32(20), e32(30), e32(40), e32(0x0000_0042)])); - let p = parse(&emf(&[erec(76, &payload)], [0; 4], [0; 4])).unwrap(); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(fill, Some([0, 0, 0, 255])); - assert_eq!(stroke, None); - assert_eq!(segs.len(), 5); -} - -#[test] -fn emf_savedc_past_the_stack_cap_stops_the_parse() { - let mut recs: Vec> = (0..=crate::MAX_STACK).map(|_| erec(33, &[])).collect(); - recs.push(erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))); - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert!(p.items.is_empty(), "records after the cap must not be drawn"); -} - -#[test] -fn canvas_stops_at_the_byte_budget() { - // Two 128 MB bitmaps fit the budget; the third would exceed it and stops the canvas. - let mut cv = Canvas::new(); - let big = || Rgba { w: 1, h: 1, px: vec![0u8; MAX_BYTES / 2] }; - cv.bitmap([0.0, 0.0, 1.0, 1.0], big()); - cv.bitmap([0.0, 0.0, 1.0, 1.0], big()); - assert!(!cv.full()); - cv.bitmap([0.0, 0.0, 1.0, 1.0], big()); - assert!(cv.full()); - assert_eq!(cv.items.len(), 2); -} - -#[test] -fn oversized_dib_header_size_is_rejected_without_overflow() { - let mut info = info_header(2, 2, 24, 16); - info[0..4].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0), info]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - assert!(p.items.is_empty()); -} - -/// An EMF record of `len` bytes (header included) with u32 fields and byte blobs written at absolute -/// record offsets, so each test places a field where the spec puts it. -fn erec_at(typ: u32, len: usize, fields: &[(usize, u32)], blobs: &[(usize, &[u8])]) -> Vec { - let mut v = vec![0u8; len]; - v[0..4].copy_from_slice(&typ.to_le_bytes()); - v[4..8].copy_from_slice(&(len as u32).to_le_bytes()); - for (off, val) in fields { - v[*off..*off + 4].copy_from_slice(&val.to_le_bytes()); - } - for (off, b) in blobs { - v[*off..*off + b.len()].copy_from_slice(b); - } - v -} - -/// A BITBLT-style record (BITBLT, STRETCHBLT, ALPHABLEND layout) with its DIB at 112: the bmi and bits -/// offsets and lengths go at 84 and 92. `fields` and `blobs` add the other fields. -fn dib_rec(typ: u32, fields: &[(usize, u32)], blobs: &[(usize, &[u8])], info: &[u8], bits: &[u8]) -> Vec { - let at = 112; - let bits_at = at + info.len(); - let mut f = fields.to_vec(); - f.extend([(84, at as u32), (88, info.len() as u32), (92, bits_at as u32), (96, bits.len() as u32)]); - let mut b: Vec<(usize, &[u8])> = blobs.to_vec(); - b.extend([(at, info), (bits_at, bits)]); - erec_at(typ, bits_at + bits.len(), &f, &b) -} - -/// BITBLT (76) with destination `dst` = [x, y, w, h] and a 40-byte header DIB. -fn bitblt_rec(rop: u32, dst: [u32; 4], info: &[u8], bits: &[u8]) -> Vec { - let fields = [(24, dst[0]), (28, dst[1]), (32, dst[2]), (36, dst[3]), (40, rop)]; - dib_rec(76, &fields, &[], info, bits) -} - -#[test] -fn wmf_font_takes_an_object_slot_so_handles_line_up() { - // The font is handle 0, so the pen created after it is handle 1. - let recs = [ - wrec(0x02FB, &[0u8; 18]), - wrec(0x02FA, &cat(vec![h16(0), h16(4), h16(0), h32(0x0000_FF00)])), - wrec(0x012D, &h16(1)), - wrec(0x0325, &cat(vec![h16(2), h16(0), h16(0), h16(50), h16(0), h16(50)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - let (_, _, stroke, _) = path_segs(&p.items[0]); - assert_eq!(stroke, Some(([0, 255, 0, 255], 4.0))); -} - -#[test] -fn emf_polybezierto16_continues_the_open_path() { - // BEGINPATH, MOVETO a, LINETO b, POLYBEZIERTO16, CLOSEFIGURE, FILLPATH: one closed figure from a. - let mut bezier = vec![0u8; 16]; - bezier.extend(cat(vec![e32(3), h16(10), h16(10), h16(20), h16(10), h16(20), h16(0)])); - let recs = [ - erec(59, &[]), - erec(27, &cat(vec![e32(0), e32(0)])), - erec(54, &cat(vec![e32(10), e32(0)])), - erec(88, &bezier), - erec(61, &[]), - erec(62, &[0; 16]), - ]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 1); - let (segs, fill, _, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(10.0, 0.0), Seg::Cubic(10.0, 10.0, 20.0, 10.0, 20.0, 0.0), Seg::Close]); - assert_eq!(fill, Some([255, 255, 255, 255])); -} - -#[test] -fn emf_polybezier_starts_its_own_figure_and_keeps_the_current_point() { - // POLYBEZIER (2) starts at its first point; the LINETO after it still starts at the MOVETO point. - let mut bezier = vec![0u8; 16]; - bezier.extend(cat(vec![e32(4), e32(0), e32(0), e32(5), e32(5), e32(10), e32(5), e32(10), e32(0)])); - let recs = [erec(27, &cat(vec![e32(3), e32(3)])), erec(2, &bezier), erec(54, &cat(vec![e32(50), e32(50)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 2); - let (segs, ..) = path_segs(&p.items[0]); - assert_eq!(segs[0], Seg::Move(0.0, 0.0)); - let (segs, ..) = path_segs(&p.items[1]); - assert_eq!(segs, &vec![Seg::Move(3.0, 3.0), Seg::Line(50.0, 50.0)]); -} - -#[test] -fn hairline_pen_stays_zero_under_an_anisotropic_window() { - // Window 2000 x 2000 onto a 1 x 1 viewport: a cosmetic pen must not become one device unit wide. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020C, &cat(vec![h16(2000), h16(2000)])), - wrec(0x020E, &cat(vec![h16(1), h16(1)])), - wrec(0x0214, &cat(vec![h16(0), h16(0)])), - wrec(0x0213, &cat(vec![h16(2000), h16(2000)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (1.0, 1.0)); - let (segs, _, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs.last(), Some(&Seg::Line(1.0, 1.0))); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn null_pen_is_recognised_under_extra_style_bits() { - // Pen style 0x105: PS_NULL (5) with a flag above the style nibble still draws no outline. - let pen = erec_at(38, 28, &[(8, 0), (12, 0x105), (16, 1), (24, 0)], &[]); - let recs = [pen, erec(37, &h32(0)), erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - let (_, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(fill, Some([255, 255, 255, 255])); - assert_eq!(stroke, None); -} - -#[test] -fn metric_map_mode_flips_y_and_scales_to_device_pixels_emf() { - // LOMETRIC is 0.1 mm per unit; the header maps 4 device pixels to 1 mm. Points go y-up, so the - // drawing lies below its origin and the picture frame moves up to its top. - let recs = [erec(17, &h32(2)), erec(27, &cat(vec![e32(0), e32(0)])), erec(54, &cat(vec![e32(100), e32(50)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - let (segs, ..) = path_segs(&p.items[0]); - assert!(close_seg(&segs[0], Seg::Move(0.0, 20.0)) && close_seg(&segs[1], Seg::Line(40.0, 0.0)), "{segs:?}"); -} - -#[test] -fn metric_map_mode_uses_96_dpi_for_wmf() { - let recs = [wrec(0x0103, &h16(2)), wrec(0x0214, &cat(vec![h16(0), h16(0)])), wrec(0x0213, &cat(vec![h16(50), h16(100)]))]; - let p = parse(&wmf(&recs, None)).unwrap(); - let px_mm = 96.0 / 25.4; - let (segs, ..) = path_segs(&p.items[0]); - let (x, y) = (100.0 * 0.1 * px_mm, 50.0 * 0.1 * px_mm); - assert!(close_seg(&segs[0], Seg::Move(0.0, y as f32)) && close_seg(&segs[1], Seg::Line(x as f32, 0.0)), "{segs:?}"); -} - -/// Segment equality within [`close`] tolerance. -fn close_seg(a: &Seg, b: Seg) -> bool { - match (*a, b) { - (Seg::Move(x, y), Seg::Move(u, v)) | (Seg::Line(x, y), Seg::Line(u, v)) => close(x, u) && close(y, v), - _ => false, - } -} - -#[test] -fn isotropic_mode_uses_one_scale_and_keeps_axis_signs() { - // Window 100 x 50; viewport 400 x -100: the scale is min(4, 2) = 2 on both axes, y flipped. - let recs = [ - wrec(0x0103, &h16(7)), - wrec(0x020C, &cat(vec![h16(50), h16(100)])), - wrec(0x020E, &cat(vec![h16(-100), h16(400)])), - wrec(0x0214, &cat(vec![h16(0), h16(0)])), - wrec(0x0213, &cat(vec![h16(25), h16(50)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - let (segs, ..) = path_segs(&p.items[0]); - assert!(close_seg(&segs[0], Seg::Move(0.0, 100.0)) && close_seg(&segs[1], Seg::Line(100.0, 50.0)), "{segs:?}"); -} - -#[test] -fn modify_world_with_an_unknown_mode_keeps_the_transform() { - let scale2 = cat([2.0f32, 0.0, 0.0, 2.0, 0.0, 0.0].iter().map(|v| v.to_le_bytes().to_vec()).collect()); - let identity = cat([1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().map(|v| v.to_le_bytes().to_vec()).collect()); - let recs = - [erec(35, &scale2), erec(36, &cat(vec![identity, h32(99)])), erec(27, &cat(vec![e32(0), e32(0)])), erec(54, &cat(vec![e32(10), e32(5)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - let (segs, ..) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(20.0, 10.0)]); -} - -#[test] -fn round_rect_accepts_reversed_corners() { - let normal = crate::geom::round_rect(0.0, 0.0, 10.0, 20.0, 4.0, 4.0); - assert_eq!(crate::geom::round_rect(10.0, 20.0, 0.0, 0.0, 4.0, 4.0), normal); - assert_eq!(crate::geom::round_rect(10.0, 0.0, 0.0, 20.0, 4.0, 4.0), normal); -} - -#[test] -fn stroke_width_is_clamped_to_the_picture_diagonal() { - // A 1440-unit placeable picture is 72 points square (diagonal 101.8); a 5000-unit pen would be 250. - let recs = [ - wrec(0x02FA, &cat(vec![h16(0), h16(5000), h16(0), h32(0)])), - wrec(0x012D, &h16(0)), - wrec(0x041B, &cat(vec![h16(1440), h16(1440), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, Some([0, 0, 1440, 1440]))).unwrap(); - assert_eq!((p.width, p.height), (72.0, 72.0)); - let (_, _, stroke, _) = path_segs(&p.items[0]); - assert!(close(stroke.unwrap_or(([0; 4], 0.0)).1, 72.0 * 2.0f32.sqrt()), "{stroke:?}"); -} - -/// A WMF rectangle from (0, 0) to (1, 1), so a picture's frame starts at the origin. -fn origin_rect() -> Vec { - wrec(0x041B, &cat(vec![h16(1), h16(1), h16(0), h16(0)])) -} - -#[test] -fn wmf_dibbitblt_without_a_dib_is_a_pattern_fill() { - // The 12-word form: rop(4), ySrc, xSrc, reserved, height, width, yDest, xDest; PATCOPY fills with the brush. - let params = cat(vec![h32(0x00F0_0021), h16(0), h16(0), h16(0), h16(10), h16(20), h16(5), h16(7)]); - let p = parse(&wmf(&[origin_rect(), wrec(0x0940, ¶ms)], None)).unwrap(); - let (segs, fill, _, _) = path_segs(&p.items[1]); - assert_eq!(fill, Some([255, 255, 255, 255])); - assert_eq!(segs, &vec![Seg::Move(7.0, 5.0), Seg::Line(27.0, 5.0), Seg::Line(27.0, 15.0), Seg::Line(7.0, 15.0), Seg::Close]); -} - -#[test] -fn wmf_dibstretchblt_without_a_dib_is_a_rop_fill() { - // The 14-word form: rop(4), srcH, srcW, ySrc, xSrc, reserved, destH, destW, yDest, xDest; BLACKNESS fills black. - let params = cat(vec![h32(0x0000_0042), h16(2), h16(2), h16(0), h16(0), h16(0), h16(10), h16(20), h16(5), h16(7)]); - let p = parse(&wmf(&[origin_rect(), wrec(0x0B41, ¶ms)], None)).unwrap(); - let (segs, fill, stroke, _) = path_segs(&p.items[1]); - assert_eq!((fill, stroke), (Some([0, 0, 0, 255]), None)); - assert_eq!(segs, &vec![Seg::Move(7.0, 5.0), Seg::Line(27.0, 5.0), Seg::Line(27.0, 15.0), Seg::Line(7.0, 15.0), Seg::Close]); -} - -#[test] -fn wmf_dibstretchblt_stretches_the_dib_into_its_destination() { - // rop(4), srcH, srcW, ySrc, xSrc, destH, destW, yDest, xDest, then the DIB (no reserved word). - let mut params = cat(vec![h32(0x00CC_0020), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(6), h16(5)]); - params.extend(dib24_bottom_up()); - let p = parse(&wmf(&[origin_rect(), wrec(0x0B41, ¶ms)], None)).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[1] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[5.0, 6.0, 20.0, 10.0]); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn wmf_negative_destination_height_mirrors_the_rows() { - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(-10), h16(20), h16(0), h16(0), dib24_bottom_up()]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 20.0, 10.0]); - // Blue, green on top; red, white below. - assert_eq!(rgba.as_slice(), [0, 0, 255, 255, 0, 255, 0, 255, 255, 0, 0, 255, 255, 255, 255, 255]); -} - -#[test] -fn wmf_dibbitblt_copies_the_dib_at_its_destination() { - // The rectangle fixes the picture origin at (0, 0); the DIB lands at x = 5, y = 6. - let mut params = cat(vec![h32(0x00CC_0020), h16(0), h16(0), h16(2), h16(2), h16(6), h16(5)]); - params.extend(dib24_bottom_up()); - let recs = [wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)])), wrec(0x0940, ¶ms)]; - let p = parse(&wmf(&recs, None)).unwrap(); - let Item::Bitmap { rect, width, height, rgba } = &p.items[1] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[5.0, 6.0, 2.0, 2.0]); - assert_eq!((*width, *height), (2, 2)); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_setdibitstodevice_draws_the_image_at_its_own_size() { - let dib = dib24_bottom_up(); - let (info, bits) = (&dib[..40], &dib[40..]); - // Destination x/y at 24, src x/y at 32, size at 40, bmi at 48 (offset, length), bits at 56, scan start - // 68 and scan count 72. - let fields = [(24, 10), (28, 20), (40, 2), (44, 2), (48, 112), (52, 40), (56, 152), (60, 16), (72, 2)]; - let rec = erec_at(80, 168, &fields, &[(112, info), (152, bits)]); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 2.0, 2.0]); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_setdibitstodevice_source_counts_from_the_start_scan() { - // ySrc 1 with the bits starting at scan 1 is source row 0 of the bits: the bottom row (blue, green), - // drawn cxSrc x cySrc = 2 x 1 at the destination. - let dib = dib24_bottom_up(); - let (info, bits) = (&dib[..40], &dib[40..]); - let fields = [(24, 10), (28, 20), (36, 1), (40, 2), (44, 1), (48, 112), (52, 40), (56, 152), (60, 16), (68, 1), (72, 2)]; - let rec = erec_at(80, 168, &fields, &[(112, info), (152, bits)]); - let r = erec(43, &cat(vec![e32(0), e32(0), e32(1), e32(1)])); - let p = parse(&emf(&[r, rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[1] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[10.0, 20.0, 2.0, 1.0]); - assert_eq!(rgba.as_slice(), [0, 0, 255, 255, 0, 255, 0, 255]); -} - -#[test] -fn emf_alphablend_uses_constant_and_per_pixel_alpha() { - // Constant alpha 128 (BLENDFUNCTION bytes at 40: op, flags, constant, format) over a 24-bit DIB. - let blend = [0u8, 0, 128, 0]; - let dib = dib24_bottom_up(); - let rec = dib_rec(114, &[(24, 0), (28, 0), (32, 2), (36, 2), (44, 0), (48, 0), (100, 2), (104, 2)], &[(40, &blend[..])], &dib[..40], &dib[40..]); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - let alpha: Vec = rgba.as_chunks::<4>().0.iter().map(|px| px[3]).collect(); - assert_eq!(alpha, vec![128; 4]); - // Per-pixel alpha (AC_SRC_ALPHA) over a 32-bit premultiplied DIB: BGRA 0, 0, 128, 128 is straight red at - // half alpha, and the constant 128 halves the alpha again. - let one_px = |constant: u8, bgra: [u8; 4]| { - let blend = [0u8, 0, constant, 1]; - let info = info_header(1, 1, 32, 4); - let rec = dib_rec(114, &[(24, 0), (28, 0), (32, 1), (36, 1), (44, 0), (48, 0), (100, 1), (104, 1)], &[(40, &blend[..])], &info, &bgra); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - rgba.clone() - }; - assert_eq!(one_px(255, [0, 0, 128, 128]), [255, 0, 0, 128]); - assert_eq!(one_px(128, [0, 0, 128, 128]), [255, 0, 0, 64]); - assert_eq!(one_px(255, [10, 20, 64, 128]), [128, 40, 20, 128], "rounded to the nearest value"); -} - -#[test] -fn emf_srcand_mask_draws_all_but_its_white_pixels() { - // SRCAND over white paper is the source itself; white keeps the destination, so it is transparent. - let dib = dib24_bottom_up(); - let rec = bitblt_rec(0x0088_00C6, [0, 0, 2, 2], &dib[..40], &dib[40..]); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), [255, 0, 0, 255, 255, 255, 255, 0, 0, 0, 255, 255, 0, 255, 0, 255]); -} - -#[test] -fn emf_srcpaint_makes_black_pixels_transparent() { - // A 2 x 1 DIB: black, then red. SRCPAINT leaves black transparent; SRCCOPY keeps it opaque. - let info = info_header(2, 1, 24, 8); - let bits = [0u8, 0, 0, 0, 0, 255, 0, 0]; - let p = parse(&emf(&[bitblt_rec(0x00EE_0086, [0, 0, 2, 1], &info, &bits)], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), [0, 0, 0, 0, 255, 0, 0, 255]); - let p = parse(&emf(&[bitblt_rec(0x00CC_0020, [0, 0, 2, 1], &info, &bits)], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), [0, 0, 0, 255, 255, 0, 0, 255]); -} - -#[test] -fn wmf_dib_palette_entries_are_skipped_before_the_bits() { - // A 24-bit DIB with biClrUsed = 2 carries two RGBQUADs (8 bytes) before its pixel bits. - let mut info = info_header(2, 2, 24, 16); - info[32..36].copy_from_slice(&2u32.to_le_bytes()); - let mut dib = info; - dib.extend([9u8; 8]); - dib.extend(&dib24_bottom_up()[40..]); - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0), dib]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_point_counts_past_the_budget_are_rejected() { - // A count of 4 billion points in a record that cannot hold them: nothing is drawn and nothing is allocated. - let mut poly = vec![0u8; 16]; - poly.extend(cat(vec![h32(u32::MAX), h32(0), h32(0)])); - let mut groups = vec![0u8; 16]; - groups.extend(cat(vec![h32(u32::MAX), h32(u32::MAX), h32(1)])); - let p = parse(&emf(&[erec(4, &poly), erec(7, &groups)], [0; 4], [0; 4])).unwrap(); - assert!(p.items.is_empty()); -} - -#[test] -fn emf_polypolygon_counts_must_fit_the_record() { - // A polygon count within the point budget in a record too short to hold the counts draws nothing. - let mut short = vec![0u8; 16]; - short.extend(cat(vec![h32(crate::MAX_PATH_OPS as u32), h32(3), h32(3)])); - // POLYPOLYGON16: two triangles of three points each. - let mut two = vec![0u8; 16]; - two.extend(cat(vec![h32(2), h32(6), h32(3), h32(3)])); - two.extend(cat([0, 0, 10, 0, 0, 10, 20, 0, 30, 0, 20, 10].iter().map(|v| h16(*v)).collect())); - let p = parse(&emf(&[erec(91, &short), erec(91, &two)], [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 1); - let (segs, ..) = path_segs(&p.items[0]); - assert_eq!(segs.iter().filter(|s| matches!(s, Seg::Move(..))).count(), 2, "{segs:?}"); -} - -/// EMR_EXTCREATEPEN into slot 1 with LogPenEx style, width and brush style, then a selected rectangle. -fn ext_pen_rect(style: u32, width: u32, brush: u32) -> Option<([u8; 4], f32)> { - let pen = erec_at(95, 52, &[(8, 1), (28, style), (32, width), (36, brush), (40, 0x0000_FF00)], &[]); - let recs = [pen, erec(37, &h32(1)), erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - path_segs(&p.items[0]).2 -} - -#[test] -fn emf_ext_pen_cosmetic_is_a_hairline_and_null_brush_draws_nothing() { - // PS_COSMETIC widths are device pixels: a hairline, not one logical unit. - assert_eq!(ext_pen_rect(0, 1, 0), Some(([0, 255, 0, 255], 0.0))); - // PS_GEOMETRIC (0x10000) keeps its logical width. - assert_eq!(ext_pen_rect(0x0001_0000, 4, 0), Some(([0, 255, 0, 255], 4.0))); - // A BS_NULL brush draws no line. - assert_eq!(ext_pen_rect(0x0001_0000, 4, 1), None); -} - -#[test] -fn flip_tolerates_a_short_pixel_buffer() { - let mut img = Rgba { w: 2, h: 2, px: vec![1u8; 7] }; - crate::dib::flip(&mut img, true, true); - assert_eq!(img.px.len(), 7); - // Three rows held of four: only the rows present swap (0 with 2). - let mut img = Rgba { w: 1, h: 4, px: (0u8..12).collect() }; - crate::dib::flip(&mut img, false, true); - assert_eq!(img.px, [8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3]); -} - -#[test] -fn place_fits_the_frame_scales_strokes_and_drops_far_paths() { - let pic = crate::Picture { - width: 100.0, - height: 50.0, - items: vec![ - Item::Path { segs: vec![Seg::Move(0.0, 0.0), Seg::Line(10.0, 10.0)], fill: None, stroke: Some(([0, 0, 0, 255], 4.0)), even_odd: true }, - Item::Path { segs: vec![Seg::Move(0.0, 0.0), Seg::Line(2e6, 0.0)], fill: None, stroke: None, even_odd: true }, - ], - }; - let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]); - assert_eq!(placed.len(), 1); - let crate::PlacedItem::Path { stroke, .. } = &placed[0] else { panic!("expected a path") }; - assert_eq!(stroke.map(|s| s.1), Some(8.0)); -} - -/// #1899: a crop keeps what the file says down to a sliver (a header's bar is 2.7% of a page-sized -/// metafile), and junk sides give a finite part of the source with some area. -#[test] -fn crop_window_keeps_a_sliver_and_stays_finite() { - let [x, y, w, h] = crate::crop_window([0.0, 0.51771, 0.0, 0.45485]); - assert!(x == 0.0 && w == 1.0 && (y - 0.51771).abs() < 1e-6 && (h - 0.02744).abs() < 1e-5, "{y} {h}"); - let pic = crate::Picture { width: 100.0, height: 1000.0, items: Vec::new() }; - let tf = pic.fit(kurbo::Rect::new(0.0, 0.0, 100.0, 27.44), [0.0, 0.51771, 0.0, 0.45485]).unwrap(); - // The kept band of the source (517.71..545.15) is the frame (0..27.44). - let top = tf * kurbo::Point::new(0.0, 517.71); - let bottom = tf * kurbo::Point::new(0.0, 545.15); - assert!(top.y.abs() < 1e-3 && (bottom.y - 27.44).abs() < 1e-3, "{top:?} {bottom:?}"); - for c in [[f32::NAN, f32::INFINITY, -1.0, 2.0], [0.9; 4], [1.0, 1.0, 0.0, 0.0], [f32::MAX, f32::MIN, f32::NEG_INFINITY, 0.5]] { - let [x, y, w, h] = crate::crop_window(c); - assert!([x, y, w, h].iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && x + w <= 1.0 + 1e-9 && y + h <= 1.0 + 1e-9, "{c:?}"); - } -} - -/// The narrowest crop on the largest frame layout makes (4000 pt, far down a 22-inch page) still -/// places the source's content: none of it is left out as far off the page. -#[test] -fn the_narrowest_crop_on_the_largest_frame_keeps_its_content() { - let pic = crate::Picture { - width: 100.0, - height: 100.0, - items: vec![ - Item::Bitmap { rect: [0.0, 0.0, 100.0, 100.0], width: 1, height: 1, rgba: vec![255; 4] }, - Item::Path { segs: vec![Seg::Move(0.0, 0.0), Seg::Line(100.0, 100.0)], fill: None, stroke: Some(([0, 0, 0, 255], 1.0)), even_odd: false }, - ], - }; - let frame = kurbo::Rect::new(1584.0, 1584.0, 5584.0, 5584.0); - // The last sliver, the first sliver, and sides that overlap. - for crop in [[1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0], [0.9999, 0.6, 0.5, 0.9999]] { - assert_eq!(pic.place(frame, crop).len(), 2, "{crop:?}"); - } -} - -#[test] -fn place_keeps_only_finite_bounded_bitmaps_with_area() { - let bitmap = |rect: [f32; 4]| Item::Bitmap { rect, width: 1, height: 1, rgba: vec![0; 4] }; - let pic = crate::Picture { - width: 100.0, - height: 50.0, - items: vec![ - bitmap([f32::NAN, 0.0, 10.0, 10.0]), - bitmap([0.0, 0.0, 0.0, 10.0]), - bitmap([0.0, 0.0, 2e6, 10.0]), - bitmap([0.0, 0.0, f32::INFINITY, 10.0]), - bitmap([10.0, 5.0, 10.0, 10.0]), - ], - }; - let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]); - assert_eq!(placed.len(), 1); - let crate::PlacedItem::Bitmap { index, rect } = &placed[0] else { panic!("expected a bitmap") }; - assert_eq!((*index, *rect), (4, kurbo::Rect::new(20.0, 10.0, 40.0, 30.0))); -} - -/// `size` against the full parse: same numbers or same error, and whether the header decided it. -fn assert_size_matches_parse(file: &[u8], from_header: bool, what: &str) { - let full = parse(file).map(|p| (p.width, p.height)); - assert_eq!(crate::size(file), full, "{what}"); - assert_eq!(crate::size::header_size(crate::bytes::Bytes(file)).is_some(), from_header, "{what}: header path"); - if let Some(s) = crate::size::header_size(crate::bytes::Bytes(file)) { - assert_eq!(Ok(s), full, "{what}: header size"); - } -} - -#[test] -fn size_from_the_header_equals_the_full_parse() { - let rect = || erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let emfs = [ - ("emf with a frame", emf(&[rect()], [0, 0, 50, 25], [0, 0, 2500, 1250]), true), - ("emf with a large frame", emf(&[rect()], [0, 0, 50, 25], [-90_000, 0, 900_000, 1_250_000]), true), - ("emf with an empty frame", emf(&[rect()], [0, 0, 50, 25], [0; 4]), false), - ("emf with no records", emf(&[], [0, 0, 50, 25], [0, 0, 2500, 1250]), false), - ("emf with no frame and no bounds", emf(&[rect()], [0; 4], [0; 4]), false), - ]; - for (what, file, header) in &emfs { - assert_size_matches_parse(file, *header, what); - } - let draw = [wrec(0x041B, &cat(vec![h16(1440), h16(2880), h16(0), h16(0)]))]; - let wmfs = [ - ("placeable wmf", wmf(&draw, Some([0, 0, 2880, 1440])), true), - ( - "placeable wmf with a window mapping", - wmf( - &[wrec(0x0103, &h16(8)), wrec(0x020C, &cat(vec![h16(100), h16(200)])), wrec(0x020E, &cat(vec![h16(50), h16(100)])), draw[0].clone()], - Some([0, 0, 200, 100]), - ), - false, - ), - ( - "placeable wmf with a zero viewport", - wmf(&[wrec(0x0103, &h16(8)), wrec(0x020E, &cat(vec![h16(0), h16(0)])), draw[0].clone()], Some([0, 0, 200, 100])), - false, - ), - ("placeable wmf with a window only", wmf(&[wrec(0x020C, &cat(vec![h16(100), h16(200)])), draw[0].clone()], Some([0, 0, 200, 100])), true), - ("placeable wmf with an empty box", wmf(&draw, Some([0, 0, 0, 0])), false), - ("placeable wmf with no records", wmf(&[], Some([0, 0, 2880, 1440])), false), - ("plain wmf", wmf(&draw, None), false), - ]; - for (what, file, header) in &wmfs { - assert_size_matches_parse(file, *header, what); - } - assert_size_matches_parse(b"not a metafile at all", false, "garbage"); - assert_size_matches_parse(&[], false, "empty"); -} - -#[test] -fn size_of_a_truncated_or_mutated_file_equals_the_full_parse() { - let rect = erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let draw = wrec(0x041B, &cat(vec![h16(1440), h16(2880), h16(0), h16(0)])); - let files = [emf(&[rect], [0, 0, 50, 25], [0, 0, 2500, 1250]), wmf(&[draw], Some([0, 0, 2880, 1440]))]; - let mut seed = 0x1234_5678_9ABC_DEF0u64; - for file in &files { - for len in 0..=file.len() { - let cut = &file[..len]; - assert_eq!(crate::size(cut), parse(cut).map(|p| (p.width, p.height)), "cut at {len}"); - } - for _ in 0..3000 { - let mut m = file.clone(); - for _ in 0..3 { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - let at = (seed % m.len() as u64) as usize; - m[at] = (seed >> 32) as u8; - } - let full = parse(&m).map(|p| (p.width, p.height)); - let fast = crate::size(&m); - assert_eq!(fast, full, "{m:?}"); - } - } -} - -/// Time of the full parse against the header-only size for an EMF with one 8000 x 5000, 1 bpp bitmap -/// (5 MB, decodes to 160 MB): `cargo test -p wordcraft-metafile --release -- --ignored --nocapture size_speed`. -#[test] -#[ignore = "timing only"] -fn size_speed() { - let (w, h) = (8000i32, 5000i32); - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![ - e32(0), - e32(0), - e32(0), - e32(0), - e32(w), - e32(h), - e32(80), - e32(48), - e32(128), - h32((w / 8 * h) as u32), - e32(0), - e32(0x00CC_0020), - e32(100), - e32(50), - ])); - payload.extend(info_header(w, h, 1, 0)); - payload.extend([0, 0, 0, 0, 255, 255, 255, 0]); - payload.extend((0..(w / 8 * h) as usize).map(|i| (i * 31) as u8)); - let file = emf(&[erec(81, &payload)], [0, 0, 100, 50], [0, 0, 2500, 1250]); - for round in 0..4 { - let t = std::time::Instant::now(); - let full = parse(&file).map(|p| (p.width, p.height)); - let full_ms = t.elapsed().as_secs_f64() * 1e3; - let t = std::time::Instant::now(); - let fast = crate::size(&file); - let fast_ms = t.elapsed().as_secs_f64() * 1e6; - assert_eq!(full, fast); - eprintln!("round {round}: parse {full_ms:.1} ms, size {fast_ms:.1} us"); - } -} - -#[test] -fn take_pixels_returns_only_drawable_bitmaps() { - let mut ok = Item::Bitmap { rect: [0.0; 4], width: 2, height: 1, rgba: vec![7; 8] }; - assert_eq!(ok.take_pixels(), Some((2, 1, vec![7; 8]))); - assert!(matches!(&ok, Item::Bitmap { rgba, .. } if rgba.is_empty()), "the pixels move out"); - let mut short = Item::Bitmap { rect: [0.0; 4], width: 2, height: 2, rgba: vec![0; 8] }; - assert_eq!(short.take_pixels(), None); - let side = crate::MAX_BITMAP_SIDE + 1; - let mut wide = Item::Bitmap { rect: [0.0; 4], width: side, height: 1, rgba: vec![0; side as usize * 4] }; - assert_eq!(wide.take_pixels(), None); - let mut path = Item::Path { segs: Vec::new(), fill: None, stroke: None, even_odd: false }; - assert_eq!(path.take_pixels(), None); - let pic = |width: f32, height: f32| crate::Picture { width, height, items: Vec::new() }; - assert!(pic(1.0, 2.0).has_size()); - assert!(!pic(0.0, 2.0).has_size() && !pic(f32::NAN, 2.0).has_size() && !pic(1.0, f32::INFINITY).has_size()); -} - -/// The rectangle a WMF RECTANGLE record covers, from its path's corners. -fn rect_extent(item: &Item) -> (f32, f32, f32, f32) { - let (segs, ..) = path_segs(item); - let pts: Vec<(f32, f32)> = segs - .iter() - .filter_map(|s| match s { - Seg::Move(x, y) | Seg::Line(x, y) => Some((*x, *y)), - _ => None, - }) - .collect(); - let (xs, ys): (Vec, Vec) = pts.into_iter().unzip(); - let lo = |v: &[f32]| v.iter().copied().fold(f32::MAX, f32::min); - let hi = |v: &[f32]| v.iter().copied().fold(f32::MIN, f32::max); - (lo(&xs), lo(&ys), hi(&xs), hi(&ys)) -} - -#[test] -fn plain_anisotropic_wmf_without_a_viewport_fills_its_window() { - // Anisotropic, window 200 x 100, no viewport (a logo strip saved without a placeable header): the - // window is the target, not a 1 x 1 viewport that squeezes the picture to a point. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020B, &cat(vec![h16(0), h16(0)])), - wrec(0x020C, &cat(vec![h16(100), h16(200)])), - wrec(0x041B, &cat(vec![h16(100), h16(200), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (200.0, 100.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 200.0) && close(y1, 100.0), "{x0} {y0} {x1} {y1}"); -} - -#[test] -fn placeable_wmf_window_records_replace_the_bounds() { - // The placeable bounds say 1440 square (72 points); the file then draws in a window centred on the - // origin, as a coat of arms saved by a drawing program does. The window maps onto the 72-point - // target, so the drawing fills it instead of being blown up around the bounds. - let recs = [ - wrec(0x020C, &cat(vec![h16(2000), h16(2000)])), - wrec(0x020B, &cat(vec![h16(-1000), h16(-1000)])), - wrec(0x041B, &cat(vec![h16(1000), h16(1000), h16(-1000), h16(-1000)])), - ]; - let p = parse(&wmf(&recs, Some([238, 539, 1678, 1979]))).unwrap(); - assert_eq!((p.width, p.height), (72.0, 72.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 72.0) && close(y1, 72.0), "{x0} {y0} {x1} {y1}"); -} - -#[test] -fn placeable_wmf_keeps_its_target_when_the_window_changes_shape() { - // Bounds 600 x 300 (30 x 15 points), then a portrait window 100 x 200 for a bitmap-sized drawing: - // the drawing still fills the target (Word stretches it to the picture's box). - let recs = [wrec(0x0103, &h16(8)), wrec(0x020C, &cat(vec![h16(200), h16(100)])), wrec(0x041B, &cat(vec![h16(200), h16(100), h16(0), h16(0)]))]; - let p = parse(&wmf(&recs, Some([0, 0, 600, 300]))).unwrap(); - assert_eq!((p.width, p.height), (30.0, 15.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 30.0) && close(y1, 15.0), "{x0} {y0} {x1} {y1}"); -} - -#[test] -fn rop2_nop_draws_nothing_until_the_mode_changes() { - // A coat of arms that first draws its bounding rectangle with the R2_NOP mix mode (no output), - // then its shapes with R2_COPYPEN. Restoring a saved state brings R2_NOP back. - let rect = |n: i32| wrec(0x041B, &cat(vec![h16(n), h16(n), h16(0), h16(0)])); - let recs = [wrec(0x0104, &h16(11)), rect(100), wrec(0x001E, &[]), wrec(0x0104, &h16(13)), rect(50), wrec(0x0127, &h16(-1)), rect(20)]; - let p = parse(&wmf(&recs, Some([0, 0, 100, 100]))).unwrap(); - assert_eq!(p.items.len(), 1, "{:?}", p.items); - let (_, _, x1, y1) = rect_extent(&p.items[0]); - // 50 of 100 units in a 5-point picture. - assert!(close(x1, 2.5) && close(y1, 2.5), "{x1} {y1}"); -} - -#[test] -fn plain_wmf_target_comes_from_a_window_that_was_read() { - // A window record too short to read, then the real one: the target is the real window, not the - // 1 x 1 default the short record left in place. A viewport origin set before it is kept. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020D, &cat(vec![h16(0), h16(0)])), - wrec(0x020C, &[]), - wrec(0x020C, &cat(vec![h16(100), h16(200)])), - wrec(0x041B, &cat(vec![h16(100), h16(200), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (200.0, 100.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 200.0) && close(y1, 100.0), "{x0} {y0} {x1} {y1}"); -} - -/// A poly-polygon's group counts are file data: a long list of empty groups adds no ops, so it -/// mustn't reserve room for them either (the canvas charges what a path holds, capacity included). -#[test] -fn empty_poly_groups_reserve_nothing() { - let pts = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]; - let mut counts = vec![0usize; 100_000]; - counts.push(3); - let ops = crate::geom::subpaths(&pts, &counts, true); - assert_eq!(ops.len(), 4, "M L L Z"); - assert!(ops.capacity() <= 8, "capacity {}", ops.capacity()); - // Counts past the points are cut short, and the size still matches. - let ops = crate::geom::subpaths(&pts, &[2, 5, 4], false); - assert_eq!((ops.len(), ops.capacity()), (3, 3)); -} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs deleted file mode 100644 index 54c14271f7..0000000000 --- a/crates/metafile/src/wmf.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! WMF reader (MS-WMF). A file is an optional 22-byte placeable header, a 9-word standard header, then -//! records of (size in 16-bit words, function, parameters). Parameters are read at byte 6 of each record. - -use crate::bytes::Bytes; -use crate::canvas::{Brush, Canvas, Obj, Pen, colorref}; -use crate::dib; -use crate::geom::{self, ArcKind, P}; -use crate::{Error, Frame, MAX_PATH_OPS}; - -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; -const DEFAULT_INCH: f64 = 1440.0; - -pub(crate) fn is_wmf(b: Bytes) -> bool { - if b.u32(0) == Some(PLACEABLE_KEY) { - return true; - } - matches!(b.u16(0), Some(1 | 2)) && b.u16(2) == Some(9) && matches!(b.u16(4), Some(0x100 | 0x300)) -} - -/// Reads all records. Returns the drawing state and the picture frame, or an error when no record -/// could be read at all. -pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { - let placeable = input.u32(0) == Some(PLACEABLE_KEY); - // Placeable bounds: logical corners (left, top, right, bottom) and their size in points. - let (hdr, bounds) = if placeable { - let [l, t, r, b] = [6, 8, 10, 12].map(|o| input.i16(o).map(f64::from)); - let (Some(l), Some(t), Some(r), Some(b)) = (l, t, r, b) else { return Err(Error::BadHeader) }; - let inch = input.u16(14).filter(|v| *v > 0).map_or(DEFAULT_INCH, f64::from); - let (w, h) = (r - l, b - t); - let bounds = (w > 0.0 && h > 0.0).then_some(([l, t, r, b], (w * 72.0 / inch, h * 72.0 / inch))); - (22, bounds) - } else { - (0, None) - }; - let hsize = input.u16(hdr + 2).ok_or(Error::BadHeader)? as usize; - if hsize < 9 { - return Err(Error::BadHeader); - } - let mut pos = hdr.checked_add(hsize.checked_mul(2).ok_or(Error::BadHeader)?).ok_or(Error::BadHeader)?; - // Played into a target like Word does: the placeable bounds are the first window, the target (the - // picture size) the viewport. A plain WMF's target is its first window. - let mut cv = Canvas::new(); - if let Some((c, size)) = bounds { - cv.play_into(Some([c[0], c[1], c[2] - c[0], c[3] - c[1]]), size); - } - let mut player_viewport = bounds.is_some(); - let mut parsed = 0usize; - while !cv.full() { - let (Some(words), Some(func)) = (input.u32(pos), pos.checked_add(4).and_then(|o| input.u16(o))) else { break }; - let Some(len) = (words as usize).checked_mul(2).filter(|l| *l >= 6) else { break }; - let Some(rec) = input.slice(pos, len) else { break }; - if func == 0 { - break; - } - record(&mut cv, func, Bytes(rec)); - if func == 0x020C && cv.window_set && !player_viewport && !cv.viewport_set { - let we = cv.map.window_ext(); - cv.play_into(None, (we.0.abs(), we.1.abs())); - player_viewport = true; - } - parsed += 1; - let Some(next) = pos.checked_add(len) else { break }; - pos = next; - } - if parsed == 0 { - return Err(Error::NoRecords); - } - let frame = match bounds { - // Played into its target: the frame is the target. - Some((_, size)) if !cv.viewport_set && cv.map.uses_extents() => Some(Frame { rect: [0.0, 0.0, size.0, size.1], size: Some(size) }), - // The file set its own viewport, so the drawing is in its device units and the logical bounds - // go through the final mapping. - Some((c, size)) => { - let (a, b) = (cv.map.device((c[0], c[1])), cv.map.device((c[2], c[3]))); - let rect = [a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()]; - (rect[2] > 0.0 && rect[3] > 0.0).then_some(Frame { rect, size: Some(size) }) - } - None if player_viewport && !cv.viewport_set && cv.map.uses_extents() => { - let ve = cv.map.viewport_ext(); - Some(Frame { rect: [0.0, 0.0, ve.0, ve.1], size: None }) - } - None if cv.window_set => Some(Frame { rect: cv.map.window_rect(), size: None }), - None => None, - }; - Ok((cv, frame)) -} - -fn record(cv: &mut Canvas, func: u16, r: Bytes) { - if cv.full() { - return; - } - let _ = match func { - 0x0103 => r.u16(6).map(|m| cv.set_map_mode(u32::from(m))), - 0x0106 => r.u16(6).map(|m| cv.set_polyfill(u32::from(m))), - 0x0104 => r.u16(6).map(|m| cv.set_rop2(u32::from(m))), - // Y is stored before X in these records. - 0x020B => xy16(r, 6).map(|p| cv.set_window_org(p)), - 0x020C => xy16(r, 6).map(|p| cv.set_window_ext(p)), - 0x020D => xy16(r, 6).map(|p| cv.set_viewport_org(p)), - 0x020E => xy16(r, 6).map(|p| cv.set_viewport_ext(p)), - 0x001E => { - cv.save_dc(); - Some(()) - } - 0x0127 => r.i16(6).map(|n| cv.restore_dc(i32::from(n))), - 0x0214 => xy16(r, 6).map(|p| cv.move_to(p)), - 0x0213 => xy16(r, 6).map(|p| cv.line_to(p)), - 0x0325 => counted_points(r).map(|pts| cv.poly(&pts, false, false, true)), - 0x0324 => counted_points(r).map(|pts| cv.poly(&pts, true, true, true)), - 0x0538 => polypolygon(r).map(|ops| cv.shape(ops, true, true)), - 0x041B => rect16(r, 6).map(|[l, t, rr, b]| cv.shape(geom::rect(l, t, rr, b), true, true)), - 0x061C => { - let [ew, eh] = [r.i16(8), r.i16(6)]; - let (Some(ew), Some(eh)) = (ew, eh) else { return }; - rect16(r, 10).map(|[l, t, rr, b]| { - cv.shape(geom::round_rect(l, t, rr, b, f64::from(ew), f64::from(eh)), true, true); - }) - } - 0x0418 => rect16(r, 6).map(|[l, t, rr, b]| cv.shape(geom::ellipse(l, t, rr, b), true, true)), - 0x0817 | 0x081A | 0x0830 => arc16(r).map(|(bounds, s, e)| { - let kind = match func { - 0x0817 => ArcKind::Arc, - 0x081A => ArcKind::Pie, - _ => ArcKind::Chord, - }; - let [l, t, rr, b] = bounds; - cv.shape(geom::arc_shape(l, t, rr, b, s, e, kind), kind != ArcKind::Arc, true); - }), - 0x02FA => create_pen(cv, r), - 0x02FC => create_brush(cv, r), - // Fonts, palettes, pattern brushes and regions take a handle slot too, so later SELECTOBJECT - // handles count them; selecting one draws nothing. - 0x02FB | 0x00F7 | 0x01F9 | 0x0142 | 0x06FF => { - cv.add_object(None, Obj::Other); - Some(()) - } - 0x012D => r.u16(6).map(|h| cv.select(wmf_handle(h))), - 0x01F0 => r.u16(6).map(|h| cv.delete_object(u32::from(h))), - // STRETCHDIB: rop(4) usage(2) srcH srcW ySrc xSrc destH destW yDest xDest, then the DIB. - 0x0F43 => { - let rop = r.u32(6).unwrap_or(0); - dib_blit(cv, r, 28, rop, [i16s(r, 26), i16s(r, 24), i16s(r, 22), i16s(r, 20)], [i16s(r, 18), i16s(r, 16), i16s(r, 14), i16s(r, 12)]) - } - 0x0B41 => dib_stretchblt(cv, r), - 0x0940 => dib_bitblt(cv, r), - _ => Some(()), - }; -} - -/// A 16-bit WMF handle as a canvas object index: stock objects are `0x8000 | index`, which the -/// canvas reads with the 32-bit stock flag. -fn wmf_handle(h: u16) -> u32 { - let h = u32::from(h); - if h & 0x8000 != 0 { (h & 0x7FFF) | 0x8000_0000 } else { h } -} - -/// An i16 field as f64; 0 past the end. -fn i16s(r: Bytes, off: usize) -> f64 { - r.i16(off).map_or(0.0, f64::from) -} - -/// CREATEPENINDIRECT: style, width (x, y), colour. Only the width's x component is used. -fn create_pen(cv: &mut Canvas, r: Bytes) -> Option<()> { - let style = r.u16(6)?; - let width = r.i16(8)?; - let color = r.u32(12)?; - cv.add_object(None, Obj::Pen(Pen { style: u32::from(style), width: f64::from(width), color: colorref(color) })); - Some(()) -} - -/// CREATEBRUSHINDIRECT: style, colour, hatch (hatch is not drawn). -fn create_brush(cv: &mut Canvas, r: Bytes) -> Option<()> { - let style = r.u16(6)?; - let color = r.u32(8)?; - cv.add_object(None, Obj::Brush(Brush { style: u32::from(style), color: colorref(color) })); - Some(()) -} - -/// (x, y) from a Y-then-X pair stored at `off`. -fn xy16(r: Bytes, off: usize) -> Option

{ - Some((f64::from(r.i16(off + 2)?), f64::from(r.i16(off)?))) -} - -/// Rectangle stored as bottom, right, top, left (the order MS-WMF uses for RECTANGLE and ELLIPSE). -fn rect16(r: Bytes, off: usize) -> Option<[f64; 4]> { - let (b, rr, t, l) = (r.i16(off)?, r.i16(off + 2)?, r.i16(off + 4)?, r.i16(off + 6)?); - Some([f64::from(l), f64::from(t), f64::from(rr), f64::from(b)]) -} - -/// ARC, PIE and CHORD: end Y, end X, start Y, start X, then the bounding rectangle (bottom, right, top, left). -fn arc16(r: Bytes) -> Option<([f64; 4], P, P)> { - let end = xy16(r, 6)?; - let start = xy16(r, 10)?; - let bounds = rect16(r, 14)?; - Some((bounds, start, end)) -} - -/// A count of 16-bit points, then the points (POLYLINE, POLYGON). -fn counted_points(r: Bytes) -> Option> { - let n = r.u16(6)? as usize; - r.tail(8)?.points(0, n, false) -} - -/// POLYPOLYGON: polygon count, one 16-bit point count per polygon, then all points. -fn polypolygon(r: Bytes) -> Option> { - let n = r.u16(6)? as usize; - let mut counts = Vec::with_capacity(n); - for i in 0..n { - counts.push(r.u16(i.checked_mul(2)?.checked_add(8)?)? as usize); - } - let total = counts.iter().try_fold(0usize, |a, c| a.checked_add(*c))?; - if total > MAX_PATH_OPS { - return None; - } - let pts = r.tail(n.checked_mul(2)?.checked_add(8)?)?.points(0, total, false)?; - Some(geom::subpaths(&pts, &counts, true)) -} - -/// Whether a DIBBITBLT or DIBSTRETCHBLT record carries a bitmap: without one it is exactly -/// `(function >> 8) + 3` words long (MS-WMF 2.3.1.2, 2.3.1.3). -fn has_bitmap(func: u16, r: Bytes) -> bool { - r.0.len() / 2 > usize::from(func >> 8) + 3 -} - -/// META_DIBBITBLT: rop(4), ySrc, xSrc, then height, width, yDest, xDest and the DIB at 22. The -/// bitmap-less form has a reserved word before the height, so its fields sit 2 bytes later; it, or -/// a source-less raster operation, fills the destination. -fn dib_bitblt(cv: &mut Canvas, r: Bytes) -> Option<()> { - let rop = r.u32(6)?; - if !has_bitmap(0x0940, r) { - cv.fill_rop([i16s(r, 22), i16s(r, 20), i16s(r, 18), i16s(r, 16)], rop); - return Some(()); - } - let dst = [i16s(r, 20), i16s(r, 18), i16s(r, 16), i16s(r, 14)]; - if Canvas::sourceless(rop) { - cv.fill_rop(dst, rop); - return Some(()); - } - let src = [i16s(r, 12), i16s(r, 10), dst[2], dst[3]]; - dib_blit(cv, r, 22, rop, dst, src) -} - -/// META_DIBSTRETCHBLT: rop(4), srcH, srcW, ySrc, xSrc, then destH, destW, yDest, xDest and the DIB at -/// 26. The bitmap-less form has a reserved word after xSrc, so the destination sits 2 bytes later; -/// it, or a source-less raster operation, fills the destination. -fn dib_stretchblt(cv: &mut Canvas, r: Bytes) -> Option<()> { - let rop = r.u32(6)?; - if !has_bitmap(0x0B41, r) { - cv.fill_rop([i16s(r, 26), i16s(r, 24), i16s(r, 22), i16s(r, 20)], rop); - return Some(()); - } - let dst = [i16s(r, 24), i16s(r, 22), i16s(r, 20), i16s(r, 18)]; - if Canvas::sourceless(rop) { - cv.fill_rop(dst, rop); - return Some(()); - } - let src = [i16s(r, 16), i16s(r, 14), i16s(r, 12), i16s(r, 10)]; - dib_blit(cv, r, 26, rop, dst, src) -} - -/// A DIB at `at`, stretched from source rectangle `src` into `dst` (both in logical units, pixels for `src`). -/// The raster operation `rop` decides how the pixels combine (see [`dib::prepare`]). -fn dib_blit(cv: &mut Canvas, r: Bytes, at: usize, rop: u32, dst: [f64; 4], src: [f64; 4]) -> Option<()> { - let dib = r.tail(at)?; - let n = dib::info_len(dib)?; - let info = dib.slice(0, n)?; - let bits = dib.tail(n)?; - let (mut img, dst) = dib::decode_clip(Bytes(info), bits, false, src.map(|v| v as i64), dst)?; - dib::prepare(&mut img, dib::Blend::Rop(rop)); - cv.bitmap(dst, img); - Some(()) -} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 01006d4f63..80c33d85b4 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-doc = { workspace = true } wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-fonts = { workspace = true } wordcraft-layout = { workspace = true } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } craft-pdf = { workspace = true } kurbo = { workspace = true } image = { workspace = true } diff --git a/crates/pdf/src/exporter.rs b/crates/pdf/src/exporter.rs index 77fe80c348..48cfecf374 100644 --- a/crates/pdf/src/exporter.rs +++ b/crates/pdf/src/exporter.rs @@ -90,7 +90,7 @@ impl Exporter<'_> { fn vector(&mut self, key: &str) -> Option> { let doc = self.doc; let bytes = doc.media.get(key)?; - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return None; } if let Some(v) = self.vectors.get(key) { diff --git a/crates/pdf/src/exporter/draw.rs b/crates/pdf/src/exporter/draw.rs index 5ad2f16a36..7ae7c511bf 100644 --- a/crates/pdf/src/exporter/draw.rs +++ b/crates/pdf/src/exporter/draw.rs @@ -324,7 +324,7 @@ impl Exporter<'_> { s.set_fill(None); return; }; - let [cl, ct, vis_w, vis_h] = wordcraft_metafile::crop_window(*crop).map(|v| v as f32); + let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop).map(|v| v as f32); let (fw, fh) = (rect.w / vis_w, rect.h / vis_h); let Some(size) = Size::from_wh(fw.max(0.01), fh.max(0.01)) else { return }; let fade = alpha < 0.999; diff --git a/crates/pdf/src/exporter/text.rs b/crates/pdf/src/exporter/text.rs index d1eeeb74b3..e0038570a0 100644 --- a/crates/pdf/src/exporter/text.rs +++ b/crates/pdf/src/exporter/text.rs @@ -1,6 +1,6 @@ use super::{ - Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, glyph_outlines, - left_to_right, norm, ok, paint_of, rgb, split_clusters, visual_order, + Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rect, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, + glyph_outlines, left_to_right, norm, ok, paint_of, rect_path, rgb, split_clusters, visual_order, }; /// How a run of glyphs is painted: its colour, opacity and synthetic bold and italic. @@ -181,11 +181,11 @@ impl Exporter<'_> { } /// Draws a metafile text run as PDF text (outlines when the font cannot be embedded). `tf` maps - /// the run's own space (see [`PlacedItem::Text`]) to the page. - pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &wordcraft_metafile::Text, tf: kurbo::Affine) { + /// its text space (`craft_metafile::Text::transform`) to the page. + pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &craft_metafile::Text, tf: kurbo::Affine) { let (face, shaped) = wordcraft_layout::metafile_text_run(t); let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect(); - let Some(lay) = t.layout(face.upem, face.ascent, face.descent, &glyphs) else { return }; + let Some(lay) = wordcraft_layout::metafile_text_layout(t, face.upem, face.ascent, face.descent, &glyphs) else { return }; let font = self.font(&face); if font.is_none() && !self.outlined.contains(&face.id()) { return; @@ -198,6 +198,15 @@ impl Exporter<'_> { let (paint, opacity) = paint_of(t.color); s.push_transform(&Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5])); s.set_stroke(None); + // An opaque background mode fills the character cells first. + if let Some(bg) = t.background { + let [x0, y0, x1, y1] = lay.cell.map(|v| v as f32); + if let Some(cell) = rect_path(&Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }) { + let (paint, opacity) = paint_of(bg); + s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero })); + s.draw_path(&cell); + } + } s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero })); match font { Some(font) => { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index de43694a7f..e4454f0694 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -28,6 +28,7 @@ use std::collections::{HashMap, HashSet}; use std::num::NonZeroU16; use std::sync::Arc; +use craft_metafile::{Picture, PlacedItem}; use craft_pdf::write::{self, Metadata, WriteError, Writer, backend as krilla}; use krilla::annotation::{Annotation, LinkAnnotation, Target}; use krilla::color::rgb; @@ -52,7 +53,6 @@ use wordcraft_layout::display::Paint; use wordcraft_layout::display::{Draw, ItemDisplay, Stroke as LineStyle}; use wordcraft_layout::para::{ClKind, LineEnd}; use wordcraft_layout::{DocLayout, LayoutCache, NumeralMode, Page, Placed, layout}; -use wordcraft_metafile::{Picture, PlacedItem}; mod export; mod exporter; diff --git a/crates/pdf/src/picture.rs b/crates/pdf/src/picture.rs index 66b9938a0b..59c2f15d6a 100644 --- a/crates/pdf/src/picture.rs +++ b/crates/pdf/src/picture.rs @@ -1,28 +1,51 @@ use super::exporter::Exporter; use super::paint::{append_path, norm}; use super::{ - Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, Surface, Transform, rgb, + Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, StrokeDash, Surface, + Transform, krilla, rgb, }; +use craft_metafile::Item; +use kurbo::Shape as _; use wordcraft_doc::picfx::PicFx; /// Largest picture side we embed (pixels). const MAX_IMAGE_SIDE: u32 = 30_000; -/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps are -/// embedded images, one per picture item (None for paths and undecodable bitmaps). +/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps and +/// pattern tiles are embedded images, one per picture item (None for paths, text and undecodable +/// bitmaps). Fills that share a tile share its image. `averages` holds each pattern fill's tile +/// average color (transparent for other items), computed once a tile. pub(crate) struct Vector { pic: Picture, images: Vec>, + averages: Vec<[u8; 4]>, } -/// Parses a metafile and embeds its bitmaps. None when the picture has no usable size. +/// Parses a metafile and embeds its bitmaps and pattern tiles. None when the picture has no usable +/// size. pub(crate) fn build_vector(bytes: &[u8]) -> Option { - let mut pic = wordcraft_metafile::parse(bytes).ok()?; + let mut pic = craft_metafile::parse(bytes).ok()?; if !pic.has_size() { return None; } - let images = pic.items.iter_mut().map(|it| it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h))).collect(); - Some(Vector { pic, images }) + let mut tiles: std::collections::HashMap, [u8; 4])> = std::collections::HashMap::new(); + let (images, averages) = pic + .items + .iter_mut() + .map(|it| match it { + Item::Pattern { tile, .. } => tiles + .entry(Arc::as_ptr(tile) as usize) + .or_insert_with(|| { + let n = (tile.width as usize).saturating_mul(tile.height as usize).saturating_mul(4); + let img = (tile.width > 0 && tile.height > 0 && tile.rgba.len() == n) + .then(|| Image::from_rgba8(tile.rgba.clone(), tile.width, tile.height)); + (img, wordcraft_layout::metafile_average_color(&tile.rgba)) + }) + .clone(), + _ => (it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h)), [0; 4]), + }) + .unzip(); + Some(Vector { pic, images, averages }) } /// A straight RGBA colour as a krilla colour and opacity. @@ -36,9 +59,10 @@ pub(crate) fn paint_of(c: [u8; 4]) -> (rgb::Color, NormalizedF32) { const HAIRLINE: f64 = 0.25; /// Draws a metafile picture into the clip (the picture frame): paths are filled and stroked in page -/// space (strokes keep their width under non-uniform scaling), bitmaps stretched, all faded by `alpha`. -/// Every path sets its fill and stroke, so none carries over; strokes have round caps and joins. Text -/// runs are drawn as text. +/// space (strokes keep their width under non-uniform scaling), bitmaps stretched (or turned by their +/// transform), pattern fills tiled, each item inside its clip region and clip paths, all faded by +/// `alpha`. Every path sets its fill and stroke, so none carries over; strokes take the pen's caps, +/// joins and dashes. Text runs are drawn as text. pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: &Rect, crop: &[f32; 4], clip: &Path, alpha: f32) { let target = kurbo::Rect::new(f64::from(r.x), f64::from(r.y), f64::from(r.x + r.w), f64::from(r.y + r.h)); let fade = alpha < 0.999; @@ -46,9 +70,9 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: s.push_opacity(norm(alpha)); } s.push_clip_path(clip, &FillRule::NonZero); - for it in v.pic.place(target, *crop) { + for it in v.pic.place(target, wordcraft_layout::crop_sides(*crop)) { match it { - PlacedItem::Path { path, fill, stroke, even_odd } => { + PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => { let Some(p) = path_from(&path) else { continue }; let fill = fill.map(|c| { let (paint, opacity) = paint_of(c); @@ -57,30 +81,63 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: }); let stroke = stroke.map(|(c, w)| { let (paint, opacity) = paint_of(c); - Stroke { - paint: paint.into(), - width: w.max(HAIRLINE) as f32, - opacity, - line_cap: LineCap::Round, - line_join: LineJoin::Round, - ..Default::default() - } + pen(paint.into(), opacity, w, &line, &path) }); + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; s.set_fill(fill); s.set_stroke(stroke); s.draw_path(&p); + pop_clips(s, n); } - PlacedItem::Bitmap { index, rect } => { + PlacedItem::Bitmap { index, rect, transform, region, clips } => { let Some(Some(img)) = v.images.get(index) else { continue }; - let Some(size) = Size::from_wh(rect.width() as f32, rect.height() as f32) else { continue }; - s.push_transform(&Transform::from_translate(rect.x0 as f32, rect.y0 as f32)); + let c = transform.as_coeffs(); + // Upright and not mirrored: the bitmap fills `rect`. + let upright = c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0; + let (tf, size) = if upright { + (Transform::from_translate(rect.x0 as f32, rect.y0 as f32), Size::from_wh(rect.width() as f32, rect.height() as f32)) + } else { + // A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place. + let c = c.map(|v| v as f32); + (Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), Size::from_wh(1.0, 1.0)) + }; + let Some(size) = size else { continue }; + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; + s.push_transform(&tf); s.draw_image(img.clone(), size); s.pop(); + pop_clips(s, n); } - PlacedItem::Text { index, tf } => { - if let Some(wordcraft_metafile::Item::Text(t)) = v.pic.items.get(index) { - ex.vector_text(s, t, tf); + PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => { + let Some(p) = path_from(&path) else { continue }; + let Some(craft_metafile::Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { continue }; + let rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; + let paint = match v.images.get(index) { + Some(Some(img)) => tile_pattern(s, img, t.width, t.height, tile).map(|p| (p.into(), norm(1.0))), + _ => None, + }; + let (paint, opacity) = paint.unwrap_or_else(|| { + let (c, o) = paint_of(v.averages.get(index).copied().unwrap_or([0; 4])); + (c.into(), o) + }); + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; + s.set_fill(Some(Fill { paint, opacity, rule })); + s.set_stroke(None); + s.draw_path(&p); + pop_clips(s, n); + } + PlacedItem::Text { index, transform, clip, region, clips } => { + let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) else { continue }; + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; + let text_clip = clip.and_then(|c| path_from(&c.to_path(0.1))); + if let Some(c) = &text_clip { + s.push_clip_path(c, &FillRule::NonZero); } + ex.vector_text(s, t, transform); + if text_clip.is_some() { + s.pop(); + } + pop_clips(s, n); } } } @@ -92,6 +149,69 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: } } +/// Pushes a metafile item's clip region and clip paths; pop them with [`pop_clips`] and the count +/// returned. None (nothing pushed) when a clip has no area to draw in. +fn push_clips(s: &mut Surface, region: Option<&kurbo::BezPath>, clips: &[Arc]) -> Option { + let mut paths = Vec::with_capacity(clips.len() + 1); + if let Some(region) = region { + paths.push((path_from(region)?, FillRule::NonZero)); + } + for c in clips { + paths.push((path_from(&c.path)?, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero })); + } + for (p, rule) in &paths { + s.push_clip_path(p, rule); + } + Some(paths.len()) +} + +fn pop_clips(s: &mut Surface, n: usize) { + for _ in 0..n { + s.pop(); + } +} + +/// A metafile pen for `path`: `width` (points, at least [`HAIRLINE`]), the pen's caps, joins, +/// miter limit and dashes (`wordcraft_layout::metafile_dashes`, with the hairline as the pixel). +fn pen(paint: krilla::paint::Paint, opacity: NormalizedF32, width: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> Stroke { + let line_cap = match line.cap { + craft_metafile::Cap::Round => LineCap::Round, + craft_metafile::Cap::Square => LineCap::Square, + craft_metafile::Cap::Flat => LineCap::Butt, + }; + let line_join = match line.join { + craft_metafile::Join::Round => LineJoin::Round, + craft_metafile::Join::Bevel => LineJoin::Bevel, + craft_metafile::Join::Miter => LineJoin::Miter, + }; + let dash = if line.dash.is_empty() { None } else { wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, HAIRLINE, path.perimeter(1.0)) }; + Stroke { + paint, + width: width.max(HAIRLINE) as f32, + miter_limit: wordcraft_layout::metafile_miter_limit(line.miter_limit), + line_cap, + line_join, + opacity, + dash: dash.map(|d| StrokeDash { array: d.iter().map(|v| *v as f32).collect(), offset: 0.0 }), + } +} + +/// A tiling pattern of `img` (`w` × `h` pixels); `tile` maps tile pixels to page space. None when +/// the mapping is not finite. +fn tile_pattern(s: &mut Surface, img: &Image, w: u32, h: u32, tile: kurbo::Affine) -> Option { + let c = tile.as_coeffs().map(|v| v as f32); + if !c.iter().all(|v| v.is_finite()) { + return None; + } + let size = Size::from_wh(w as f32, h as f32)?; + let mut sb = s.stream_builder(); + let mut ps = sb.surface(); + ps.draw_image(img.clone(), size); + ps.finish(); + let stream = sb.finish(); + Some(krilla::paint::Pattern { stream, transform: Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), width: w as f32, height: h as f32 }) +} + /// A kurbo path as a krilla path (None when empty). fn path_from(b: &kurbo::BezPath) -> Option { let mut pb = PathBuilder::new(); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index d767b7b644..490eafb1b2 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1306,6 +1306,117 @@ fn emf_rec(typ: u32, fields: &[i32]) -> Vec { v } +/// The PDF of a document holding one 70 pt metafile picture, uncompressed. +fn metafile_pdf(emf: Vec) -> String { + String::from_utf8_lossy(&metafile_pdf_bytes(emf)).into_owned() +} + +fn metafile_pdf_bytes(emf: Vec) -> Vec { + let mut d = Document::new(); + let media = d.add_media(emf, "emf"); + let mut p = Paragraph::with_text("Figure: ", CharProps::default()); + let n = p.len(); + p.insert_object( + n, + InlineObject::Image { + media, + w: 70.0, + h: 70.0, + alt: String::new(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }, + &CharProps::default(), + ) + .unwrap(); + d.body = vec![para_block(p)]; + export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap() +} + +/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a 32bppPARGB bitmap: the bitmap is +/// embedded as an image. +#[test] +fn emf_plus_only_bitmap_is_embedded() { + let plus_rec = |typ: u16, flags: u16, data: &[u8]| { + let mut v = typ.to_le_bytes().to_vec(); + v.extend(flags.to_le_bytes()); + v.extend(((12 + data.len()) as u32).to_le_bytes()); + v.extend((data.len() as u32).to_le_bytes()); + v.extend(data); + v + }; + let le32 = |vals: &[i32]| -> Vec { vals.iter().flat_map(|v| v.to_le_bytes()).collect() }; + let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96])); + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 2, 8, 0x000E_200B, 0]); + image.extend([0u8, 0, 255, 255].repeat(4)); + let object = plus_rec(0x4008, 0x0500, &image); + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, 2.0, 2.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes())); + let draw = plus_rec(0x401A, 0, &draw); + let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec(); + comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat()); + let mut rec = 70u32.to_le_bytes().to_vec(); + rec.extend(((12 + comment.len()) as u32).to_le_bytes()); + rec.extend((comment.len() as u32).to_le_bytes()); + rec.extend(comment); + let bytes = metafile_pdf_bytes(emf_file(&[rec, emf_rec(14, &[0; 3])])); + let images = pdf_images(&bytes); + assert!(images.iter().any(|(w, h, ..)| (*w, *h) == (2, 2)), "the 2 × 2 bitmap is embedded"); + assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn"); +} + +/// A dotted cosmetic pen (CREATEPEN, PS_DOT, width 0) draws hairline dots: its dashes and gaps are +/// the hairline's width, not the file's device units scaled to the frame (0.7 pt here). +#[test] +fn metafile_cosmetic_dotted_pen_draws_hairline_dots() { + let recs = [emf_rec(38, &[1, 2, 0, 0, 0]), emf_rec(37, &[1]), emf_rec(27, &[0, 50]), emf_rec(54, &[100, 50]), emf_rec(14, &[0; 3])]; + let raw = metafile_pdf(emf_file(&recs)); + assert!(raw.contains("[0.25 0.25]0 d"), "the dots are hairline-sized"); +} + +/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below the hairline draws its line +/// solid: no dash array is written. +#[test] +fn metafile_sub_pixel_dashes_draw_solid() { + let mut emf = emf_file(&[]); + // 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide. + let le32 = |vals: &[i32]| -> Vec { vals.iter().flat_map(|v| v.to_le_bytes()).collect() }; + emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000])); + emf[72..80].copy_from_slice(&le32(&[10_000, 10_000])); + let pen = emf_rec(95, &[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]); + let recs = [pen, emf_rec(37, &[1]), emf_rec(27, &[0, 500]), emf_rec(54, &[1000, 500]), emf_rec(14, &[0; 3])]; + emf.extend(recs.concat()); + let raw = metafile_pdf(emf); + assert!(raw.contains(" w ") && !raw.contains("]0 d"), "a stroke with no dash array"); +} + +/// A clip region (INTERSECTCLIPRECT) adds a clip around the rectangle it clips. +#[test] +fn metafile_clip_region_is_a_clip() { + let clips = |raw: &str| raw.matches("\nW\nn").count() + raw.matches("\nW*\nn").count(); + let draw = |clip: bool| { + let mut recs = vec![emf_rec(39, &[1, 0, 0x0000_00FF, 0]), emf_rec(37, &[1])]; + if clip { + recs.push(emf_rec(30, &[0, 0, 50, 100])); + } + recs.extend([emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]); + metafile_pdf(emf_file(&recs)) + }; + let (with, without) = (clips(&draw(true)), clips(&draw(false))); + assert!(without > 0 && with == without + 1, "one clip more with the region: {with} and {without}"); +} + +/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED) fills through a tiling pattern, not with a +/// solid color. +#[test] +fn metafile_hatch_brush_is_a_tiling_pattern() { + let recs = [emf_rec(39, &[1, 2, 0x0000_00FF, 1]), emf_rec(37, &[1]), emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]; + let raw = metafile_pdf(emf_file(&recs)); + assert!(raw.contains("/PatternType 1"), "the hatch is a tiling pattern"); +} + #[test] fn metafile_strokes_use_round_caps_and_joins() { // A 4-unit black pen (handle 1) outlines a rectangle, so the stroke is drawn with round caps and joins. @@ -1426,6 +1537,17 @@ fn emf_text_records(text: &str) -> Vec> { vec![font, emf_rec(37, &[1]), emf_rec(24, &[0]), out] } +/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text +/// run's character cells are filled red behind the text. +#[test] +fn metafile_text_fills_its_opaque_background() { + let mut recs = vec![emf_rec(25, &[0x0000_00FF])]; + recs.extend(emf_text_records("Hi")); + recs.push(emf_rec(14, &[0; 3])); + let raw = metafile_pdf(emf_file(&recs)); + assert!(raw.contains("1 0 0 rg"), "the character cells are filled red"); +} + /// #1764: the text of an EMF picture (EXTTEXTOUTW) is drawn, so it is in the PDF's text layer. #[test] fn metafile_text_records_are_drawn_as_text() { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 99aa12093b..0224baed65 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } wordcraft-layout = { workspace = true } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } vello_cpu = { workspace = true } image = { workspace = true } log = { workspace = true } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8e57e07713..f4befb2459 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, Weak}; +use craft_metafile::{Item, Picture, PlacedItem, Seg}; use vello_cpu::kurbo::{self, Affine, BezPath, Shape}; use vello_cpu::peniko; use vello_cpu::{Pixmap, RenderContext, Resources}; @@ -14,7 +15,6 @@ use wordcraft_fonts::FontDb; use wordcraft_layout::Page; use wordcraft_layout::display::Paint; use wordcraft_layout::display::{DisplayOptions, Draw, Stroke, page_layers}; -use wordcraft_metafile::{Item, Picture, PlacedItem, Seg}; mod media; @@ -858,7 +858,7 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) { return; }; let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64); - let [cl, ct, vis_w, vis_h] = wordcraft_metafile::crop_window(*crop); + let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop); let sx = r.width() / (pw * vis_w); let sy = r.height() / (ph * vis_h); ctx.set_transform(view); diff --git a/crates/render/src/media.rs b/crates/render/src/media.rs index 2dbf1faf88..73c484e0ae 100644 --- a/crates/render/src/media.rs +++ b/crates/render/src/media.rs @@ -126,11 +126,11 @@ pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { /// extension it is stored under (`"wmf"` or `"emf"`), or None for anything else (#802). Very large /// frames are scaled down to 22 inches on the longer side, keeping the shape. pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> { - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return None; } // The frame comes from the header where the file has one, so no bitmap is decoded for it. - let (w, h) = wordcraft_metafile::size(bytes).ok()?; + let (w, h) = craft_metafile::size(bytes).ok()?; if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } @@ -140,28 +140,50 @@ pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> { Some((w * k, h * k, ext)) } -/// A metafile (WMF/EMF) picture, parsed once. The geometry comes placed by the metafile crate; the -/// bitmaps are pixmaps, one per picture item (None for paths and undecodable bitmaps). +/// A metafile (WMF/EMF/EMF+) picture, parsed once. The geometry comes placed by the metafile crate; +/// the bitmaps and pattern tiles are pixmaps, one per picture item (None for paths, text and +/// undecodable bitmaps). Fills that share a tile share its pixmap. `averages` holds each pattern +/// fill's tile average color (transparent for other items), computed once a tile. pub(crate) struct Vector { pic: Picture, pixmaps: Vec>>, + averages: Vec<[u8; 4]>, } impl Vector { - /// Approximate memory held: pixels and path segments. - fn bytes(&self) -> usize { - let px: usize = self.pixmaps.iter().flatten().map(|p| p.width() as usize * p.height() as usize * 4).sum(); - let segs: usize = self - .pic - .items - .iter() - .map(|it| match it { - Item::Path { segs, .. } => segs.len() * std::mem::size_of::(), - Item::Bitmap { .. } => 0, - Item::Text(t) => t.text.len() + t.dx.len() * 4, - }) - .sum(); - px + segs + /// Approximate memory held: pixmaps, the pattern tiles' own pixels, path segments, dash + /// patterns, clip regions, clip lists, clip paths and text, each shared allocation once. + pub(crate) fn bytes(&self) -> usize { + let mut seen = std::collections::HashSet::new(); + let mut total = self.averages.len() * 4; + for p in self.pixmaps.iter().flatten() { + if seen.insert(Arc::as_ptr(p) as usize) { + total = total.saturating_add(p.width() as usize * p.height() as usize * 4); + } + } + let seg = std::mem::size_of::(); + for it in &self.pic.items { + let (own, region, clips) = match it { + Item::Path { segs, line, region, clips, .. } => ((segs.len() * seg).saturating_add(line.dash.len() * 4), region, clips), + Item::Pattern { segs, tile, region, clips, .. } => { + let tile_bytes = if seen.insert(Arc::as_ptr(tile) as usize) { tile.rgba.len() } else { 0 }; + ((segs.len() * seg).saturating_add(tile_bytes), region, clips) + } + Item::Bitmap { region, clips, .. } => (0, region, clips), + Item::Text(t) => (t.text.len() + t.dx.len() * 4, &t.region, &t.clips), + }; + // Each item holds its own copy of the clip region's rectangles and its own list of the + // clip paths it shares. + let region = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>()); + let list = clips.len() * std::mem::size_of::>(); + total = total.saturating_add(own).saturating_add(region).saturating_add(list); + for c in clips { + if seen.insert(Arc::as_ptr(c) as usize) { + total = total.saturating_add(c.segs.len() * seg); + } + } + } + total } } @@ -169,7 +191,7 @@ impl Vector { /// the caller falls back to the raster path (and the grey box). pub(crate) fn vector_for(doc: &Document, key: &str) -> Option> { let bytes = doc.media.get(key)?; - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return None; } if let Some(v) = lock(vectors()).get(key, bytes) { @@ -184,25 +206,45 @@ pub(crate) fn vector_for(doc: &Document, key: &str) -> Option> { v } -/// Parses a metafile and decodes its bitmaps. None when the picture has no usable size. -fn build_vector(bytes: &[u8]) -> Option { - let mut pic = wordcraft_metafile::parse(bytes).ok()?; +/// Parses a metafile and decodes its bitmaps and pattern tiles. None when the picture has no +/// usable size. +pub(crate) fn build_vector(bytes: &[u8]) -> Option { + let mut pic = craft_metafile::parse(bytes).ok()?; if !pic.has_size() { return None; } - // The pixels move into the pixmaps; the picture keeps only the geometry. - let pixmaps = pic.items.iter_mut().map(|it| it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new)).collect(); - Some(Vector { pic, pixmaps }) + // The pixels move into the pixmaps; the picture keeps only the geometry. A tile shared by + // several fills is converted and averaged once. + let mut tiles: HashMap>, [u8; 4])> = HashMap::new(); + let (pixmaps, averages) = pic + .items + .iter_mut() + .map(|it| match it { + Item::Pattern { tile, .. } => tiles + .entry(Arc::as_ptr(tile) as usize) + .or_insert_with(|| { + (premul_pixmap(tile.width, tile.height, &tile.rgba).map(Arc::new), wordcraft_layout::metafile_average_color(&tile.rgba)) + }) + .clone(), + _ => (it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new), [0; 4]), + }) + .unzip(); + Some(Vector { pic, pixmaps, averages }) } fn rgba_color(c: [u8; 4]) -> peniko::Color { peniko::Color::from_rgba8(c[0], c[1], c[2], c[3]) } +/// Pattern tiles smaller than this (device pixels on both sides) are drawn as the tile's average +/// color: a sub-pixel pattern would only alias. +const MIN_TILE_PX: f64 = 1.5; + /// Draws a metafile picture into `r` (page points): fills and strokes in page space (so strokes keep -/// their width under non-uniform scaling), bitmaps stretched, all clipped to `r` and faded by `alpha`. -/// Strokes have round caps and joins, as GDI draws them, and are at least one device pixel wide, so -/// cosmetic (width 0) pens show as hairlines at any zoom. +/// their width under non-uniform scaling), bitmaps stretched (or turned by their transform), +/// pattern fills tiled, each item inside its clip region and clip paths, all clipped to `r` and +/// faded by `alpha`. Strokes take the pen's caps, joins and dashes and are at least one device +/// pixel wide, so cosmetic (width 0) pens show as hairlines at any zoom. pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, crop: &[f32; 4], alpha: f32, view: Affine) { ctx.set_transform(view); let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 }; @@ -212,9 +254,9 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, } ctx.push_clip_layer(&r.to_path(0.1)); let pixel = device_pixel(view); - for it in v.pic.place(*r, *crop) { + for it in v.pic.place(*r, wordcraft_layout::crop_sides(*crop)) { match it { - PlacedItem::Path { path, fill, stroke, even_odd } => { + PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| { if let Some(f) = fill { ctx.set_paint(rgba_color(f)); ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero }); @@ -222,25 +264,71 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, } if let Some((s, w)) = stroke { ctx.set_paint(rgba_color(s)); - ctx.set_stroke(kurbo::Stroke::new(w.max(pixel)).with_caps(kurbo::Cap::Round).with_join(kurbo::Join::Round)); + ctx.set_stroke(pen(w, pixel, &line, &path)); ctx.stroke_path(&path); } - } - PlacedItem::Bitmap { index, rect } => { - let Some(Some(pm)) = v.pixmaps.get(index) else { continue }; + }), + PlacedItem::Bitmap { index, rect, transform, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| { + let Some(Some(pm)) = v.pixmaps.get(index) else { return }; let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64); ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm.clone()), sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium), }); - ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph)); - ctx.fill_rect(&rect); - ctx.reset_paint_transform(); - } - PlacedItem::Text { index, tf } => { - if let Some(Item::Text(t)) = v.pic.items.get(index) { - draw_vector_text(ctx, t, view * tf); + let c = transform.as_coeffs(); + // Upright and not mirrored: the bitmap fills `rect`. + if c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0 { + ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph)); + ctx.fill_rect(&rect); + } else { + // A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place. + ctx.set_paint_transform(transform * Affine::scale_non_uniform(1.0 / pw, 1.0 / ph)); + ctx.fill_path(&(transform * kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1))); } + ctx.reset_paint_transform(); + }), + PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| { + let Some(Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { return }; + ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero }); + // `tile` maps one tile pixel to page points: the tile's sides are its columns and + // its rows under that, in device pixels. The tile is drawn when either side is at + // least `MIN_TILE_PX`. + let c = (view * tile).as_coeffs(); + let across = c[0].hypot(c[1]) * f64::from(t.width); + let down = c[2].hypot(c[3]) * f64::from(t.height); + match v.pixmaps.get(index) { + Some(Some(pm)) if across.max(down) >= MIN_TILE_PX => { + ctx.set_paint(vello_cpu::Image { + image: vello_cpu::ImageSource::Pixmap(pm.clone()), + sampler: peniko::ImageSampler { + x_extend: peniko::Extend::Repeat, + y_extend: peniko::Extend::Repeat, + quality: peniko::ImageQuality::Low, + alpha: 1.0, + }, + }); + ctx.set_paint_transform(tile); + ctx.fill_path(&path); + ctx.reset_paint_transform(); + } + _ => { + ctx.set_paint(rgba_color(v.averages.get(index).copied().unwrap_or([0; 4]))); + ctx.fill_path(&path); + } + } + }), + PlacedItem::Text { index, transform, clip, region, clips } => { + clipped(ctx, region.as_deref(), &clips, |ctx| { + let Some(Item::Text(t)) = v.pic.items.get(index) else { return }; + if let Some(c) = clip { + ctx.push_clip_layer(&c.to_path(0.1)); + } + draw_vector_text(ctx, t, view * transform); + ctx.set_transform(view); + if clip.is_some() { + ctx.pop_layer(); + } + }); ctx.set_transform(view); } } @@ -252,15 +340,76 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, } } -/// Draws a metafile text run: `tf` maps the run's own space (see [`PlacedItem::Text`]) to the device. -fn draw_vector_text(ctx: &mut RenderContext, t: &wordcraft_metafile::Text, tf: Affine) { +/// Draws `draw` inside a metafile item's clip region and every one of its clip paths (page +/// points, under the current transform). No region is the default clip. +fn clipped( + ctx: &mut RenderContext, + region: Option<&kurbo::BezPath>, + clips: &[Arc], + draw: impl FnOnce(&mut RenderContext), +) { + if let Some(region) = region { + ctx.set_fill_rule(peniko::Fill::NonZero); + ctx.push_clip_layer(region); + } + for c in clips { + ctx.set_fill_rule(if c.even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero }); + ctx.push_clip_layer(&c.path); + } + ctx.set_fill_rule(peniko::Fill::NonZero); + draw(ctx); + for _ in 0..clips.len() + usize::from(region.is_some()) { + ctx.pop_layer(); + } +} + +/// A metafile pen for `path` as a stroke `width` wide (page points, at least one device `pixel`): +/// its caps, joins, miter limit and dashes (`wordcraft_layout::metafile_dashes`). +fn pen(width: f64, pixel: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> kurbo::Stroke { + let cap = match line.cap { + craft_metafile::Cap::Round => kurbo::Cap::Round, + craft_metafile::Cap::Square => kurbo::Cap::Square, + craft_metafile::Cap::Flat => kurbo::Cap::Butt, + }; + let join = match line.join { + craft_metafile::Join::Round => kurbo::Join::Round, + craft_metafile::Join::Bevel => kurbo::Join::Bevel, + craft_metafile::Join::Miter => kurbo::Join::Miter, + }; + let stroke = kurbo::Stroke::new(width.max(pixel)) + .with_caps(cap) + .with_join(join) + .with_miter_limit(f64::from(wordcraft_layout::metafile_miter_limit(line.miter_limit))); + if line.dash.is_empty() { + return stroke; + } + match wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, pixel, path.perimeter(1.0)) { + Some(dash) => stroke.with_dashes(0.0, dash), + None => stroke, + } +} + +/// Draws a metafile text run: `tf` maps its text space (`craft_metafile::Text::transform`) to the +/// device. +fn draw_vector_text(ctx: &mut RenderContext, t: &craft_metafile::Text, tf: Affine) { let (face, shaped) = wordcraft_layout::metafile_text_run(t); let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect(); - let Some(lay) = t.layout(face.upem, face.ascent, face.descent, &glyphs) else { return }; + let Some(lay) = wordcraft_layout::metafile_text_layout(t, face.upem, face.ascent, face.descent, &glyphs) else { return }; let k = lay.em / face.upem.max(1.0); + let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); + // An opaque background mode fills the character cells first. + if let Some(bg) = t.background { + let [x0, y0, x1, y1] = lay.cell; + let cell = tf * kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + let b = cell.bounding_box(); + if x1 > x0 && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_GLYPH_PIXELS * 16.0) && b.overlaps(canvas) { + ctx.set_transform(Affine::IDENTITY); + ctx.set_paint(rgba_color(bg)); + ctx.fill_path(&cell); + } + } ctx.set_paint(rgba_color(t.color)); let db = FontDb::global(); - let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); let mut oversized = 0usize; for (g, (x, y)) in shaped.iter().zip(&lay.glyphs) { let o = db.outline(&face, g.gid); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index c18f75790d..9e11f56461 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1037,6 +1037,237 @@ fn metafile_picture_is_drawn_as_vectors() { assert!(left[..3].iter().all(|c| *c > 200), "left half should be paper, not the grey box: {left:?}"); } +/// #6636: an EMF+ only file (no plain EMF drawing records) whose EmfPlusDrawImage draws a +/// 32bppPARGB bitmap over the right half: the bitmap's pixels are drawn. +#[test] +fn emf_plus_only_bitmap_is_drawn() { + // EmfPlusObject 0, an image (type 5): a 2 × 1 bitmap in PixelFormat32bppPARGB, opaque red + // and then red at half opacity (premultiplied BGRA 0, 0, 128, 128). + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]); + image.extend([0u8, 0, 255, 255, 0, 0, 128, 128]); + let object = plus_rec(0x4008, 0x0500, &image); + // EmfPlusDrawImage of image 0: the whole bitmap (pixel units) into x 50..100, y 0..100. + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, 2.0, 1.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes())); + let emf = emf_plus_file(&[object, plus_rec(0x401A, 0, &draw)]); + + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32); + let (opaque, half, left) = (at(0.6), at(0.9), at(0.25)); + assert!(is_red(opaque), "the bitmap's opaque red is drawn on the right half: {opaque:?}"); + // Premultiplied half-opacity red over white paper is (255, 127, 127); read as straight + // color it would be about (191, 127, 127). + assert!(half[0] > 235 && (110..145).contains(&half[1]) && (110..145).contains(&half[2]), "half-opacity red: {half:?}"); + assert!(is_paper(left), "left half should be paper: {left:?}"); +} + +/// An EMF+ record for [`emf_plus_file`]: type, flags and data. +fn plus_rec(typ: u16, flags: u16, data: &[u8]) -> Vec { + let mut v = typ.to_le_bytes().to_vec(); + v.extend(flags.to_le_bytes()); + v.extend(((12 + data.len()) as u32).to_le_bytes()); + v.extend((data.len() as u32).to_le_bytes()); + v.extend(data); + v +} + +/// An EMF+ only file with the frame of [`red_right_half_emf`]: an EmfPlusHeader (96 dpi), then +/// `records`, then EmfPlusEndOfFile, in one comment record. +fn emf_plus_file(records: &[Vec]) -> Vec { + let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec(); + comment.extend(plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]))); + comment.extend(records.concat()); + comment.extend(plus_rec(0x4002, 0, &[])); + let mut payload = (comment.len() as u32).to_le_bytes().to_vec(); + payload.extend(comment); + let mut emf = red_right_half_emf()[..88].to_vec(); + emf.extend([emf_rec(70, &payload), emf_rec(14, &[0; 12])].concat()); + emf +} + +/// Renders a document holding one 70 pt metafile picture with `crop` at `scale`: the page and the +/// picture's frame (points). +fn emf_on_page(emf: Vec, crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) { + emf_on_page_sized(emf, (70.0, 70.0), crop, scale) +} + +/// [`emf_on_page`] with the picture `size` (points). +fn emf_on_page_sized(emf: Vec, size: (f32, f32), crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) { + let mut d = Document::new(); + let media = d.add_media(emf, "emf"); + let mut p = wordcraft_doc::Paragraph::new(); + let obj = wordcraft_doc::para::InlineObject::Image { + media, + w: size.0, + h: size.1, + alt: String::new(), + float: Default::default(), + crop, + fx: Default::default(), + ole: None, + }; + p.insert_object(0, obj, &Default::default()).unwrap(); + d.body = vec![wordcraft_doc::para_block(p)]; + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let opts = RenderOptions::default(); + let rect = page_display(&d, &l.pages[0], &opts.display) + .iter() + .find_map(|i| match i { + Draw::Image { rect, .. } => Some(*rect), + _ => None, + }) + .expect("a picture on the page"); + (render_page(&d, &l.pages[0], scale, &opts), rect) +} + +/// Whether a pixel is close to pure red. +fn is_red(p: [u8; 4]) -> bool { + p[0] > 200 && p[1] < 60 && p[2] < 60 +} + +/// Whether a pixel is paper. +fn is_paper(p: [u8; 4]) -> bool { + p[..3].iter().all(|c| *c > 200) +} + +/// A clip region (INTERSECTCLIPRECT to the left half) keeps a red rectangle over the whole +/// picture to that half; once RESTOREDC drops it, a second rectangle across the bottom shows on +/// both halves. +#[test] +fn metafile_clip_region_clips_and_ends() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0])); + let recs = [ + brush, + emf_rec(37, &le32(&[1])), + emf_rec(33, &[]), + emf_rec(30, &le32(&[0, 0, 50, 100])), + emf_rec(43, &le32(&[0, 0, 100, 60])), + emf_rec(34, &le32(&[-1])), + emf_rec(43, &le32(&[0, 80, 100, 100])), + emf_rec(14, &[0; 12]), + ]; + emf.extend(recs.concat()); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32); + assert!(is_red(at(0.25, 0.3)), "inside the clip: {:?}", at(0.25, 0.3)); + assert!(is_paper(at(0.75, 0.3)), "outside the clip: {:?}", at(0.75, 0.3)); + assert!(is_red(at(0.75, 0.9)), "after the clip is restored away: {:?}", at(0.75, 0.9)); +} + +/// The vector cache counts each item's copy of the clip region: 100 rectangles drawn inside a +/// clip region hold 100 copies of its rectangle more than without it. +#[test] +fn metafile_cache_counts_clip_regions() { + let bytes = |clip: bool| { + let mut emf = red_right_half_emf()[..88].to_vec(); + if clip { + emf.extend(emf_rec(30, &le32(&[0, 0, 50, 100]))); + } + for i in 0..100 { + emf.extend(emf_rec(43, &le32(&[i % 50, 0, i % 50 + 10, 10]))); + } + emf.extend(emf_rec(14, &[0; 12])); + media::build_vector(&emf).map(|v| v.bytes()) + }; + let (with, without) = (bytes(true).expect("a picture"), bytes(false).expect("a picture")); + assert!(with >= without + 100 * 16, "{with} and {without}"); +} + +/// A hatch tile squeezed to well under a pixel tall but several pixels wide (the picture is 70 pt +/// wide and 2 pt tall) keeps its vertical lines: the row crosses red lines and the background +/// between them, not one blended color. +#[test] +fn metafile_narrow_hatch_tile_keeps_its_lines() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1])); + // The stock NULL_PEN leaves the rectangle without an outline. + let no_pen = emf_rec(37, &le32(&[0x8000_0008_u32 as i32])); + emf.extend([brush, emf_rec(37, &le32(&[1])), no_pen, emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat()); + let (img, rect) = emf_on_page_sized(emf, (70.0, 2.0), [0.0; 4], 1.0); + let y = (rect.y + rect.h / 2.0) as u32; + let row: Vec = ((rect.x + 2.0) as u32..(rect.x + rect.w - 2.0) as u32).map(|x| img.pixel(x, y)[1]).collect(); + assert!(row.iter().any(|g| *g < 160) && row.iter().any(|g| *g > 240), "red lines and background: {row:?}"); +} + +/// A clip path (a rectangle path over the left half, SELECTCLIPPATH with RGN_COPY) keeps a red +/// rectangle over the whole picture to that half. +#[test] +fn metafile_clip_path_clips() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0])); + let recs = [ + brush, + emf_rec(37, &le32(&[1])), + emf_rec(59, &[]), + emf_rec(43, &le32(&[0, 0, 50, 100])), + emf_rec(60, &[]), + emf_rec(67, &le32(&[5])), + emf_rec(43, &le32(&[0, 0, 100, 100])), + emf_rec(14, &[0; 12]), + ]; + emf.extend(recs.concat()); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32); + assert!(is_red(at(0.25)), "inside the clip path: {:?}", at(0.25)); + assert!(is_paper(at(0.75)), "outside the clip path: {:?}", at(0.75)); +} + +/// A bitmap under a world transform that turns it a quarter turn clockwise about the picture's +/// center (EmfPlusSetWorldTransform): its left pixel (red) is drawn at the top and its right pixel +/// (blue) at the bottom. +#[test] +fn emf_plus_turned_bitmap_is_drawn_turned() { + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]); + // BGRA: red, then blue. + image.extend([0u8, 0, 255, 255, 255, 0, 0, 255]); + let turn = plus_rec(0x402A, 0, &[0.0f32, 1.0, -1.0, 0.0, 100.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, 2.0, 1.0, 25.0, 25.0, 50.0, 50.0].iter().flat_map(|v| v.to_le_bytes())); + let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), turn, plus_rec(0x401A, 0, &draw)]); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32); + let (top_right, bottom_left) = (at(0.65, 0.37), at(0.35, 0.62)); + assert!(is_red(top_right), "red at the top: {top_right:?}"); + assert!(bottom_left[2] > 200 && bottom_left[0] < 60, "blue at the bottom: {bottom_left:?}"); +} + +/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below a pixel draws its line solid +/// instead of splitting it into dashes too small to see. +#[test] +fn metafile_sub_pixel_dashes_draw_solid() { + let mut emf = red_right_half_emf()[..88].to_vec(); + // 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide. + emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000])); + emf[72..80].copy_from_slice(&le32(&[10_000, 10_000])); + // EXTCREATEPEN 1: PS_GEOMETRIC | PS_ENDCAP_FLAT | PS_USERSTYLE, 80 units wide, black, two + // entries of 1 unit. + let pen = emf_rec(95, &le32(&[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1])); + let recs = [pen, emf_rec(37, &le32(&[1])), emf_rec(27, &le32(&[0, 500])), emf_rec(54, &le32(&[1000, 500])), emf_rec(14, &[0; 12])]; + emf.extend(recs.concat()); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let y = (rect.y + rect.h * 0.5) as u32; + let (x0, x1) = ((rect.x + 5.0) as u32, (rect.x + rect.w - 5.0) as u32); + let dark = (x0..x1).filter(|&x| img.pixel(x, y)[..3].iter().all(|c| *c < 60)).count(); + assert_eq!(dark, (x1 - x0) as usize, "the line is solid black"); +} + +/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED, HS_VERTICAL) fills with its red lines over +/// the background, not with a solid red. +#[test] +fn metafile_hatch_brush_draws_its_lines() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1])); + emf.extend([brush, emf_rec(37, &le32(&[1])), emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat()); + let scale = 4.0; + let (img, rect) = emf_on_page(emf, [0.0; 4], scale); + let y = ((rect.y + rect.h / 2.0) * scale) as u32; + let (x0, x1) = (((rect.x + 2.0) * scale) as u32, ((rect.x + rect.w - 2.0) * scale) as u32); + let red = (x0..x1).filter(|&x| img.pixel(x, y)[1] < 128).count(); + let n = (x1 - x0) as usize; + assert!(red > 0 && red < n * 3 / 4, "the row crosses red lines and the background between them: {red} of {n} red"); +} + /// #1899: a crop that keeps a sliver of the picture (3% here; a header's bar can be 2.7% of a /// page-sized metafile) stretches that sliver over the frame, as the file says, for vector and /// bitmap pictures alike. Both pictures are paper on the left half and red on the right. @@ -1082,6 +1313,45 @@ fn a_crop_keeping_a_sliver_fills_the_frame_with_it() { } } +/// A negative crop side draws as no crop on that side, for vector and bitmap pictures alike: a +/// left side of -0.5 does not pad the source, so the frame at 55% shows the source at 55% (red). +#[test] +fn a_negative_crop_side_draws_uncropped() { + let mut png = Vec::new(); + image::RgbaImage::from_fn(100, 100, |x, _| image::Rgba(if x >= 50 { [255, 0, 0, 255] } else { [255; 4] })) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + for (bytes, ext) in [(red_right_half_emf(), "emf"), (png, "png")] { + let mut d = Document::new(); + let media = d.add_media(bytes, ext); + let mut p = wordcraft_doc::Paragraph::new(); + let obj = wordcraft_doc::para::InlineObject::Image { + media, + w: 70.0, + h: 70.0, + alt: String::new(), + float: Default::default(), + crop: [-0.5, 0.0, 0.0, 0.0], + fx: Default::default(), + ole: None, + }; + p.insert_object(0, obj, &Default::default()).unwrap(); + d.body = vec![wordcraft_doc::para_block(p)]; + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let opts = RenderOptions::default(); + let rect = page_display(&d, &l.pages[0], &opts.display) + .iter() + .find_map(|i| match i { + Draw::Image { rect, .. } => Some(*rect), + _ => None, + }) + .expect("a picture on the page"); + let img = render_page(&d, &l.pages[0], 1.0, &opts); + let px = img.pixel((rect.x + rect.w * 0.55) as u32, (rect.y + rect.h * 0.5) as u32); + assert!(is_red(px), "{ext}: {px:?}"); + } +} + #[test] fn cosmetic_metafile_pen_is_one_device_pixel_wide() { // MOVETO (0, 50), LINETO (100, 50) with the default cosmetic black pen: a hairline across the middle. @@ -1166,6 +1436,29 @@ fn metafile_text_records_are_painted() { assert!(dark > 50, "the text is painted inside the picture: {dark} dark pixels"); } +/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text +/// run's character cells are filled red behind the black text. +#[test] +fn metafile_text_fills_its_opaque_background() { + let mut font = emf_rec(82, &le32(&[1, -20, 0, 0, 0, 400, 0, 0])); + let mut name: Vec = "Arial".encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + name.resize(64, 0); + font.extend(name); + font[4..8].copy_from_slice(&104u32.to_le_bytes()); + let mut text = emf_rec(84, &le32(&[0, 0, 100, 100, 1, 0, 0, 5, 40, 4, 76, 0, 0, 0, 0, 0, 0])); + text.extend("WWWW".encode_utf16().flat_map(|u| u.to_le_bytes())); + text[4..8].copy_from_slice(&84u32.to_le_bytes()); + let mut emf = red_right_half_emf()[..88].to_vec(); + let bk = emf_rec(25, &le32(&[0x0000_00FF])); + emf.extend([bk, font, emf_rec(37, &le32(&[1])), emf_rec(24, &le32(&[0])), text, emf_rec(14, &[0; 12])].concat()); + let scale = 2.0; + let (img, rect) = emf_on_page(emf, [0.0; 4], scale); + let (x0, y0) = ((rect.x * scale) as u32, (rect.y * scale) as u32); + let (x1, y1) = (((rect.x + rect.w) * scale) as u32, ((rect.y + rect.h) * scale) as u32); + let red = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| is_red(img.pixel(x, y))).count(); + assert!(red > 50, "the character cells are filled red: {red} red pixels"); +} + /// An EMF text run whose anchor sits inside the picture but whose font is billions of units /// tall: each glyph's curves would span billions of device pixels, which the rasteriser /// subdivides for ever. Glyphs that big (or off the raster) are left out; the page renders. diff --git a/docs/architecture.md b/docs/architecture.md index e22d36a891..20362b09a2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -21,7 +21,7 @@ crate name links to its source tree. | L0 | [`geom`](../crates/geom/src) | 1,271 | Units (points, twips, EMU, inches, cm), rectangles and measurement parsing | | L1 | [`doc`](../crates/doc/src) | 23,719 | Document model: stories, paragraphs, runs, tables, sections, styles, numbering, fields, notes, comments, revisions and equations; edit primitives and bidi | | L1 | [`fonts`](../crates/fonts/src) | 7,088 | Font database, metrics, outlines, HarfRust shaping, Word font substitution and OpenType MATH | -| L1 | [`metafile`](../crates/metafile/src) | 3,614 | Shared Windows Metafile parsing and drawing primitives used by format readers and renderers | +| L1 (external) | [`craft-metafile`](https://github.com/storytold/craft-libs/tree/main/crates/metafile) | — | WMF, EMF and EMF+ reader shared with the other Craft apps: paths, pattern fills, bitmaps and text with their clips, placed into a picture frame for the renderers | | L1 (external) | [`craft-proof`](https://github.com/storytold/craft-libs/tree/main/crates/proof) (package alias `wordcraft-proof`) | — | Proofing moved to craft-libs (CP1, 2026-11): fifteen spelling dictionaries: English (US, GB, CA), Polish, Portuguese, Italian, Croatian, Turkish, Russian, Czech, Indonesian and Spanish (Spain, Mexico, Latin America, Uruguay); language modules provide spelling, suggestions and grammar, while Bulgarian and German have hyphenation only. Its word lists and patterns are craft-i18n's `language-data/`, embedded from `CRAFT_I18N_DIR` at the commit in `craft-i18n.rev` (CI and releases set `CRAFT_I18N_REQUIRED=1`); without them English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off (Bulgarian, Turkish and Russian hyphenate by rule) | | L2 | [`docbin`](../crates/docbin/src) | 8,815 | Word 97–2003 `.doc` reader (FIB, piece table, FKPs, SPRMs, stylesheet, lists, tables, notes, pictures) over a CFB container | | L2 | [`docx`](../crates/docx/src) | 37,376 | OOXML WordprocessingML reader/writer (Transitional and Strict), OMML, custom properties and preserved VBA parts | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 818f30e3d2..cd66695b33 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -93,7 +93,7 @@ Weights are the share of a Word user's file traffic (estimate). Read/write: ✅ | Encrypted/password-protected `.doc` (XOR/RC4) | <1% | R | 🟡 | — | ~60% | 1–2 | `crates/docbin/src/tests/encrypted.rs` | XOR obfuscation, RC4 and RC4 CryptoAPI open with a password (`docbin` `crypt.rs`, #1079). An AES header (`fAES`) is refused with a clear message: [MS-OFFCRYPTO] defines AES only for encrypted packages, which open through the `.docx` reader (gap 9) | | `.md` Markdown | — | (no) | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word | | `.tex` LaTeX | — | — | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word (#11), incl. math | -| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf` at their own frame size (#802), drawn by `crates/metafile`. Not yet: SVG, TIFF, ICO, HEIC | +| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf`, EMF+ records included (#6636), at their own frame size (#802), drawn with craft-libs' `craft-metafile`. Not yet: SVG, TIFF, ICO, HEIC | | `.png` page images | — | (Save as picture, Mac) | — | ✅ | — | — | `io_ext.rs` | | | `.json` document model | — | — | ✅ | ✅ | — | — | engine tests | For agents. A table cell's span is any number in the file; Insert Column and Merge Cells count it as at most 63 columns, as the `.docx` reader does (#3637) | diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index ed4f7eab98..31b694ee2d 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -37,7 +37,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("control-key", Class::Standalone), ("doc", Class::Layer(1)), ("fonts", Class::Layer(1)), - ("metafile", Class::Layer(1)), ("layout", Class::Layer(2)), ("docx", Class::Layer(2)), ("docbin", Class::Layer(2)), From 7ccfd4caef43c2dff554ee06a5f5f9c86942d738 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:40:12 -0800 Subject: [PATCH 02/99] Tests: EMF+ only bitmaps in ARGB, RGB, PNG and JPEG are drawn The page renderer and the PDF exporter each get a test that draws an EmfPlusDrawImage bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB, and a compressed PNG and JPEG bitmap, from an EMF+ only file. --- crates/pdf/src/tests.rs | 56 ++++++++++++++++++++++++++++++++++++++ crates/render/src/tests.rs | 41 ++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 490eafb1b2..b4f7220ed5 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1367,6 +1367,62 @@ fn emf_plus_only_bitmap_is_embedded() { assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn"); } +/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB, +/// 24bppRGB or 32bppRGB, or a compressed PNG or JPEG bitmap: the bitmap is embedded as an image. +#[test] +fn emf_plus_only_bitmap_formats_are_embedded() { + let plus_rec = |typ: u16, flags: u16, data: &[u8]| { + let mut v = typ.to_le_bytes().to_vec(); + v.extend(flags.to_le_bytes()); + v.extend(((12 + data.len()) as u32).to_le_bytes()); + v.extend((data.len() as u32).to_le_bytes()); + v.extend(data); + v + }; + let le32 = |vals: &[i32]| -> Vec { vals.iter().flat_map(|v| v.to_le_bytes()).collect() }; + let encoded = |png: bool| { + let red = [255u8, 0, 0].repeat(15); + let mut out = Vec::new(); + if png { + let enc = image::codecs::png::PngEncoder::new(&mut out); + image::ImageEncoder::write_image(enc, &red, 5, 3, image::ExtendedColorType::Rgb8).unwrap(); + } else { + let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 100); + image::ImageEncoder::write_image(enc, &red, 5, 3, image::ExtendedColorType::Rgb8).unwrap(); + } + out + }; + // Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data. + let cases: [(&str, i32, i32, i32, u32, i32, Vec); 5] = [ + ("32bppARGB", 2, 2, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(4)), + ("24bppRGB", 2, 2, 8, 0x0002_1808, 0, [0u8, 0, 255, 0, 0, 255, 0, 0].repeat(2)), + ("32bppRGB", 2, 2, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(4)), + ("PNG", 5, 3, 0, 0, 1, encoded(true)), + ("JPEG", 5, 3, 0, 0, 1, encoded(false)), + ]; + for (name, w, h, stride, format, kind, data) in cases { + let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96])); + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]); + image.extend(data); + // Records are a multiple of 4 bytes long. + image.resize(image.len().next_multiple_of(4), 0); + let object = plus_rec(0x4008, 0x0500, &image); + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes())); + let draw = plus_rec(0x401A, 0, &draw); + let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec(); + comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat()); + let mut rec = 70u32.to_le_bytes().to_vec(); + rec.extend(((12 + comment.len()) as u32).to_le_bytes()); + rec.extend((comment.len() as u32).to_le_bytes()); + rec.extend(comment); + let bytes = metafile_pdf_bytes(emf_file(&[rec, emf_rec(14, &[0; 3])])); + let images = pdf_images(&bytes); + assert!(images.iter().any(|(iw, ih, ..)| (*iw, *ih) == (w as u32, h as u32)), "{name}: the {w} × {h} bitmap is embedded"); + assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "{name}: the gray placeholder box is not drawn"); + } +} + /// A dotted cosmetic pen (CREATEPEN, PS_DOT, width 0) draws hairline dots: its dashes and gaps are /// the hairline's width, not the file's device units scaled to the frame (0.7 pt here). #[test] diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9e11f56461..86d44fb26a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1061,6 +1061,47 @@ fn emf_plus_only_bitmap_is_drawn() { assert!(is_paper(left), "left half should be paper: {left:?}"); } +/// #6636: EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB, and a +/// compressed PNG or JPEG bitmap, in an EMF+ only file. +#[test] +fn emf_plus_only_bitmap_formats_are_drawn() { + let encoded = |png: bool| { + let red = [255u8, 0, 0].repeat(64); + let mut out = Vec::new(); + if png { + let enc = image::codecs::png::PngEncoder::new(&mut out); + image::ImageEncoder::write_image(enc, &red, 8, 8, image::ExtendedColorType::Rgb8).unwrap(); + } else { + let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 100); + image::ImageEncoder::write_image(enc, &red, 8, 8, image::ExtendedColorType::Rgb8).unwrap(); + } + out + }; + // Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data. + let cases: [(&str, i32, i32, i32, u32, i32, Vec); 5] = [ + ("32bppARGB", 2, 1, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(2)), + ("24bppRGB", 2, 1, 8, 0x0002_1808, 0, vec![0, 0, 255, 0, 0, 255, 0, 0]), + ("32bppRGB", 2, 1, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(2)), + ("PNG", 8, 8, 0, 0, 1, encoded(true)), + ("JPEG", 8, 8, 0, 0, 1, encoded(false)), + ]; + for (name, w, h, stride, format, kind, data) in cases { + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]); + image.extend(data); + // Records are a multiple of 4 bytes long. + image.resize(image.len().next_multiple_of(4), 0); + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes())); + let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), plus_rec(0x401A, 0, &draw)]); + + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32); + let (right, left) = (at(0.75), at(0.25)); + assert!(is_red(right), "{name}: the red bitmap is drawn on the right half: {right:?}"); + assert!(is_paper(left), "{name}: left half should be paper: {left:?}"); + } +} + /// An EMF+ record for [`emf_plus_file`]: type, flags and data. fn plus_rec(typ: u16, flags: u16, data: &[u8]) -> Vec { let mut v = typ.to_le_bytes().to_vec(); From 26b805a4b0ffe2988ccb0296e883970257b037b9 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:07:49 +0300 Subject: [PATCH 03/99] Line breaks: no break after the '?' of a query, nor after '/' before '_' Word keeps "/portal/_back/?type=..." whole: a web address goes to the next line whole, and a long one breaks only where it no longer fits. UAX #14 allows a break after the '?' of a query and after a slash before an underscore, and the slash rule that keeps "and/or" whole covered only a letter or digit after the slash. --- crates/layout/src/para/paragraph.rs | 9 +++++---- crates/layout/src/tests.rs | 31 +++++++++++++++++++++++++++++ docs/layout-parity.md | 1 + 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..59df08f841 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -815,10 +815,11 @@ fn break_text<'a>(source: &'a str, skip: &[std::ops::Range]) -> (std::bor fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec { let mut found = Vec::new(); for (i, o) in unicode_linebreak::linebreaks(text) { - // Word keeps "and/or" and web addresses whole: no break right after a slash (a word - // too long for the line still breaks anywhere). - let after_slash = - text.get(..i).is_some_and(|t| t.ends_with('/')) && text.get(i..).and_then(|t| t.chars().next()).is_some_and(char::is_alphanumeric); + // Word keeps "and/or" and web addresses whole: no break right after a slash, or the question + // mark of a query ("/?type="), before a letter, digit or underscore ("/_back") (a word too + // long for the line still breaks anywhere). + let after_slash = text.get(..i).is_some_and(|t| t.ends_with(['/', '?'])) + && text.get(i..).and_then(|t| t.chars().next()).is_some_and(|c| c.is_alphanumeric() || c == '_'); if (o == unicode_linebreak::BreakOpportunity::Allowed || i < text.len()) && !after_slash { found.push(i); } diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index e9be02b217..49b16c05eb 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -7713,6 +7713,37 @@ fn no_line_break_right_after_a_slash() { assert!(lines > 10, "{lines} lines"); } +/// The text of every laid-out line. +fn body_lines(l: &DocLayout, text: &str) -> Vec { + l.pages + .iter() + .flat_map(|p| &p.items) + .filter_map(|it| { + if let Placed::Lines { para, l0, l1, .. } = it { + Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string())) + } else { + None + } + }) + .flatten() + .collect() +} + +#[test] +fn no_line_break_inside_a_query_address() { + // Word keeps "/?type=" and "/_back" whole (measured: a request address went to the next + // line whole, a long one breaking only where it no longer fits). + for addr in ["https://example.org/portal/_back/?type=objects_export&action=get", "https://example.org/portal/_back_office/reports/_export_all"] { + for k in 0..60 { + let text = format!("{}{addr} end", "a ".repeat(k)); + let lines = body_lines(&lay(&Document::from_text(&text)), &text); + for (a, b) in lines.iter().zip(&lines[1..]) { + assert!(!a.ends_with('?') && !a.ends_with('/'), "{k}: a line ends inside the address: {a:?} / {b:?}"); + } + } + } +} + /// #2963: a word after a slash ("caption /заполняется") wraps whole, as in Word. UAX #14 forbids a /// break between the space and the slash, and the break after the slash is dropped (Word keeps /// "and/or" whole), so the slash word had no break before it and split between two letters. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 034e6cd8cb..331242b525 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -528,6 +528,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | | 2026-11-12 | minor | Added layout.fitOnePage: heuristic search over discrete font half-point steps and spacing compression with anti-clutter safeguards (line-spacing floor and font-size floor) to condense multi-page documents by one page while preserving hierarchy | +| 2026-10-31 | trivial | Web addresses: no line break after the `?` of a query (`/?type=`) or after a slash before an underscore (`/portal/_back`). Word for Mac 16.93 kept such an address whole and moved it to the next line; WordCraft broke it there (UAX #14 allows both). With the address moved along the line one word at a time (60 paragraphs, Times New Roman 12pt), WordCraft's lines now match Word's line for line; 23 (query) and 19 (underscore) paragraphs broke inside the address before. `layout::tests::no_line_break_inside_a_query_address` | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From 6574fedb87921808472f59aa99de3c0d40c0e26c Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:15:13 +0300 Subject: [PATCH 04/99] Line breaks: a question mark keeps its break in CJK text, a path after a space wraps whole Review follow-up. The break after '?' is dropped only before an ASCII letter, digit or underscore, so a '?' in CJK text keeps the break UAX #14 gives it. The break before a slash that starts a word now also takes '/_': with the break after '/' before '_' gone, "caption /_back" had no break left there and split mid-word when it did not fit. --- crates/layout/src/para/paragraph.rs | 22 +++++++++++++----- crates/layout/src/tests.rs | 35 +++++++++++++++++++++++++++++ docs/layout-parity.md | 2 +- 3 files changed, 52 insertions(+), 7 deletions(-) diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 59df08f841..b6da050323 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -812,14 +812,24 @@ fn break_text<'a>(source: &'a str, skip: &[std::ops::Range]) -> (std::bor } } +/// A character that continues a word or a path segment after a slash: a letter, a digit or `_`. +fn word_char(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec { let mut found = Vec::new(); for (i, o) in unicode_linebreak::linebreaks(text) { - // Word keeps "and/or" and web addresses whole: no break right after a slash, or the question - // mark of a query ("/?type="), before a letter, digit or underscore ("/_back") (a word too - // long for the line still breaks anywhere). - let after_slash = text.get(..i).is_some_and(|t| t.ends_with(['/', '?'])) - && text.get(i..).and_then(|t| t.chars().next()).is_some_and(|c| c.is_alphanumeric() || c == '_'); + // Word keeps "and/or" and web addresses whole: no break right after a slash before a letter, + // digit or underscore ("/_back"), nor after the question mark of a query ("/?type="), which + // takes an ASCII one (a question mark in CJK text keeps its break). A word too long for + // the line still breaks anywhere. + let next = text.get(i..).and_then(|t| t.chars().next()); + let after_slash = match text.get(..i).and_then(|t| t.chars().next_back()) { + Some('/') => next.is_some_and(word_char), + Some('?') => next.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'), + _ => false, + }; if (o == unicode_linebreak::BreakOpportunity::Allowed || i < text.len()) && !after_slash { found.push(i); } @@ -831,7 +841,7 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec .match_indices('/') .filter(|&(i, _)| { text.get(..i).and_then(|t| t.chars().next_back()).is_some_and(|c| c.is_whitespace() && !matches!(c, '\u{a0}' | '\u{2007}' | '\u{202f}')) - && text.get(i + 1..).and_then(|t| t.chars().next()).is_some_and(char::is_alphanumeric) + && text.get(i + 1..).and_then(|t| t.chars().next()).is_some_and(word_char) }) .map(|(i, _)| i) .collect(); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 49b16c05eb..87837efe5e 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -7744,6 +7744,41 @@ fn no_line_break_inside_a_query_address() { } } +/// A path that starts after a space ("caption /_back") wraps whole: UAX #14 has no break between +/// the space and the slash, so the break before the slash is the only one there. +#[test] +fn a_path_after_a_space_wraps_whole() { + let text = "enregistrement /_back_office_reports"; + let mut wrapped = 0; + // Down to the width where the path still fits on a line (it no longer does at 425 pt). + for m in 100..=420 { + let mut d = Document::from_text(text); + d.last_section.margin_right = m as f32; + let lines = body_lines(&lay(&d), text); + if lines.len() < 2 { + continue; // fits on one line + } + wrapped += 1; + assert_eq!(lines, ["enregistrement ", "/_back_office_reports"], "the path is split at margin {m}"); + } + assert!(wrapped > 50, "{wrapped} widths wrapped"); +} + +/// A question mark in CJK text keeps the break after it: only a query's `?` before an ASCII +/// letter, digit or underscore loses it. +#[test] +fn a_question_mark_in_cjk_text_keeps_its_break() { + let text = "你好?世界".repeat(40); + let mut ended = false; + for m in 300..=440 { + let mut d = Document::from_text(&text); + d.last_section.margin_right = m as f32; + let lines = body_lines(&lay(&d), &text); + ended |= lines[..lines.len() - 1].iter().any(|l| l.ends_with('?')); + } + assert!(ended, "no line ever ends after the question mark"); +} + /// #2963: a word after a slash ("caption /заполняется") wraps whole, as in Word. UAX #14 forbids a /// break between the space and the slash, and the break after the slash is dropped (Word keeps /// "and/or" whole), so the slash word had no break before it and split between two letters. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 331242b525..35dfd88534 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -528,7 +528,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | | 2026-11-12 | minor | Added layout.fitOnePage: heuristic search over discrete font half-point steps and spacing compression with anti-clutter safeguards (line-spacing floor and font-size floor) to condense multi-page documents by one page while preserving hierarchy | -| 2026-10-31 | trivial | Web addresses: no line break after the `?` of a query (`/?type=`) or after a slash before an underscore (`/portal/_back`). Word for Mac 16.93 kept such an address whole and moved it to the next line; WordCraft broke it there (UAX #14 allows both). With the address moved along the line one word at a time (60 paragraphs, Times New Roman 12pt), WordCraft's lines now match Word's line for line; 23 (query) and 19 (underscore) paragraphs broke inside the address before. `layout::tests::no_line_break_inside_a_query_address` | +| 2026-10-31 | trivial | Web addresses: no line break after the `?` of a query (`/?type=`) or after a slash before an underscore (`/portal/_back`). Word for Mac 16.93 kept such an address whole and moved it to the next line; WordCraft broke it there (UAX #14 allows both). With the address moved along the line one word at a time (60 paragraphs, Times New Roman 12pt), WordCraft's lines now match Word's line for line; 23 (query) and 19 (underscore) paragraphs broke inside the address before. A `?` keeps its break before anything but an ASCII letter, digit or underscore (CJK text), and a path after a space (`caption /_back`) wraps whole. `layout::tests::no_line_break_inside_a_query_address`, `a_path_after_a_space_wraps_whole`, `a_question_mark_in_cjk_text_keeps_its_break` | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From 1d150004f7761cd8c6737482d97f6e188d6babc7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:40:21 -0800 Subject: [PATCH 05/99] Tests: EMF+ only bitmaps are drawn over their EmfPlusDrawImage rectangle The two EMF+ bitmap tests checked only that the bitmap is embedded. They now also read the page through hayro's interpreter and check that the page draws each bitmap over the right half of the picture, where its EmfPlusDrawImage rectangle places it. --- crates/pdf/src/tests.rs | 85 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 80 insertions(+), 5 deletions(-) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index b4f7220ed5..00b92e6b1d 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1312,6 +1312,36 @@ fn metafile_pdf(emf: Vec) -> String { } fn metafile_pdf_bytes(emf: Vec) -> Vec { + export(&metafile_doc(emf), &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap() +} + +/// The uncompressed PDF of a document holding one 70 pt metafile picture, and the picture's box +/// on the first page in PDF space (points, y up). +fn metafile_pdf_and_box(emf: Vec) -> (Vec, kurbo::Rect) { + let d = metafile_doc(emf); + let bytes = export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap(); + let lay = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let page = &lay.pages[0]; + let h = f64::from(page.h); + let r = wordcraft_layout::display::page_display(&d, page, &DisplayOptions::default()) + .into_iter() + .find_map(|item| if let Draw::Image { rect, .. } = item { Some(rect) } else { None }) + .expect("the picture is laid out"); + let (x, y, w, ph) = (f64::from(r.x), f64::from(r.y), f64::from(r.w), f64::from(r.h)); + (bytes, kurbo::Rect::new(x, h - y - ph, x + w, h - y)) +} + +/// The right half of a box. +fn right_half(r: kurbo::Rect) -> kurbo::Rect { + kurbo::Rect::new((r.x0 + r.x1) / 2.0, r.y0, r.x1, r.y1) +} + +/// Whether two boxes have the same edges, to within half a point. +fn same_box(a: kurbo::Rect, b: kurbo::Rect) -> bool { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.5) +} + +fn metafile_doc(emf: Vec) -> Document { let mut d = Document::new(); let media = d.add_media(emf, "emf"); let mut p = Paragraph::with_text("Figure: ", CharProps::default()); @@ -1332,11 +1362,11 @@ fn metafile_pdf_bytes(emf: Vec) -> Vec { ) .unwrap(); d.body = vec![para_block(p)]; - export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap() + d } /// #6636: an EMF+ only file whose EmfPlusDrawImage draws a 32bppPARGB bitmap: the bitmap is -/// embedded as an image. +/// embedded as an image, and the page draws it into the EmfPlusDrawImage rectangle. #[test] fn emf_plus_only_bitmap_is_embedded() { let plus_rec = |typ: u16, flags: u16, data: &[u8]| { @@ -1361,14 +1391,20 @@ fn emf_plus_only_bitmap_is_embedded() { rec.extend(((12 + comment.len()) as u32).to_le_bytes()); rec.extend((comment.len() as u32).to_le_bytes()); rec.extend(comment); - let bytes = metafile_pdf_bytes(emf_file(&[rec, emf_rec(14, &[0; 3])])); + let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])])); let images = pdf_images(&bytes); assert!(images.iter().any(|(w, h, ..)| (*w, *h) == (2, 2)), "the 2 × 2 bitmap is embedded"); + let drawn = pdf_drawn_images(&bytes); + assert!( + drawn.iter().any(|&(w, h, r)| (w, h) == (2, 2) && same_box(r, right_half(pic))), + "the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}" + ); assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn"); } /// #6636: an EMF+ only file whose EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB, -/// 24bppRGB or 32bppRGB, or a compressed PNG or JPEG bitmap: the bitmap is embedded as an image. +/// 24bppRGB or 32bppRGB, or a compressed PNG or JPEG bitmap: the bitmap is embedded as an image, +/// and the page draws it into the EmfPlusDrawImage rectangle. #[test] fn emf_plus_only_bitmap_formats_are_embedded() { let plus_rec = |typ: u16, flags: u16, data: &[u8]| { @@ -1416,9 +1452,14 @@ fn emf_plus_only_bitmap_formats_are_embedded() { rec.extend(((12 + comment.len()) as u32).to_le_bytes()); rec.extend((comment.len() as u32).to_le_bytes()); rec.extend(comment); - let bytes = metafile_pdf_bytes(emf_file(&[rec, emf_rec(14, &[0; 3])])); + let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])])); let images = pdf_images(&bytes); assert!(images.iter().any(|(iw, ih, ..)| (*iw, *ih) == (w as u32, h as u32)), "{name}: the {w} × {h} bitmap is embedded"); + let drawn = pdf_drawn_images(&bytes); + assert!( + drawn.iter().any(|&(iw, ih, r)| (iw, ih) == (w as u32, h as u32) && same_box(r, right_half(pic))), + "{name}: the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}" + ); assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "{name}: the gray placeholder box is not drawn"); } } @@ -2338,6 +2379,40 @@ fn pdf_images(bytes: &[u8]) -> Vec<(u32, u32, Vec, Vec>)> { out } +/// The images the pages draw, through hayro's interpreter: pixel width and height, and the box each +/// one is drawn into, in PDF space (points, y up). +fn pdf_drawn_images(bytes: &[u8]) -> Vec<(u32, u32, kurbo::Rect)> { + use hayro_interpret::font::Glyph; + use hayro_interpret::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, + interpret_page, + }; + struct Ex(Vec<(u32, u32, kurbo::Rect)>); + impl Device<'_> for Ex { + fn set_soft_mask(&mut self, _: Option>) {} + fn set_blend_mode(&mut self, _: BlendMode) {} + fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {} + fn push_clip_path(&mut self, _: &ClipPath) {} + fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} + fn draw_glyph(&mut self, _: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {} + fn draw_image(&mut self, image: Image<'_, '_>, t: kurbo::Affine) { + // The transform maps the image's pixel grid onto the page. + let (w, h) = (image.width(), image.height()); + self.0.push((w, h, t.transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, f64::from(w), f64::from(h))))); + } + fn pop_clip_path(&mut self) {} + fn pop_transparency_group(&mut self) {} + } + let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse"); + let cache = InterpreterCache::new(); + let mut ex = Ex(Vec::new()); + for page in pdf.pages().iter() { + let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default()); + interpret_page(page, &mut ctx, &mut ex); + } + ex.0 +} + /// The fill opacities (`ca`) of the PDF's graphics states. fn pdf_fill_opacities(bytes: &[u8]) -> Vec { use hayro_syntax::object::Object; From d53a740be1a179fd0f1e126a27d2110dfffc5df8 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:25:09 +0100 Subject: [PATCH 06/99] #6757: lay out a paragraph over many pages in linear time Each page's piece of a paragraph walked every line of the paragraph in place_objects to find the pictures and shapes to draw with it, skipping all but its own lines and the late-float anchor lines. A paragraph over many pages was quadratic in its lines. A later piece now walks only its own lines and the late-float anchor lines, in the same order. unequal_formats_lay_out_in_linear_time reads 8.0x for 8x the runs in a debug build, down from 15.0x, so it no longer fails in the slower SonarCloud coverage build. Co-Authored-By: Claude Opus 5.5 --- crates/layout/src/floats.rs | 16 +++++++++++----- crates/layout/src/tests/linear.rs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/layout/src/floats.rs b/crates/layout/src/floats.rs index 933c09c321..89264cbb27 100644 --- a/crates/layout/src/floats.rs +++ b/crates/layout/src/floats.rs @@ -718,12 +718,18 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec Document { + let mut d = Document::from_text(""); + d.body = vec![wordcraft_doc::para_block(Paragraph::with_text(&"x\n".repeat(n), CharProps::default()))]; + d +} + +/// The piece of a long paragraph on each page looked through every line of the paragraph for the +/// pictures and shapes to draw with it (#6757). +#[test] +fn a_paragraph_over_many_pages_lays_out_in_linear_time() { + let pages = lay(&many_lines(SCALE * 400), &LayoutOptions::default()).pages.len(); + assert!(pages > 40, "the paragraph runs over many pages: {pages}"); + assert_layout_linear("a paragraph over many pages", 400, many_lines, &LayoutOptions::default()); +} + /// A table of `n` rows of 60 cells, each row exactly half a point high, so every cell clips its /// (empty) paragraph and the whole table fits on the first page. fn clipped_table(n: usize) -> Document { From 97c13a2990c91e32b659e521fa0aa46a4c1c0c48 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 06:44:41 -0500 Subject: [PATCH 07/99] geom: delegate TIFF compression inspection to craft-tiff --- Cargo.lock | 12 +++++++++++- Cargo.toml | 1 + crates/geom/Cargo.toml | 3 ++- crates/geom/src/picture.rs | 31 +------------------------------ 4 files changed, 15 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01400750b0..7ffc85d3f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1248,7 +1248,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa dependencies = [ "brotli-decompressor 6.3.1", "chrono", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)", "quick-xml 0.41.0", "serde", ] @@ -1392,6 +1392,15 @@ name = "craft-sheet" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09bed09c2911c51810a90f15496fddd2402c11bd#09bed09c2911c51810a90f15496fddd2402c11bd" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -7407,6 +7416,7 @@ name = "wordcraft-geom" version = "0.18.1" dependencies = [ "craft-image-codecs", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09bed09c2911c51810a90f15496fddd2402c11bd)", "image", "serde", ] diff --git a/Cargo.toml b/Cargo.toml index 63ca129867..a79961a660 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ brotli-decompressor = "5" vello_cpu = "0.2" image = { version = "0.25", default-features = false } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "09bed09c2911c51810a90f15496fddd2402c11bd", version = "=0.1.0" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml index 640ea50eae..e2fbda13fe 100644 --- a/crates/geom/Cargo.toml +++ b/crates/geom/Cargo.toml @@ -10,9 +10,10 @@ workspace = true [features] # Picture decoding within a memory budget (`picture`), for the crates that decode pictures. -image = ["dep:image", "dep:craft-image-codecs"] +image = ["dep:image", "dep:craft-image-codecs", "dep:craft-tiff"] [dependencies] craft-image-codecs = { workspace = true, optional = true } +craft-tiff = { workspace = true, optional = true } image = { workspace = true, optional = true } serde = { workspace = true } diff --git a/crates/geom/src/picture.rs b/crates/geom/src/picture.rs index 846b3e8f85..42a097b874 100644 --- a/crates/geom/src/picture.rs +++ b/crates/geom/src/picture.rs @@ -539,36 +539,7 @@ fn worst_coefficients(bytes: &[u8]) -> u64 { /// tag is missing. None when the header can't be read, or when the tag appears more than once: /// the decoder keeps the last copy, so a harmless first one must not hide a JPEG one after it. fn tiff_compression(bytes: &[u8]) -> Option { - let le = match bytes.get(..4)? { - b"II*\0" => true, - b"MM\0*" => false, - _ => return None, - }; - let u16_at = |at: usize| -> Option { - let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?]; - Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) - }; - let u32_at = |at: usize| -> Option { - let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; - Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) - }; - let ifd = usize::try_from(u32_at(4)?).ok()?; - let mut found = None; - for i in 0..usize::from(u16_at(ifd)?) { - let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?; - if u16_at(entry)? != 259 { - continue; - } - if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 { - return None; - } - found = Some(match u16_at(entry.checked_add(2)?)? { - 3 => u16_at(entry.checked_add(8)?)?, - 4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?, - _ => return None, - }); - } - Some(found.unwrap_or(1)) + craft_tiff::probe::first_image_compression(bytes) } /// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask From 54e3e1cf345ede3d0ecf631809af9de3116347f2 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:06:41 +0100 Subject: [PATCH 08/99] CI: fix red SonarCloud on main (#6859) The coverage shards failed six tests on every main push: - three UI glyph tests: the Sonar job had no craft-fonts. Pass the same fonts-ref as ci.yml. - three layout linear-time tests: llvm-cov instrumentation pushes the 8x time ratio past 24 (24.2-31.2). Ignore them under cfg(coverage), which cargo llvm-cov sets; the gate CI still runs them. Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8 Co-authored-by: Claude Opus 5.5 --- .github/workflows/sonarcloud.yml | 3 +++ Cargo.toml | 2 ++ crates/layout/src/tests.rs | 3 +++ 3 files changed, 8 insertions(+) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3b..983bdf8ad5 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -18,4 +18,7 @@ jobs: sonarcloud: # Tracked at @main so org-wide CI improvements propagate without PR churn. uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + # Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts. + fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 secrets: inherit diff --git a/Cargo.toml b/Cargo.toml index 63ca129867..f8f63c7812 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -122,6 +122,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data [workspace.lints.rust] unsafe_code = "forbid" +# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation. +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] } [workspace.lints.clippy] cognitive_complexity = "deny" diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 5218ad5c7f..40144d7f8e 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -914,6 +914,7 @@ fn long_word_beside_a_float(n: usize) -> Document { /// A word with no break opportunity in it: measuring the word for every line it takes scanned /// the whole paragraph each time, so the layout was quadratic in the word's length. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")] fn a_long_unbreakable_word_lays_out_in_linear_time() { let (t1, tk, ratio) = layout_time_ratio(long_word_beside_a_float, 50_000, &LayoutOptions::default()); eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}"); @@ -1134,6 +1135,7 @@ fn long_word_with_alternating_advances_beside_a_float(n: usize) -> Document { /// A word whose advances alternate in sign lays out in linear time: the measurement that asks /// whether it would fit the full line must not walk the word again for every line it takes. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")] fn a_word_with_alternating_advances_lays_out_in_linear_time() { let (t1, tk, ratio) = layout_time_ratio(long_word_with_alternating_advances_beside_a_float, 50_000, &LayoutOptions::default()); eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}"); @@ -7839,6 +7841,7 @@ fn a_no_break_space_before_a_slash_still_holds() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")] fn unequal_formats_lay_out_in_linear_time() { crate::test_fonts(); // Runs whose formats never compare equal (NaN spacing from a hostile file) each get a style; From 4356771236ced4bbc64b23fb5843bfb919b4ef10 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 16:05:20 +0100 Subject: [PATCH 09/99] geom: pin craft-tiff to craft-libs main at the merge of #1867 (6ef2c053) --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7ffc85d3f5..152e056f71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1395,7 +1395,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=09bed09c2911c51810a90f15496fddd2402c11bd#09bed09c2911c51810a90f15496fddd2402c11bd" +source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" dependencies = [ "serde", "thiserror 2.0.21", @@ -1404,7 +1404,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1" dependencies = [ "serde", "thiserror 2.0.21", @@ -7416,7 +7416,7 @@ name = "wordcraft-geom" version = "0.18.1" dependencies = [ "craft-image-codecs", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09bed09c2911c51810a90f15496fddd2402c11bd)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)", "image", "serde", ] diff --git a/Cargo.toml b/Cargo.toml index a79961a660..aca54fca1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,7 @@ brotli-decompressor = "5" vello_cpu = "0.2" image = { version = "0.25", default-features = false } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "09bed09c2911c51810a90f15496fddd2402c11bd", version = "=0.1.0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } From 837a61013389d6803d62b0d482c63510ed88c664 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:20:15 +0100 Subject: [PATCH 10/99] M14: explain hyperlink URL input limits (#6789) --- crates/engine/src/cmd/insert/links.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/insert/links.rs b/crates/engine/src/cmd/insert/links.rs index 2a0535a651..d38e78f603 100644 --- a/crates/engine/src/cmd/insert/links.rs +++ b/crates/engine/src/cmd/insert/links.rs @@ -51,7 +51,7 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult { }, }; if url.is_empty() || url.len() > 4096 { - return Err(CmdError::Params("bad url".into())); + return Err(CmdError::Params("`url` must be non-empty and at most 4096 UTF-8 bytes".into())); } let style = Some("Hyperlink".to_string()); if s.sel.is_collapsed() { From 82f0c467bee153f5c8ff45bd0fd581abb9d8a4a6 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:32:11 +0100 Subject: [PATCH 11/99] M14: describe encrypted OpenDocument command support (#6776) --- crates/engine/src/cmd/file.rs | 8 ++++---- crates/engine/src/io.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0a067b6d4c..1301213659 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -90,7 +90,7 @@ pub fn specs() -> Vec { CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(), CommandSpec::new("file.open", "Open", "File", open) .key("Mod+O / Mod+F12 / Mod+Alt+F2") - .params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#) + .params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#) .pure(), CommandSpec::new("file.save", "Save", "File", save) .key("Mod+S / Shift+F12 / Alt+Shift+F2") @@ -100,7 +100,7 @@ pub fn specs() -> Vec { // 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) - .params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#) + .params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#) .pure(), CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| { // No path (the command search, say): the app asks where to save, as File › Export @@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult { Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()})) } -/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved -/// with from now on, or none. +/// File › Info › Protect Document › Encrypt with Password: the password Word packages and +/// OpenDocument text files (.odt, .ott) are saved with from now on, or none. fn encrypt(s: &mut Session, v: &Value) -> CmdResult { let password = match v.get("password") { Some(Value::Null) => None, diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 4f149d8eda..a7760d3282 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -464,7 +464,7 @@ pub fn save_bytes_opts(name: &str, doc: &Document, opts: &ExportOptions) -> Resu } /// [`save_bytes`], encrypted with `password` when there is one and the format is a Word package -/// (other formats are copies and are written as they are). +/// or OpenDocument text file (.odt, .ott); other formats are copies and are written as they are. pub fn save_bytes_with(name: &str, doc: &Document, password: Option<&str>, opts: &ExportOptions) -> Result, String> { let bytes = save_bytes_opts(name, doc, opts)?; match password { From 78dfa8f648e9451426c9b62471905c0cdf698391 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:48:11 +0100 Subject: [PATCH 12/99] M14: label Alt Text pane inputs for assistive technology (#6726) --- crates/ui-egui/src/a11y_pane.rs | 89 ++++++++++++++++++++++++++++++--- 1 file changed, 82 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/a11y_pane.rs b/crates/ui-egui/src/a11y_pane.rs index ea46cb4448..aba7d2825e 100644 --- a/crates/ui-egui/src/a11y_pane.rs +++ b/crates/ui-egui/src/a11y_pane.rs @@ -90,7 +90,8 @@ pub fn alt_text(app: &mut WordApp, ui: &mut Ui) { let decorative = obj.is_decorative(); ui.label(egui::RichText::new(tl!("Describe what this object shows, for people who can't see it.")).weak()); ui.add_space(4.0); - if let Some(text) = draft_box(ui, ("alt_obj", &pos), obj.alt_text(), !decorative, true) + let label = ui.label(tl!("Description:")); + if let Some(text) = draft_box(ui, ("alt_obj", &pos), label.id, obj.alt_text(), !decorative, true) && still_selected(app, &pos) { let _ = app.run("object.altText", json!({"text": text})); @@ -111,13 +112,13 @@ pub fn alt_text(app: &mut WordApp, ui: &mut Ui) { if let Some((tp, caption, description)) = table { ui.label(egui::RichText::new(tl!("Describe what this table shows, for people who can't see it.")).weak()); ui.add_space(4.0); - ui.label(tl!("Title:")); - if let Some(t) = draft_box(ui, ("alt_table_title", &tp), caption.as_deref().unwrap_or(""), true, false) { + let label = ui.label(tl!("Title:")); + if let Some(t) = draft_box(ui, ("alt_table_title", &tp), label.id, caption.as_deref().unwrap_or(""), true, false) { let _ = app.run("table.altText", json!({"title": t})); } ui.add_space(4.0); - ui.label(tl!("Description:")); - if let Some(t) = draft_box(ui, ("alt_table_text", &tp), description.as_deref().unwrap_or(""), true, true) { + let label = ui.label(tl!("Description:")); + if let Some(t) = draft_box(ui, ("alt_table_text", &tp), label.id, description.as_deref().unwrap_or(""), true, true) { let _ = app.run("table.altText", json!({"text": t})); } return; @@ -131,11 +132,18 @@ fn still_selected(app: &WordApp, pos: &Pos) -> bool { /// A text box editing `current`; the draft lives in egui memory while it has focus (frame-local /// buffers lose keystrokes). Returns the new text when editing ends with a change. -fn draft_box(ui: &mut Ui, key: impl std::hash::Hash + std::fmt::Debug, current: &str, enabled: bool, multiline: bool) -> Option { +fn draft_box( + ui: &mut Ui, + key: impl std::hash::Hash + std::fmt::Debug, + label: egui::Id, + current: &str, + enabled: bool, + multiline: bool, +) -> Option { let key = egui::Id::unique(key); let mut text = ui.data(|d| d.get_temp::(key)).unwrap_or_else(|| current.to_string()); let edit = if multiline { egui::TextEdit::multiline(&mut text).desired_rows(5) } else { egui::TextEdit::singleline(&mut text) }; - let r = ui.add_enabled(enabled, edit.desired_width(f32::INFINITY)); + let r = ui.add_enabled(enabled, edit.desired_width(f32::INFINITY)).labelled_by(label); if r.changed() { ui.data_mut(|d| d.insert_temp(key, text.clone())); } @@ -148,3 +156,70 @@ fn draft_box(ui: &mut Ui, key: impl std::hash::Hash + std::fmt::Debug, current: } None } + +#[cfg(test)] +mod tests { + use super::*; + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + + fn harness(app: WordApp) -> egui_kittest::Harness<'static, WordApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 400.0)).build_ui_state( + move |ui, app: &mut WordApp| { + if fonts { + alt_text(app, ui); + } else { + crate::theme::install_fonts_for(ui.ctx(), false); + fonts = true; + } + }, + app, + ); + h.run_steps(4); + h + } + + #[test] + fn object_description_is_named_commits_and_disables_when_decorative() { + let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + app.run("insert.shape", json!({"kind": "ellipse"})).unwrap(); + let mut h = harness(app); + h.get_by_role_and_label(Role::MultilineTextInput, "Description:").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::MultilineTextInput, "Description:").type_text("A green circle"); + h.run_steps(2); + assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").value().as_deref(), Some("A green circle")); + h.get_by_role_and_label(Role::CheckBox, "Mark as decorative").click(); + h.run_steps(2); + let (_, object) = wordcraft_engine::cmd::objects::selected(&h.state().session).unwrap(); + assert_eq!(object.alt_text(), "A green circle"); + assert!(object.is_decorative()); + assert!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").accesskit_node().is_disabled()); + } + + #[test] + fn table_title_and_description_are_named_and_commit_independently() { + let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + app.run("insert.table", json!({"rows": 1, "cols": 1})).unwrap(); + let mut h = harness(app); + h.get_by_role_and_label(Role::TextInput, "Title:").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Title:").type_text("Prices"); + h.run_steps(2); + assert_eq!(h.get_by_role_and_label(Role::TextInput, "Title:").value().as_deref(), Some("Prices")); + h.get_by_role_and_label(Role::MultilineTextInput, "Description:").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::MultilineTextInput, "Description:").type_text("Prices by year"); + h.run_steps(2); + assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").value().as_deref(), Some("Prices by year")); + h.get_by_role_and_label(Role::TextInput, "Title:").click(); + h.run_steps(2); + let app = h.state(); + let focus = &app.session.sel.focus; + let (path, _, _) = focus.path.cell().unwrap(); + let table = app.session.doc.table(focus.story, &path).unwrap(); + assert_eq!(table.props.caption.as_deref(), Some("Prices")); + assert_eq!(table.props.description.as_deref(), Some("Prices by year")); + } +} From 5467f998a035a0ec8866958c5e0684fbed6c046d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:51:07 +0100 Subject: [PATCH 13/99] Tests: set the fit-one-page fixtures in bundled Inter so FreeBSD pages them like other hosts (#6887) * Tests: set the fit-one-page fixtures in bundled Inter The fit-one-page fixtures count pages to the line, but they were set in the default Aptos, which each host substitutes with whatever it has installed: Arial on Windows, Liberation Sans on the Linux runners, DejaVu Sans on the FreeBSD image (its only candidate). DejaVu Sans is taller, so at 11 pt it fits 27 of the fixture lines on a page where Arial fits 28, and the nightly FreeBSD job failed fit_one_page_respects_step_pt and fit_one_page_preserves_budget_across_document_serialization. Set the fixtures in the bundled Inter, whose metrics keep a page boundary for each 0.5 pt step, recount the fixed line counts for it, and start the boundary searches below the boundary. The two tests that failed also assert that the body is laid out in Inter, not a substitute. * Tests: keep 7 to 12 body lines on the line-numbered fixture's final page A boundary search left one body line on the final page, so counting the line-number decorations too would still have stayed under the 12-line limit and the test could not catch it. Use 33 lines, 8 on the final page in Inter, and assert the body-only count is between 7 and 12. --- crates/engine/src/tests/fit_one_page.rs | 128 ++++++++++++++---------- 1 file changed, 77 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/tests/fit_one_page.rs b/crates/engine/src/tests/fit_one_page.rs index a7458bf8a2..b8c0ff2ff8 100644 --- a/crates/engine/src/tests/fit_one_page.rs +++ b/crates/engine/src/tests/fit_one_page.rs @@ -5,13 +5,40 @@ use wordcraft_doc::props::CharProps; use crate::Session; -/// Creates a document with `lines` lines of text. +/// The bundled face the fixtures are set in. Their page counts are exact to a line, so they must +/// not depend on the face the host substitutes for the default Aptos: at 11 pt, Arial and +/// Liberation Sans fit 28 of these lines on a page and DejaVu Sans, the only candidate on a bare +/// FreeBSD system, fits 27. Inter is the bundled face whose metrics give each 0.5 pt step its own +/// page boundary at this page size. +const FIXTURE_FONT: &str = "Inter"; + +/// Creates a document with `lines` lines of text in [`FIXTURE_FONT`]. Inter fits 25 lines on a +/// page at 12 pt, 26 at 11.5 pt and 27 at 11 pt. fn create_multiline_doc(lines: usize) -> Session { let mut text = String::new(); for i in 1..=lines { text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n")); } - Session::new(Document::from_text(&text)) + let mut doc = Document::from_text(&text); + std::sync::Arc::make_mut(&mut doc.styles).default_chr.font = Some(FIXTURE_FONT.into()); + Session::new(doc) +} + +/// Asserts the body is laid out in the bundled [`FIXTURE_FONT`], not a substitute. +fn assert_fixture_font(s: &mut Session) { + let layout = s.layout(); + let mut runs = 0; + for page in &layout.pages { + for item in &page.items { + if let wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, para, .. } = item { + for style in ¶.styles { + runs += 1; + assert_eq!(style.face.family, FIXTURE_FONT, "the fixture must not fall back to another family"); + } + } + } + } + assert!(runs > 0, "the font check must inspect laid-out body text"); } #[test] @@ -39,7 +66,7 @@ fn fit_one_page_fails_on_hard_page_break() { #[test] fn fit_one_page_refuses_page_break_before_before_search() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[1]) { p.props.page_break_before = Some(true); @@ -74,7 +101,7 @@ fn fit_one_page_fails_on_next_page_section_break() { #[test] fn fit_one_page_condenses_slight_overflow_and_undoes() { // Find the boundary where the document just spills onto page 2 - let mut lines = 30; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 2; @@ -102,7 +129,7 @@ fn fit_one_page_condenses_slight_overflow_and_undoes() { #[test] fn fit_one_page_respects_max_delta() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document"); let doc_backup = s.doc.clone(); @@ -117,11 +144,7 @@ fn fit_one_page_respects_max_delta() { #[test] fn fit_one_page_respects_step_pt() { - let mut text = String::new(); - for i in 1..=28 { - text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n")); - } - let mut s = Session::new(Document::from_text(&text)); + let mut s = create_multiline_doc(27); for b in &mut s.doc.body { if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) { p.mark.size = Some(11.4); @@ -131,6 +154,7 @@ fn fit_one_page_respects_step_pt() { } } assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt"); + assert_fixture_font(&mut s); // Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments. // Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail. @@ -147,7 +171,7 @@ fn fit_one_page_respects_step_pt() { #[test] fn fit_one_page_allows_spacing_only_at_font_floor() { - let mut lines = 35; + let mut lines = 20; let mut s = create_multiline_doc(lines); let set_font = |s: &mut Session| { for b in &mut s.doc.body { @@ -178,7 +202,7 @@ fn fit_one_page_allows_spacing_only_at_font_floor() { #[test] fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() { - let mut lines = 35; + let mut lines = 20; let mut s = create_multiline_doc(lines); let set_font = |s: &mut Session| { for b in &mut s.doc.body { @@ -208,7 +232,7 @@ fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() { #[test] fn fit_one_page_bounds_fine_step_loop() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -224,7 +248,7 @@ fn fit_one_page_bounds_fine_step_loop() { #[test] fn fit_one_page_supports_max_delta_above_2pt() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -244,7 +268,7 @@ fn fit_one_page_supports_max_delta_above_2pt() { #[test] fn fit_one_page_anti_compound_guard_prevents_repeated_invocations() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); loop { for b in &mut s.doc.body { @@ -314,7 +338,7 @@ fn fit_one_page_already_fits_wins_over_exhausted_budget() { #[test] fn fit_one_page_checks_complex_script_font_floor() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -340,7 +364,7 @@ fn fit_one_page_checks_complex_script_font_floor() { #[test] fn fit_one_page_checks_editable_text_box_font_floor() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -386,7 +410,7 @@ fn fit_one_page_checks_editable_text_box_font_floor() { #[test] fn fit_one_page_fails_when_overflow_exceeds_limits() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 { lines += 1; @@ -566,7 +590,7 @@ fn fit_one_page_fails_with_failed_cmd_error() { #[test] fn fit_one_page_never_populates_custom_props() { - let mut lines = 30; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 2; @@ -582,7 +606,7 @@ fn fit_one_page_never_populates_custom_props() { fn fit_one_page_allows_subsequent_fit_after_typography_reset() { use std::sync::Arc; - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -625,7 +649,7 @@ fn fit_one_page_allows_subsequent_fit_after_typography_reset() { #[test] fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() { - let mut lines = 30; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 2; @@ -646,7 +670,7 @@ fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() { #[test] fn fit_one_page_small_comment_font_never_blocks_body_fit() { - let mut lines = 30; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 2; @@ -666,7 +690,7 @@ fn fit_one_page_small_comment_font_never_blocks_body_fit() { #[test] fn fit_one_page_anti_compound_caps_total_reduction_across_runs() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); // Initial fit with -0.5 pt font reduction (spacing disabled so font budget is exercised) @@ -688,7 +712,7 @@ fn fit_one_page_anti_compound_caps_total_reduction_across_runs() { #[test] fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); // Add a 9.0 pt run to the first paragraph alongside 11.0 pt runs if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[0]) { p.runs.push(wordcraft_doc::para::Run { len: 5, props: CharProps { size: Some(9.0), ..Default::default() } }); @@ -725,7 +749,7 @@ fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() { #[test] fn fit_one_page_allows_spill_with_bottom_placed_footnote() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -751,7 +775,7 @@ fn fit_one_page_allows_spill_with_bottom_placed_footnote() { #[test] fn fit_one_page_with_final_page_footnote() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -784,7 +808,7 @@ fn fit_one_page_with_final_page_footnote() { #[test] fn fit_one_page_skips_deleted_text_when_markup_hidden() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); // Insert a deleted text run with small font (e.g. 6.0 pt, below the 8.5 pt floor) @@ -815,7 +839,7 @@ fn fit_one_page_skips_deleted_text_when_markup_hidden() { #[test] fn fit_one_page_tracks_reduced_complex_script_font_sizes() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); let styles_before = s.doc.styles.clone(); @@ -853,8 +877,9 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() { #[test] fn fit_one_page_preserves_budget_across_document_serialization() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); + assert_fixture_font(&mut s); // Apply fit let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false})); @@ -900,7 +925,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() { s.touch(); s.relayout(); }; - let mut lines = 27; + let mut lines = 20; let mut s = create_multiline_doc(lines); set_font(&mut s); while s.layout().pages.len() < 2 && lines < 120 { @@ -924,7 +949,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() { #[test] fn fit_one_page_skips_hidden_text_when_hidden_marks_off() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); // Insert a hidden text run with small font (6.0 pt, below the 8.5 pt floor) into an existing paragraph @@ -958,7 +983,7 @@ fn fit_one_page_skips_hidden_text_when_hidden_marks_off() { #[test] fn fit_one_page_accounts_for_vertical_alignment_padding() { - let mut s = create_multiline_doc(26); + let mut s = create_multiline_doc(25); let extra_p = wordcraft_doc::Paragraph::with_text("Spill line on page 2.", CharProps::default()); s.doc.body.push(wordcraft_doc::para_block(extra_p)); @@ -977,7 +1002,7 @@ fn fit_one_page_accounts_for_vertical_alignment_padding() { #[test] fn fit_one_page_accounts_for_note_separator_decor_story() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); while s.layout().pages.len() < 2 && lines < 80 { lines += 1; @@ -1012,7 +1037,7 @@ fn fit_one_page_accounts_for_note_separator_decor_story() { #[test] fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() { - let mut lines = 28; + let mut lines = 20; let mut s = create_multiline_doc(lines); let set_spacing = |s: &mut Session| { for b in &mut s.doc.body { @@ -1053,7 +1078,7 @@ fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() { #[test] fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); // Calling with zero maxDeltaPt and adjustSpacing: false produces no candidate steps @@ -1068,23 +1093,24 @@ fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() { #[test] fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() { - let mut lines = 33; - let enable_line_numbers = |s: &mut Session| { - s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default()); - s.touch(); - s.relayout(); - }; - let mut s = create_multiline_doc(lines); - enable_line_numbers(&mut s); - while s.layout().pages.len() < 2 && lines < 60 { - lines += 1; - s = create_multiline_doc(lines); - enable_line_numbers(&mut s); - } + let mut s = create_multiline_doc(33); + s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default()); + s.touch(); + s.relayout(); assert_eq!(s.layout().pages.len(), 2); // Every body line on the final page also places a line-number decoration. Counting those as - // content would double the final-page line count and refuse before any candidate is tried. + // content would double the final-page line count and refuse before any candidate is tried: + // between 7 and 12 body lines are within the 12-line limit, and twice as many are not. + let body_lines: usize = s.layout().pages[1] + .items + .iter() + .map(|item| match item { + wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, l0, l1, .. } => l1 - l0, + _ => 0, + }) + .sum(); + assert!((7..=12).contains(&body_lines), "the final page must carry 7 to 12 body lines, has {body_lines}"); let decorated = s.layout().pages[1] .items .iter() @@ -1099,7 +1125,7 @@ fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() { #[test] fn fit_one_page_counts_side_by_side_footnote_cells_once() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); // A footnote table whose row's cells sit side by side: their text occupies one vertical @@ -1134,7 +1160,7 @@ fn fit_one_page_counts_side_by_side_footnote_cells_once() { #[test] fn fit_one_page_refuses_when_formatting_changes_cannot_be_tracked() { - let mut s = create_multiline_doc(27); + let mut s = create_multiline_doc(26); assert_eq!(s.layout().pages.len(), 2); s.doc.settings.track_changes = true; s.prefs.markup.track_formatting = true; From f472620ac0e5279222206510707c5a0f25e9148f Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:03:39 +0100 Subject: [PATCH 14/99] M14: explain invalid field code values (#6725) --- crates/engine/src/cmd/fields.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fields.rs b/crates/engine/src/cmd/fields.rs index ca7208346c..ec1cb719ce 100644 --- a/crates/engine/src/cmd/fields.rs +++ b/crates/engine/src/cmd/fields.rs @@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> { fn set_code(s: &mut Session, v: &Value) -> CmdResult { let code = p::req_str(v, "code")?.trim().to_string(); if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) { - return Err(CmdError::Params("bad field code".into())); + return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into())); } let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) }; with_field(s, &f.at, |o| match o { @@ -441,7 +441,10 @@ mod tests { s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap(); let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default(); assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report")); - assert!(s.run("fields.setCode", &json!({"code": ""})).is_err()); + assert!(matches!( + s.run("fields.setCode", &json!({"code": ""})), + Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers" + )); // A locked field keeps its result. s.run("fields.lock", &json!({})).unwrap(); From 83c3b5890bb208ba4af4c5b67c7f96b1734d450e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:15:32 +0100 Subject: [PATCH 15/99] M14: describe all accepted mail-merge sort forms (#6724) --- crates/engine/src/cmd/mailings.rs | 4 ++-- crates/engine/src/cmd/mailings/filter.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/mailings.rs b/crates/engine/src/cmd/mailings.rs index 17881014d6..4836ac9554 100644 --- a/crates/engine/src/cmd/mailings.rs +++ b/crates/engine/src/cmd/mailings.rs @@ -110,7 +110,7 @@ pub fn specs() -> Vec { apply_filter(s); filter_result(s) }) - .params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#) + .params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; `sort` also accepts a field name, one key object or null; array entries may also be field names; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#) .when(has_list) .pure(), CommandSpec::new("mailings.sortRecipients", "Sort Recipients", "Mailings › Start Mail Merge › Edit Recipient List", |s, v| { @@ -118,7 +118,7 @@ pub fn specs() -> Vec { apply_filter(s); filter_result(s) }) - .params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (no params: the list's own order)"#) + .params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (`sort` also accepts a field name, one key object or null; array entries may also be field names; no params: the list's own order)"#) .when(has_list) .pure(), CommandSpec::new("mailings.insertField", "Insert Merge Field", "Mailings › Write & Insert Fields", |s, v| { diff --git a/crates/engine/src/cmd/mailings/filter.rs b/crates/engine/src/cmd/mailings/filter.rs index f74962d02d..21a0240d45 100644 --- a/crates/engine/src/cmd/mailings/filter.rs +++ b/crates/engine/src/cmd/mailings/filter.rs @@ -255,7 +255,7 @@ pub(super) fn parse_sort(headers: &[String], v: Option<&Value>) -> Result return Ok(Vec::new()), Some(Value::Array(a)) => a.clone(), Some(o @ (Value::Object(_) | Value::String(_))) => vec![o.clone()], - Some(_) => return Err(CmdError::Params("`sort` must be an array of {field, descending}".into())), + Some(_) => return Err(CmdError::Params("`sort` must be a field name, a {field, descending} object, an array of those, or null".into())), }; if arr.len() > MAX_SORT_KEYS { return Err(CmdError::Params(format!("at most {MAX_SORT_KEYS} sort keys"))); From 9fe9bd50424646f0c0e5f9498cbba4649749372e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:26:23 +0100 Subject: [PATCH 16/99] M14: clarify initial and pane spelling-review wrapping (#6720) --- docs/spelling-review.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spelling-review.md b/docs/spelling-review.md index 385f660183..f19ca53bf1 100644 --- a/docs/spelling-review.md +++ b/docs/spelling-review.md @@ -12,7 +12,7 @@ WordCraft uses this arrangement and its shared pane host, icons, typography and ## Scope and behavior -Review › Spelling & Grammar, Home › Editor and F7 open the task pane. The pass begins at the next issue from the current selection and continues to the end of the current story (body, header, note or other active text), not all document stories or only a selection. Each correction uses the existing review command and remains undoable. Ignore Once advances without changing the document or dictionaries. Ignore All lasts for the session; Add to Dictionary uses the personal dictionary. Those two actions are offered only for spelling issues. Completion remains visible; Check Again starts a wrapping search. The pane host supplies Close and docking. +Review › Spelling & Grammar, Home › Editor and F7 open the task pane. The initial search begins at the next issue from the current selection and wraps to the start of the current story if needed; pane navigation then stops at that story's end (body, header, note or other active text), not all document stories or only a selection. Each correction uses the existing review command and remains undoable. Ignore Once advances without changing the document or dictionaries. Ignore All lasts for the session; Add to Dictionary uses the personal dictionary. Those two actions are offered only for spelling issues. Completion remains visible; Check Again starts a wrapping search. The pane host supplies Close and docking. If another command changes the document body or selection, a cached suggestion is refused; Check Again obtains a fresh target. Read-only/protected document commands retain their checks. The pane is local to each window, clears on a document switch and does not alter the compact right-click menu. Programmatic review commands return structured results without opening UI. From a2f41d728e43d9ab183bfe129005630f4bfd5c57 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:41:53 +0100 Subject: [PATCH 17/99] M14: distinguish font file and unpacked size limits in errors (#6719) --- crates/fonts/src/fontdb/user.rs | 8 +++++++- crates/fonts/src/fontdb/user/tests.rs | 8 ++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/fontdb/user.rs b/crates/fonts/src/fontdb/user.rs index 03f449cdb7..b7aac73983 100644 --- a/crates/fonts/src/fontdb/user.rs +++ b/crates/fonts/src/fontdb/user.rs @@ -63,7 +63,13 @@ impl std::fmt::Display for UserFontError { match self { UserFontError::Empty => write!(f, "the font file is empty"), UserFontError::TooLarge { bytes } => { - write!(f, "the font file is too large ({} MB; at most {} MB)", bytes.div_ceil(1 << 20), MAX_FONT_FILE_BYTES >> 20) + write!( + f, + "the font is too large ({} MB; file limit {} MB, unpacked limit {} MB)", + bytes.div_ceil(1 << 20), + MAX_FONT_FILE_BYTES >> 20, + MAX_DECODED_BYTES >> 20 + ) } UserFontError::NotAFont => write!(f, "not a font file (TrueType, OpenType, TTC, WOFF or WOFF2)"), UserFontError::BadWebFont(e) => write!(f, "the web font couldn't be read: {e}"), diff --git a/crates/fonts/src/fontdb/user/tests.rs b/crates/fonts/src/fontdb/user/tests.rs index a8673e5a1e..f1a71ac985 100644 --- a/crates/fonts/src/fontdb/user/tests.rs +++ b/crates/fonts/src/fontdb/user/tests.rs @@ -210,7 +210,9 @@ fn woff1_claiming(orig: u32) -> Vec { fn a_woff_claiming_a_huge_table_is_refused_before_inflating() { // #3703: the decoder sizes a table's buffer from the directory before inflating it. for orig in [200 << 20, u32::MAX] { - assert!(matches!(decode_font_file(&woff1_claiming(orig)), Err(UserFontError::TooLarge { .. })), "{orig}"); + let error = decode_font_file(&woff1_claiming(orig)).unwrap_err(); + assert!(matches!(&error, UserFontError::TooLarge { .. }), "{orig}"); + assert!(error.to_string().contains("unpacked limit 128 MB"), "{error}"); } // A small claim reaches the decoder, which finds the data doesn't inflate to it. assert!(matches!(decode_font_file(&woff1_claiming(64)), Err(UserFontError::BadWebFont(_)))); @@ -311,7 +313,9 @@ fn junk_is_rejected_without_adding_anything() { assert_eq!(db.families().len(), n + db.user_fonts().iter().map(|u| u.families().len()).sum::()); let mut big = regular.clone(); big.resize(MAX_FONT_FILE_BYTES + 1, 0); - assert!(matches!(db.install_font("big.ttf", &big), Err(UserFontError::TooLarge { .. }))); + let error = db.install_font("big.ttf", &big).unwrap_err(); + assert!(matches!(&error, UserFontError::TooLarge { .. })); + assert!(error.to_string().contains("file limit 50 MB"), "{error}"); } #[test] From f77eef9cb6048d989460b3f02f2b7ab1523e4b88 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:57:20 +0100 Subject: [PATCH 18/99] M14: expose the keyboard shortcut capture name and current key (#6716) --- .../ui-egui/src/dialogs/dialogs_keyboard.rs | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/dialogs_keyboard.rs b/crates/ui-egui/src/dialogs/dialogs_keyboard.rs index dd71f43f2e..6d87e70574 100644 --- a/crates/ui-egui/src/dialogs/dialogs_keyboard.rs +++ b/crates/ui-egui/src/dialogs/dialogs_keyboard.rs @@ -234,8 +234,9 @@ pub fn customize_keyboard(app: &mut WordApp, ui: &mut Ui, f: &mut KeyboardForm) } }); crate::rtl::vertical(ui, |ui| { - ui.label(tl!("New shortcut:")); - close = capture(ui, f); + let label = tl!("New shortcut:"); + ui.label(label); + close = capture(ui, f, label); ui.add_space(4.0); if !f.pressed.is_empty() { let owner = match app.session.keymap.resolve(®, &f.pressed) { @@ -291,7 +292,7 @@ pub fn customize_keyboard(app: &mut WordApp, ui: &mut Ui, f: &mut KeyboardForm) /// The "New shortcut" box: takes keyboard focus and records the combination pressed. /// True when plain Escape asks to close the dialog. -fn capture(ui: &mut Ui, f: &mut KeyboardForm) -> bool { +fn capture(ui: &mut Ui, f: &mut KeyboardForm, label: &str) -> bool { let t = Tokens::get(ui.ctx()); let (rect, resp) = ui.allocate_exact_size(vec2(300.0, 26.0), Sense::click()); // Keys belong to the box whenever nothing else in the dialog has focus, so a shortcut pressed @@ -312,6 +313,8 @@ fn capture(ui: &mut Ui, f: &mut KeyboardForm) -> bool { f.pressed = k; } } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), label)); + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_value(key_text(&f.pressed))); let stroke = egui::Stroke::new(if focused { 1.5 } else { 1.0 }, if focused { t.accent } else { t.input_border }); ui.painter().rect(rect, 2.0, t.input, stroke, egui::StrokeKind::Inside); let (text, color) = if f.pressed.is_empty() { (tl!("Press a key combination").to_string(), t.text_dim) } else { (key_text(&f.pressed), t.text) }; @@ -416,6 +419,22 @@ mod tests { h } + /// The shortcut capture field has a name and reports the combination it records. + #[test] + fn shortcut_capture_exposes_its_name_and_current_value() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut h = harness("", Some("format.bold")); + let input = h.get_by_role_and_label(Role::TextInput, "New shortcut:"); + assert_eq!(input.value().as_deref(), Some("")); + input.focus(); + h.run_steps(2); + h.key_press(egui::Key::F6); + h.run_steps(2); + assert_eq!(h.state().1.pressed, "F6"); + assert_eq!(h.get_by_role_and_label(Role::TextInput, "New shortcut:").value().as_deref(), Some("F6")); + } + type KbHarness<'a> = egui_kittest::Harness<'a, (WordApp, super::KeyboardForm)>; /// The area of the Commands list that is on screen: 170 high, below the title, the item From 7adbdc574cbd9b829163277824afba83282344f5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:12:16 +0100 Subject: [PATCH 19/99] M14: describe canvas member listing without an index (#6714) --- crates/engine/src/cmd/canvas.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/canvas.rs b/crates/engine/src/cmd/canvas.rs index 3e62cdd7f2..021fe9b9dc 100644 --- a/crates/engine/src/cmd/canvas.rs +++ b/crates/engine/src/cmd/canvas.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { .when(has_canvas) .pure(), CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member) - .params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#) + .params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#) .when(has_canvas), ] } @@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult { result(&o) } -/// `canvas.member`: move, resize or remove one member; with no change, list the members. +/// `canvas.member`: move, resize or remove one member; without index, list the members. fn member(s: &mut Session, v: &Value) -> CmdResult { let pos = canvas_pos(s)?; let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else { From ace000b4a4e5cf12d407de6bf6df8e678b23788c Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:26:12 +0100 Subject: [PATCH 20/99] M14: expose table-style formatting names and selection (#6711) --- .../src/dialogs/dialogs_table_style.rs | 65 +++++++++++++++++-- 1 file changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/dialogs_table_style.rs b/crates/ui-egui/src/dialogs/dialogs_table_style.rs index 1b253222e8..23abf9c15c 100644 --- a/crates/ui-egui/src/dialogs/dialogs_table_style.rs +++ b/crates/ui-egui/src/dialogs/dialogs_table_style.rs @@ -288,6 +288,7 @@ fn edge_glyph(ui: &mut Ui, edges: &str) { fn align_button(ui: &mut Ui, (v, h): (VAlign, Align), on: bool, tip: &str) -> egui::Response { let t = Tokens::get(ui.ctx()); let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), on, tip)); let resp = resp.on_hover_text(tip); let p = ui.painter_at(r); let bg = if on { @@ -523,9 +524,9 @@ pub fn body(app: &mut WordApp, ui: &mut Ui, f: Form) -> bool { } let size = ui.add(egui::TextEdit::singleline(&mut r.size).desired_width(36.0)); size.on_hover_text(tl!("Size:")).accessible_name(tl!("Size:")); - ui.toggle_value(&mut r.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold")); - ui.toggle_value(&mut r.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic")); - ui.toggle_value(&mut r.underline, egui::RichText::new("U").underline()).on_hover_text(tl!("Underline")); + ui.toggle_value(&mut r.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold")).accessible_name(tl!("Bold")); + ui.toggle_value(&mut r.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic")).accessible_name(tl!("Italic")); + ui.toggle_value(&mut r.underline, egui::RichText::new("U").underline()).on_hover_text(tl!("Underline")).accessible_name(tl!("Underline")); ui.push_id("tstyle_color", |ui| { ui.label(tl!("Font color:")); color_menu(ui, &theme, &mut r.color); @@ -661,6 +662,42 @@ mod tests { use egui_kittest::kittest::Queryable; use wordcraft_engine::Session; + /// Alignment choices expose their names and current selection, and can be toggled. + #[test] + fn alignment_buttons_expose_names_selection_and_clicks() { + use egui::accesskit::{Role, Toggled}; + use egui_kittest::kittest::NodeT; + let mut h = egui_kittest::Harness::builder().with_size(vec2(200.0, 120.0)).build_ui_state( + |ui, selected: &mut Option| { + for (i, align, label) in + [(0, (VAlign::Top, Align::Left), "Align Top Left"), (1, (VAlign::Bottom, Align::Right), "Align Bottom Right")] + { + let on = *selected == Some(i); + if align_button(ui, align, on, label).clicked() { + *selected = if on { None } else { Some(i) }; + } + } + ui.add_enabled_ui(false, |ui| { + align_button(ui, (VAlign::Center, Align::Center), false, "Align Center"); + }); + }, + Some(0usize), + ); + h.run_steps(2); + assert_eq!(h.get_by_role_and_label(Role::Button, "Align Top Left").accesskit_node().toggled(), Some(Toggled::True)); + assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::False)); + assert!(h.get_by_role_and_label(Role::Button, "Align Center").accesskit_node().is_disabled()); + h.get_by_role_and_label(Role::Button, "Align Bottom Right").click(); + h.run_steps(2); + assert_eq!(*h.state(), Some(1)); + assert_eq!(h.get_by_role_and_label(Role::Button, "Align Top Left").accesskit_node().toggled(), Some(Toggled::False)); + assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::True)); + h.get_by_role_and_label(Role::Button, "Align Bottom Right").click(); + h.run_steps(2); + assert_eq!(*h.state(), None); + assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::False)); + } + fn steps(h: &mut egui_kittest::Harness<'_, WordApp>) { for _ in 0..4 { h.step(); @@ -671,11 +708,15 @@ mod tests { /// even banded rows) and no other. #[test] fn the_part_picker_edits_the_part_it_shows() { + use egui::accesskit::Toggled; + use egui_kittest::kittest::NodeT; let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); app.run("insert.table", json!({"rows": 4, "cols": 3})).unwrap(); app.run("table.newStyle", json!({"name": "Parts"})).unwrap(); app.dialog = Dialog::open("modifyTableStyle", &mut app); assert!(matches!(app.dialog, Some(Dialog::TableStyle { .. }))); + // Keep the background ribbon's character controls out of the dialog's label queries. + app.ui.tab = "Insert".into(); let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( |ui, app: &mut WordApp| { let ctx = ui.ctx().clone(); @@ -691,15 +732,25 @@ mod tests { h.get_by_label("Even Banded Rows").click(); steps(&mut h); assert!(matches!(&h.state().dialog, Some(Dialog::TableStyle { region, .. }) if *region == part_index(TablePart::Band2Horz))); - h.get_by_label("B").click(); - steps(&mut h); + for label in ["Bold", "Italic", "Underline"] { + assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::False)); + h.get_by_label(label).click(); + steps(&mut h); + assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True)); + } h.get_by_label("OK").click(); steps(&mut h); assert!(h.state().dialog.is_none(), "OK closes the dialog"); let st = h.state().session.doc.styles.get("Parts").cloned().unwrap(); - assert_eq!(st.table_part(TablePart::Band2Horz).chr.bold, Some(true)); + let chr = st.table_part(TablePart::Band2Horz).chr; + assert_eq!(chr.bold, Some(true)); + assert_eq!(chr.italic, Some(true)); + assert!(chr.underline.is_some_and(|u| u != Underline::None)); for other in [TablePart::WholeTable, TablePart::Band1Horz, TablePart::FirstRow, TablePart::Band2Vert] { - assert_ne!(st.table_part(other).chr.bold, Some(true), "{}", other.ooxml()); + let chr = st.table_part(other).chr; + assert_ne!(chr.bold, Some(true), "{}", other.ooxml()); + assert_ne!(chr.italic, Some(true), "{}", other.ooxml()); + assert!(!chr.underline.is_some_and(|u| u != Underline::None), "{}", other.ooxml()); } } From 7b26a941935b423e75697fb8e9e29335a7d5fb86 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:39:06 +0100 Subject: [PATCH 21/99] M14: clarify dictionary-folder auto reset (#6709) --- crates/engine/src/cmd/options.rs | 2 +- crates/engine/src/prefs.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/options.rs b/crates/engine/src/cmd/options.rs index add7d879d2..e7cc43dde0 100644 --- a/crates/engine/src/cmd/options.rs +++ b/crates/engine/src/cmd/options.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { vec![ CommandSpec::new("file.options", "Options", "File", options) .params( - r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: the system locations only), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#, + r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#, ) .pure(), CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| { diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 735a0b6094..b1149b5652 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -39,7 +39,7 @@ pub struct Prefs { pub region: Option, /// A folder searched for Hunspell dictionaries before the system locations (File › Options › /// Language, #1063): an app started from Finder or the Dock doesn't see - /// `WORDCRAFT_DICTIONARIES`. `None` searches the system locations only. + /// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder. pub dictionaries_folder: Option, /// The user templates folder File › New lists personal templates from and Save as Word /// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's From 3bf4c05461f9728b13e67a73ae198862878a8065 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:54:32 +0100 Subject: [PATCH 22/99] M14: explain the bookmark name rules in validation errors (#6706) --- crates/engine/src/cmd/insert/links.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/insert/links.rs b/crates/engine/src/cmd/insert/links.rs index d38e78f603..f383365134 100644 --- a/crates/engine/src/cmd/insert/links.rs +++ b/crates/engine/src/cmd/insert/links.rs @@ -188,7 +188,9 @@ pub(super) fn delete_bookmark(s: &mut Session, v: &Value) -> CmdResult { pub(super) fn bookmark(s: &mut Session, v: &Value) -> CmdResult { let name = p::req_str(v, "name")?.trim().to_string(); if !bookmark_name_ok(&name) { - return Err(CmdError::Params("bookmark names start with a letter, have no spaces and at most 40 characters".into())); + return Err(CmdError::Params( + "bookmark names start with a letter or underscore, contain only letters, numbers or underscores, and have at most 40 characters".into(), + )); } // Replace an existing bookmark of the same name. remove_bookmark(s, &name)?; From 4a347e070a5e399495f12d6b527fc6cac18bab7f Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:07:55 +0100 Subject: [PATCH 23/99] M14: expose required command inputs in discovery (#6703) --- crates/engine/src/cmd/design.rs | 3 ++- crates/engine/src/cmd/mailings.rs | 1 + crates/engine/src/cmd/para.rs | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0e091c9f47..858ccc873b 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -63,7 +63,8 @@ pub fn specs() -> Vec { let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?; set_accent(s, t.3[0]); sel_result(s) - }), + }) + .params(r#"{"name": string (see design.themes)}"#), CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set) .params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#), CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing) diff --git a/crates/engine/src/cmd/mailings.rs b/crates/engine/src/cmd/mailings.rs index 4836ac9554..fa109031a6 100644 --- a/crates/engine/src/cmd/mailings.rs +++ b/crates/engine/src/cmd/mailings.rs @@ -192,6 +192,7 @@ pub fn specs() -> Vec { refresh(s); Ok(json!({"record": idx + 1})) }) + .params(r#"{"text": string}"#) .when(has_recipients), CommandSpec::new("mailings.checkErrors", "Check for Errors", "Mailings › Finish", |s, _| { let mut missing = Vec::new(); diff --git a/crates/engine/src/cmd/para.rs b/crates/engine/src/cmd/para.rs index 06068ee65d..2f60046cad 100644 --- a/crates/engine/src/cmd/para.rs +++ b/crates/engine/src/cmd/para.rs @@ -274,7 +274,8 @@ pub fn specs() -> Vec { st.quick = on; } sel_result(s) - }), + }) + .params(r#"{"style": string (name or id), "value"?: bool (default true)}"#), // Advanced paragraph tools (#5043, as in WPS Office): conversions and cleanup over the // selection, or the whole document with `scope: "all"`. One undo step per command. CommandSpec::new("para.convertBreaks", "Convert Line Breaks to Paragraphs", "Home › Paragraph › Paragraph Tools", convert_breaks) From 646fbc7cd55c86d8a63d73231c5aaa8173c9ec34 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:20:17 +0100 Subject: [PATCH 24/99] M10: clarify Zotero command response shapes (#6700) --- docs/zotero.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/zotero.md b/docs/zotero.md index 4e96520ad5..11f03a80df 100644 --- a/docs/zotero.md +++ b/docs/zotero.md @@ -19,11 +19,14 @@ Citations (each runs one of the commands below). | `ui.zotero.status` | `{busy, waitingForAnswer, last}` | | `ui.zotero.answer` | `{"button": n}`: answer a question Zotero is asking (OK/Yes 1, No/Cancel 0; with Yes/No/Cancel: Yes 2, No 1, Cancel 0) | -They run in the app (and through the control channel and MCP bridged to the app). A command -returns at once with `{"started": …}`; Zotero then works in its own window and WordCraft answers -it in the background. All changes from one command are one undo step. If New or Open replaces -the document while a command is running, Zotero's remaining calls for it get an error and the -new document is left as it is. +They run in the app (and through the control channel and MCP bridged to the app). The six Zotero +actions return at once with `{"started": …}`; Zotero then works in its own window and WordCraft +answers it in the background. All changes from one action are one undo step. If New or Open +replaces the document while an action is running, Zotero's remaining calls for it get an error +and the new document is left as it is. + +`ui.zotero.status` returns the current state. A successful `ui.zotero.answer` returns +`{"answered": n}` for the selected button. From a terminal, against a file: From b2306fe5ef70dc66e4554c312fd0b11f99542c84 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:36:03 +0100 Subject: [PATCH 25/99] M3: explain invalid font name values (#6698) --- crates/engine/src/cmd/format.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index ce35c9b348..3d6beb50d9 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult { let Some(n) = v.get(k) else { return Ok(None) }; let n = n.as_str().map(str::trim).unwrap_or(""); if n.is_empty() || n.len() > 128 { - return Err(CmdError::Params(format!("bad font name `{k}`"))); + return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes"))); } Ok(Some(n.to_string())) }; From cd23034f6518f45a17bd11329543f5425a9e9ee9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:52:01 +0100 Subject: [PATCH 26/99] M14: clarify when layout tests need explicit font initialization (#6697) --- docs/testing.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index 4b166bfaa4..2b47bbcb4a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -5,12 +5,14 @@ Source Serif 4, Inter and JetBrains Mono, with their bundled styles. Family list legacy style names such as Inter Medium. They do not load installed fonts, user font preferences, or the optional `CRAFT_FONTS_DIR` input. No download or extra font checkout is required. -Every layout unit test starts with `crate::test_fonts();`, before constructing its fixture or -resolving a font. This initializes the process-wide database once, including when a single test is -run by name. The `wordcraft-fonts/test-support` development feature exposes the initializer; -enabling the feature alone has no effect. Initialization fails if an application database already -exists, rather than replacing a database whose faces may be in the shaping or math caches. -Other test binaries and application builds keep their normal font discovery behavior. +Layout entry points (`layout`, `layout_para`, `layout_equation` and +`display::mark_text_width`) initialize the process-wide font database once in unit-test builds, +including when a single test is run by name. Tests that resolve fonts before calling a layout +entry point must first call `crate::test_fonts();`. The `wordcraft-fonts/test-support` +development feature exposes the initializer; enabling the feature alone has no effect. +Initialization fails if an application database already exists, rather than replacing a database +whose faces may be in the shaping or math caches. Other test binaries and application builds +keep their normal font discovery behavior. Uninstalled requested families use the normal substitution lists, restricted to this fixed set. In particular, the default Aptos request resolves to Source Sans 3. These fonts are not Calibri From ae2d2b43d694885d57e65889c0b35545bd6095ef Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:03:22 +0100 Subject: [PATCH 27/99] M3: describe the 32-bit comment identifier limit (#6696) --- crates/engine/src/cmd/review.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index f0539f0a1c..d2a8724bd7 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -28,12 +28,12 @@ pub fn specs() -> Vec { vec![ CommandSpec::new("review.newComment", "New Comment", "Review › Comments", new_comment).key(super::mac_or("Mod+Alt+A / Mod+Alt+M", "Mod+Alt+M")).params(r#"{"text": string}"#), CommandSpec::new("review.reply", "Reply", "Review › Comments", reply) - .params(r#"{"id": non-negative JSON integer, "text": string}"#) + .params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#) .when(comments_change), CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment) - .params(r#"{"id": non-negative JSON integer, "text": string}"#) + .params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#) .when(comments_change), - CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "all"?: bool}"#), + CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#), CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| { validate_comment_id(v)?; let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { c.resolved = p::bool(v, "value").unwrap_or(!c.resolved); sel_result(s) }) - .params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#), + .params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#), CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(), CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(), CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(), From 5d871d05197f0b11aa6304400edd1dc2c434aa9a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:15:46 +0100 Subject: [PATCH 28/99] M14: document the selection collapse end parameter (#6695) --- crates/engine/src/cmd/caret.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/caret.rs b/crates/engine/src/cmd/caret.rs index 23b83e7084..c519c9e060 100644 --- a/crates/engine/src/cmd/caret.rs +++ b/crates/engine/src/cmd/caret.rs @@ -68,6 +68,7 @@ pub fn specs() -> Vec { sel_result(s) }) .key("Escape") + .params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#) .pure(), ] } From 435716653115f42c1ee13159dd200497a57dce47 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:28:39 +0100 Subject: [PATCH 29/99] M14: report the supported ICO image bounds (#6694) --- xtask/src/ico.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/xtask/src/ico.rs b/xtask/src/ico.rs index 42413b1299..171d7075ad 100644 --- a/xtask/src/ico.rs +++ b/xtask/src/ico.rs @@ -19,7 +19,7 @@ pub fn png_size(png: &[u8]) -> Result<(u32, u32), String> { /// An ICO file holding `pngs`, which must be square and at most 256 px. pub fn pack(pngs: &[Vec]) -> Result, String> { if pngs.is_empty() || pngs.len() > u16::MAX as usize { - return Err("need at least one PNG".into()); + return Err("need between 1 and 65535 PNGs".into()); } let mut out = Vec::new(); out.extend_from_slice(&0u16.to_le_bytes()); // reserved @@ -29,7 +29,7 @@ pub fn pack(pngs: &[Vec]) -> Result, String> { for png in pngs { let (w, h) = png_size(png)?; if w != h || w == 0 || w > 256 { - return Err(format!("icon images must be square and at most 256 px, got {w}x{h}")); + return Err(format!("icon images must be square and between 1 and 256 px, got {w}x{h}")); } let dim = if w == 256 { 0 } else { w as u8 }; out.extend_from_slice(&[dim, dim, 0, 0]); // width, height, palette size, reserved @@ -87,10 +87,13 @@ mod tests { #[test] fn rejects_bad_input() { - assert!(pack(&[]).is_err()); - assert!(pack(&[fake_png(512)]).is_err()); + assert_eq!(pack(&[]).unwrap_err(), "need between 1 and 65535 PNGs"); + assert_eq!(pack(&vec![Vec::new(); usize::from(u16::MAX) + 1]).unwrap_err(), "need between 1 and 65535 PNGs"); + assert_eq!(pack(&[fake_png(0)]).unwrap_err(), "icon images must be square and between 1 and 256 px, got 0x0"); + assert_eq!(pack(&[fake_png(512)]).unwrap_err(), "icon images must be square and between 1 and 256 px, got 512x512"); assert!(pack(&[b"GIF89a".to_vec()]).is_err()); assert_eq!(png_size(&fake_png(48)).unwrap(), (48, 48)); + assert!(pack(&[fake_png(1)]).is_ok()); } #[test] From 8377ea8e8f20d799c0172d215d90527746581b61 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:59:18 +0100 Subject: [PATCH 30/99] M7: document the explicit stop flag for protection (#6690) --- crates/engine/src/cmd/protect.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/protect.rs b/crates/engine/src/cmd/protect.rs index 986b46fe53..1eb1cd41fd 100644 --- a/crates/engine/src/cmd/protect.rs +++ b/crates/engine/src/cmd/protect.rs @@ -22,7 +22,7 @@ const MODES: [&str; 5] = ["none", "readOnly", "comments", "trackedChanges", "for pub fn specs() -> Vec { vec![ CommandSpec::new("review.restrict", "Restrict Editing", "Review › Protect", restrict).params( - r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (start enforcing; "none" stops), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool, "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#, + r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (editing restriction; use "none" with "formatting": true for formatting-only protection), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool (true: stop protection), "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#, ), ] } From 739491f5c79f8b1a13ad15ba4fb021a4955ed0c4 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:13:51 +0100 Subject: [PATCH 31/99] M14: list xtask version and point layering help at public docs (#6688) --- xtask/src/main.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 23cbc5f0e4..2f59d773e7 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -19,7 +19,7 @@ usage: cargo xtask commands: assets check that every icon/image/font/asset is attributed in ATTRIBUTION.md - layers enforce the crate dependency layering (plan/architecture.md §3) + layers enforce the crate dependency layering (docs/architecture.md, Layers) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call) test workspace tests (cargo nextest when installed, else cargo test), the interface audit with its missing-translation report, then doctests @@ -34,6 +34,8 @@ commands: show where test corpora live; --download fetches PngSuite into corpus/pngsuite stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) parity recompute the Word feature-parity summary in docs/parity-checklist.md + version [set X.Y.Z[-pre]] + show the workspace version, or set it and update Cargo.lock visual-diff [--private] [--dpi N] compare two PDFs of a document page by page (SSIM, line breaks, offsets); needs poppler (pdftoppm, pdftotext) @@ -100,7 +102,7 @@ pub fn metadata() -> Result { fn cmd_layers() -> Result<(), String> { let crates = layers::from_metadata(&metadata()?)?; - println!("Dependency layering (plan/architecture.md §3)\n"); + println!("Dependency layering (docs/architecture.md, Layers)\n"); println!("{:<28} {:<14} workspace deps", "crate", "layer"); for c in &crates { let ws: Vec = c From a61cef5d4525be06682f651b7136438ce7aacab9 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:29:41 +0100 Subject: [PATCH 32/99] edit.replace reports whether it replaced and what it selected (#6877) (#6879) --- crates/engine/src/cmd/edit.rs | 19 +++++++++++++++---- crates/engine/src/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e776eab85a..ae221791b8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -141,7 +141,9 @@ pub fn specs() -> Vec { .key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp")) .params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#) .pure(), - CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#), + CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params( + r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#, + ), // Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening // it changes nothing, so it is its own command and never marks the document edited. CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| { @@ -746,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult { let story = s.sel.focus.story; let results = search_full(s, story, true)?; let (a, b) = s.sel.ordered(); - // Replace the current match if selected, then move to the next. + // Replace the current match if selected, then move to the next. The result says which + // happened (#6877): a first call that only selects a match reads as `replaced: 0`. + let mut replaced = 0; if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) { super::paste_text(s, &f.rep.unwrap_or_default())?; + replaced = 1; } - let _ = step(s, 1); - Ok(json!({"remaining": search(s, story)?.len()})) + let selected = match step(s, 1) { + Ok(_) => { + let (start, end) = s.sel.ordered(); + json!({"start": pos_json(&start), "end": pos_json(&end)}) + } + Err(_) => Value::Null, + }; + Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected})) } /// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bdd80d61d3..c9de4b79a2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1108,6 +1108,26 @@ fn replace_under_track_changes_skips_deleted_text() { assert_eq!(text(&s), "one dog two dog"); } +#[test] +fn replace_reports_whether_it_replaced_and_what_it_selected() { + // Replace follows Word's button: the first call only selects a match. Agents read + // `remaining` alone as done (#6877), so the result says whether anything was replaced. + let mut s = s(); + run(&mut s, "document.setText", json!({"text": "alpha XX beta XX gamma XX"})); + run(&mut s, "caret.docStart", json!({})); + let calls: Vec<_> = (0..5).map(|_| run(&mut s, "edit.replace", json!({"text": "XX", "with": "YY"}))).collect(); + let replaced: Vec<_> = calls.iter().map(|r| r["replaced"].clone()).collect(); + assert_eq!(replaced, [json!(0), json!(1), json!(1), json!(1), json!(0)]); + let remaining: Vec<_> = calls.iter().map(|r| r["remaining"].clone()).collect(); + assert_eq!(remaining, [json!(3), json!(2), json!(1), json!(0), json!(0)]); + let selected: Vec<_> = calls.iter().map(|r| (r["selected"]["start"]["off"].clone(), r["selected"]["end"]["off"].clone())).collect(); + assert_eq!(selected[0], (json!(6), json!(8))); + assert_eq!(selected[1], (json!(14), json!(16))); + assert_eq!(selected[2], (json!(23), json!(25))); + assert!(calls[3]["selected"].is_null() && calls[4]["selected"].is_null(), "no match is left to select"); + assert_eq!(text(&s), "alpha YY beta YY gamma YY"); +} + #[test] fn find_reads_the_text_around_tracked_deletions() { // `edits` are (start, end) byte ranges deleted with Track Changes on, last first. From 9144b9bfdaaa07d864b006365f8d85995b59420c Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:45:40 +0100 Subject: [PATCH 33/99] =?UTF-8?q?Insert=20=E2=80=BA=20Shapes:=20the=20Arro?= =?UTF-8?q?w=20tile=20is=20the=20block=20arrow=20it=20inserts=20(#6768)=20?= =?UTF-8?q?(#6882)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/icons.rs | 40 +++++++++++++++++++++++++++++++++++-- docs/ui-parity.md | 3 ++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 87a6cb6720..803bf454bb 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -1645,9 +1645,19 @@ fn shape(pen: &Pen, kind: &str) -> bool { "triangle" => solid(&[(10.0, 3.5), (17.0, 16.5), (3.0, 16.5)]), "diamond" => solid(&[(10.0, 3.0), (17.0, 10.0), (10.0, 17.0), (3.0, 10.0)]), "line" => pen.line(&[(4.0, 16.0), (16.0, 4.0)]), + // The block arrow the tile inserts (#6768), from the outline the document draws it with. "arrow" => { - pen.line(&[(4.0, 16.0), (14.5, 5.5)]); - head((16.5, 3.5), (4.0, 16.0)); + let (x0, y0, w, h) = (3.0, 5.0, 14.0, 10.0); + let pts: Vec<(f32, f32)> = wordcraft_doc::wrap::arrow_outline(wordcraft_doc::para::ShapeKind::Arrow, w, h) + .iter() + .map(|&(u, v)| (x0 + u * w, y0 + v * h)) + .collect(); + // Concave: the shaft and the head are tinted apart, then the outline. + if let [tail_top, neck_top, barb_top, tip, barb_bottom, neck_bottom, tail_bottom] = pts[..] { + pen.fill(&[tail_top, neck_top, neck_bottom, tail_bottom], tint); + pen.fill(&[barb_top, tip, barb_bottom], tint); + } + pen.closed(&pts, c); } "star" => { let pts: Vec<(f32, f32)> = (0..10) @@ -1745,6 +1755,32 @@ mod tests { assert!(!has_default_highlight_bar("shadingNoBar")); } + /// #6768: the Insert › Shapes Arrow tile is the block arrow that tile inserts, outlined as the + /// document draws it, not a thin line with a head. + #[test] + fn the_arrow_tile_is_the_block_arrow_it_inserts() { + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| { + paint(ui.painter(), Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), "shape.arrow", Color32::BLACK, Color32::BLUE); + }); + let outline: Vec = output + .shapes + .iter() + .find_map(|s| match &s.shape { + // The outline, not the tinted fills (closed too, but without a stroke). + Shape::Path(path) if path.closed && path.stroke.width > 0.0 => Some(path.points.clone()), + _ => None, + }) + .expect("the arrow is outlined"); + output.drop_without_applying_deltas(); + let want = wordcraft_doc::wrap::arrow_outline(wordcraft_doc::para::ShapeKind::Arrow, 14.0, 10.0); + assert_eq!(outline.len(), want.len(), "{outline:?}"); + for (got, (u, v)) in outline.iter().zip(want) { + let expected = pos2(3.0 + u * 14.0, 5.0 + v * 10.0); + assert!(got.distance(expected) < 0.01, "{got:?} vs {expected:?}"); + } + } + /// Verify that the fitOnePage vector icon renders without panics and emits shapes. #[test] fn fit_one_page_icon_paints_without_panic() { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 896df8ef65..f73ec040ba 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (while editing a header or footer, a click on its Behind Text picture selects it wherever no header or footer line's band (plus 40pt) covers it, down over the body or in a clear area inside the band, and a right-click selects it too so Reset Picture and Wrap Text act on it); previously trivial (File › Print opened again no longer shows the last job's "submitted" or failure message when that window already said it; decided per window, the shared message and `ui.printSettings` untouched); previously trivial (Save As and Export offer Browse in WordCraft… on Linux/BSD, as Open does, #3535); previously trivial (Language dialog: whole-document OK sends Do not check only when the box was clicked, so per-run proofing state is not flattened; glossary skipped while Track Formatting is on and reported as `glossarySkipped`, #3518); previously trivial (Language dialog: Apply to the whole document sets the proofing language or no-proof for every story in one undo step, #3518); previously trivial (Ctrl/Cmd+Shift+V pastes the formatting picked up with Ctrl/Cmd+Shift+C or the Format Painter, or text only when none was, as in Word, #1537); previously trivial (Auto interface size capped to the screen, Ctrl+Shift+0 returns to Auto, #4030); previously trivial (clipboard: a copied picture reaches the system clipboard as PNG, with HTML where the host writes it, while a copy of only shapes stays in WordCraft, #6205); previously trivial (Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (a press the canvas handles, such as Ctrl+click on a link, no longer also shows the link tooltip that frame, #4683); previously trivial (the window moves by its title bar behind a modal dialog, as in Word for Mac, #5124); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux and the BSDs no longer looks semi-bold); previously trivial (the document's scroll bars show wherever the pointer is, not only at the window's edge, #5746); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (dragging an In Line with Text object shows a bold insertion cursor, as in Word, instead of a faint dashed one, #4195); previously trivial (the shapes, pictures and text boxes inside a Drawing Canvas are picked, moved and resized on their own, #2637); previously trivial (Shape Format › Size shows the interface unit and takes any typed unit, #4196); previously trivial (over a turned picture, shape or text box the resize arrows turn with it, #3932); previously trivial (the status bar's count is words by default and can be characters with or without spaces, chosen from its right-click menu or File › Options › Display and kept between runs, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (dialogs are modal except Find and Replace, Symbol, Mark Index Entry, Cross-reference and Insert Merge Field, and a press beside one shakes it, #3859); previously trivial (showing the Format Shape pane leaves a gradient angle above 359.9° as it is, #3955); previously trivial (Return on File › Print prints, as Word's default Print button does); previously trivial (N-up and booklet printing, #641; readiness unchanged); previously trivial (missing fonts flagged in the font box and status bar, read from what layout drew; metric-compatible substitutes and symbol fonts not flagged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (a long comment's card and balloon stop at ten lines, #3382); previously minor (Arabic mirrored interface: ribbon, panes, File page, dialogs, menus; document canvas independent, #1195); previously trivial (Alt, F badges the Backstage pages; Alt, F, P and V open Print, #4960); previously trivial (View › Macros opens a Macros dialog with Run, Delete and Record, #4327); previously trivial (aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (Table Properties: row, column and cell settings apply to the selected rows, columns and cells; mixed row check boxes, #4857); previously trivial (Insert › Shapes shows the basic shapes as a grid of drawn icon tiles, #4349); previously trivial (File › Options › Proofing › AutoCorrect Options opens with no document open, #4585); previously trivial (the Shading buttons show the last picked colour, #4412); previously trivial (a blank User Name in File › Options stays blank after a restart, #4368); previously trivial (window size falls back to the screen rectangle when the reported inner size is invalid; equation symbol tooltips no longer repeat a missing glyph's name); previously trivial (window titles and suggested file names omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (the Insert › Shapes Arrow tile is drawn as the block arrow it inserts, not a thin line arrow, #6768); previously trivial (while editing a header or footer, a click on its Behind Text picture selects it wherever no header or footer line's band (plus 40pt) covers it, down over the body or in a clear area inside the band, and a right-click selects it too so Reset Picture and Wrap Text act on it); previously trivial (File › Print opened again no longer shows the last job's "submitted" or failure message when that window already said it; decided per window, the shared message and `ui.printSettings` untouched); previously trivial (Save As and Export offer Browse in WordCraft… on Linux/BSD, as Open does, #3535); previously trivial (Language dialog: whole-document OK sends Do not check only when the box was clicked, so per-run proofing state is not flattened; glossary skipped while Track Formatting is on and reported as `glossarySkipped`, #3518); previously trivial (Language dialog: Apply to the whole document sets the proofing language or no-proof for every story in one undo step, #3518); previously trivial (Ctrl/Cmd+Shift+V pastes the formatting picked up with Ctrl/Cmd+Shift+C or the Format Painter, or text only when none was, as in Word, #1537); previously trivial (Auto interface size capped to the screen, Ctrl+Shift+0 returns to Auto, #4030); previously trivial (clipboard: a copied picture reaches the system clipboard as PNG, with HTML where the host writes it, while a copy of only shapes stays in WordCraft, #6205); previously trivial (Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (a press the canvas handles, such as Ctrl+click on a link, no longer also shows the link tooltip that frame, #4683); previously trivial (the window moves by its title bar behind a modal dialog, as in Word for Mac, #5124); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux and the BSDs no longer looks semi-bold); previously trivial (the document's scroll bars show wherever the pointer is, not only at the window's edge, #5746); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (dragging an In Line with Text object shows a bold insertion cursor, as in Word, instead of a faint dashed one, #4195); previously trivial (the shapes, pictures and text boxes inside a Drawing Canvas are picked, moved and resized on their own, #2637); previously trivial (Shape Format › Size shows the interface unit and takes any typed unit, #4196); previously trivial (over a turned picture, shape or text box the resize arrows turn with it, #3932); previously trivial (the status bar's count is words by default and can be characters with or without spaces, chosen from its right-click menu or File › Options › Display and kept between runs, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (dialogs are modal except Find and Replace, Symbol, Mark Index Entry, Cross-reference and Insert Merge Field, and a press beside one shakes it, #3859); previously trivial (showing the Format Shape pane leaves a gradient angle above 359.9° as it is, #3955); previously trivial (Return on File › Print prints, as Word's default Print button does); previously trivial (N-up and booklet printing, #641; readiness unchanged); previously trivial (missing fonts flagged in the font box and status bar, read from what layout drew; metric-compatible substitutes and symbol fonts not flagged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (a long comment's card and balloon stop at ten lines, #3382); previously minor (Arabic mirrored interface: ribbon, panes, File page, dialogs, menus; document canvas independent, #1195); previously trivial (Alt, F badges the Backstage pages; Alt, F, P and V open Print, #4960); previously trivial (View › Macros opens a Macros dialog with Run, Delete and Record, #4327); previously trivial (aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (Table Properties: row, column and cell settings apply to the selected rows, columns and cells; mixed row check boxes, #4857); previously trivial (Insert › Shapes shows the basic shapes as a grid of drawn icon tiles, #4349); previously trivial (File › Options › Proofing › AutoCorrect Options opens with no document open, #4585); previously trivial (the Shading buttons show the last picked colour, #4412); previously trivial (a blank User Name in File › Options stays blank after a restart, #4368); previously trivial (window size falls back to the screen rectangle when the reported inner size is invalid; equation symbol tooltips no longer repeat a missing glyph's name); previously trivial (window titles and suggested file names omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. @@ -128,6 +128,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | Date | Change | Summary | |---|---|---| +| 2026-11-16 | trivial | Insert › Shapes: the Arrow tile is drawn as the block arrow it inserts, from the outline the document draws it with, instead of a thin line with a head (#6768) | | 2026-11-15 | trivial | Header/footer pictures: while editing the header or footer, a click on its Behind Text picture selects it wherever no header or footer text covers it: drawn down over the body (anchored in the header, positioned outside the band) or in a clear area inside the band. What counts as header or footer text is each line's own band (the width available to it, so a centred or right-aligned line covers the empty space beside its ink, while an indent or a float beside the line narrows it) plus a 40pt margin either side; a drag there moves it, and a right-click selects it so Reset Picture and Wrap Text act on it. Over header or footer text the click still goes to the text, and from the body a click there is still body text (`canvas::tests::header_picture_clear_of_header_text_is_selected_while_editing_the_header`, `canvas::tests::footer_picture_clear_of_footer_text_is_selected_while_editing_the_footer`, `canvas::tests::right_clicking_a_repeated_header_picture_selects_it_on_its_own_page`, `tests::header_text_covers_the_whole_band_of_centred_and_right_lines`) | | 2026-11-15 | trivial | File › Print opened again no longer shows how the last job went ("Print job submitted…", a failure): that was said once in the status bar. A failure that comes in while the page is open stays, and printer status (finding printers, none found) shows each time. Decided per window: a result a window never said (it arrived under File's other pages, or in another window) still shows there, and the shared message that `ui.printSettings` reports is never cleared | | 2026-11-14 | trivial | Save As and Export (also the formats on the Print page) offer Browse in WordCraft… on Linux/BSD, as Open does; exporting there lists Export's formats as the types, whose extension replaces a known document extension on the name; an export refusal or failure shows on the Export page, as Save As's does (#3535) | From 211f62231d32502dce1c2015f603436d75099fbf Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:03:15 +0100 Subject: [PATCH 34/99] M14: correct control protocol parameter examples (#6684) --- docs/control-protocol.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9ab4c4d705..c987bf8fb1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-11-09 · #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows. +> **Last updated:** 2026-11-14 · Correct the force-close request envelope and document the optional command search parameter; command behavior unchanged. #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows. Start the app with a control port: `wordcraft --control 7981` (or `WORDCRAFT_CONTROL_PORT=7981`). A missing or invalid port after `--control` (not 1–65535) prints an error and exits with status 2. @@ -85,7 +85,7 @@ let apps move windows, so there Arrange All and Side by Side only resize. | Method | Params | Result | |---|---|---| | `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"\|"export"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576; `export` offers File › Export's formats as its types, #3535), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) | -| `engine.commands` | — | every command: id, label, location, shortcut, params, enabled | +| `engine.commands` | `search?` | every command: id, label, location, shortcut, params, enabled | | `document.inspect` | `text?`, `doc?` | blocks (text, style, runs, lists, tables), parts, sections, selection, pages | | `ui.inspect` | — | UI state, view, dialog, window size, page rects on screen, caret, comment balloons (`balloons`: id + screen rect; `balloon`: the selected one), perf; `windows`: the other windows as the drawn window sees them (`available`, `others`, `sideBySide`, `syncScroll`); `document`: the active document's id; `documents`: the open documents (`id`, `title`, `path`, `dirty`, `active`) | | `ui.click` | `x`, `y`, `button?`, `count?`, `shift?`, `cmd?`, `alt?` | real pointer input at window coordinates | @@ -187,7 +187,7 @@ discard unsaved work is **refused with an error** (the app keeps running and the save first (`file.save`), or pass `{"force": true}` to discard the changes and go ahead. `file.close` closes the shown document, so it is refused while that document has unsaved -changes; the bare form `{"method": "file.close", "force": true}` (a method name that is a +changes; the bare form `{"method": "file.close", "params": {"force": true}}` (a method name that is a command id) is guarded the same way, and only a boolean `true` counts as `force`. A document without unsaved changes closes at once (#1268). Closing closes the document and its window, and the window focused before it becomes the active one. The last window stays open with no page, From ff0823f40d3e0591f4b194ba1a7c8704aa6719c5 Mon Sep 17 00:00:00 2001 From: Diego Guerini <106814760+D13GOOOO@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:19:00 +0100 Subject: [PATCH 35/99] Track Changes: a deleted list item's number is drawn as deleted text (#4828) (#4836) Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/layout/src/display/lines.rs | 57 ++++++++++++++-- crates/layout/src/tests.rs | 102 +++++++++++++++++++++++++++++ docs/gaps.md | 5 +- docs/layout-parity.md | 4 +- 5 files changed, 164 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index d193359773..31b65c8ae9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,7 +8,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. @@ -151,6 +151,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged. fix/6146-touchpad-scroll-speed - 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed. @@ -922,6 +923,7 @@ MATH glyphs that reference the same construction now share its immutable variant | Date | Change | Summary | |---|---|---| +| 2026-10-30 | trivial | Progress log: under Track Changes a list item deleted whole shows its number as deleted text, in the deletion's colour and mark (#4828); readiness unchanged | | 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) | | 2026-11-04 | trivial | Progress log: #4501 refactor regressions restored (#4683) | | 2026-11-06 | trivial | Progress log: edited ODT paragraphs keep custom styles with an outline level (gap 19) | diff --git a/crates/layout/src/display/lines.rs b/crates/layout/src/display/lines.rs index 3fabfbfb01..22ccbf7dfe 100644 --- a/crates/layout/src/display/lines.rs +++ b/crates/layout/src/display/lines.rs @@ -470,12 +470,41 @@ fn character_backgrounds(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { } fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { + // A list number goes with its paragraph mark: when the mark is a tracked deletion the number + // is drawn as deleted text is, in the deletion's colour and with its mark (struck through by + // default, a caret, #s, bold…), and not at all where deletions aren't shown (#4828). Only + // when the item is deleted whole, its text too: a deleted mark alone joins the item to the + // next one, and its text and number stay as they are. + let m = &ctx.opts.revisions; + let whole = ctx.para.is_some_and(|p| p.runs.iter().all(|r| r.len == 0 || r.props.del.is_some())); + let mark_del = ctx.para.filter(|_| whole).and_then(|p| p.mark.del); + let moved = mark_del.is_some() && ctx.doc.move_name(mark_del).is_some(); + let hidden = mark_del.is_some() && (!ctx.opts.markup || m.hides_deletion(moved)); + let deleted = mark_del.filter(|_| ctx.opts.markup && m.insertions_deletions); + let del_mark = deleted.map(|_| if moved { m.move_from_mark } else { m.delete_mark }); + // Moved-away text marked (none) is plain text, and so is its number. + let plain_move = moved && del_mark == Some(DeleteMark::None); + let del_color = + deleted.filter(|_| !plain_move).map(|r| if moved { m.move_from_color } else { m.delete_color }.unwrap_or_else(|| ctx.authors.color(r))); if ctx.li == ctx.pl.label_line() + && !hidden && let Some(label) = &ctx.pl.label { let gx = ctx.x + label.x; + let first = label.runs.first().and_then(|r| ctx.pl.styles.get(r.style as usize)); + if let (Some(DeleteMark::Caret), Some(color), Some(style)) = (del_mark, del_color, first) { + // A caret where the number was, instead of the number. + let (h, w, y) = (style.size * 0.3, (style.size / 18.0).max(0.6), ctx.base + 1.0); + for (x0, y0, x1, y1) in [(gx - h * 0.6, y, gx, y - h), (gx, y - h, gx + h * 0.6, y)] { + out.push(Draw::Line { x0, y0, x1, y1, width: w, color, stroke: Stroke::Solid, alpha: ctx.alpha, text_bg: None }); + } + return draw_hyphen(ctx, out); + } for run in &label.runs { let Some(style) = ctx.pl.styles.get(run.style as usize) else { continue }; + let color = del_color.unwrap_or_else(|| ctx.ink(&style.rc.color, None)); + // Each deleted character shows as #. + let hash = (del_mark == Some(DeleteMark::Hash)).then(|| style.face.glyph_for('#')); out.push(Draw::Glyphs { face: style.face, size: style.size, @@ -484,12 +513,12 @@ fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { .get(run.glyphs.clone()) .into_iter() .flatten() - .map(|g| (g.gid, gx + g.dx, ctx.base - style.shift - g.dy)) + .map(|g| (hash.unwrap_or(g.gid), gx + g.dx, ctx.base - style.shift - g.dy)) .collect(), - color: ctx.ink(&style.rc.color, None), + color, alpha: ctx.alpha, - synth_bold: style.synth_bold, - synth_italic: style.synth_italic, + synth_bold: style.synth_bold || del_mark == Some(DeleteMark::Bold), + synth_italic: style.synth_italic || del_mark == Some(DeleteMark::Italic), text: run.text.clone(), link: None, ranges: Vec::new(), @@ -497,7 +526,27 @@ fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { x_scale: 1.0, }); } + // Struck through or underlined once, across the whole number, in its first run's size. + if let (Some(color), Some(mark), Some(style)) = (del_color, del_mark, first) { + let strike_y = ctx.base - style.shift - style.size * 0.28; + let under_y = ctx.base - style.shift + style.size * 0.12; + let line = match mark { + DeleteMark::Strikethrough => Some((strike_y, Stroke::Solid)), + DeleteMark::DoubleStrikethrough => Some((strike_y, Stroke::Double)), + DeleteMark::Underline => Some((under_y, Stroke::Solid)), + DeleteMark::DoubleUnderline => Some((under_y, stroke_of(Underline::Double))), + _ => None, + }; + if let Some((y, stroke)) = line { + let width = (style.size / 18.0).max(0.5); + out.push(Draw::Line { x0: gx, y0: y, x1: gx + label.width, y1: y, width, color, stroke, alpha: ctx.alpha, text_bg: None }); + } + } } + draw_hyphen(ctx, out); +} + +fn draw_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { if let Some((style_index, glyph, advance)) = ctx.line.hyphen && let Some(style) = ctx.pl.styles.get(style_index as usize) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 40144d7f8e..4f05f3f1a7 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -1997,6 +1997,108 @@ fn break_only_list_has_no_label() { } } +/// #4828: a list item deleted whole (its text and its mark) under Track Changes shows its number +/// as deleted text, in the deletion's colour and struck through, with markup shown; without +/// markup the number is drawn no more than the text. +#[test] +fn a_deleted_list_items_number_is_drawn_as_deleted_text() { + let mut d = Document::from_text("Intro\nChapter two\nBody"); + d.revisions.push(wordcraft_doc::Revision { + kind: wordcraft_doc::RevisionKind::Delete, + author: "Ana".into(), + date: String::new(), + move_name: None, + }); + let id = std::sync::Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered); + d.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap(); + d.format_range(&Pos::body(1, 0), &Pos::body(1, 11), &|c| c.del = Some(0)).unwrap(); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.del = Some(0); + let l = lay(&d); + let draws = |markup: bool| display::page_display(&d, &l.pages[0], &display::DisplayOptions { markup, ..Default::default() }); + let glyph_color = |items: &[display::Draw], want: &str| { + items.iter().find_map(|i| match i { + display::Draw::Glyphs { text, color, glyphs, .. } if text.contains(want) => Some((*color, glyphs.first().map_or(0.0, |g| g.1))), + _ => None, + }) + }; + let marked = draws(true); + let (number, nx) = glyph_color(&marked, "1.").expect("the number is drawn with markup"); + let (text, _) = glyph_color(&marked, "Chapter").expect("the deleted text is drawn with markup"); + assert_eq!(number, text, "the number takes the deletion's colour"); + let struck = marked + .iter() + .any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= nx + 0.01 && *x1 > nx + 1.0)); + assert!(struck, "the number is struck through"); + // The number takes the other deletion marks as its text does. + let with_mark = |mark: display::DeleteMark| { + let mut o = display::DisplayOptions { markup: true, ..Default::default() }; + o.revisions.delete_mark = mark; + display::page_display(&d, &l.pages[0], &o) + }; + let caret = with_mark(display::DeleteMark::Caret); + assert!(glyph_color(&caret, "1.").is_none(), "a caret replaces the number"); + assert!(caret.iter().any(|i| matches!(i, display::Draw::Line { x1, .. } if (*x1 - nx).abs() < 0.01)), "the caret is where the number was"); + let bold = with_mark(display::DeleteMark::Bold); + assert!(bold.iter().any(|i| matches!(i, display::Draw::Glyphs { text, synth_bold: true, .. } if text.contains("1.")))); + let hashed = with_mark(display::DeleteMark::Hash); + let ids = |items: &[display::Draw], want: &str| { + items.iter().find_map(|i| match i { + display::Draw::Glyphs { text, glyphs, .. } if text.contains(want) => Some(glyphs.iter().map(|g| g.0).collect::>()), + _ => None, + }) + }; + let (numbers, hashes) = (ids(&marked, "1.").unwrap(), ids(&hashed, "1.").unwrap()); + assert!(hashes.len() == numbers.len() && hashes.windows(2).all(|w| w[0] == w[1]) && hashes != numbers, "each character shows as #"); + let plain_label = |items: &[display::Draw]| { + items.iter().any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= nx + 0.01 && *x1 > nx + 1.0)) + }; + assert!(!plain_label(&with_mark(display::DeleteMark::ColorOnly)), "colour only: no line through or under the number"); + // Moved-away text marked (none) is plain, its number too. + let mut moved = d.clone(); + if let Some(r) = moved.revisions.get_mut(0) { + r.move_name = Some("move1".into()); + } + let mut o = display::DisplayOptions { markup: true, ..Default::default() }; + o.revisions.move_from_mark = display::DeleteMark::None; + let shown = display::page_display(&moved, &l.pages[0], &o); + let (moved_number, _) = glyph_color(&shown, "1.").expect("the moved number is drawn"); + let (moved_text, _) = glyph_color(&shown, "Chapter").expect("the moved text is drawn"); + assert_eq!(moved_number, moved_text, "plain, like its text"); + assert!(!plain_label(&shown)); + // With markup but deletions hidden in Track Changes Options, the number isn't drawn either. + assert!(glyph_color(&with_mark(display::DeleteMark::Hidden), "1.").is_none(), "deletions marked hidden"); + let mut o = display::DisplayOptions { markup: true, ..Default::default() }; + o.revisions.insertions_deletions = false; + assert!(glyph_color(&display::page_display(&d, &l.pages[0], &o), "1.").is_none(), "insertions and deletions not shown"); + // Without markup neither the text nor its number is drawn. + let plain = draws(false); + assert!(glyph_color(&plain, "Chapter").is_none() && glyph_color(&plain, "1.").is_none()); + // A number whose paragraph mark isn't deleted is drawn as before. + let mut kept = Document::from_text("Intro\nChapter two\nBody"); + let id = std::sync::Arc::make_mut(&mut kept.numbering).add_list(wordcraft_doc::ListKind::Numbered); + kept.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap(); + let kl = lay(&kept); + let plain = display::page_display(&kept, &kl.pages[0], &display::DisplayOptions { markup: false, ..Default::default() }); + assert!(glyph_color(&plain, "1.").is_some()); + // #4828 review: only the paragraph mark deleted (Delete at the end of the item): the text + // stays, and so does its number, plain, with markup and without (and in print, where markup + // is off). + let mut joined = kept.clone(); + joined.revisions = d.revisions.clone(); + joined.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.del = Some(0); + let jl = lay(&joined); + for markup in [false, true] { + let shown = display::page_display(&joined, &jl.pages[0], &display::DisplayOptions { markup, ..Default::default() }); + let (number, jx) = glyph_color(&shown, "1.").unwrap_or_else(|| panic!("markup {markup}: the number stays")); + let (text, _) = glyph_color(&shown, "Chapter").unwrap_or_else(|| panic!("markup {markup}: the text stays")); + assert_eq!(number, text, "markup {markup}: in the text's colour"); + let struck = shown + .iter() + .any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= jx + 0.01 && *x1 > jx + 1.0)); + assert!(!struck, "markup {markup}: not struck through"); + } +} + #[test] fn empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing() { // Word (#3982): a list item whose paragraph mark is hidden, and whose text is empty or hidden diff --git a/docs/gaps.md b/docs/gaps.md index b3a778c828..f41f200dee 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ > **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** trivial (clipboard: a copied picture now reaches the system clipboard as PNG, with HTML where the host writes it; a copy of only shapes still stays in WordCraft, #6205); previously trivial (#4501 refactor regressions restored, #4683; no ranked gap changed); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** trivial (#5: a list item deleted whole under Track Changes shows its number as deleted text, #4828); previously trivial (clipboard: a copied picture now reaches the system clipboard as PNG, with HTML where the host writes it; a copy of only shapes still stays in WordCraft, #6205); previously trivial (#4501 refactor regressions restored, #4683; no ranked gap changed); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -92,7 +92,7 @@ Page drawing indexes text-box warp lookups by paragraph and story for the curren | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | In-line pictures raised or lowered (`w:position`) set their line's height as in Word, past their own height too (#3984, #5796). SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; a cell's last Normal paragraph drops its contextual space after (#5450); [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; a cell's last Normal paragraph drops its contextual space after (#5450); [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250); one anchored right after a page break, before text, is drawn on the new page (#4262). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | | 2 | **Word's native ink is not drawn from its strokes**; OLE objects show only their picture | B | Every native ink form is preserved: drawing-level ink with its optional picture fallback, direct run-level content parts, and ink members of groups and drawing canvases (kept in their place among the members, drawn from their fallback picture). Drawing canvases are read and written (#344); group shapes (`wpg`) read and written (#267). Charts and SmartArt are drawn (#292) and, with OLE objects, written back with all their parts on save (#319) | Pen notes from Word show only as their picture and can't be edited; OLE objects can't be opened | 45–70 to render and edit charts and SmartArt (#13) | [file-format-parity.md](file-format-parity.md) | -| 5 | **Content controls** landed (#381): `w:sdt` kept, shown and edited (Developer tab, Design Mode, Properties). Move tracking landed (#400): `w:moveFrom`/`w:moveTo` with their named ranges round-trip, a tracked cut and paste of a paragraph or sentence records a move, either end accepts/rejects both, green double strike/underline markup and "Moved from/to" balloons; Track Changes Options has the Moves rows (Moved from / Moved to mark and colour) and `w:doNotTrackMoves` (Track moves off: a cut and paste is a deletion and an insertion) round-trips; still missing: drag-and-drop moves (no text drag yet). Formatting revisions landed (#41): `w:rPrChange`/`w:pPrChange`/`w:tblPrChange`/`w:trPrChange`/`w:tcPrChange`/`w:sectPrChange`/`w:numberingChange` round-trip, are recorded while tracking, accepted/rejected and shown in balloons; tracked style paragraph/run-property changes landed (#2697): `w:pPrChange`/`w:rPrChange` inside styles round-trip, `styles.modify` and `styles.updateToMatch` record those properties as they were, and accept/reject plus the Reviewing Pane resolve them (table, row, cell and section property changes now record in WordCraft too, #41 follow-up). Opaque custom XML backing stores now survive saves; binding evaluation remains absent. Replace All now checks content-control locks before editing any match; a refused batch preserves the document and undo history. | B | List-label pitch corrected in synthetic metric controls; Issues #41, #400, #2697; source grep | Legal and editorial review workflows; templates with form controls | 5–8 | [file-format-parity.md](file-format-parity.md) | +| 5 | **Content controls** landed (#381): `w:sdt` kept, shown and edited (Developer tab, Design Mode, Properties). Move tracking landed (#400): `w:moveFrom`/`w:moveTo` with their named ranges round-trip, a tracked cut and paste of a paragraph or sentence records a move, either end accepts/rejects both, green double strike/underline markup and "Moved from/to" balloons; Track Changes Options has the Moves rows (Moved from / Moved to mark and colour) and `w:doNotTrackMoves` (Track moves off: a cut and paste is a deletion and an insertion) round-trips; still missing: drag-and-drop moves (no text drag yet). Formatting revisions landed (#41): `w:rPrChange`/`w:pPrChange`/`w:tblPrChange`/`w:trPrChange`/`w:tcPrChange`/`w:sectPrChange`/`w:numberingChange` round-trip, are recorded while tracking, accepted/rejected and shown in balloons; tracked style paragraph/run-property changes landed (#2697): `w:pPrChange`/`w:rPrChange` inside styles round-trip, `styles.modify` and `styles.updateToMatch` record those properties as they were, and accept/reject plus the Reviewing Pane resolve them (table, row, cell and section property changes now record in WordCraft too, #41 follow-up). Opaque custom XML backing stores now survive saves; binding evaluation remains absent. Replace All now checks content-control locks before editing any match; a refused batch preserves the document and undo history. | B | List-label pitch corrected in synthetic metric controls; a list item deleted whole shows its number as deleted text (#4828); Issues #41, #400, #2697; source grep | Legal and editorial review workflows; templates with form controls | 5–8 | [file-format-parity.md](file-format-parity.md) | | 6 | **Print dialog depth**: desktop printer choice, copies, collation, duplex and grayscale submit through craft-print; File › Print retains preview, page ranges and odd/even (#641) and scales pages to another paper size (#2108); print-only N-up and booklets are available; driver tray/options remain; web prints through the browser (#209) | B | `ui.print` → `apps/wordcraft/src/print.rs`; issue #15 | Everyone who prints | 5–8 | [hardware-parity.md](hardware-parity.md) | | 7 | **Dialog depth**: Word-observed spelling/grammar task pane added (shared review commands, current-story traversal; see [spelling-review.md](spelling-review.md)); 61 modal dialogs vs Word's ~100 (Custom Document Properties from File › Info, #2982; Drop Cap Options matches Word's menu and dialog; Split Cells and Convert Text to Table match Word's observed limits and defaults; Format Page Numbers carries Word's number formats and Continue from previous section / Start at, #1113) | B | `Dialog` enum in `crates/ui-egui/src/dialogs.rs`; Cell Margins (#1960) now opens with current defaults and applies only confirmed edits | Power users reach for dialogs the ribbon alone doesn't cover | 11–19 | [ui-parity.md](ui-parity.md) | | 9 | **Password-protected `.doc` files with an AES header in the Word 97-2003 format** can't be opened: [MS-OFFCRYPTO] defines AES only for encrypted packages, so these are refused with a clear message. Encrypted packages open under any Word extension (`.docx`, `.doc`, `.dot`…) with either agile (Word 2010+) or Standard (Word 2007, AES-ECB) encryption; protected `.docx` saves with agile encryption (#55, #281, gap 9) | | `crates/docx/src/crypt.rs` (agile and Standard); `crates/docbin/src/crypt.rs` opens XOR/RC4/RC4 CryptoAPI `.doc` with a password (#1079). All synthetic fixtures; untested on Word-written files | Corporate and legal users with old files | 0 (refused by design; nothing left to build) | [file-format-parity.md](file-format-parity.md) | @@ -198,6 +198,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | Date | Change | Summary | |---|---|---| +| 2026-10-30 | trivial | #5: a list item deleted whole under Track Changes shows its number as deleted text, in the deletion's colour and mark, and hides it where deletions are hidden (#4828); estimate unchanged | | 2026-10-26 | trivial | Dialog sections improve readability across 13 dialogs; conditional scrolling keeps tall dialogs usable. Ranked gaps and estimates unchanged (#4035, #4038) | | 2026-11-12 | trivial | Clipboard: a copied picture is published to the system clipboard as PNG, with HTML where the host writes it, and WordCraft's own paste keeps the original fragment; a copy of only shapes stays in WordCraft (#6205). Native external-app paste remains untested. | | 2026-11-04 | trivial | #4501 refactor regressions restored: per-section header/footer grid, ODT default font, link tooltip (#4683); no ranked gap changed; readiness estimates unchanged | diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 034e6cd8cb..6201b80436 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: cu20we: outline caps; previously trivial: cu20we: box float paragraph origin; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial: PAGE fields in a paragraph split across pages show the page they are on, #1352; previously trivial: a dragged floating object anchors in the column it lands in, #884; previously trivial: a paragraph ending on a page with footnotes keeps its space after above the separator, #1116; previously trivial: symbol-font text drawn as Unicode symbols, #776; previously trivial: large-table scrolling measured and fixed, #811; previously trivial: text boxes use their own margins; Resize shape to fit text never cuts text, #743; previously trivial: complex-script shaping and Myanmar line breaking, #604; previously trivial: body page totals, table-cell footnotes and bookmark link pages fixed, #450 #451 #455; previously major: first version; line breaking, pagination and object placement checked against Word's behaviour from the layout source on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** trivial (a deleted list item's number is drawn as deleted text, #4828); previously minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: cu20we: outline caps; previously trivial: cu20we: box float paragraph origin; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial: PAGE fields in a paragraph split across pages show the page they are on, #1352; previously trivial: a dragged floating object anchors in the column it lands in, #884; previously trivial: a paragraph ending on a page with footnotes keeps its space after above the separator, #1116; previously trivial: symbol-font text drawn as Unicode symbols, #776; previously trivial: large-table scrolling measured and fixed, #811; previously trivial: text boxes use their own margins; Resize shape to fit text never cuts text, #743; previously trivial: complex-script shaping and Myanmar line breaking, #604; previously trivial: body page totals, table-cell footnotes and bookmark link pages fixed, #450 #451 #455; previously major: first version; line breaking, pagination and object placement checked against Word's behaviour from the layout source on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -63,6 +63,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Columns, column breaks, separators, balancing | ✅ | Columns balance on a section's last page when the next section starts continuous (also at the document end, which Word only balances when the document ends with a continuous break); not after next-page/even/odd breaks or on a page with a column break; keep-together, keep-with-next, widow/orphan control and unsplittable rows can leave them slightly uneven (#350). The line between columns (Line between, `w:sep`) runs from the top of the section's text on the page to the bottom of its tallest column, so columns for selected text, a continuous section in the middle of a page, have their line too, and it no longer runs to the page bottom under a short section (#5178) | — | | Section breaks (next page, continuous, even, odd), different first page, odd/even headers | ✅ | Section breaks don't show in Draft view (#42). A break inserted with text selected goes before the selection and keeps it, as in Word (#852). An otherwise empty section at page start retains its line (`empty_page_section_keeps_line`); a closing mark after text stays quiet, but one after another section's mark takes its line while it fits and then stays at the page's bottom, so the text after a long run starts the next page; a run of continuous sections with text goes onto new pages like plain text, and a kept-together paragraph low in a continuous section is measured against the next page's body (its header, footer and carried notes), not the current one's (#3907). | 1–2 | | Labels on page-break-only list paragraphs | ✅ | `layout::tests::break_only_list_has_no_label`: no bullet or number on the break, but the next number is still 3 after item 1 and a break. Plain empty items keep their labels. Synthetic DOCX observed through Adobe PDF conversion | — | +| List labels of a deleted list item (Track Changes) | ✅ | A list item deleted whole, its text and its paragraph mark, shows its number as deleted text with markup shown: in the deletion's colour and with its mark (Track Changes Options), as its text is: struck through by default, a caret in its place, #s, bold, italic or underlined, and plain when moved-away text is marked (none). With markup but deletions hidden (Track Changes Options: deletions marked Hidden, or Insertions and Deletions off) the number is not drawn. Without markup (No Markup) neither is drawn, and the item takes no room (#4828, `layout::tests::a_deleted_list_items_number_is_drawn_as_deleted_text`). An item whose text alone is deleted keeps its mark and so its number, and one whose mark alone is deleted (Delete at its end, which joins it to the next item) keeps its text and its number as they are | — | | List labels after a leading page break | ✅ | `layout::tests::bidi::list_label_after_leading_page_break_uses_its_text_lines_alignment`: the number/bullet and text retain the no-break horizontal positions for start, centre, end and justified alignment, LTR/RTL, including text with a tab. The issue's synthetic DOCX exports with the number before the heading, matching the reporter's Word/LibreOffice reference (#2964); reference applications were not rerun locally | — | | List labels: number formats (decimal, letters, Russian letters, roman, ordinal text, Chinese/Japanese/Korean counting and legal, 一〇一 digits, 甲乙丙, ①…⑳, full-width), `%n` text such as `第%1章` / `(%1)`, legal numbering | ✅ | a level above that hasn't counted yet takes its first number at the first deeper item, as measured in Word: after 10.1–10.4 the next level-1 item is 11 (`doc::numbering::tests::a_deeper_item_first_counts_the_levels_above_it`); `doc::cjk_numbers` tests, `doc::section::tests::russian_letters_follow_word`, `layout::tests::chinese_counting_list_labels_and_their_font_runs`, `layout::tests::russian_letter_list_labels_draw_cyrillic`; a label mixing faces (digit + CJK comma) is drawn run by run (#534); Russian letters skip ё, й, ъ and ь and then double (аа, бб), as observed in Word. Hebrew, Hindi, Thai and Vietnamese formats show decimal; `arabicAlpha` and `arabicAbjad` draw Arabic letters, then double (أأ, بب) (`doc::section::tests::arabic_letters_count_in_both_orders`). The label stays attached to the start of the text when the paragraph is centred or aligned to the end, as in Word (#1159). A level with number format `none` is an ordinary level whose own number reads as nothing, as in Word for Windows (Microsoft 365, checked by MeHail-02): its label is its text with that number empty (`RESPONSE:`; `Part` above `%1.%2` gives `.1`), it counts and restarts the levels below it, it stays empty in legal numbering, and an empty label still tabs the text to the indent unless it already ends there (Heading 2 of the Chapter 1 list stays at the margin) (#4985; `doc::numbering::tests::a_none_level_shows_its_text_and_still_counts`, `layout::tests::a_none_format_label_shows_its_text_and_tabs_to_the_indent`). | — | | Body top below a tall header, footer pushes body up | ✅ | #138; a footer taller than the bottom margin moves the body bottom up (#453), and a header or footer linked to the previous section takes its room too (#454) | — | @@ -307,6 +308,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| +| 2026-10-29 | trivial | A list item deleted whole under Track Changes shows its number in the deletion's colour and with its mark (struck through by default) with markup, and not at all without (#4828) | | 2026-11-04 | trivial | Headers, footers and note separators of the second and later sections are measured with their own section's document grid and SECTION/SECTIONPAGES values, not the previous section's; a regression from the #4501 refactor (#4683). `layout::tests::pages::a_sections_header_is_measured_without_the_previous_sections_grid` | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | From c817cc95c67d97e6b10093a6f08b8bc55d47e3f6 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 17 Nov 2026 03:32:02 +0100 Subject: [PATCH 36/99] Render: keep a metafile with huge bitmaps in the cache instead of parsing it on every repaint (#5494) Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/media.rs | 156 ++++++++++++++++++-------- crates/render/src/tests.rs | 218 +++++++++++++++++++++++++++++++++++++ 2 files changed, 331 insertions(+), 43 deletions(-) diff --git a/crates/render/src/media.rs b/crates/render/src/media.rs index cebbd1bda0..13e9878326 100644 --- a/crates/render/src/media.rs +++ b/crates/render/src/media.rs @@ -1,4 +1,6 @@ use super::{Affine, Arc, Document, FontDb, HashMap, Item, Mutex, Page, Picture, Pixmap, PlacedItem, RenderContext, Seg, Shape, Weak, kurbo, peniko}; +use craft_metafile::{ClipPath, Tile}; +use std::collections::HashSet; /// Upper bound on the bytes the two decoded-media caches keep together (about 256 MB), half each; /// past its half a cache starts over. @@ -151,42 +153,61 @@ pub(crate) struct Vector { } impl Vector { - /// Approximate memory held: pixmaps, the pattern tiles' own pixels, path segments, dash - /// patterns, clip regions, clip lists, clip paths and text, each shared allocation once. + /// Approximate memory held: pixels (a tile shared by several fills once), path segments and the + /// per-item bookkeeping. pub(crate) fn bytes(&self) -> usize { - let mut seen = std::collections::HashSet::new(); - let mut total = self.averages.len() * 4; - for p in self.pixmaps.iter().flatten() { - if seen.insert(Arc::as_ptr(p) as usize) { - total = total.saturating_add(p.width() as usize * p.height() as usize * 4); - } - } - let seg = std::mem::size_of::(); - for it in &self.pic.items { - let (own, region, clips) = match it { - Item::Path { segs, line, region, clips, .. } => ((segs.len() * seg).saturating_add(line.dash.len() * 4), region, clips), - Item::Pattern { segs, tile, region, clips, .. } => { - let tile_bytes = if seen.insert(Arc::as_ptr(tile) as usize) { tile.rgba.len() } else { 0 }; - ((segs.len() * seg).saturating_add(tile_bytes), region, clips) - } - Item::Bitmap { region, clips, .. } => (0, region, clips), - Item::Text(t) => (t.text.len() + t.dx.len() * 4, &t.region, &t.clips), - }; - // Each item holds its own copy of the clip region's rectangles and its own list of the - // clip paths it shares. - let region = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>()); - let list = clips.len() * std::mem::size_of::>(); - total = total.saturating_add(own).saturating_add(region).saturating_add(list); - for c in clips { - if seen.insert(Arc::as_ptr(c) as usize) { - total = total.saturating_add(c.segs.len() * seg); - } - } - } - total + let mut seen: HashSet<*const Pixmap> = HashSet::new(); + let px: usize = self.pixmaps.iter().flatten().filter(|p| seen.insert(Arc::as_ptr(p))).map(|p| bitmap_bytes(p)).sum(); + px.saturating_add(self.averages.capacity() * 4).saturating_add(geometry_bytes(&self.pic)) } } +/// Memory held by one decoded bitmap: its pixels plus the pixmap and its `Arc` header. +fn bitmap_bytes(p: &Pixmap) -> usize { + usize::from(p.width()) * usize::from(p.height()) * 4 + std::mem::size_of::() + 2 * std::mem::size_of::() +} + +/// Approximate memory held by a picture's items: path segments and text (charged by capacity, as a +/// parsed vector keeps its growth slack), the item itself (a bitmap +/// item stays in the list after its pixels move out), a path's dash array, a text's boxed record and +/// font name, the pixmap slot kept for it, a pattern's path +/// and tile, and every item's clip rectangles and clip paths. Tiles and clip paths are shared between +/// the items that use them, so each is charged once. +pub(crate) fn geometry_bytes(pic: &Picture) -> usize { + let slot = std::mem::size_of::>>(); + let seg = std::mem::size_of::(); + let mut tiles: HashSet<*const Tile> = HashSet::new(); + let mut clip_paths: HashSet<*const ClipPath> = HashSet::new(); + let mut total = 0usize; + for it in &pic.items { + let (region, clips): (&Option>, &[Arc]) = match it { + Item::Path { region, clips, .. } | Item::Bitmap { region, clips, .. } | Item::Pattern { region, clips, .. } => (region, clips), + Item::Text(t) => (&t.region, &t.clips), + }; + let own = match it { + Item::Path { segs, line, .. } => (segs.capacity() * seg).saturating_add(line.dash.capacity() * std::mem::size_of::()), + Item::Bitmap { .. } => 0, + Item::Pattern { segs, tile, .. } => { + let tile_bytes = if tiles.insert(Arc::as_ptr(tile)) { tile.rgba.len().saturating_add(std::mem::size_of::()) } else { 0 }; + (segs.capacity() * seg).saturating_add(tile_bytes) + } + Item::Text(t) => { + std::mem::size_of::() + t.text.len() + t.dx.len() * std::mem::size_of::() + t.font.family.len() + } + }; + let region_bytes = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>()); + let clip_bytes: usize = clips + .iter() + .map(|c| { + let arc = std::mem::size_of::() * 2 + std::mem::size_of::>(); + if clip_paths.insert(Arc::as_ptr(c)) { arc + std::mem::size_of::() + c.segs.capacity() * seg } else { arc } + }) + .sum(); + total = total.saturating_add(slot + std::mem::size_of::()).saturating_add(own).saturating_add(region_bytes).saturating_add(clip_bytes); + } + total +} + /// The metafile picture for a media key. None when the bytes are not a metafile or do not parse, so /// the caller falls back to the raster path (and the grey box). pub(crate) fn vector_for(doc: &Document, key: &str) -> Option> { @@ -214,24 +235,73 @@ pub(crate) fn build_vector(bytes: &[u8]) -> Option { return None; } // The pixels move into the pixmaps; the picture keeps only the geometry. A tile shared by - // several fills is converted and averaged once. + // several fills is converted and averaged once. Only the bitmaps are fitted to the cache: a + // tile is small and stays as it is, but counts against the budget. let mut tiles: HashMap>, [u8; 4])> = HashMap::new(); - let (pixmaps, averages) = pic - .items - .iter_mut() - .map(|it| match it { - Item::Pattern { tile, .. } => tiles - .entry(Arc::as_ptr(tile) as usize) + let mut tile_bytes = 0usize; + let mut bitmaps: Vec> = Vec::with_capacity(pic.items.len()); + let mut averages: Vec<[u8; 4]> = Vec::with_capacity(pic.items.len()); + let mut patterns: Vec>> = Vec::with_capacity(pic.items.len()); + for it in pic.items.iter_mut() { + if let Item::Pattern { tile, .. } = it { + let key = Arc::as_ptr(tile) as usize; + let fresh = !tiles.contains_key(&key); + let (pm, avg) = tiles + .entry(key) .or_insert_with(|| { (premul_pixmap(tile.width, tile.height, &tile.rgba).map(Arc::new), wordcraft_layout::metafile_average_color(&tile.rgba)) }) - .clone(), - _ => (it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new), [0; 4]), - }) - .unzip(); + .clone(); + if fresh { + tile_bytes = tile_bytes.saturating_add(pm.as_ref().map_or(0, |p| bitmap_bytes(p))); + } + bitmaps.push(None); + patterns.push(pm); + averages.push(avg); + } else { + bitmaps.push(it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px))); + patterns.push(None); + averages.push([0; 4]); + } + } + let bitmaps = fit_cache(bitmaps, geometry_bytes(&pic).saturating_add(tile_bytes)); + let pixmaps = bitmaps.into_iter().zip(patterns).map(|(b, t)| b.map(Arc::new).or(t)).collect(); Some(Vector { pic, pixmaps, averages }) } +/// The bitmaps of a metafile at a size its whole picture is kept in the cache. When geometry and +/// bitmaps together are past the cache budget (a metafile with a 6000 x 6000 bitmap is 144 MB), the +/// cache would refuse the picture and every repaint would parse and decode the file again, so the +/// bitmaps are box-averaged down to an eighth of the budget between them, in proportion to their +/// size, as large raster pictures are (#3665, which uses half). An eighth because the cache starts +/// over when full: several huge pictures on screen together must fit side by side, and not clear +/// the small ones with them. Geometry that is itself an eighth or more still leaves the bitmaps a +/// sixteenth, as long as the whole budget has room for it. A picture that still cannot fit after shrinking stays uncached, +/// as before. Pictures within the budget keep their full resolution. Printing (`render_page`) draws +/// the shrunk bitmaps too, as it does large raster pictures; PDF export parses the metafile itself +/// and is unaffected. +pub(crate) fn fit_cache(mut pixmaps: Vec>, geometry: usize) -> Vec> { + let pixels = |p: &Pixmap| usize::from(p.width()) * usize::from(p.height()) * 4; + let total: usize = pixmaps.iter().flatten().map(pixels).sum(); + let fixed: usize = pixmaps.iter().flatten().map(|p| bitmap_bytes(p) - pixels(p)).sum(); + if total.saturating_add(fixed).saturating_add(geometry) <= CACHE_BYTES { + return pixmaps; + } + // The bitmaps get what is left of an eighth, but never less than a sixteenth (so the allowance does + // not drop to nothing as geometry reaches the eighth) and never more than the whole budget leaves. + let target = CACHE_BYTES / 8; + let allowance = target.saturating_sub(geometry).max(target / 2).min(CACHE_BYTES.saturating_sub(geometry)); + let room = allowance.saturating_sub(fixed) / 4; + for pm in pixmaps.iter_mut().flatten() { + // This bitmap's share of the pixels that fit. + let share = (room as u128 * pixels(pm) as u128 / total.max(1) as u128) as u64; + if let Some(small) = shrink(pm, share) { + *pm = small; + } + } + pixmaps +} + fn rgba_color(c: [u8; 4]) -> peniko::Color { peniko::Color::from_rgba8(c[0], c[1], c[2], c[3]) } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index f6f9641696..eeb41b22b2 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::media::fit_cache; use wordcraft_layout::display::page_display; use wordcraft_layout::{LayoutCache, LayoutOptions, layout}; @@ -1041,6 +1042,124 @@ fn metafile_picture_is_drawn_as_vectors() { assert!(left[..3].iter().all(|c| *c > 200), "left half should be paper, not the grey box: {left:?}"); } +/// An EMF whose only record is one `w` x `h` 1 bpp black and white bitmap over the whole picture. +fn emf_with_1bpp_bitmap(w: i32, h: i32) -> Vec { + let mut hdr = vec![0u8; 88]; + hdr[0..4].copy_from_slice(&1u32.to_le_bytes()); + hdr[4..8].copy_from_slice(&88u32.to_le_bytes()); + hdr[8..24].copy_from_slice(&le32(&[0, 0, 100, 100])); + hdr[24..40].copy_from_slice(&le32(&[0, 0, 2500, 2500])); + hdr[40..44].copy_from_slice(&0x464D_4520u32.to_le_bytes()); + hdr[72..88].copy_from_slice(&le32(&[1000, 1000, 250, 250])); + let stride = (w as usize).div_ceil(32) * 4; + let mut payload = vec![0u8; 16]; + payload.extend(le32(&[0, 0, 0, 0, w, h, 80, 48, 128, (stride * h as usize) as i32, 0, 0x00CC_0020, 100, 100])); + payload.extend(le32(&[40, w, h, 1 | (1 << 16), 0, 0, 0, 0, 0, 0])); + payload.extend([0, 0, 0, 0, 255, 255, 255, 0]); + payload.extend((0..stride * h as usize).map(|i| (i * 31) as u8)); + [hdr, emf_rec(81, &payload), emf_rec(14, &[0; 12])].concat() +} + +/// #5482: a metafile whose bitmaps are past the whole cache budget was parsed and decoded again on +/// every repaint, because the cache refused it. It is now kept (its bitmaps at a smaller size). +#[test] +fn a_metafile_with_a_huge_bitmap_is_parsed_once() { + // 8000 x 5000 is 160 MB of RGBA, past the 128 MB cache, from a 5 MB file. + let mut d = Document::new(); + // A key of its own: the vector cache is global and tests running in threads share `image1.emf`. + let key = "huge-parsed-once.emf"; + d.media.insert(key.to_string(), Arc::new(emf_with_1bpp_bitmap(8000, 5000))); + let first = vector_for(&d, key).expect("the metafile reads"); + let again = vector_for(&d, key).expect("the metafile reads"); + assert!(Arc::ptr_eq(&first, &again), "the second repaint reuses the parsed picture"); + assert!(first.bytes() <= CACHE_BYTES / 8, "{} bytes", first.bytes()); +} + +/// Several huge metafiles on screen together (zoomed-out pages, thumbnails) sit side by side in the +/// cache instead of clearing it, so a small metafile drawn with them stays a hit. +#[test] +fn huge_metafiles_do_not_push_a_small_one_out_of_the_cache() { + let mut d = Document::new(); + let small = "evict-small.emf"; + d.media.insert(small.to_string(), Arc::new(emf_with_1bpp_bitmap(64, 64))); + let huge: Vec = (0..4).map(|n| format!("evict-huge-{n}.emf")).collect(); + for (n, k) in huge.iter().enumerate() { + // Distinct bytes per file (the width differs; 8000 x 5000 is the most pixels a metafile decodes), so each is its own cache entry. + d.media.insert(k.clone(), Arc::new(emf_with_1bpp_bitmap(8000 - n as i32, 5000))); + } + let small_first = vector_for(&d, small).expect("the small metafile reads"); + for round in 0..2 { + for k in &huge { + assert!(vector_for(&d, k).is_some(), "round {round}"); + } + } + let kept: Vec<_> = huge.iter().map(|k| vector_for(&d, k).unwrap()).collect(); + let again: Vec<_> = huge.iter().map(|k| vector_for(&d, k).unwrap()).collect(); + for (a, b) in kept.iter().zip(&again) { + assert!(Arc::ptr_eq(a, b), "a huge metafile is parsed once while four are drawn together"); + } + assert!(Arc::ptr_eq(&small_first, &vector_for(&d, small).unwrap()), "the small metafile is still cached"); +} + +/// Time of three repaints of a picture with a 160 MB bitmap: +/// `cargo test -p wordcraft-render --release -- --ignored --nocapture huge_metafile_repaint_time`. +#[test] +#[ignore = "timing only"] +fn huge_metafile_repaint_time() { + let mut d = Document::new(); + let key = d.add_media(emf_with_1bpp_bitmap(8000, 5000), "emf"); + for n in 1..=4 { + let t = std::time::Instant::now(); + assert!(vector_for(&d, &key).is_some()); + eprintln!("repaint {n}: vector_for {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + } +} + +#[test] +fn bitmaps_are_shrunk_in_proportion_only_when_the_picture_is_past_the_cache() { + let px = vello_cpu::color::PremulRgba8 { r: 1, g: 2, b: 3, a: 255 }; + let pm = |w: u16, h: u16| Some(Pixmap::from_parts(vec![px; usize::from(w) * usize::from(h)], w, h)); + let bytes = |v: &[Option]| v.iter().flatten().map(|p| usize::from(p.width()) * usize::from(p.height()) * 4).sum::(); + // Within the budget: untouched. + let kept = fit_cache(vec![pm(1000, 1000), None, pm(2000, 2000)], 1_000_000); + assert_eq!(kept.iter().flatten().map(|p| (p.width(), p.height())).collect::>(), [(1000, 1000), (2000, 2000)]); + assert!(kept[1].is_none(), "a path item keeps its place in the list"); + // A 144 MB and a 36 MB bitmap: both shrink by the same factor. + let fit = fit_cache(vec![pm(6000, 6000), pm(3000, 3000)], 4_000_000); + assert!(bytes(&fit) + 4_000_000 <= CACHE_BYTES / 8, "{} bytes", bytes(&fit)); + let (a, b) = (fit[0].as_ref().unwrap(), fit[1].as_ref().unwrap()); + assert_eq!((a.width(), b.width()), (1500, 750), "each bitmap keeps its share of the pixels that fit"); + assert!(a.data().iter().all(|p| (p.r, p.g, p.b, p.a) == (1, 2, 3, 255)), "flat stays flat"); +} + +/// Geometry of an eighth of the budget or more leaves the bitmaps a positive allowance, so the +/// picture is still kept (and reused) when it fits the whole budget after shrinking; one whose +/// geometry alone fills the budget stays uncached. +#[test] +fn heavy_geometry_still_leaves_the_bitmaps_a_cacheable_size() { + let px = vello_cpu::color::PremulRgba8 { r: 1, g: 2, b: 3, a: 255 }; + let pm = |w: u16, h: u16| Some(Pixmap::from_parts(vec![px; usize::from(w) * usize::from(h)], w, h)); + let bytes = |v: &[Option]| v.iter().flatten().map(|p| usize::from(p.width()) * usize::from(p.height()) * 4).sum::(); + let geometry = CACHE_BYTES / 8 + 4_000_000; + let fit = fit_cache(vec![pm(6000, 6000)], geometry); + let size = bytes(&fit); + assert!(size > 0 && size < 6000 * 6000 * 4, "shrunk, not dropped: {size} bytes"); + 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 = MediaCache { map: Default::default(), bytes: 0 }; + 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. + for g in [CACHE_BYTES / 8 - 1, CACHE_BYTES / 8, CACHE_BYTES / 8 + 1] { + let size = bytes(&fit_cache(vec![pm(6000, 6000)], g)); + assert!(size > 0 && size < 6000 * 6000 * 4 && size + g <= CACHE_BYTES / 4, "geometry {g}: {size} bytes"); + } + // Geometry that takes the whole budget leaves nothing to shrink to: the bitmap stays as it is. + let full = fit_cache(vec![pm(6000, 6000)], CACHE_BYTES); + assert_eq!(bytes(&full), 6000 * 6000 * 4); +} + /// #6636: an EMF+ only file (no plain EMF drawing records) whose EmfPlusDrawImage draws a /// 32bppPARGB bitmap over the right half: the bitmap's pixels are drawn. #[test] @@ -1857,3 +1976,102 @@ fn undecodable_pictures_keep_their_grey_box_pixels() { let h = img.pixels.iter().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)); assert_eq!(h, 0x79f9f1d3602a9925, "{h:#x}"); } + +/// The cache charge for a metafile's geometry covers what its items keep after their pixels move +/// out: a pattern's path and tile, and the clip rectangles and clip paths of every kind of item. +/// A tile or clip path shared by several items is charged once. +#[test] +fn geometry_bytes_counts_pattern_tiles_and_clips_once() { + use craft_metafile::{ClipPath, Tile}; + let segs = |n: usize| vec![Seg::Line(0.0, 0.0); n]; + let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 }; + let base = crate::media::geometry_bytes(&pic(vec![])); + let tile = Arc::new(Tile { width: 1000, height: 1000, rgba: vec![0; 4_000_000], cell: [1.0, 1.0], origin: [0.0, 0.0] }); + let pattern = |tile: &Arc| Item::Pattern { segs: segs(1000), even_odd: false, tile: tile.clone(), region: None, clips: vec![] }; + let one = crate::media::geometry_bytes(&pic(vec![pattern(&tile)])); + assert!(one - base >= 4_000_000 + 1000 * std::mem::size_of::(), "{} bytes", one - base); + // Two fills of the same brush keep one tile. + let two = crate::media::geometry_bytes(&pic(vec![pattern(&tile), pattern(&tile)])); + assert!(two - one < 1_000_000, "the shared tile is charged once: {} bytes more", two - one); + // A clip path shared by two bitmaps is charged once; a clip region is charged per item. + let clip = Arc::new(ClipPath { segs: segs(100_000), even_odd: false }); + let bitmap = |clips: Vec>, region: Option>| Item::Bitmap { + rect: [0.0; 4], + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + width: 0, + height: 0, + rgba: vec![], + region, + clips, + }; + let plain = crate::media::geometry_bytes(&pic(vec![bitmap(vec![], None)])); + let clipped = crate::media::geometry_bytes(&pic(vec![bitmap(vec![clip.clone()], None), bitmap(vec![clip.clone()], None)])); + let clip_bytes = 100_000 * std::mem::size_of::(); + assert!(clipped - 2 * plain >= clip_bytes && clipped - 2 * plain < 2 * clip_bytes, "{} bytes", clipped - 2 * plain); + let region = crate::media::geometry_bytes(&pic(vec![bitmap(vec![], Some(vec![[0.0; 4]; 1000]))])); + assert!(region - plain >= 1000 * 16, "{} bytes", region - plain); +} + +/// The parser collects segments and dashes without shrinking them, so the charge follows the +/// capacity a vector keeps, not only its length. +#[test] +fn geometry_bytes_charges_the_capacity_of_segment_and_dash_vectors() { + use craft_metafile::LineStyle; + let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 }; + let path = |segs: Vec, dash: Vec| Item::Path { + segs, + fill: None, + stroke: Some(([0, 0, 0, 255], 1.0)), + line: LineStyle { dash, ..LineStyle::default() }, + even_odd: false, + region: None, + clips: vec![], + }; + let tight = crate::media::geometry_bytes(&pic(vec![path(vec![Seg::Line(0.0, 0.0); 2], vec![1.0; 2])])); + let mut segs = Vec::with_capacity(10_000); + segs.extend([Seg::Line(0.0, 0.0); 2]); + let mut dash = Vec::with_capacity(1_000); + dash.extend([1.0f32; 2]); + let slack = crate::media::geometry_bytes(&pic(vec![path(segs, dash)])); + assert!(slack - tight >= 9_000 * std::mem::size_of::(), "{} bytes more", slack - tight); +} + +/// A stroked path keeps its dash array on the heap, and a text item keeps its boxed record and font +/// name; the cache charge counts both, so many dashed paths or text records are not under-counted. +#[test] +fn geometry_bytes_counts_dash_arrays_and_text_records() { + use craft_metafile::{Font, HAlign, LineStyle, Text, VAlign}; + let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 }; + let path = |dash: usize| Item::Path { + segs: vec![Seg::Line(0.0, 0.0); 2], + fill: None, + stroke: Some(([0, 0, 0, 255], 1.0)), + line: LineStyle { dash: vec![1.0; dash], ..LineStyle::default() }, + even_odd: false, + region: None, + clips: vec![], + }; + let solid = crate::media::geometry_bytes(&pic(vec![path(0)])); + let dashed = crate::media::geometry_bytes(&pic(vec![path(16)])); + assert_eq!(dashed - solid, 16 * std::mem::size_of::()); + let text = |family: &str| { + Item::Text(Box::new(Text { + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + text: "ab".into(), + dx: vec![1.0; 2], + font: Font { family: family.into(), ..Font::default() }, + color: [0, 0, 0, 255], + background: None, + h_align: HAlign::default(), + v_align: VAlign::default(), + clip: None, + region: None, + clips: vec![], + })) + }; + let bare = crate::media::geometry_bytes(&pic(vec![text("")])); + let named = crate::media::geometry_bytes(&pic(vec![text("Some Long Face Name")])); + assert_eq!(named - bare, "Some Long Face Name".len()); + let empty = crate::media::geometry_bytes(&pic(vec![])); + assert!(bare - empty >= std::mem::size_of::(), "the boxed Text struct is charged: {} bytes", bare - empty); +} From 266407e8409b5d1167cba31979d91fcf208391cd Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:46:09 +0100 Subject: [PATCH 37/99] M14: expose file-browser row names and selection (#6790) --- crates/ui-egui/src/file_browser.rs | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/ui-egui/src/file_browser.rs b/crates/ui-egui/src/file_browser.rs index c6c7c28e4d..897db5b3a9 100644 --- a/crates/ui-egui/src/file_browser.rs +++ b/crates/ui-egui/src/file_browser.rs @@ -419,6 +419,9 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option> } for e in entries.get(range).unwrap_or(&[]) { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW), Sense::click()); + resp.widget_info(|| { + egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), b.selected.as_ref() == Some(&e.path), &e.name) + }); if b.selected.as_ref() == Some(&e.path) { ui.painter().rect_filled(r, 2.0, t.checked); } else if resp.hovered() { @@ -765,6 +768,54 @@ mod tests { assert!(crate::keytips::suppressed(&a, &ctx)); } + /// Drawn entries have names and selection state, and choosing one still picks its path. + #[test] + fn entries_expose_names_selection_and_picking() { + use egui::accesskit::{Role, Toggled}; + use egui_kittest::kittest::{NodeT, Queryable}; + let dir = scratch("entry_accessibility"); + let folder = dir.join("Drafts"); + let file = dir.join("chapter.docx"); + std::fs::create_dir(&folder).unwrap(); + std::fs::write(&file, b"x").unwrap(); + let browser = + FileBrowser::new(FileDialogRequest::Open { purpose: "document".into() }, AfterPick::OpenDocument { document: 0 }, dir.clone(), false); + // Font changes take effect next frame; the buttons need the named semibold family. + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(760.0, 520.0)).build_ui_state( + move |ui, state: &mut (FileBrowser, Option>)| { + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + let t = Tokens::get(ui.ctx()); + if let Some(picked) = body(ui, &mut state.0, &t) { + state.1 = Some(picked); + } + }, + (browser, None), + ); + h.run_steps(4); + for name in ["Drafts", "chapter.docx"] { + assert_eq!(h.get_by_role_and_label(Role::Button, name).accesskit_node().toggled(), Some(Toggled::False)); + } + h.get_by_role_and_label(Role::Button, "Drafts").click(); + h.run_steps(2); + assert_eq!(h.state().0.selected.as_ref(), Some(&folder)); + assert_eq!(h.get_by_role_and_label(Role::Button, "Drafts").accesskit_node().toggled(), Some(Toggled::True)); + h.get_by_role_and_label(Role::Button, "chapter.docx").click(); + h.run_steps(2); + assert_eq!(h.state().0.selected.as_ref(), Some(&file)); + assert_eq!(h.state().0.name, "chapter.docx"); + assert_eq!(h.get_by_role_and_label(Role::Button, "Drafts").accesskit_node().toggled(), Some(Toggled::False)); + assert_eq!(h.get_by_role_and_label(Role::Button, "chapter.docx").accesskit_node().toggled(), Some(Toggled::True)); + h.get_by_role_and_label(Role::Button, "Open").click(); + h.run_steps(2); + assert_eq!(h.state().1, Some(Some(file))); + let _ = std::fs::remove_dir_all(&dir); + } + /// #3535: exporting offers File › Export's formats as the types; the chosen one is the format, /// the name's extension follows it, and the export writes that format. #[test] From 8a9d04eeb1e162ab9b83182d1182427a16d64f9c Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:59:04 +0100 Subject: [PATCH 38/99] M14: restore save stamps after immediate web-save errors (#6824) --- crates/ui-egui/src/app/commands.rs | 29 ++++++++++- crates/ui-egui/src/file_dialogs/tests.rs | 64 ++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index fa87a8db9b..76d27fc45c 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -157,6 +157,14 @@ impl WordApp { } self.session.run("file.encrypt", &json!({"password": pw})).map_err(|e| e.to_string())?; } + // Like a failed native save, a failed serialization or delivery keeps the save stamps. + let before_stamp = ( + self.session.doc.settings.zoom, + self.session.doc.core.last_modified_by.clone(), + self.session.doc.core.created.clone(), + self.session.doc.core.modified.clone(), + self.session.doc.core.revision, + ); // A save is a save, download or not: advance the revision and modified stamp (#262). if matches!(id, "file.save" | "file.saveAs") { self.session.stamp_save(); @@ -165,7 +173,19 @@ impl WordApp { let password = if matches!(id, "file.save" | "file.saveAs") { self.session.password.as_ref().map(wordcraft_engine::Password::as_str) } else { None }; let opts = wordcraft_engine::cmd::file::export_options(&self.session, ¶ms); - let bytes = wordcraft_engine::io::save_bytes_with(&name, &self.session.doc, password, &opts)?; + let bytes = match wordcraft_engine::io::save_bytes_with(&name, &self.session.doc, password, &opts) { + Ok(bytes) => bytes, + Err(error) => { + ( + 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, + ) = before_stamp; + return Err(error); + } + }; // A ticket left over from an earlier call isn't this save's. let saves = self.services.async_saves.clone(); if let Some(saves) = &saves { @@ -185,6 +205,13 @@ impl WordApp { (None, None) => Ok(()), }; if let Err(e) = delivered { + ( + 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, + ) = before_stamp; let msg = i18n::fmt(tl!("Couldn't download {name}: {error}"), &[("name", &name), ("error", &e)]); log::error!("download of {name} failed: {e}"); self.status(msg.clone()); diff --git a/crates/ui-egui/src/file_dialogs/tests.rs b/crates/ui-egui/src/file_dialogs/tests.rs index 000aca1108..57dee3503e 100644 --- a/crates/ui-egui/src/file_dialogs/tests.rs +++ b/crates/ui-egui/src/file_dialogs/tests.rs @@ -465,6 +465,70 @@ fn export_pdf_without_a_path_asks_where_to_save() { let _ = std::fs::remove_dir_all(&dir); } +/// A synchronous web save failure must not stamp a save that never reached its destination. +#[test] +fn failed_web_saves_restore_the_save_stamps() { + for id in ["file.save", "file.saveAs"] { + for (name, hosted, dirty, expected_calls) in [ + ("draft.unsupported", false, true, vec![]), + ("draft.docx", false, true, vec!["download"]), + ("draft.docx", true, true, vec!["host"]), + ("draft.docx", false, false, vec!["download"]), + ] { + let calls = Rc::new(RefCell::new(Vec::new())); + let downloaded = calls.clone(); + let host_calls = calls.clone(); + let services = Services { + download: Some(Box::new(move |_, _| { + downloaded.borrow_mut().push("download"); + Err("download refused".into()) + })), + host_save: hosted.then(|| { + Box::new(move |_: &str, _: &[u8], _: bool| { + host_calls.borrow_mut().push("host"); + Err("host refused".into()) + }) as crate::HostSaveFn + }), + ..Default::default() + }; + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text(UNSAVED)), services); + a.session.dirty = dirty; + a.session.path = Some("original.docx".into()); + a.session.view.zoom = 1.37; + a.session.doc.core.created.clear(); + a.session.doc.core.modified = "2020-01-02T03:04:05Z".into(); + a.session.doc.core.last_modified_by = "Previous author".into(); + a.session.doc.core.revision = 7; + let path_before = a.session.path.clone(); + let core_before = a.session.doc.core.clone(); + let zoom_before = a.session.doc.settings.zoom; + let undo_before = a.session.undo_depth(); + assert!(a.run(id, json!({"path": name})).is_err(), "{id}: {name}"); + assert_eq!(*calls.borrow(), expected_calls, "{id}: {name}"); + assert_eq!(a.session.doc.core, core_before, "{id}: {name}"); + assert_eq!(a.session.doc.settings.zoom, zoom_before, "{id}: {name}"); + assert_eq!(a.session.undo_depth(), undo_before, "{id}: {name}"); + assert_eq!(a.session.dirty, dirty, "{id}: {name}"); + assert_eq!(a.session.path, path_before, "{id}: {name}"); + } + let services = Services { + download: Some(Box::new(|_, bytes| { + assert!(bytes.starts_with(b"PK")); + Ok(()) + })), + ..Default::default() + }; + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text(UNSAVED)), services); + a.session.dirty = true; + let revision_before = a.session.doc.core.revision; + assert_eq!(a.run(id, json!({"path": "draft.docx"})).unwrap()["downloaded"], "draft.docx"); + assert_eq!(a.session.doc.core.revision, revision_before.saturating_add(1)); + assert_eq!(a.session.doc.core.last_modified_by, a.session.author); + assert!(!a.session.doc.core.created.is_empty() && !a.session.doc.core.modified.is_empty()); + assert!(!a.session.dirty); + } +} + /// An explicit web PDF export keeps an existing PDF suffix regardless of ASCII case. #[test] fn web_pdf_export_keeps_an_existing_suffix_in_any_case() { From 8e8ab631fd74cef5d295a68baa4fb618d15da76f Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:16:20 +0100 Subject: [PATCH 39/99] M14: document optional run commands and PNG save options (#6687) --- apps/wordcraft-cli/src/main.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/wordcraft-cli/src/main.rs b/apps/wordcraft-cli/src/main.rs index a7c38c628c..0bcf8377ea 100644 --- a/apps/wordcraft-cli/src/main.rs +++ b/apps/wordcraft-cli/src/main.rs @@ -35,10 +35,11 @@ USAGE: --strict writes nothing and exits 3 if a character on the 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}' [--cmd …] - [--save OUT] [--print] [--author NAME] + wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …] + [--save OUT] [--page N] [--scale S] [--print] [--author NAME] run commands headlessly, then save (--author names who tracked changes and comments are by). + 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, \"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save From 840efd03fb185be4587b20f517345309e98bf35d Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:30:24 +0100 Subject: [PATCH 40/99] M14: link PDF revision guidance to the workspace manifest (#6685) --- docs/shared-pdf.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/shared-pdf.md b/docs/shared-pdf.md index 92596b59ab..0612669644 100644 --- a/docs/shared-pdf.md +++ b/docs/shared-pdf.md @@ -1,8 +1,8 @@ # Shared PDF writer WordCraft uses `craft-pdf` with default features disabled and `write` enabled. Both that dependency -and the required root Krilla patch use the immutable `storytold/craft-libs` revision -`b926b5c03e256c86ca10934f58d03f628810b5b7`. Rust 1.95 or newer is required. The revision must be +and the required root Krilla patch use the same immutable `storytold/craft-libs` revision, +pinned in [`Cargo.toml`](../Cargo.toml). Rust 1.95 or newer is required. The revision must be available from the remote before a fresh checkout can resolve it. The shared writer checks a backend marker at compile time so an unpatched Krilla cannot replace the required backend. From 68f758928e256f7aa5e46dc5dd3cdce9745f40ac Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:45:21 +0100 Subject: [PATCH 41/99] M14: keep the type_text description in one MCP table row (#6683) --- docs/mcp.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 26e728fc6f..7a20d0d97b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # MCP server -> **Last updated:** 2026-10-31 · Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. +> **Last updated:** 2026-11-14 · Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. WordCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so Claude and other agents can write and edit documents. @@ -173,10 +173,7 @@ test source in File › Options › Language and on the bar's Install. | `new_document` | blank, sample, letter, resume, report; opens beside the open documents | | `open_document` / `save_document` | docx, doc (open only), odt, rtf, html, md, tex, txt, json; save also pdf, png | | `list_documents` | the open documents: `id`, `title`, `path`, `dirty`, `active` | -| `type_text` | type at the caret (`paragraphs: true` splits lines into paragraphs: one undo - step; each break is the Enter it stands for, so AutoFormat and AutoCorrect run and a - one-line control refuses; at most 10,000 lines — the cap is `text.insert`'s own, so a - control-channel or CLI call is held to it too) | +| `type_text` | type at the caret (`paragraphs: true` splits lines into paragraphs: one undo step; each break is the Enter it stands for, so AutoFormat and AutoCorrect run and a one-line control refuses; at most 10,000 lines — the cap is `text.insert`'s own, so a control-channel or CLI call is held to it too) | | `select_text` | select the n-th occurrence of some text | | `get_text` / `inspect_document` | read the document back (verify without screenshots) | | `render_page` | a page as PNG | From b3f31666d331a2a267b8dba22710374f86e5324e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:00:18 +0100 Subject: [PATCH 42/99] M14: align release guide with scheduled dry runs (#6682) --- docs/releasing.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index 73c0866396..99ee3851a5 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,6 +1,7 @@ # Releasing WordCraft -1. Bump the version on `main`: `cargo xtask version set 0.2.0` (the one source of truth is +1. On a branch, bump the version with `cargo xtask version set 0.2.0`, then open and + merge a pull request into `main` (the one source of truth is `[workspace.package] version`; the app shows it in `--version` and About, with the commit from `WORDCRAFT_BUILD_SHA`). 2. Merge `main` into `release` and push. `.github/workflows/release.yml` builds: @@ -17,12 +18,13 @@ 3. The run drafts a GitHub Release `WordCraft v` with `SHA256SUMS.txt`; review and publish it. Signing secrets live in the repository's `release` environment (deployment branch: `release` only), -synced from the release manager's machine. Missing secrets -produce unsigned builds with a warning, so forks still build. +synced from the release manager's machine. On the release branch, the shared workflow fails the +macOS and Windows jobs if their signing credentials are missing. Local packaging can still +produce unsigned builds with a warning. Local packaging: `packaging/macos/package.sh --arch universal`, `packaging/windows/package.ps1`, `packaging/linux/package.sh` (then `packaging/linux/flatpak-bundle.sh` for the Flatpak), `packaging/web/package.sh`. -Dry run: `gh workflow run release.yml --ref ` builds the unsigned jobs (version, Linux, -Linux riscv64, Flatpak, FreeBSD, web) on any branch; the signing jobs are refused there by the `release` -environment's branch rule, so no draft release is made. +A scheduled dry run runs on `main` nightly at 03:00 UTC. It builds every release target except +macOS, without signing, entering the `release` environment, pushing Flatpak images or making a +draft release. Manual dispatch uses the normal release path (`dry-run` is false). From 739cdcad0b4abc7502906a57ac1019613669437b Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:15:46 +0100 Subject: [PATCH 43/99] M15: correct English proofing credits in README (#6681) --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 42d0e27b82..ee41a08d2d 100644 --- a/README.md +++ b/README.md @@ -451,8 +451,10 @@ Copyright (c) 2026 ArtCraft Team and the WordCraft contributors. Required notice Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md). -The English spelling dictionary and hyphenation come from Grady Ward's public-domain Moby -Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as +English spelling first tries a matching Hunspell dictionary from the Dictionaries folder. +Otherwise it uses dialect-specific SCOWL 2026 dictionaries when built with language data; +without it, spelling falls back to system Hunspell dictionaries or Grady Ward's public-domain +Moby Hyphenator II word list. English hyphenation uses the Moby list and patterns trained from it. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as do Russian, Portuguese, Czech, Italian, Croatian and Turkish spelling (how to install them: [docs/spelling-dictionaries.md](docs/spelling-dictionaries.md)), and Polish hyphenation the TeX patterns by Hanna Kołodziejska, Bogusław Jackowski and Marek Ryćko (MIT From 2dd0f9a67bc7f0261b4ca9d142c34ad9b8e1a9ab Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Mon, 16 Nov 2026 20:37:06 -0800 Subject: [PATCH 44/99] Field dialog: text fields have a Format list for capitalization (#5062) --- ROADMAP.md | 2 + crates/engine/src/cmd/mailings/merge.rs | 5 +- crates/engine/src/cmd/mailings/tests.rs | 27 ++++ .../src/dialogs/dialogs_insert/field.rs | 120 +++++++++++++++- .../src/dialogs/dialogs_insert/tests.rs | 135 ++++++++++++++++++ docs/ui-parity.md | 1 + 6 files changed, 281 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 31b65c8ae9..dd88207e56 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -729,6 +729,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-12 | Table style editor (#714): New/Modify Table Style edits each of the 13 table style parts (header row, total row, first/last column, odd/even bands, corner cells) with font, colour, fill, borders and cell alignment; every table using the style follows; all parts round-trip in DOCX; `table.modifyStyle` takes `part`/`parts` and per-edge borders | | 2026-10-12 | STYLEREF fields (#775): running headers and footers show each page's chapter title (page's first, or `\l` last, paragraph of the style, else the nearest before), style names, ids, heading levels and character styles, number switches; body STYLEREF updates with the other fields; STYLEREF in the Field dialog; PDF export follows the layout | | 2026-10-24 | Document information fields: SUBJECT, KEYWORDS, COMMENTS, LASTSAVEDBY, REVNUM and NUMCHARS update with the other fields and are listed in the Field dialog; a quoted text after TITLE, SUBJECT, AUTHOR, KEYWORDS or COMMENTS replaces that document property (at most 255 characters), and NUMWORDS, NUMCHARS and REVNUM take a `\*` number format | +| 2026-10-31 | Field dialog capitalization: AUTHOR, COMMENTS, FILENAME, KEYWORDS, LASTSAVEDBY, SUBJECT, TITLE, REF, STYLEREF and MERGEFIELD have a Format list with Uppercase, Lowercase, First capital and Title case, which writes `\* Upper`, `\* Lower`, `\* FirstCap` or `\* Caps` before `\* MERGEFORMAT`; Hide Codes sets the list from the typed code's last such switch and keeps every capitalization switch the code had, in order, until another Format is chosen; Preview Results and Finish & Merge apply a MERGEFIELD's capitalization switch to the record's value, and IF, NEXTIF and SKIPIF rules apply the tested MERGEFIELD's capitalization switch before comparing | | 2026-10-24 | Field capitalization switches: `\* Upper`, `\* Lower`, `\* Caps` and `\* FirstCap` apply to the document information, DOCPROPERTY, FILENAME, date, REF, PAGEREF, SEQ, STYLEREF and table formula results that Update Field computes and to the page-number fields, and `\* CardText` and `\* OrdText` results are lowercase unless one of them follows (`\* CardText \* Caps` shows "Seven Hundred Ninety"); a table formula takes a `\*` number format (`=SUM(A1:B2) \* CardText`), and other `\*` switches such as `\* MERGEFORMAT` no longer make it a syntax error | | 2026-10-24 | Field `\* DollarText` and `\* Hex` switches: `{ = 9.20 + 5.35 \* DollarText \* Upper }` shows "FOURTEEN AND 55/100" and `\* Hex` writes uppercase hexadecimal digits (458 shows "1CA"), in table formulas and in the page-number, SEQ, PAGEREF and count fields; `{ PAGE \* ArabicDash }` shows "- 31 -"; cardinal, ordinal and dollar text past 999,999 keep their digits | | 2026-10-12 | Undo history list (#701): a ▾ beside the Quick Access Toolbar's Undo lists recent steps newest first; hovering highlights what a click undoes ("Undo 3 Actions"), and a click undoes them in one go. `edit.undoTo {count}` and `edit.undoHistory` (newest first, up to 100) for CLI and MCP | @@ -1446,6 +1447,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-10-27 | trivial | Progress log: AutoCorrect Options with no document open (#4585) | | 2026-10-28 | trivial | Progress log: RTF metafile pictures are imported (#4259) | | 2026-10-28 | trivial | Progress log: Chinese and Japanese text counts a word per character (#4547) | +| 2026-10-31 | trivial | Progress log: Field dialog capitalization Format list for text fields | | 2026-10-27 | trivial | 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged. | | 2026-10-27 | trivial | 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. | > 2026-10-29 · Port #3915 to split layout modules: ordinary LTR tab groups follow paragraph alignment. Positional tabs, lists, RTL and display math retain their alignment paths. Source port only; no test execution or new native measurements. diff --git a/crates/engine/src/cmd/mailings/merge.rs b/crates/engine/src/cmd/mailings/merge.rs index 80fad25da7..f26fb1aba2 100644 --- a/crates/engine/src/cmd/mailings/merge.rs +++ b/crates/engine/src/cmd/mailings/merge.rs @@ -107,7 +107,8 @@ fn condition(s: &Session, t: &str, row: usize) -> (bool, Vec) { let op: String = rest.trim_start().chars().take_while(|c| matches!(c, '<'..='>')).collect(); let mut texts = field_words(rest).into_iter().filter(|(_, q)| *q).map(|(w, _)| w); let cmp = texts.next().unwrap_or_default(); - let v = value(s, row, &field); + let tested = t.split_once('{').and_then(|(_, r)| r.split('}').next()).unwrap_or(""); + let v = wordcraft_layout::fields::apply_case_switch(tested, value(s, row, &field)); // Numbers compare as numbers (Word: "7" = "7.0"), everything else as text. let ord = match (v.trim().parse::(), cmp.trim().parse::()) { (Ok(a), Ok(b)) => a.partial_cmp(&b), @@ -134,7 +135,7 @@ fn keyword(instr: &str) -> String { fn act(s: &Session, instr: &str, row: usize) -> Option { let t = instr.trim(); if let Some(n) = mergefield_name(t) { - return Some(Act::Text(value(s, row, &n))); + return Some(Act::Text(wordcraft_layout::fields::apply_case_switch(t, value(s, row, &n)))); } Some(match keyword(t).as_str() { "ADDRESSBLOCK" => Act::Text(address_block(s, row)), diff --git a/crates/engine/src/cmd/mailings/tests.rs b/crates/engine/src/cmd/mailings/tests.rs index 720668aa64..f8f1c60455 100644 --- a/crates/engine/src/cmd/mailings/tests.rs +++ b/crates/engine/src/cmd/mailings/tests.rs @@ -147,6 +147,33 @@ fn merge_field_types_ignore_case() { assert_eq!(s.doc.plain_text(StoryRef::Body), "Alpha\nBeta (b)"); } +/// A merge field's capitalization switch (`\* Upper`, `\* Lower`, `\* Caps`, `\* FirstCap`) +/// applies to the record's value in Preview Results and Finish & Merge. +#[test] +fn merge_fields_apply_their_capitalization_switch() { + let mut s = Session::new(Document::new()); + s.run("mailings.recipients", &json!({"rows": [{"City": "new york", "Name": "ADA lovelace"}]})).unwrap(); + s.run("insert.field", &json!({"instr": r"MERGEFIELD City \* Upper \* MERGEFORMAT", "result": ""})).unwrap(); + s.run("text.insert", &json!({"text": " "})).unwrap(); + s.run("insert.field", &json!({"instr": r#"MERGEFIELD "Name" \* Lower"#, "result": ""})).unwrap(); + s.run("mailings.preview", &json!({"value": true})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace"); + s.run("mailings.finish", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace"); +} + +/// An IF, NEXTIF or SKIPIF compares the tested merge field after its capitalization switch. +#[test] +fn rule_conditions_apply_the_tested_fields_capitalization_switch() { + let mut s = Session::new(Document::new()); + s.run("mailings.recipients", &json!({"rows": [{"City": "new york"}, {"City": "paris"}]})).unwrap(); + s.run("insert.field", &json!({"instr": r#"IF { MERGEFIELD City \* Upper } = "NEW YORK" "match" "other""#, "result": ""})).unwrap(); + s.run("mailings.preview", &json!({"value": true})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "match"); + s.run("mailings.next", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "other"); +} + /// An IF is a merge rule only when the field it tests is a MERGEFIELD: the word in a quoted /// value doesn't make `IF { PAGE } = "mergefield" …` one. #[test] diff --git a/crates/ui-egui/src/dialogs/dialogs_insert/field.rs b/crates/ui-egui/src/dialogs/dialogs_insert/field.rs index c482ebbdff..b08798ec12 100644 --- a/crates/ui-egui/src/dialogs/dialogs_insert/field.rs +++ b/crates/ui-egui/src/dialogs/dialogs_insert/field.rs @@ -93,6 +93,45 @@ pub const NUMBER_FORMATS: &[(&str, &str)] = &[ ("OrdText", "First, Second, Third, …"), ]; +/// Capitalization formats for the `\*` switch of a text field: (switch value, label). +pub const TEXT_FORMATS: &[(&str, &str)] = + &[("", "(none)"), ("Upper", "Uppercase"), ("Lower", "Lowercase"), ("FirstCap", "First capital"), ("Caps", "Title case")]; + +/// Whether the dialog offers the capitalization Format list for `name` (the fields whose result +/// is text). +pub fn takes_text_format(name: &str) -> bool { + matches!(name, "AUTHOR" | "COMMENTS" | "FILENAME" | "KEYWORDS" | "LASTSAVEDBY" | "SUBJECT" | "TITLE" | "REF" | "STYLEREF" | "MERGEFIELD") +} + +/// The capitalization switches in a field code, as their [`TEXT_FORMATS`] values, in the order +/// they appear (layout applies them in that order). Quoted text in the code is not a switch. +pub fn text_formats(code: &str) -> Vec<&'static str> { + let mut chars = code.chars().peekable(); + let mut quoted = false; + let mut all = Vec::new(); + while let Some(c) = chars.next() { + match c { + '\\' if quoted => { + chars.next(); + } + '"' => quoted = !quoted, + '\\' if chars.peek() == Some(&'*') => { + chars.next(); + while chars.next_if(|c| c.is_whitespace()).is_some() {} + let mut word = String::new(); + while let Some(c) = chars.next_if(|c| !c.is_whitespace() && *c != '\\' && *c != '"') { + word.push(c); + } + if let Some((v, _)) = TEXT_FORMATS.iter().find(|(v, _)| !v.is_empty() && v.eq_ignore_ascii_case(&word)) { + all.push(*v); + } + } + _ => {} + } + } + all +} + pub fn field_kind(name: &str) -> FieldKind { match name { "DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => FieldKind::Date, @@ -117,6 +156,12 @@ pub struct FieldForm { pub date_format: String, /// `\*` value for number fields (empty = none). pub number_format: String, + /// `\*` capitalization value for text fields (empty = none). + pub text_format: String, + /// Every capitalization switch of the code typed in Field Codes, in order. The code keeps them + /// all while the Format list shows the last of them. + #[serde(skip)] + typed_text_formats: Vec<&'static str>, /// Bookmark (REF, PAGEREF), sequence name (SEQ), merge field (MERGEFIELD) or style name /// (STYLEREF). pub target: String, @@ -148,6 +193,8 @@ impl FieldForm { name: "DATE".into(), date_format: DATE_FORMATS.first().copied().unwrap_or("M/d/yyyy").to_string(), number_format: String::new(), + text_format: String::new(), + typed_text_formats: Vec::new(), target: String::new(), preserve: true, codes: false, @@ -178,6 +225,8 @@ impl FieldForm { pub fn select(&mut self, name: &str) { self.name = name.to_string(); self.number_format.clear(); + self.text_format.clear(); + self.typed_text_formats.clear(); self.target = match field_kind(name) { FieldKind::Bookmark => self.bookmarks.first().cloned().unwrap_or_default(), FieldKind::Sequence => "Figure".into(), @@ -230,6 +279,15 @@ impl FieldForm { if matches!(field_kind(&self.name), FieldKind::Number | FieldKind::Sequence) && !self.number_format.is_empty() { s.push_str(&format!(" \\* {}", self.number_format)); } + if takes_text_format(&self.name) && !self.text_format.is_empty() { + if self.typed_text_formats.last().is_some_and(|v| *v == self.text_format) { + for v in &self.typed_text_formats { + s.push_str(&format!(" \\* {v}")); + } + } else { + s.push_str(&format!(" \\* {}", self.text_format)); + } + } if self.preserve && field_kind(&self.name) != FieldKind::Toc { s.push_str(" \\* MERGEFORMAT"); } @@ -241,6 +299,27 @@ impl FieldForm { if self.codes { self.code.trim().to_string() } else { self.instruction() } } + /// The Format list: a choice replaces the capitalization switches kept from a typed code. + pub fn choose_text_format(&mut self, value: &str) { + self.text_format = value.to_string(); + self.typed_text_formats.clear(); + } + + /// Field Codes / Hide Codes: showing the code starts it from the options; hiding it sets the + /// Format list to the code's last capitalization switch when the code is for the chosen field, + /// and keeps all of the code's capitalization switches until another Format is chosen. + pub fn toggle_codes(&mut self) { + if !self.codes { + self.code = self.instruction(); + } else if takes_text_format(&self.name) + && (wordcraft_layout::fields::field_name(&self.code) == self.name || self.name == "MERGEFIELD" && is_merge_field(&self.code)) + { + self.typed_text_formats = text_formats(&self.code); + self.text_format = self.typed_text_formats.last().copied().unwrap_or_default().to_string(); + } + self.codes = !self.codes; + } + /// The `insert.field` parameters (a merge field shows «name» until merged). pub fn params(&self) -> Option { let code = self.final_code(); @@ -248,13 +327,29 @@ impl FieldForm { return None; } let name = wordcraft_layout::fields::field_name(&code); - Some(if name == "MERGEFIELD" { json!({"instr": code, "result": format!("«{}»", merge_field_name(&code))}) } else { json!({"instr": code}) }) + Some(if name == "MERGEFIELD" || is_merge_field(&code) { + json!({"instr": code, "result": format!("«{}»", merge_field_name(&code))}) + } else { + json!({"instr": code}) + }) } } +/// The byte where a field code's type ends: at a space or a quote, as mail merge reads it. +fn field_type_end(code: &str) -> usize { + code.find(|c: char| c.is_whitespace() || c == '"').unwrap_or(code.len()) +} + +/// Whether a typed code is a `MERGEFIELD`, including one with no space before its quoted name. +fn is_merge_field(code: &str) -> bool { + let code = code.trim_start(); + code[..field_type_end(code)].eq_ignore_ascii_case("MERGEFIELD") +} + /// The merge field a `MERGEFIELD` code names (quoted names may hold spaces). fn merge_field_name(code: &str) -> String { - let rest = code.trim_start().split_once(char::is_whitespace).map(|x| x.1.trim_start()).unwrap_or(""); + let code = code.trim_start(); + let rest = code[field_type_end(code)..].trim_start(); match rest.strip_prefix('"') { Some(q) => q.split('"').next().unwrap_or("").to_string(), None => rest.split_whitespace().next().unwrap_or("").to_string(), @@ -318,10 +413,7 @@ pub(super) fn field_ui(app: &mut WordApp, ui: &mut Ui, f: &mut FieldForm) -> boo ui.horizontal(|ui| { let label = if f.codes { "Hide Codes" } else { "Field Codes" }; if ui.button(tl!(label)).clicked() { - if !f.codes { - f.code = f.instruction(); - } - f.codes = !f.codes; + f.toggle_codes(); } }); let params = f.params(); @@ -409,7 +501,21 @@ fn field_options(ui: &mut Ui, f: &mut FieldForm, t: &Tokens) { } } FieldKind::Toc | FieldKind::Plain => { - ui.label(egui::RichText::new(tl!("This field has no options.")).small().color(t.text_dim)); + if !takes_text_format(&f.name) { + ui.label(egui::RichText::new(tl!("This field has no options.")).small().color(t.text_dim)); + } } } + if takes_text_format(&f.name) { + ui.add_space(4.0); + ui.label(tl!("Format:")); + let shown = TEXT_FORMATS.iter().find(|(v, _)| *v == f.text_format).map(|(_, l)| *l).unwrap_or("(none)"); + craft_ui::ComboBox::from_id_salt("field_text").selected_text(tl!(shown)).width(200.0).show_ui(ui, |ui| { + for (v, l) in TEXT_FORMATS { + if ui.selectable_label(f.text_format == *v, tl!(l)).clicked() { + f.choose_text_format(v); + } + } + }); + } } diff --git a/crates/ui-egui/src/dialogs/dialogs_insert/tests.rs b/crates/ui-egui/src/dialogs/dialogs_insert/tests.rs index dbf82530ea..b9f2f61ec5 100644 --- a/crates/ui-egui/src/dialogs/dialogs_insert/tests.rs +++ b/crates/ui-egui/src/dialogs/dialogs_insert/tests.rs @@ -149,6 +149,141 @@ fn field_dialog_builds_the_instruction() { assert!(f.params().is_none()); } +/// Text fields take a capitalization Format: each choice writes its `\*` switch before +/// `\* MERGEFORMAT`, after the field's own arguments and switches, and (none) writes none. +#[test] +fn field_dialog_text_format_writes_its_switch() { + let a = app(); + let mut f = FieldForm::new(&a); + f.select("AUTHOR"); + assert_eq!(f.text_format, ""); + assert_eq!(f.instruction(), r"AUTHOR \* MERGEFORMAT"); + for v in ["Upper", "Lower", "FirstCap", "Caps"] { + f.text_format = v.into(); + assert_eq!(f.instruction(), format!(r"AUTHOR \* {v} \* MERGEFORMAT")); + } + let labels: Vec<&str> = field::TEXT_FORMATS.iter().map(|(_, l)| *l).collect(); + assert_eq!(labels, ["(none)", "Uppercase", "Lowercase", "First capital", "Title case"]); + f.select("REF"); + f.target = "intro".into(); + f.text_format = "Upper".into(); + assert_eq!(f.instruction(), r"REF intro \h \* Upper \* MERGEFORMAT"); + f.select("STYLEREF"); + f.style_switches = "l".into(); + f.text_format = "Caps".into(); + f.preserve = false; + assert_eq!(f.instruction(), r#"STYLEREF "Heading 1" \l \* Caps"#); + f.select("MERGEFIELD"); + f.target = "City".into(); + f.text_format = "Lower".into(); + assert_eq!(f.params().unwrap(), json!({"instr": r"MERGEFIELD City \* Lower", "result": "«City»"})); + // Choosing another field starts from (none). + f.select("TITLE"); + assert_eq!((f.text_format.as_str(), f.instruction().as_str()), ("", "TITLE")); +} + +/// The list is offered for the text fields only; date, number, PAGEREF, SEQ and TOC keep their +/// own options and never take a capitalization switch from it. +#[test] +fn field_dialog_text_format_is_for_text_fields_only() { + for name in ["AUTHOR", "COMMENTS", "FILENAME", "KEYWORDS", "LASTSAVEDBY", "SUBJECT", "TITLE", "REF", "STYLEREF", "MERGEFIELD"] { + assert!(field::takes_text_format(name), "{name}"); + } + let a = app(); + let mut f = FieldForm::new(&a); + for name in ["DATE", "PAGE", "NUMPAGES", "PAGEREF", "SEQ", "TOC"] { + assert!(!field::takes_text_format(name), "{name}"); + f.select(name); + let before = f.instruction(); + f.text_format = "Upper".into(); + assert_eq!(f.instruction(), before, "{name}"); + } +} + +/// Hide Codes sets the Format list from the typed code's last capitalization switch outside +/// quotes, and to (none) when the code has none. +#[test] +fn field_dialog_text_format_follows_the_typed_code() { + assert_eq!(field::text_formats(r#"AUTHOR "a \* Lower" \* upper \* Caps \* MERGEFORMAT"#), ["Upper", "Caps"]); + assert!(field::text_formats(r#"MERGEFIELD "x \* FirstCap""#).is_empty()); + assert!(field::text_formats(r"PAGE \* roman").is_empty()); + let a = app(); + let mut f = FieldForm::new(&a); + f.select("SUBJECT"); + f.toggle_codes(); + assert_eq!(f.code, r"SUBJECT \* MERGEFORMAT"); + f.code = r"SUBJECT \* FIRSTCAP \* MERGEFORMAT".into(); + f.toggle_codes(); + assert!(!f.codes); + assert_eq!(f.instruction(), r"SUBJECT \* FirstCap \* MERGEFORMAT"); + f.toggle_codes(); + f.code = "SUBJECT".into(); + f.toggle_codes(); + assert_eq!(f.text_format, ""); + // A code for another field leaves the list as it was. + f.text_format = "Lower".into(); + f.toggle_codes(); + f.code = r"TITLE \* Upper".into(); + f.toggle_codes(); + assert_eq!(f.text_format, "Lower"); +} + +/// Hide Codes keeps every capitalization switch of the typed code, in order, so the inserted field +/// shows what the typed code shows; choosing another Format writes that one switch only. +#[test] +fn field_dialog_text_format_keeps_every_typed_case_switch() { + use wordcraft_layout::fields::apply_case_switch; + let a = app(); + let mut f = FieldForm::new(&a); + f.select("SUBJECT"); + f.toggle_codes(); + f.code = r"SUBJECT \* Lower \* Caps".into(); + let typed = apply_case_switch(&f.code, "WEEKLY REPORT".into()); + assert_eq!(typed, "Weekly Report"); + f.toggle_codes(); + assert_eq!(f.text_format, "Caps"); + assert_eq!(f.final_code(), r"SUBJECT \* Lower \* Caps \* MERGEFORMAT"); + assert_eq!(apply_case_switch(&f.final_code(), "WEEKLY REPORT".into()), typed); + // Field Codes shows the same switches again. + f.toggle_codes(); + assert_eq!(f.code, r"SUBJECT \* Lower \* Caps \* MERGEFORMAT"); + f.toggle_codes(); + // A Format the user chooses replaces the typed switches, and choosing Title case again + // does not bring them back. + f.choose_text_format("Upper"); + assert_eq!(f.final_code(), r"SUBJECT \* Upper \* MERGEFORMAT"); + f.choose_text_format("Caps"); + assert_eq!(f.final_code(), r"SUBJECT \* Caps \* MERGEFORMAT"); + f.choose_text_format(""); + assert_eq!(f.final_code(), r"SUBJECT \* MERGEFORMAT"); + // Choosing another field forgets them. + f.toggle_codes(); + f.code = r"SUBJECT \* Lower \* Caps".into(); + f.toggle_codes(); + f.select("SUBJECT"); + f.text_format = "Caps".into(); + assert_eq!(f.final_code(), r"SUBJECT \* Caps \* MERGEFORMAT"); +} + +/// A typed `MERGEFIELD` code's type ends at a quote as well as a space, as mail merge reads it. +#[test] +fn field_dialog_reads_a_typed_merge_field_with_no_space_before_its_quote() { + let a = app(); + let mut f = FieldForm::new(&a); + f.select("MERGEFIELD"); + f.toggle_codes(); + f.code = r#"MERGEFIELD"City" \* Lower"#.into(); + assert_eq!(f.params().unwrap()["result"], "«City»"); + f.toggle_codes(); + assert_eq!(f.text_format, "Lower"); + // Another field whose name only starts the same way is not this one. + f.choose_text_format(""); + f.toggle_codes(); + f.code = r"MERGEFIELDX \* Lower".into(); + f.toggle_codes(); + assert_eq!(f.text_format, ""); +} + /// The Field dialog lists Word's document information fields, and the counts take a number /// format. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f73ec040ba..2fb2379831 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -390,6 +390,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-10-11 | trivial | Field codes (#339): View › Field Codes (Alt+F9), Toggle Field Codes (Shift+F9), a field-code popup (double-click, right-click › Edit Field…; Ctrl+F9 opens the Field dialog), unlink/lock/unlock and next/previous field keys; field items in the context menu | | 2026-10-10 | trivial | Tabs dialog (Paragraph › Tabs…, double-click a ruler tab) and Borders and Shading with Borders, Page Border and Shading tabs (#320) | | 2026-10-10 | trivial | Columns (presets, unequal widths, line between, apply to), Symbol (font coverage grid by Unicode subset, recently used, character code, Special Characters) and Field (categories, options, field codes) dialogs (#321) | +| 2026-10-31 | trivial | Field dialog: AUTHOR, COMMENTS, FILENAME, KEYWORDS, LASTSAVEDBY, SUBJECT, TITLE, REF, STYLEREF and MERGEFIELD have a Format list with Uppercase, Lowercase, First capital and Title case (`\* Upper`, `\* Lower`, `\* FirstCap`, `\* Caps`); Hide Codes sets it from the typed code's last such switch and keeps every capitalization switch the code had, in order, until another Format is chosen; Preview Results and Finish & Merge apply a MERGEFIELD's capitalization switch to the record's value, and IF, NEXTIF and SKIPIF rules apply the tested MERGEFIELD's capitalization switch before comparing | | 2026-10-10 | trivial | Define New Multilevel List (all nine levels, live preview, `list.define`) and Track Changes Options (show, balloons, insertion/deletion marks and colours, changed-line bars; `review.trackingOptions`, saved per user) (#328) | | 2026-10-11 | trivial | Enclose Characters dialog and Home › Font button (#297) | | 2026-10-10 | trivial | Shortcuts: Alt+Shift+Up/Down move paragraphs, Alt+Shift+Left/Right promote/demote (⌃⇧ arrows on macOS), Shift+F5 Go Back, Alt+X Toggle Unicode (#343) | From 0cb315edaf6db0f5494ed3133bd05cc696579aa2 Mon Sep 17 00:00:00 2001 From: Marc <184940552+marcwgls@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:53:08 +0100 Subject: [PATCH 45/99] fix(ui): Recent shortens long names and paths to the row (#5212) (#5321) --- crates/ui-egui/src/backstage.rs | 72 ++++++- crates/ui-egui/src/backstage/tests.rs | 283 ++++++++++++++++++++++++++ 2 files changed, 350 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index e0456d3277..7788db71c2 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -635,17 +635,27 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) { let shown = app.ui.recent.iter().take(app.ui.recent_shown()).cloned().collect::>(); let file_name = |p: &str| std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(p.to_string()); let names = shown.iter().map(|p| file_name(p)).collect::>(); + let (mut focused, mut hovered) = (None, None); + use egui::epaint::text::TextDirection; for (p, name) in shown.iter().zip(&names) { // #2716: each row carries its own Remove, as Word's context menu does. The × is a button // of its own at the trailing end, so it never opens the document; clicking the rest of the // row opens it as before. let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width().min(700.0) - REMOVE_W, 40.0), Sense::click()); - // The row shows a name and a path that may not fit: the path in full is its tooltip. - let resp = resp.on_hover_text(crate::i18n::isolate_path(p)); // Two documents with the same file name are told apart by their path, as on screen. - let spoken = if names.iter().filter(|n| *n == name).count() > 1 { format!("{name}, {p}") } else { name.clone() }; + let twin = names.iter().filter(|n| *n == name).count() > 1; + let spoken = if twin { format!("{name}, {p}") } else { name.clone() }; resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &spoken)); + // Only one row shows its path as a tooltip, so every row gives a screen reader the path + // itself, unless its label already says it. + if !twin { + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_description(crate::i18n::isolate_path(p))); + } + if resp.has_focus() { + focused = Some((resp.clone(), p)); + } if resp.hovered() { + hovered = Some((resp.clone(), p)); ui.painter().rect_filled(r, 4.0, t.hover); } // Names and paths are set apart (a right-to-left line would scramble their marks and @@ -659,8 +669,25 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) { t.accent, ); let side = crate::rtl::lead_center(rtl); - ui.painter().text(pos2(crate::rtl::lead_x(rtl, r, 40.0), r.min.y + 13.0), side, crate::i18n::isolate(name), medium(13.0), t.text); - ui.painter().text(pos2(crate::rtl::lead_x(rtl, r, 40.0), r.min.y + 29.0), side, crate::i18n::isolate_path(p), regular(11.0), t.text_dim); + // A wide row on Home can push the row past the visible area at small window sizes, so the + // text stops at the visible edge and its ellipsis stays in view. Only its far end does: it + // starts at the row's start, in view or not. + let clip = ui.clip_rect(); + let room = if rtl { r.max.x - r.min.x.max(clip.min.x) } else { r.max.x.min(clip.max.x) - r.min.x }; + let text_w = (room - 48.0).max(0.0); + let fit = |text: String, direction: TextDirection, font: egui::FontId, color: egui::Color32, y: f32| { + let mut job = egui::text::LayoutJob::simple_singleline(text, font, color); + job.direction = direction; + job.wrap = egui::text::TextWrapping::truncate_at_width(text_w); + let g = ui.painter().layout_job(job); + let at = side.anchor_size(pos2(crate::rtl::lead_x(rtl, r, 40.0), y), g.size()).min; + ui.painter().galley(at, g, color); + }; + // An isolate hides a right-to-left name's direction from its line, which would put the + // ellipsis beside the name's first letters. + let direction = if wordcraft_doc::bidi::first_strong_is_rtl(name) { TextDirection::RightToLeft } else { TextDirection::Auto }; + fit(crate::i18n::isolate(name), direction, medium(13.0), t.text, r.min.y + 13.0); + fit(crate::i18n::isolate_path(p), TextDirection::Auto, regular(11.0), t.text_dim, r.min.y + 29.0); let xr = Rect::from_min_max(pos2(r.max.x + 2.0, r.min.y + 4.0), pos2(r.max.x + REMOVE_W, r.max.y - 4.0)); // Right-to-left: the × sits on the left, past the row's trailing edge. let xr = if rtl { xr.translate(vec2(-(r.width() + REMOVE_W + 2.0), 0.0)) } else { xr }; @@ -691,6 +718,41 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) { { let _ = app.run("ui.recentClear", json!({})); } + // A row shows a name and a path that may not fit: the path in full is its tooltip, for the + // hovered row or, after a key press, the focused one. egui shows one tooltip per layer, so + // only one of them is drawn, and the focus tooltip lets the pointer through to the rows below. + let keyboard = recent_keyboard_last(ui); + match (focused, hovered) { + (Some((resp, p)), hovered) if keyboard || hovered.is_none() => { + egui::Tooltip::for_widget(&resp).show(|ui| ui.label(crate::i18n::isolate_path(p))); + } + (_, Some((resp, p))) => { + resp.on_hover_text(crate::i18n::isolate_path(p)); + } + _ => {} + } +} + +/// Was a key pressed more recently than the pointer moved? Kept across passes, so a focused +/// Recent row keeps its tooltip while the pointer rests on another row. +fn recent_keyboard_last(ui: &Ui) -> bool { + let id = egui::Id::unique("backstage_recent_keyboard_last"); + let now = ui.input(|i| { + if i.pointer.delta() != egui::Vec2::ZERO { + Some(false) + } else if i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })) { + Some(true) + } else { + None + } + }); + match now { + Some(keyboard) => { + ui.ctx().data_mut(|d| d.insert_temp(id, keyboard)); + keyboard + } + None => ui.ctx().data(|d| d.get_temp(id)).unwrap_or(false), + } } /// Stable storage id for the Recent list's open error. diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index 80b4dcbf9b..3c3282dc2e 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -75,6 +75,289 @@ fn opening_a_missing_recent_file_keeps_file_open_with_the_error() { assert!(app.ui.backstage, "File stays open"); } +/// Opens File > Home in a window of `size` with one long Recent entry; returns its name and path. +fn long_recent_harness(size: egui::Vec2) -> (egui_kittest::Harness<'static, WordApp>, String, String) { + let name = format!("{}.docx", "AVeryLongDocumentName".repeat(8)); + let path = format!("C:/Users/Someone/{}/{name}", "LongFolderName".repeat(20)); + (recent_harness(std::slice::from_ref(&path), size), name, path) +} + +/// Opens File > Home in a window of `size` with `recent` as the Recent list. +fn recent_harness(recent: &[String], size: egui::Vec2) -> egui_kittest::Harness<'static, WordApp> { + let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default()); + a.ui.recent = recent.to_vec(); + a.run("ui.backstage", json!({"value": true, "page": "home"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + h.run_steps(4); + h +} + +/// Collects every text shape, including those nested in shape lists. +fn collect_text<'a>(s: &'a egui::Shape, out: &mut Vec<&'a egui::epaint::TextShape>) { + match s { + egui::Shape::Text(ts) => out.push(ts), + egui::Shape::Vec(v) => { + for child in v { + collect_text(child, out); + } + } + _ => {} + } +} + +/// Returns the painted bounds and clip rect of the Recent entry's name and path texts, and +/// whether each ends with an ellipsis. +fn recent_text_bounds(h: &egui_kittest::Harness<'_, WordApp>) -> Vec<(String, egui::Rect, egui::Rect, bool)> { + let mut found = Vec::new(); + for cs in &h.output().shapes { + let mut texts = Vec::new(); + collect_text(&cs.shape, &mut texts); + for ts in texts { + let text = ts.galley.text(); + if text.contains("C:/Users/Someone") || text.contains("AVeryLongDocumentName") { + let ellipsis = ts.galley.rows.first().and_then(|row| row.glyphs.last()).is_some_and(|g| g.chr == '\u{2026}'); + found.push((text.to_owned(), ts.visual_bounding_rect(), cs.clip_rect, ellipsis)); + } + } + } + found +} + +/// #5212: long names and paths in File > Home > Recent shorten to fit their row and show on hover. +#[test] +fn recent_shortens_a_long_name_and_path_to_its_row() { + let (mut h, name, path) = long_recent_harness(egui::vec2(1440.0, 900.0)); + let row = h.get_by_label(&name).rect(); + let texts = recent_text_bounds(&h); + assert_eq!(texts.len(), 2, "both file name and path shapes must be found"); + for (text, bounds, _, ellipsis) in &texts { + assert!(*ellipsis, "text '{text}' must end with an ellipsis"); + assert!(bounds.max.x <= row.max.x + 0.5, "text '{text}' bounds.max.x ({}) > row.max.x + 0.5 ({})", bounds.max.x, row.max.x + 0.5); + } + + h.event(egui::Event::PointerMoved(row.center())); + h.run_steps(4); + h.get_by_label(&path); +} + +/// #5212: at the smallest window width the shortened texts end inside the visible area, so the +/// ellipsis is not cut off. +#[test] +fn recent_texts_end_inside_the_visible_area_at_the_smallest_window() { + let (h, _, _) = long_recent_harness(egui::vec2(760.0, 480.0)); + let texts = recent_text_bounds(&h); + assert_eq!(texts.len(), 2, "both file name and path shapes must be found"); + for (text, bounds, clip, ellipsis) in &texts { + assert!(*ellipsis, "text '{text}' must end with an ellipsis"); + assert!(bounds.max.x <= clip.max.x + 0.5, "text '{text}' ends at {} past the visible edge {}", bounds.max.x, clip.max.x); + } +} + +/// #5212: a Recent row focused with the keyboard shows its full path, as hovering does. +#[test] +fn recent_shows_the_full_path_when_a_row_has_keyboard_focus() { + let (mut h, name, path) = long_recent_harness(egui::vec2(1440.0, 900.0)); + assert!(h.query_by_label(&path).is_none(), "the full path must not show before focus"); + h.get_by_label(&name).focus(); + h.run_steps(4); + h.get_by_label(&path); +} + +/// #5212: the focus tooltip lets the pointer through, so the Recent row under it still gets +/// hovered, shows its own path and opens on click. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn recent_focus_tooltip_does_not_block_the_row_below() { + let dir = std::env::temp_dir().join(format!("wordcraft-5212-{}", std::process::id())); + let paths = ["one.docx", "two.docx"].map(|n| dir.join(n).to_string_lossy().to_string()); + let mut h = recent_harness(&paths, egui::vec2(1440.0, 900.0)); + h.get_by_label("one.docx").focus(); + h.run_steps(4); + let tip = h.get_by_label(&paths[0]).rect(); + let below = tip.intersect(h.get_by_label("two.docx").rect()); + assert!(below.is_positive(), "the focus tooltip must cover part of the next row: tip={tip:?}"); + h.event(egui::Event::PointerMoved(below.center())); + h.run_steps(4); + h.get_by_label(&paths[1]); + + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: below.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); + let error = h.ctx.data(|d| d.get_temp::(super::open_error_id())).unwrap_or_default(); + assert!(error.contains("two.docx"), "the click must reach two.docx and try to open it, got error '{error}'"); +} + +/// #5212: every Recent row gives a screen reader its full path, not only the hovered or +/// focused row that shows the path as a tooltip. +#[test] +fn recent_rows_describe_their_full_path_without_hover_or_focus() { + use egui_kittest::kittest::NodeT; + let dir = std::env::temp_dir().join("wordcraft-5212-describe"); + let paths = ["one.docx", "two.docx"].map(|n| dir.join(n).to_string_lossy().to_string()); + let mut h = recent_harness(&paths, egui::vec2(1440.0, 900.0)); + let one = h.get_by_label("one.docx").rect(); + h.event(egui::Event::PointerMoved(one.center())); + h.run_steps(4); + for (name, path) in ["one.docx", "two.docx"].iter().zip(&paths) { + let described = h.get_by_label(name).accesskit_node().description(); + assert_eq!(described.as_deref(), Some(crate::i18n::isolate_path(path).as_str()), "{name} must describe its full path"); + } +} + +/// A right-to-left language for the Recent tests. `rtl` goes by its code, so it needs no Arabic font. +fn recent_right_to_left() -> crate::i18n::Lang { + crate::i18n::fixture_lang("ar", "\tHome\tHome\n") +} + +/// The Recent list alone with one `path`, in `lang`, in a window 1000 wide. `start` points on the +/// side its rows start from and `end` points on the other side are out of view, as on a page +/// scrolled sideways or wider than the window. +fn recent_list_cut(path: &str, lang: crate::i18n::Lang, start: f32, end: f32) -> egui_kittest::Harness<'static, WordApp> { + let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default()); + a.ui.recent = vec![path.to_string()]; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 500.0)).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + crate::i18n::set_current(lang); + crate::rtl::sync(&ctx); + let mut clip = ui.clip_rect(); + let (left, right) = if crate::rtl::on() { (end, start) } else { (start, end) }; + clip.min.x += left; + clip.max.x -= right; + ui.set_clip_rect(clip); + super::open_list(app, ui); + }, + a, + ); + h.run_steps(4); + h +} + +/// #5212: text runs from its row's start, so a row whose start is out of view has as much room +/// for its text as before. Only the far end stops at the visible edge. +#[test] +fn recent_text_keeps_its_room_when_its_row_starts_out_of_view() { + let name = format!("{}.docx", "AVeryLongDocumentName".repeat(8)); + let path = format!("C:/Users/Someone/{name}"); + for lang in [crate::i18n::Lang::EN, recent_right_to_left()] { + let widths = |cut| recent_text_bounds(&recent_list_cut(&path, lang, cut, 0.0)).iter().map(|t| t.1.width().round()).collect::>(); + let whole = widths(0.0); + assert_eq!(whole.len(), 2, "both lines must be painted: {whole:?}"); + assert_eq!(widths(500.0), whole, "the cut must not take room from the text"); + } + crate::i18n::set_current(crate::i18n::Lang::EN); +} + +/// #5212: a row running past the visible area stops its text there, in either direction, with +/// its ellipsis in view. +#[test] +fn recent_text_stops_at_the_visible_edge_in_either_direction() { + let name = format!("{}.docx", "AVeryLongDocumentName".repeat(8)); + let path = format!("C:/Users/Someone/{name}"); + for lang in [crate::i18n::Lang::EN, recent_right_to_left()] { + let texts = recent_text_bounds(&recent_list_cut(&path, lang, 0.0, 400.0)); + assert_eq!(texts.len(), 2, "both lines must be painted"); + for (text, bounds, clip, ellipsis) in &texts { + assert!( + bounds.left() >= clip.left() - 0.5 && bounds.right() <= clip.right() + 0.5, + "{text} must end inside the visible area: {bounds:?} in {clip:?}" + ); + assert!(ellipsis, "{text} must end in an ellipsis"); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); +} + +/// #5212: multibyte text is cut between its characters and stays in its row, starting at the +/// side the row starts from, in either direction. +#[test] +fn recent_shortens_multibyte_text_in_either_direction() { + let name = format!("AVeryLongDocumentName{}.docx", "\u{fc}\u{20ac}".repeat(120)); + let path = format!("C:/Users/Someone/{name}"); + for lang in [crate::i18n::Lang::EN, recent_right_to_left()] { + let h = recent_list_cut(&path, lang, 0.0, 0.0); + let row = h.get_by_label(&name).rect(); + let texts = recent_text_bounds(&h); + assert_eq!(texts.len(), 2, "both lines must be painted"); + for (text, bounds, _, ellipsis) in &texts { + let lead = if lang.rtl() { row.right() - bounds.right() } else { bounds.left() - row.left() }; + assert!((lead - 40.0).abs() < 1.0, "{text} must start at its row's start: {bounds:?} in {row:?}"); + assert!(bounds.left() >= row.left() - 0.5 && bounds.right() <= row.right() + 0.5, "{text} must stay in its row: {bounds:?} in {row:?}"); + assert!(ellipsis, "{text} must end in an ellipsis"); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); +} + +/// #5212: a right-to-left name runs from the right, so it is cut on its left, and its ellipsis +/// belongs there, not beside the name's first letters. +#[test] +fn recent_puts_the_ellipsis_at_the_end_of_a_right_to_left_name() { + let name = format!("{}.docx", "\u{5d0}\u{5d1}\u{5d2} ".repeat(120)); + let h = recent_list_cut(&format!("/docs/{name}"), recent_right_to_left(), 0.0, 0.0); + let output = h.output(); + let mut texts = Vec::new(); + for clipped in &output.shapes { + collect_text(&clipped.shape, &mut texts); + } + let shown = texts.iter().find(|t| t.galley.text().contains('\u{5d0}')).expect("the name"); + let glyphs = &shown.galley.rows[0].glyphs; + let ellipsis = glyphs.iter().find(|g| g.chr == '\u{2026}').expect("an ellipsis"); + let left = glyphs.iter().filter(|g| g.size().x > 0.0).map(|g| g.pos.x).fold(f32::MAX, f32::min); + assert!(ellipsis.pos.x <= left + 0.5, "the ellipsis must be the leftmost glyph: {} against {left}", ellipsis.pos.x); + crate::i18n::set_current(crate::i18n::Lang::EN); +} + +/// #5212: two files with one name speak their path in the label, so it isn't read twice. +#[test] +fn recent_rows_with_one_name_speak_their_path_once() { + use egui_kittest::kittest::NodeT; + let dir = std::env::temp_dir().join("wordcraft-5212-twins"); + let paths = ["one", "two"].map(|d| dir.join(d).join("same.docx").to_string_lossy().to_string()); + let h = recent_harness(&paths, egui::vec2(1440.0, 900.0)); + for path in &paths { + let label = format!("same.docx, {path}"); + assert_eq!(h.get_by_label(&label).accesskit_node().description(), None, "{label} must not repeat its path"); + } +} + +/// #5212: with the pointer resting on one Recent row, Tab to the next row shows the focused +/// row's path, and moving the pointer again brings back the hovered row's path. +#[test] +fn recent_tab_shows_the_focused_path_while_the_pointer_rests_on_another_row() { + let dir = std::env::temp_dir().join("wordcraft-5212-tab"); + let paths = ["one.docx", "two.docx"].map(|n| dir.join(n).to_string_lossy().to_string()); + let mut h = recent_harness(&paths, egui::vec2(1440.0, 900.0)); + let one = h.get_by_label("one.docx").rect(); + h.event(egui::Event::PointerMoved(one.center())); + h.run_steps(4); + h.get_by_label(&paths[0]); + + h.get_by_label("one.docx").focus(); + h.run_steps(1); + // The first Tab goes to the row's own Remove ×, the second to the next row. + for _ in 0..2 { + h.key_press(egui::Key::Tab); + h.run_steps(4); + } + assert!(h.get_by_label("two.docx").is_focused(), "Tab must move focus to the next Recent row"); + assert!(h.query_by_label(&paths[1]).is_some(), "the focused row's path must show while the pointer rests on another row"); + + h.event(egui::Event::PointerMoved(one.center() + egui::vec2(4.0, 0.0))); + h.run_steps(4); + assert!(h.query_by_label(&paths[0]).is_some(), "moving the pointer must bring back the hovered row's path"); +} + /// #1873: the macOS back chevron sits beside the traffic lights windowed, at the plain /// control inset in full screen. #[test] From 93bf14883c7a57a802f383cbcce880aae1328cc8 Mon Sep 17 00:00:00 2001 From: ljkx Date: Tue, 17 Nov 2026 06:06:04 +0100 Subject: [PATCH 46/99] #3773: a WordCraft process saves only the preferences it changed (#5258) Co-Authored-By: Claude Opus 5.5 --- apps/wordcraft/src/main.rs | 180 +++++++++- apps/wordcraft/src/prefs_merge.rs | 550 ++++++++++++++++++++++++++++++ 2 files changed, 714 insertions(+), 16 deletions(-) create mode 100644 apps/wordcraft/src/prefs_merge.rs diff --git a/apps/wordcraft/src/main.rs b/apps/wordcraft/src/main.rs index 18b7b7935f..302b97d4f7 100644 --- a/apps/wordcraft/src/main.rs +++ b/apps/wordcraft/src/main.rs @@ -23,6 +23,7 @@ mod graphics; mod logging; #[cfg(all(unix, not(target_os = "macos")))] mod portal_save; +mod prefs_merge; mod print; mod region; #[cfg(target_os = "macos")] @@ -222,31 +223,44 @@ fn user_dict_path() -> Option { wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE)) } -fn load_user_dictionary(app: &mut WordApp) { - if !prefs_enabled() { - return; - } - if let Some(p) = user_dict_path() { - wordcraft_proof::load_user_dictionary(&p); - app.session.user_dict_path = Some(p); - } -} - /// Runs without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. fn prefs_enabled() -> bool { std::env::var_os("WORDCRAFT_NO_PREFS").is_none() } +/// The preferences as this process last loaded or saved them, which `save_prefs` compares with +/// to write only what this process changed since (#3773, see `prefs_merge`). +static LOADED_PREFS: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Apply the saved preferences (`ui.json`) and the user dictionary to `app`, and remember the +/// result for `save_prefs`. Runs without preferences neither read nor keep them. fn load_prefs(app: &mut WordApp) { if !prefs_enabled() { return; } - if let Some(p) = prefs_path() - && let Ok(bytes) = std::fs::read(&p) + let loaded = load_prefs_from(app, prefs_path().as_deref(), user_dict_path()); + if let Ok(mut slot) = LOADED_PREFS.lock() { + *slot = loaded; + } +} + +/// Apply the preferences saved at `prefs` to `app`, then load the user dictionary at `dict` +/// (`custom-dictionary.txt`, #40), and give back the preferences as `prefs()` does after both: +/// the words only the dictionary file has are part of what was loaded, so a word another process +/// removes from `ui.json` isn't written back as one added here (#3773). +fn load_prefs_from(app: &mut WordApp, prefs: Option<&std::path::Path>, dict: Option) -> Option { + if let Some(p) = prefs + && let Ok(bytes) = std::fs::read(p) && let Some(ui) = UiState::from_json(&bytes) { app.apply_prefs(ui); } + if let Some(p) = dict { + wordcraft_proof::load_user_dictionary(&p); + app.session.user_dict_path = Some(p); + } + // As `prefs()` gives them back, so a setting nobody touched compares equal at exit. + serde_json::to_value(app.prefs()).ok() } /// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts @@ -332,6 +346,8 @@ fn x11_libraries() -> Result<(), String> { if missing.is_empty() { Ok(()) } else { Err(missing.join("; ")) } } +/// Write `app`'s preferences to `ui.json`, merged with what other processes saved since this one +/// loaded it (`merged_prefs`). fn save_prefs(app: &WordApp) { if let Err(e) = try_save_prefs(app) { log::warn!("preferences: {e}"); @@ -348,11 +364,79 @@ fn try_save_prefs(app: &WordApp) -> Result { if let Some(dir) = p.parent() { std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; } - let bytes = serde_json::to_vec_pretty(&app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?; - write_prefs(&p, &bytes).map_err(|e| format!("cannot save {}: {e}", p.display()))?; + let ours = serde_json::to_value(app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?; + let mut base = LOADED_PREFS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + save_merged(&p, &mut base, ours)?; Ok(true) } +/// Writes `ours` to `path`, merged with what other WordCraft processes saved there since this one +/// loaded or saved `base` (`merged_prefs`), and makes `ours` the new `base`: a setting changed here +/// before this save and by another process after it then takes the other's value at the next save. +/// Holds `lock_prefs` from the read to the rename. +fn save_merged(path: &std::path::Path, base: &mut Option, ours: serde_json::Value) -> Result<(), String> { + let _lock = lock_prefs(path); + let merged = merged_prefs(path, base.as_ref(), ours.clone()); + let bytes = serde_json::to_vec_pretty(&merged).map_err(|e| format!("cannot serialize: {e}"))?; + write_prefs(path, &bytes).map_err(|e| format!("cannot save {}: {e}", path.display()))?; + *base = Some(ours); + Ok(()) +} + +/// `ours` with what other WordCraft processes saved to `path` since this one loaded or saved +/// `base`, for the settings this one left alone (#3773, see `prefs_merge`). `ours` as it is when +/// there's no `base`, or the file is missing or isn't preferences now. +fn merged_prefs(path: &std::path::Path, base: Option<&serde_json::Value>, ours: serde_json::Value) -> serde_json::Value { + let Some(base) = base else { return ours }; + let disk = match std::fs::read(path) { + Ok(bytes) => prefs_merge::as_read(&bytes), + Err(e) => { + if e.kind() != std::io::ErrorKind::NotFound { + log::debug!("preferences: cannot read {} to merge, saving this process's: {e}", path.display()); + } + return ours; + } + }; + match disk { + Some(disk) => prefs_merge::merge(base, ours, &disk), + None => { + log::debug!("preferences: {} isn't preferences, saving this process's", path.display()); + ours + } + } +} + +/// How long a save waits for another process's save to finish before going ahead anyway: a save +/// takes milliseconds, and a process stuck holding the lock mustn't stop this one from saving. +const PREFS_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + +/// An advisory lock beside `path` (`.ui.json.lock`), held while it is returned, so that two +/// processes saving at once (logging out closes every window together) take turns at reading, +/// merging and replacing `ui.json` instead of one losing the other's changes. `None` (save +/// unlocked) when the lock file can't be opened or the lock isn't free within [`PREFS_LOCK_WAIT`]. +fn lock_prefs(path: &std::path::Path) -> Option { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into()); + let lock = path.with_file_name(format!(".{name}.lock")); + let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) { + Ok(f) => f, + Err(e) => { + log::debug!("preferences: cannot open {}, saving without it: {e}", lock.display()); + return None; + } + }; + let start = std::time::Instant::now(); + loop { + match file.try_lock() { + Ok(()) => return Some(file), + Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < PREFS_LOCK_WAIT => std::thread::sleep(std::time::Duration::from_millis(10)), + Err(e) => { + log::warn!("preferences: {} is held, saving without it: {e}", lock.display()); + return None; + } + } + } +} + /// Writes `bytes` to a sibling temporary file and renames it over `path`, so a failed or /// interrupted write leaves the previous preferences in place. fn write_prefs(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { @@ -626,7 +710,6 @@ fn main() -> eframe::Result { if updates_unsafe { app.disable_self_update(); } - load_user_dictionary(&mut app); // Language packs from the suite's font store; an Install click is the person's own. wordcraft_engine::packs::use_font_store(true); // A region chosen in File › Options replaces the system's for the first blank @@ -839,7 +922,72 @@ mod launch_arg_tests { #[cfg(test)] mod prefs_tests { - use super::write_prefs; + use serde_json::{Value, json}; + use wordcraft_ui_egui::{UiState, theme::Appearance}; + + use super::{load_prefs_from, lock_prefs, prefs_merge, save_merged, write_prefs}; + + /// The preferences saved with `theme` (every other setting at its default). + fn with_theme(theme: &str) -> Value { + prefs_merge::as_read(&serde_json::to_vec(&json!({"theme": theme})).unwrap()).unwrap() + } + + /// The theme the next process loads from `path`. + fn saved_theme(path: &std::path::Path) -> Appearance { + UiState::from_json(&std::fs::read(path).unwrap()).unwrap().theme + } + + #[test] + fn a_setting_changed_by_another_process_after_a_save_here_keeps_its_value() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ui.json"); + std::fs::write(&path, serde_json::to_vec(&with_theme("light")).unwrap()).unwrap(); + // A loads Light, switches to Dark and saves before exiting (taking a document off the + // recent list does). + let mut a = Some(with_theme("light")); + save_merged(&path, &mut a, with_theme("dark")).unwrap(); + assert_eq!(saved_theme(&path), Appearance::Dark); + // B starts, loads Dark, switches to Light and exits. + save_merged(&path, &mut Some(with_theme("dark")), with_theme("light")).unwrap(); + // A exits without touching the theme since its save: B's choice, made later, stays. + save_merged(&path, &mut a, with_theme("dark")).unwrap(); + assert_eq!(saved_theme(&path), Appearance::Light); + } + + #[test] + fn the_loaded_preferences_include_the_words_of_the_dictionary_file() { + // A word only `custom-dictionary.txt` has is loaded, not added here: if another process + // removes it from `ui.json`, this one mustn't write it back. + let dir = tempfile::tempdir().unwrap(); + let (prefs, dict) = (dir.path().join("ui.json"), dir.path().join("custom-dictionary.txt")); + std::fs::write(&prefs, br#"{"dictionary": ["zqxinjson"]}"#).unwrap(); + std::fs::write(&dict, "zqxinfile\n").unwrap(); + let mut app = wordcraft_ui_egui::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default()); + let loaded = load_prefs_from(&mut app, Some(&prefs), Some(dict)).unwrap(); + let words = loaded["dictionary"].as_array().unwrap(); + for word in ["zqxinjson", "zqxinfile"] { + assert!(words.contains(&json!(word)), "{word}: {words:?}"); + } + wordcraft_engine::proof::remove_word("zqxinjson"); + wordcraft_engine::proof::remove_word("zqxinfile"); + } + + #[test] + fn a_save_waits_for_another_process_saving_at_the_same_moment() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ui.json"); + // Another process is between reading and replacing `ui.json`. + let held = lock_prefs(&path).expect("the lock is free"); + let saver = { + let path = path.clone(); + std::thread::spawn(move || save_merged(&path, &mut None, with_theme("dark"))) + }; + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!path.exists(), "saved while another process held the lock"); + drop(held); + saver.join().unwrap().unwrap(); + assert_eq!(saved_theme(&path), Appearance::Dark); + } #[test] fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() { diff --git a/apps/wordcraft/src/prefs_merge.rs b/apps/wordcraft/src/prefs_merge.rs new file mode 100644 index 0000000000..b052737ccd --- /dev/null +++ b/apps/wordcraft/src/prefs_merge.rs @@ -0,0 +1,550 @@ +//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts +//! another). Each reads it at start-up and writes it at exit (and when a change must survive a +//! crash, like taking a document off the recent list), so without a merge the process that writes +//! last writes back what it loaded and loses the others' changes (#3773). +//! +//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting +//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are +//! left out), and write it with only what this process changed since it last loaded or saved its +//! preferences (`base`). Every other setting keeps what the file holds now, including the absence +//! of one another process removed (a shortcut, a task pane's place). +//! +//! - A setting both changed takes this process's value. +//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon, +//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the +//! window's size and place, or one task pane's place, are never mixed from two processes. +//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed +//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens, +//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process +//! added are kept, entries either process removed stay removed, and an entry both changed takes +//! this process's version. A ribbon or toolbar left as it comes counts as its default entries. +//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used +//! again first, then the file's, without duplicates, without the entries this process removed, +//! and within each list's limit ([`merge_recent`]). +//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting. +//! +//! What this process changed is found by comparing with `base`, not by recording each change: a +//! setting changed and then changed back counts as untouched, so the file's value stays, and a +//! recent entry used again without moving (it was already first) counts as not used. + +use std::collections::{HashMap, HashSet}; + +use serde_json::{Map, Value}; +use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout}; +use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert}; + +/// Whether two entries of a recent list are the same entry. +type Same = fn(&Value, &Value) -> bool; + +/// What tells an entry of a list of user entries from the others. Entries with the same key are +/// told apart by their order ([`ids`]). +type Key = fn(&Value) -> String; + +/// How a setting this process changed merges with the file's. +#[derive(Clone, Copy)] +enum Rule { + /// A group of settings: each entry on its own. + Group, + /// A recent list, most recent first: how many entries it keeps, and when two are the same. + Recent(usize, Same), + /// A list of user entries: each entry on its own. + Entries(Key), + /// One setting: this process's value. + Whole, +} + +/// The rule for the setting at `path` (`ui.json`'s keys from the top). +fn rule(path: &[&str]) -> Rule { + match path { + [] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => { + Rule::Group + } + ["recent"] => Rule::Recent(MAX_RECENT, same_entry), + ["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry), + ["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry), + ["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font), + ["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text), + ["ribbon", "tabs"] => Rule::Entries(tab_name), + ["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"] + | ["keyboard", "removed"] + | ["ribbon", "qat"] + | ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry), + _ => Rule::Whole, + } +} + +/// What a setting saved only when it isn't its default stands for when it is missing: the +/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the +/// default merge entry by entry. +fn when_missing(path: &[&str]) -> Option { + match path { + ["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(), + ["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(), + _ => None, + } +} + +/// Entries saved alike (colours are saved normalised, `colors::push_recent`). +fn same_entry(a: &Value, b: &Value) -> bool { + a == b +} + +/// Font names ignoring case, as `push_recent_font` compares them. +fn same_font(a: &Value, b: &Value) -> bool { + match (a.as_str(), b.as_str()) { + (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), + _ => a == b, + } +} + +/// The entry as saved. +fn whole_entry(v: &Value) -> String { + v.to_string() +} + +/// An AutoCorrect entry `[from, to]` by the text it replaces. +fn replaced_text(v: &Value) -> String { + v.get(0).unwrap_or(v).to_string() +} + +/// A ribbon tab by its name, ignoring case as the ribbon does. +fn tab_name(v: &Value) -> String { + v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase) +} + +/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't +/// preferences at all. +pub fn as_read(bytes: &[u8]) -> Option { + serde_json::to_value(UiState::from_json(bytes)?).ok() +} + +/// The preferences to write: `ours` (this process's, now), with every value it left as it was in +/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]). +pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value { + let fallback = ours.clone(); + merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback) +} + +/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it +/// alone and another process removed it). +fn merge_setting(path: &mut Vec, base: Option<&Value>, ours: Option, disk: Option<&Value>) -> Option { + if base == ours.as_ref() { + // Unchanged here: whatever the file holds now. + return disk.cloned(); + } + let ours = ours?; + let keys: Vec<&str> = path.iter().map(String::as_str).collect(); + Some(match (rule(&keys), ours, base, disk) { + (Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => { + Value::Object(merge_group(path, base, ours, disk)) + } + (Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => { + Value::Array(merge_recent(base, ours, disk, cap, same)) + } + (Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => { + Value::Array(merge_entries(base, &ours, disk, key)) + } + (_, ours, ..) => ours, + }) +} + +/// A group of settings, entry by entry: this process's entries in their order, then those only +/// the file or `base` has. +fn merge_group(path: &mut Vec, base: &Map, mut ours: Map, disk: &Map) -> Map { + let mut names: Vec = ours.keys().cloned().collect(); + let mut seen: HashSet = names.iter().cloned().collect(); + for k in disk.keys().chain(base.keys()) { + if seen.insert(k.clone()) { + names.push(k.clone()); + } + } + let mut merged = Map::new(); + for k in names { + path.push(k.clone()); + let keys: Vec<&str> = path.iter().map(String::as_str).collect(); + let missing = when_missing(&keys); + let base_v = base.get(&k).cloned().or_else(|| missing.clone()); + let disk_v = disk.get(&k).cloned().or_else(|| missing.clone()); + let ours_v = ours.remove(&k).or_else(|| missing.clone()); + let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref()); + path.pop(); + // A setting saved only when it isn't its default is left out when it is. + if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) { + merged.insert(k, v); + } + } + merged +} + +/// A list entry: its key, and how many entries before it have the same key. +type Id = (String, usize); + +/// The entries of `list` told apart by `key`, in order. +fn ids(list: &[Value], key: Key) -> Vec { + let mut seen: HashMap = HashMap::new(); + list.iter() + .map(|v| { + let k = key(v); + let n = seen.entry(k.clone()).or_default(); + *n += 1; + (k, *n - 1) + }) + .collect() +} + +/// A list of user entries, entry by entry. An entry either process added is kept, one either +/// removed stays removed, and one this process changed takes its version (else the file's). The +/// order is this process's if it reordered the entries it loaded, else the file's; an entry only +/// the other list has goes after the entry it follows there. +fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec { + let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key)); + let index = |ids: &[Id], list: &[Value]| -> HashMap { ids.iter().cloned().zip(list.iter().cloned()).collect() }; + let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk)); + let value = |id: &Id| -> Option<&Value> { + match (b.get(id), o.get(id), d.get(id)) { + // Left alone here: the file's, or gone if the other process removed it. + (Some(b), Some(o), d) if b == o => d, + // Added or changed here. + (_, Some(o), _) => Some(o), + // Removed here. + (Some(_), None, _) => None, + // Added there. + (None, None, d) => d, + } + }; + let common = |ids: &[Id], other: &HashMap| -> Vec { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() }; + let reordered = common(&ours_ids, &b) != common(&base_ids, &o); + let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) }; + let in_first: HashSet<&Id> = first.iter().collect(); + let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect(); + // Entries only `second` has, by the kept entry they follow there (`None`: at the start). + let mut after: HashMap, Vec<&Id>> = HashMap::new(); + let mut anchor = None; + for id in second { + if kept.contains(id) { + anchor = Some(id); + } else if !in_first.contains(id) && value(id).is_some() { + after.entry(anchor).or_default().push(id); + } + } + let mut merged = Vec::new(); + let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned())); + emit(after.get(&None).map_or(&[], Vec::as_slice)); + for id in first.iter().filter(|id| kept.contains(id)) { + emit(&[id]); + emit(after.get(&Some(id)).map_or(&[], Vec::as_slice)); + } + merged +} + +/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving +/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at +/// most `cap` entries. Entries are told apart by `same`. +fn merge_recent(base: &[Value], ours: Vec, disk: &[Value], cap: usize, same: Same) -> Vec { + let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v)); + let removed = |v: &Value| has(base, v) && !has(&ours, v); + let touched = &ours[..touched_len(base, &ours, same)]; + let mut merged: Vec = Vec::new(); + for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) { + if merged.len() == cap { + break; + } + if !has(&merged, &v) { + merged.push(v); + } + } + merged +} + +/// How many of `ours`'s first entries this process added or used again. Each use moves an entry +/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the +/// longest such tail is untouched, and everything before it (new entries, and entries that moved +/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded +/// (the first entry used again) can't be told from no use, and merges as none. +fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize { + let mut end = base.len(); + for (i, v) in ours.iter().enumerate().rev() { + match base[..end].iter().rposition(|b| same(b, v)) { + Some(at) => end = at, + None => return i + 1, + } + } + 0 +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use wordcraft_ui_egui::UiState; + + use super::{as_read, merge}; + + /// The preferences a process holds after loading a `ui.json` with `settings` (every other + /// setting at its default), as it saves them. + fn prefs(settings: Value) -> Value { + as_read(&serde_json::to_vec(&settings).unwrap()).unwrap() + } + + /// What the next process loads from the merged preferences. + fn reloaded(merged: &Value) -> UiState { + UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap() + } + + /// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`. + fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value { + let after_b = merge(loaded, b, loaded); + merge(loaded, a, &after_b) + } + + #[test] + fn two_processes_keep_each_others_changes() { + // #3773: A and B both start from the same file. + let loaded = + json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}}); + // B changes the theme and opens c.docx, then exits first. + let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}}); + // A changes the author name and opens d.docx, then exits. + let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}}); + assert_eq!( + b_then_a(&loaded, b, a), + json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}}) + ); + } + + #[test] + fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() { + let loaded = json!({"theme": "light", "recent": ["a.docx"]}); + let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]}); + assert_eq!(merge(&loaded, loaded.clone(), &disk), disk); + } + + #[test] + fn this_process_wins_a_setting_both_changed() { + let loaded = json!({"theme": "light"}); + assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"})); + } + + #[test] + fn a_setting_changed_and_changed_back_counts_as_untouched() { + // Changes are found by comparing with what was loaded: A switched to dark and back. + let loaded = json!({"theme": "light"}); + assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"})); + } + + #[test] + fn a_recent_entry_removed_here_stays_removed() { + let loaded = json!({"recent": ["a.docx", "b.docx"]}); + let ours = json!({"recent": ["b.docx"]}); + let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]})); + // Clear Recent clears what the other process had added too only if it was loaded here. + assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]})); + } + + #[test] + fn a_recent_entry_used_again_here_moves_to_the_front() { + // Applying a font already in Recently Used Fonts moves it to the front without adding one. + let loaded = json!({"recentFonts": ["A", "B"]}); + assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]})); + // Here C was used again, D opened and A removed; the other process used B again and added E. + let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]}); + let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]}); + let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]})); + // Entries this process only kept, in the order it loaded them, don't override the file's order. + let loaded = json!({"recentSymbols": ["x", "y", "z"]}); + let ours = json!({"recentSymbols": ["w", "x", "z"]}); + let disk = json!({"recentSymbols": ["z", "x", "y"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]})); + } + + #[test] + fn recent_fonts_are_one_entry_whatever_their_case() { + // Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and + // there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten. + let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]}); + let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]})); + // Other lists compare their entries as saved. + let loaded = json!({"recent": ["a.docx"]}); + assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]})); + } + + #[test] + fn merged_recent_lists_keep_their_limit() { + // Recently Used Fonts keeps ten. + let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]}); + let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}); + assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]})); + } + + #[test] + fn a_bad_recent_entry_in_the_file_is_not_carried_forward() { + // A non-string entry makes the whole list read as empty (`options::lenient` falls back per + // setting). Merging it in would keep Recent empty in every later session; instead the + // list reads as this version reads it, and the next save heals it. + let loaded = prefs(json!({"recent": []})); + let ours = prefs(json!({"recent": ["x.docx"]})); + let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap(); + let merged = merge(&loaded, ours, &disk); + assert_eq!(merged["recent"], json!(["x.docx"])); + assert_eq!(loaded_recent(&merged), ["x.docx"]); + // Same for recent symbols. + let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]})); + let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap(); + assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1); + } + + /// The recent documents the next process loads. + fn loaded_recent(merged: &Value) -> Vec { + reloaded(merged).recent + } + + #[test] + fn only_keys_this_version_writes_are_kept() { + // A legacy key read once to migrate, and junk, are not written back, even from the file. + let loaded = prefs(json!({"theme": "light"})); + let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap(); + let merged = merge(&loaded, loaded.clone(), &disk); + for gone in ["dark", "interfaceSize", "junk"] { + assert!(merged.get(gone).is_none(), "{gone}"); + } + assert_eq!(merged["theme"], "light"); + } + + #[test] + fn a_file_another_process_damaged_gives_way_to_ours() { + let loaded = json!({"theme": "light", "recent": ["a.docx"]}); + let ours = json!({"theme": "dark", "recent": ["a.docx"]}); + // Not preferences at all: everything comes from this process. + assert_eq!(as_read(b"\"garbage\""), None); + assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours); + // A list replaced by something else keeps ours. + assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]})); + } + + #[test] + fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() { + let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}})); + // B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and + // removes `approx.`. Each added entry follows the entry it was added after. + let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}})); + let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}})); + let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect; + let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect(); + assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]); + assert_eq!(ac.exceptions, ["fig."]); + } + + #[test] + fn keyboard_customisations_merge_key_by_key() { + let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}})); + // B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and + // assigns Mod+Shift+J. + let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}})); + let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}})); + let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard; + assert_eq!(keys.assigned.into_iter().collect::>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]); + assert_eq!(keys.removed.into_iter().collect::>(), ["Mod+B", "Mod+I"]); + } + + #[test] + fn ribbon_changes_from_both_processes_are_kept() { + // Both start from the default ribbon. B hides Draw; A adds a custom tab after Home. + let loaded = prefs(json!({})); + let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}})); + let mut a_tabs = default_tabs(); + a_tabs.insert(1, json!({"name": "Mine", "custom": true})); + let a = prefs(json!({"ribbon": {"tabs": a_tabs}})); + let mut want = hide(default_tabs(), "Draw"); + want.insert(1, json!({"name": "Mine", "custom": true})); + assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want)); + } + + #[test] + fn a_toolbar_reset_by_one_process_stays_reset() { + // B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a + // custom tab. The toolbar stays the default. + let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}})); + let b = prefs(json!({})); + let mut a_tabs = default_tabs(); + a_tabs.push(json!({"name": "Mine", "custom": true})); + let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}})); + let merged = b_then_a(&loaded, b, a); + assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]); + let ribbon = loaded_ribbon(&merged); + assert_eq!(ribbon.qat, None); + assert!(ribbon.tabs.iter().any(|t| t.name == "Mine")); + // Two processes customizing the default toolbar: both commands, Save removed by A gone. + let loaded = prefs(json!({})); + let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}})); + let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}})); + assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]); + } + + /// The default ribbon tabs, as saved once the ribbon is customized. + fn default_tabs() -> Vec { + serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap() + } + + /// `tabs` with the tab `name` hidden. + fn hide(mut tabs: Vec, name: &str) -> Vec { + for t in &mut tabs { + if t["name"] == name { + t["hidden"] = json!(true); + } + } + tabs + } + + /// The ribbon the next process loads. + fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout { + reloaded(merged).ribbon + } + + #[test] + fn a_pane_order_changed_by_the_other_process_is_kept() { + // `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and + // switches to dark. + let loaded = prefs(json!({})); + let order = json!(["styles", "navigation"]); + let b = prefs(json!({"paneOrder": order})); + let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"}))); + assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark"))); + // B goes back to the default order; A, which loaded B's order and left it, doesn't bring + // it back. + let loaded = prefs(json!({"paneOrder": order})); + let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"}))); + assert!(merged.get("paneOrder").is_none(), "{merged}"); + assert_eq!(merged["theme"], "dark"); + } + + #[test] + fn the_window_and_a_pane_place_are_one_setting_each() { + // A moved its window and B resized its own: the window is A's, not A's place with B's size. + let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}}); + let loaded = prefs(window(0.0, 800.0)); + let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0))); + assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]); + } + + #[test] + fn pens_labels_and_dictionary_words_from_both_processes_are_kept() { + let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0}); + let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]})); + // B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a + // label of its own. Identical pens stay apart, by their order. + let b = prefs( + json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}), + ); + let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]})); + let merged = b_then_a(&loaded, b, a); + let ui = reloaded(&merged); + let colors: Vec = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect(); + assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]); + assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]); + assert_eq!(merged["dictionary"], json!(["foo", "baz"])); + } +} From 406befeaa2ef8322ad8580f11a4d88a9296ba8b6 Mon Sep 17 00:00:00 2001 From: socrabs151 Date: Tue, 17 Nov 2026 08:19:32 +0300 Subject: [PATCH 47/99] #3720: budget hostile large parameters, and cap the TOC title (#5824) --- crates/engine/src/cmd/references.rs | 2 +- crates/engine/src/cmd/references/tests.rs | 12 ++++ crates/engine/src/cmd/references/toc.rs | 17 +++++- crates/engine/src/tests.rs | 69 +++++++++++++++++++++++ 4 files changed, 97 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs index 5fb6195e8e..f5a3904973 100644 --- a/crates/engine/src/cmd/references.rs +++ b/crates/engine/src/cmd/references.rs @@ -32,7 +32,7 @@ use toc::{insert_toc, remove_toc, toc_range}; pub fn specs() -> Vec { vec![ CommandSpec::new("references.toc", "Table of Contents", "References › Table of Contents", insert_toc).params( - r#"{"levels"?: 1-9, "title"?: string, "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#, + r#"{"levels"?: 1-9, "title"?: string (at most 1024 characters), "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#, ), CommandSpec::new("references.updateToc", "Update Table", "References › Table of Contents", |s, _| { update_toc(s)?; diff --git a/crates/engine/src/cmd/references/tests.rs b/crates/engine/src/cmd/references/tests.rs index 1462f6600f..5835c4c612 100644 --- a/crates/engine/src/cmd/references/tests.rs +++ b/crates/engine/src/cmd/references/tests.rs @@ -1,6 +1,18 @@ use super::properties::{new_property_value, text_result}; use super::*; +#[test] +fn a_toc_title_is_capped() { + let mut s = Session::new(wordcraft_doc::Document::new()); + let before = s.doc.body.len(); + let long = "x".repeat(super::toc::MAX_TOC_TITLE + 1); + let r = s.run("references.toc", &json!({"title": long})); + assert!(matches!(r, Err(crate::CmdError::Params(_))), "{r:?}"); + assert_eq!(s.doc.body.len(), before, "a rejected title changes nothing"); + let at_cap = "x".repeat(super::toc::MAX_TOC_TITLE); + s.run("references.toc", &json!({"title": at_cap})).unwrap(); +} + fn fields(s: &Session) -> Vec<(String, String)> { let mut out = Vec::new(); for path in s.doc.para_paths(StoryRef::Body) { diff --git a/crates/engine/src/cmd/references/toc.rs b/crates/engine/src/cmd/references/toc.rs index a267f9187f..bd90494846 100644 --- a/crates/engine/src/cmd/references/toc.rs +++ b/crates/engine/src/cmd/references/toc.rs @@ -3,6 +3,18 @@ use super::{ StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, sel_result, }; +/// A table-of-contents title is a heading, not document body: longer titles are rejected +/// instead of laying out megabytes of text (#3720). +pub(super) const MAX_TOC_TITLE: usize = 1024; + +fn checked_title(v: &Value) -> Result, CmdError> { + let Some(title) = p::str(v, "title") else { return Ok(None) }; + if title.chars().count() > MAX_TOC_TITLE { + return Err(CmdError::Params(format!("`title` is longer than {MAX_TOC_TITLE} characters"))); + } + Ok(Some(title)) +} + /// A level range such as `1-3` (or one level, `2`), clamped to 1–9. pub fn level_range(s: &str) -> Option<(u8, u8)> { let mut it = s.split('-').map(|x| x.trim().parse::().ok()); @@ -382,6 +394,7 @@ pub(super) fn cached_toc_tabs(s: &Session) -> Vec<(String, Vec)> { } pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { + let title = checked_title(v)?.unwrap_or("Contents").to_string(); let tabs = cached_toc_tabs(s); range_toc_to_field(s)?; let replace = v.as_object().is_some_and(|m| !m.is_empty()); @@ -410,7 +423,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { } None => delete_selection(s)?, }; - let title = p::str(v, "title").unwrap_or("Contents").to_string(); if at.story != StoryRef::Body || at.path.depth() > 0 { return Err(CmdError::Failed("a table of contents goes in the main text".into())); } @@ -440,6 +452,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { /// (`title_above_break`): the field takes `v`'s settings, the title `v`'s `title` if one is given /// (otherwise it is kept, as Word's Insert Table of Contents keeps it), and the entries are rebuilt. fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(String, Vec)]) -> Result<(), CmdError> { + let new_title = checked_title(v)?; let instr = toc_instr(v); let field = s.doc.para_mut(StoryRef::Body, &Path::top(start))?; for o in &mut field.objects { @@ -453,7 +466,7 @@ fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(St } } field.touch(); - if let (Some(title), Some(i)) = (p::str(v, "title"), start.checked_sub(1)) { + if let (Some(title), Some(i)) = (new_title, start.checked_sub(1)) { let old = s.doc.para_mut(StoryRef::Body, &Path::top(i))?; let mut head = Paragraph::with_text(title, old.props_of_char(0).clone()); head.props = old.props.clone(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c9de4b79a2..6b727d4e7b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5,6 +5,7 @@ mod czech_test_dict; use serde_json::json; use std::sync::Arc; +use std::time::{Duration, Instant}; use wordcraft_doc::props::BorderStyle; use wordcraft_doc::{Pos, StoryRef}; @@ -5184,6 +5185,74 @@ fn hostile_file_params_never_panic() { let _ = std::fs::remove_dir_all(&base); } +/// Large parameters must return and lay out within a generous wall-clock budget, so a regression +/// that loops or allocates without a cap fails here with its command id (#3720). +#[test] +fn hostile_large_params_stay_bounded() { + const BUDGET: Duration = Duration::from_secs(5); + let reg = cmd::registry(); + // 1 MiB makes an uncapped copy or a quadratic scan visible without making the test itself + // expensive; the counts are large enough that an uncapped loop takes seconds. + let big = "x".repeat(1 << 20); + let mut deep = json!([]); + for _ in 0..64 { + deep = json!([deep]); + } + let junk = [ + json!({ + "text": big, "name": big, "label": big, "find": big, "replace": big, + "title": big, "author": big, "path": big, + }), + json!({ + "count": 1_000_000_000u64, "copies": 1_000_000_000u64, "times": 1_000_000_000u64, + "cols": 1_000_000_000u64, "rows": 1_000_000_000u64, "level": 1_000_000_000u64, + "page": 1_000_000_000u64, "from": 1_000_000_000u64, "to": 1_000_000_000u64, + "id": 1_000_000_000u64, + }), + json!({"width": 3e38, "height": 3e38, "top": -3e38, "left": 3e38}), + json!({"path": deep}), + ]; + for spec in reg.all() { + if spec.id.starts_with("file.") || spec.id == "insert.picture" || spec.id == "insert.textFromFile" { + continue; + } + for j in &junk { + let mut s = Session::new(crate::sample::sample_document()); + assert_ne!(s.read_aloud.backend, crate::speech::Backend::System, "tests must never start real speech"); + let start = Instant::now(); + let r = s.run(spec.id, j); + let elapsed = start.elapsed(); + assert!(!caught_panic(®, &r), "{} panicked on large params: {r:?}", spec.id); + assert_within_budget(spec.id, elapsed, BUDGET); + // Laying the result out is not part of the command's budget; the layout tests + // cover long text separately. It still runs so a bad parameter reaches the layout. + s.clamp_selection(); + let _ = s.layout(); + } + } +} + +fn assert_within_budget(id: &str, elapsed: Duration, budget: Duration) { + assert!(elapsed <= budget, "{id} took {elapsed:?} (budget {budget:?})"); +} + +/// The budget above fires: a command that runs past it is named, not ignored (#3720). +#[test] +#[should_panic(expected = "test.slow took")] +fn hostile_large_param_budget_flags_a_slow_command() { + let budget = Duration::from_millis(1); + let mut s = Session::new(crate::sample::sample_document()); + let slow = crate::CommandSpec::new("test.slow", "Slow", "", |_, _| { + std::thread::sleep(Duration::from_millis(20)); + Ok(json!({})) + }) + .pure(); + s.registry = Arc::new(crate::Registry::new(vec![slow])); + let start = Instant::now(); + let _ = s.run("test.slow", &json!({})); + assert_within_budget("test.slow", start.elapsed(), budget); +} + /// A panic that `Session::run`'s guard turned into an error, in a command or one it ran: still a /// crash path (#3718). Only the guard's own `"{id} panicked: "` counts, not an error that echoes /// those words. From 29d862fabca05ba1e273a60041905c5ee8a7fb52 Mon Sep 17 00:00:00 2001 From: reubgr Date: Tue, 17 Nov 2026 00:37:34 -0500 Subject: [PATCH 48/99] Compare: preserve per-segment formatting in word_diff (#3749, stage 0) (#5569) --- crates/engine/src/cmd/tools/compare.rs | 161 ++++++-- crates/engine/src/cmd/tools/tests.rs | 2 + .../src/cmd/tools/tests/compare_stage0.rs | 349 ++++++++++++++++++ 3 files changed, 486 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/cmd/tools/tests/compare_stage0.rs diff --git a/crates/engine/src/cmd/tools/compare.rs b/crates/engine/src/cmd/tools/compare.rs index a62397d830..5f4bd68d2e 100644 --- a/crates/engine/src/cmd/tools/compare.rs +++ b/crates/engine/src/cmd/tools/compare.rs @@ -34,6 +34,7 @@ struct DiffCtx<'a> { opts: &'a CompareOptions, budget: &'a mut u64, char_fallbacks: &'a mut usize, + plain_revised: bool, } /// Changed paragraphs longer than this (in characters) are compared word by word even at @@ -48,10 +49,12 @@ const MAX_CHAR_DIFF: usize = 2000; /// [`MAX_CHAR_DIFF`] characters, it falls back to word-level diff for that paragraph, surfaces the /// fallback count in `"characterFallback"`, and includes `"level"` in `"notHonoured"`. pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult { - let revised = if let Some(t) = p::str(v, "text") { - Document::from_text(t) + // A revised side given as plain text carries no real runs or properties; one opened from a + // path does. The diff takes the revised formatting only in the latter case. + let (revised, plain_revised) = if let Some(t) = p::str(v, "text") { + (Document::from_text(t), true) } else if let Some(path) = p::str(v, "path") { - crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)? + (crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)?, false) } else { return Err(CmdError::Params("`path` or `text` of the revised document is required".into())); }; @@ -97,7 +100,7 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult { let mut budget = MAX_COMPARE_CELLS; let mut char_fallbacks = 0usize; let ops = lcs_ops(&old.iter().map(key).collect::>(), &new.iter().map(key).collect::>(), &mut budget); - let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks }; + let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks, plain_revised }; let mut out: Vec> = Vec::new(); let (mut i, mut j) = (0usize, 0usize); let mut changes = 0usize; @@ -393,9 +396,11 @@ fn flatten_region(out: &mut Vec, region: &[(Op, usize, Kind)]) { /// A token of a changed paragraph: a word (or character), or an inline object without text /// of its own (a text box anchor, a picture, a bookmark…), which is compared and kept whole. +/// Each token also carries the byte range it came from in its source paragraph, so the output +/// segment can take the formatting of the run it came from instead of the paragraph's first run. enum Tok<'a> { - Text(String), - Obj(&'a InlineObject), + Text(String, std::ops::Range), + Obj(&'a InlineObject, std::ops::Range), } /// What a comparison sees of a token: the text as the options say, an object with the text of @@ -421,52 +426,131 @@ fn same_objects(doc: &Document, a: &Paragraph, b: &Paragraph) -> bool { } /// Words with the spaces after them ("The ", "cat "), or single characters, and the objects -/// between them. Objects with text (fields, equations…) count as their text. +/// between them. Objects with text (fields, equations…) count as their text. Each token records +/// the byte range it came from in `p`, so its output segment can take that source run's +/// formatting. An object's flattened text (or a broken marker's placeholder) maps to the marker's +/// own range, which is the nearest formatting the object has. fn tokens(p: &Paragraph, characters: bool) -> Vec> { - fn push(v: &mut Vec>, cur: &mut String, c: char, characters: bool) { + fn push(v: &mut Vec>, cur: &mut String, start: usize, end: usize, c: char, characters: bool) { cur.push(c); if characters || c == ' ' { - v.push(Tok::Text(std::mem::take(cur))); + v.push(Tok::Text(std::mem::take(cur), start..end)); } } let mut v = Vec::new(); let mut cur = String::new(); + let mut cur_start = 0usize; let mut objects = p.objects.iter(); - for c in p.text.chars() { + for (i, c) in p.text.char_indices() { + let marker = i..i + OBJ.len_utf8(); if c != OBJ { - push(&mut v, &mut cur, c, characters); + if cur.is_empty() { + cur_start = i; + } + push(&mut v, &mut cur, cur_start, i + c.len_utf8(), c, characters); continue; } match objects.next() { Some(o) if o.plain_text().is_empty() => { if !cur.is_empty() { - v.push(Tok::Text(std::mem::take(&mut cur))); + v.push(Tok::Text(std::mem::take(&mut cur), cur_start..i)); + } + v.push(Tok::Obj(o, marker)); + } + Some(o) => { + for c in o.plain_text().chars() { + if cur.is_empty() { + cur_start = i; + } + push(&mut v, &mut cur, cur_start, marker.end, c, characters); } - v.push(Tok::Obj(o)); } - Some(o) => o.plain_text().chars().for_each(|c| push(&mut v, &mut cur, c, characters)), None => { // A marker without its object (a broken paragraph): kept as a visible // placeholder, so the loss shows in the result instead of vanishing. log::warn!("compare: an object marker without its object"); - push(&mut v, &mut cur, char::REPLACEMENT_CHARACTER, characters); + if cur.is_empty() { + cur_start = i; + } + push(&mut v, &mut cur, cur_start, marker.end, char::REPLACEMENT_CHARACTER, characters); } } } if !cur.is_empty() { - v.push(Tok::Text(cur)); + v.push(Tok::Text(cur, cur_start..p.text.len())); } v } +/// One side's run formatting for `word_diff`: the paragraph's run ranges (from +/// [`Paragraph::run_ranges`]), walked with a forward cursor. `word_diff` consumes each side's +/// tokens in increasing offset order, so the cursor makes a token's lookup amortised O(1) +/// instead of rescanning the runs from the start for every token; an out-of-order offset falls +/// back to a binary search, so the lookup stays correct for any offset. +struct SideProps<'a> { + ranges: Vec<(std::ops::Range, &'a CharProps)>, + mark: &'a CharProps, + cursor: usize, +} + +impl<'a> SideProps<'a> { + fn new(p: &'a Paragraph) -> Self { + SideProps { ranges: p.run_ranges().collect(), mark: &p.mark, cursor: 0 } + } + + /// The props of the run holding byte `off`: that run's props, or the paragraph mark when + /// `off` is past the last run — the same answer `Paragraph::props_of_char` gives. + fn run_props(&mut self, off: usize) -> &'a CharProps { + while self.cursor < self.ranges.len() && self.ranges[self.cursor].0.end <= off { + self.cursor += 1; + } + if let Some((range, props)) = self.ranges.get(self.cursor) + && range.contains(&off) + { + return props; + } + let idx = self.ranges.partition_point(|(r, _)| r.start <= off); + match idx.checked_sub(1).and_then(|i| self.ranges.get(i)) { + Some((range, props)) if range.contains(&off) => props, + _ => self.mark, + } + } + + /// The formatting of the source run a token came from: the run holding the token's first + /// byte, with the revision metadata stripped. `ins`, `del` and `fmt_change` are indices into + /// the *source* document's own revision table, and the rebuilt paragraph lives in the result + /// document, whose table is a different one, so a source mark can never be carried across; + /// `word_diff` stamps the compare's own `ins`/`del` on the segments it marks. The consequence + /// is plain: a pre-existing pending revision inside a changed paragraph (say another author's + /// deletion) is superseded by the compare result rather than preserved. The hyperlink is + /// kept, because Reject restores it on a deleted run (at token granularity: the link is taken + /// from the token's first byte, so a token that starts unlinked can lose a mid-token link). + fn props_of(&mut self, t: &Tok<'_>) -> CharProps { + let off = match t { + Tok::Text(_, range) | Tok::Obj(_, range) => range.start, + }; + let c = self.run_props(off); + CharProps { ins: None, del: None, fmt_change: None, ..c.clone() } + } +} + +/// The props of an output token: those of the source run it came from, or — never expected, since +/// [`tokens`] and [`lcs_ops`] consume both sides in step — the given fallback. A miss is loud. +fn output_props(side: &mut SideProps<'_>, t: Option<&Tok<'_>>, fallback: &CharProps) -> CharProps { + if t.is_none() { + log::warn!("compare: a token range lookup missed; `tokens` and `lcs_ops` are out of step"); + } + t.map(|t| side.props_of(t)).unwrap_or_else(|| fallback.clone()) +} + /// Add a token at the end of `p` with `props`. fn put(p: &mut Paragraph, t: Option<&Tok<'_>>, props: &CharProps) { let at = p.len(); match t { - Some(Tok::Text(t)) => { + Some(Tok::Text(t, _)) => { let _ = p.insert_text(at, t, props); } - Some(Tok::Obj(o)) => { + Some(Tok::Obj(o, _)) => { let _ = p.insert_object(at, (*o).clone(), props); } None => {} @@ -500,10 +584,12 @@ fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_> } else { false }; + let plain_revised = ctx.plain_revised; let (ta, tb) = (tokens(a, chars), tokens(b, chars)); + let (mut a_props, mut b_props) = (SideProps::new(a), SideProps::new(b)); let key = |t: &Tok<'_>| match t { - Tok::Text(t) => Key::Text(ctx.opts.key(t)), - Tok::Obj(o) => obj_key(doc, o), + Tok::Text(t, _) => Key::Text(ctx.opts.key(t)), + Tok::Obj(o, _) => obj_key(doc, o), }; let ops = lcs_ops(&ta.iter().map(key).collect::>(), &tb.iter().map(key).collect::>(), ctx.budget); // Only at character granularity: a matched whole word almost never happens by coincidence, @@ -511,23 +597,46 @@ fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_> // a short interior match need folding back into its surrounding edit. let ops = if chars { collapse_noise_matches(&ops) } else { ops }; let mut p = Paragraph::new(); - p.props = b.props.clone(); - let base = a.runs.first().map(|r| r.props.clone()).unwrap_or_default(); + // The revised paragraph's properties are used with its revision bookkeeping stripped, like runs + // (`SideProps::props_of`) and the mark, because `fmt_change`/`num_change` are indices into the revised + // document's own revision table and are meaningless in the result document. A plain-text + // revised side, which carries no paragraph properties of its own, falls back to the original's, + // stripped the same way, so pre-existing revision state never leaks into the rebuilt paragraph. + p.props = if plain_revised && b.props.is_empty() { a.props.formatting() } else { b.props.formatting() }; + // The paragraph mark (the formatting typing into the paragraph's end would get) is the revised + // paragraph's when it comes from a document, and the original's when the revised side is plain + // text and has no mark of its own. Its own revision bookkeeping (`ins`, `del`, `fmt_change`) + // is cleared because those indices belong to another document's revision table. + p.mark = if plain_revised { + CharProps { ins: None, del: None, fmt_change: None, ..a.mark.clone() } + } else { + CharProps { ins: None, del: None, fmt_change: None, ..b.mark.clone() } + }; + let fallback = a.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default(); + let fallback_b = b.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default(); let (mut i, mut j) = (0, 0); for op in ops { match op { Op::Same => { - // Equal as compared (perhaps up to case or spacing): the revised text. - put(&mut p, tb.get(j), &base); + // Equal as compared (perhaps up to case or spacing): the revised text, but the + // formatting of the run it stands for. For a document revised side that is the + // revised run, as issue #3749 prescribes ("Copy unchanged tokens from the revised + // paragraph with their own properties"); a plain-text revised side has no runs to + // speak of, so the original run's formatting is kept instead. + let props = + if plain_revised { output_props(&mut a_props, ta.get(i), &fallback) } else { output_props(&mut b_props, tb.get(j), &fallback_b) }; + put(&mut p, tb.get(j), &props); i += 1; j += 1; } Op::Del => { - put(&mut p, ta.get(i), &CharProps { del: Some(ctx.del), ..base.clone() }); + let props = output_props(&mut a_props, ta.get(i), &fallback); + put(&mut p, ta.get(i), &CharProps { del: Some(ctx.del), ..props }); i += 1; } Op::Ins => { - put(&mut p, tb.get(j), &CharProps { ins: Some(ctx.ins), ..base.clone() }); + let props = tb.get(j).map(|t| b_props.props_of(t)).unwrap_or_else(|| fallback.clone()); + put(&mut p, tb.get(j), &CharProps { ins: Some(ctx.ins), ..props }); j += 1; } } diff --git a/crates/engine/src/cmd/tools/tests.rs b/crates/engine/src/cmd/tools/tests.rs index de2777c666..a10fbcc9a1 100644 --- a/crates/engine/src/cmd/tools/tests.rs +++ b/crates/engine/src/cmd/tools/tests.rs @@ -1,5 +1,7 @@ use super::*; +mod compare_stage0; + #[test] fn compare_marks_changes() { let mut s = Session::new(Document::from_text("The cat sat.\nKeep this.\nOld line.")); diff --git a/crates/engine/src/cmd/tools/tests/compare_stage0.rs b/crates/engine/src/cmd/tools/tests/compare_stage0.rs new file mode 100644 index 0000000000..b75a749062 --- /dev/null +++ b/crates/engine/src/cmd/tools/tests/compare_stage0.rs @@ -0,0 +1,349 @@ +//! Regression tests for #3749 Stage 0: formatting-preserving compare. +//! +//! `word_diff` carries source byte ranges through tokenization, so every output segment takes its +//! `CharProps` from the run it came from instead of stamping the original paragraph's first run on +//! everything. The revised side decides which run each segment follows: when the revised side is a +//! real document, Same/Ins take the revised run and Del takes the original run; when it is plain +//! text (with no runs of its own), Same/Del take the original run and Ins takes the (default) +//! revised run. The paragraph mark and `ParaProps` follow the revised side for a document, and fall +//! back to the original's for plain text. +//! +//! The ins/del segmentation for text-only paragraphs is unchanged: the goldens below were captured +//! from the pre-fix binary (`review.compare` over a plain original and a plain revised text, word +//! and character level) and must keep matching. + +use super::*; + +/// A run signature: its text, and whether it is marked inserted / deleted. +fn run_sig(p: &Paragraph) -> Vec<(String, bool, bool)> { + p.run_ranges().map(|(r, c)| (p.text[r].to_string(), c.ins.is_some(), c.del.is_some())).collect() +} + +/// The first run whose text contains `needle`. +fn run_with<'a>(p: &'a Paragraph, needle: &str) -> (&'a str, &'a CharProps) { + p.run_ranges() + .find(|(r, _)| p.text[r.clone()].contains(needle)) + .map(|(r, c)| (&p.text[r], c)) + .unwrap_or_else(|| panic!("no run contains {needle:?} in {:?}", p.text)) +} + +// --- mixed character formatting ----------------------------------------------------------------- + +#[test] +fn mixed_formatting_is_preserved_per_range() { + let mut s = Session::new(Document::from_text("alpha beta gamma")); + s.run("select.text", &json!({"text": "alpha"})).unwrap(); + s.run("format.bold", &json!({})).unwrap(); + s.run("select.text", &json!({"text": "gamma"})).unwrap(); + s.run("format.italic", &json!({})).unwrap(); + s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + // The deleted text stays in the tracked paragraph; the visible result is what Accept shows. + assert_eq!(p.plain_text(), "alpha beta delta gamma"); + assert_eq!(p.final_text(), "alpha delta gamma"); + let (_, alpha) = run_with(p, "alpha"); + assert_eq!(alpha.bold, Some(true), "unchanged `alpha` keeps the original's bold"); + assert_ne!(alpha.italic, Some(true)); + let (_, gamma) = run_with(p, "gamma"); + assert_eq!(gamma.italic, Some(true), "unchanged `gamma` keeps the original's italic"); + assert_ne!(gamma.bold, Some(true)); + let (_, delta) = run_with(p, "delta"); + assert!(delta.ins.is_some(), "inserted `delta` is marked inserted"); + assert_ne!(delta.bold, Some(true), "inserted text does not inherit the original's bold"); + assert_ne!(delta.italic, Some(true), "inserted text does not inherit the original's italic"); + let (_, beta) = run_with(p, "beta"); + assert!(beta.del.is_some(), "removed `beta` is marked deleted"); + assert_ne!(beta.bold, Some(true)); +} + +// --- byte-range props lookup -------------------------------------------------------------------- + +#[test] +fn change_point_on_a_multibyte_char_takes_its_own_run() { + // The change point is the second character, `ä` (2 bytes). The byte-range lookup must land on + // `ä`'s own run; a character count used as a byte offset would land inside the preceding `é` + // and stamp its bold on the deleted `ä`. + let mut s = Session::new(Document::from_text("éä")); + s.run("select.text", &json!({"text": "é"})).unwrap(); + s.run("format.bold", &json!({})).unwrap(); + s.run("select.text", &json!({"text": "ä"})).unwrap(); + s.run("format.italic", &json!({})).unwrap(); + s.run("review.compare", &json!({"text": "éö", "level": "character"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + assert_eq!(p.plain_text(), "éäö", "deleted `ä` and inserted `ö`"); + let (_, ae) = run_with(p, "ä"); + assert!(ae.del.is_some(), "the changed multi-byte char is deleted"); + assert_eq!(ae.italic, Some(true), "it takes its own run"); + assert_ne!(ae.bold, Some(true), "and not the preceding multi-byte run's props"); +} + +#[test] +fn empty_run_at_a_token_start_does_not_shadow_its_props() { + let mut s = Session::new(Document::from_text("alpha beta gamma")); + s.run("select.text", &json!({"text": "beta"})).unwrap(); + s.run("format.italic", &json!({})).unwrap(); + { + let mut p = s.doc.body[0].as_para().unwrap().clone(); + let at = p.text.find("beta").unwrap(); + let mut idx = 0usize; + let mut start = 0usize; + for (i, r) in p.runs.iter().enumerate() { + if start == at { + idx = i; + break; + } + start += r.len; + } + // An empty run with different props exactly at "beta"'s start. + p.runs.insert(idx, wordcraft_doc::para::Run { len: 0, props: CharProps { bold: Some(true), ..CharProps::default() } }); + s.doc.body[0] = std::sync::Arc::new(Block::Para(p)); + } + s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + let (_, beta) = run_with(p, "beta"); + assert!(beta.del.is_some()); + assert_eq!(beta.italic, Some(true), "the token takes the run after the empty one"); + assert_ne!(beta.bold, Some(true), "an empty run at the token's start must not shadow the next run's props"); +} + +// --- hyperlinks --------------------------------------------------------------------------------- + +#[test] +fn middle_run_hyperlink_survives_and_reject_restores_it() { + let mut s = Session::new(Document::from_text("click here now")); + s.run("select.text", &json!({"text": "here"})).unwrap(); + s.run("insert.link", &json!({"url": "https://example.com"})).unwrap(); + s.run("review.compare", &json!({"text": "click there now"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + let (_, here) = run_with(p, "here"); + assert!(here.del.is_some(), "the removed word is deleted"); + assert_eq!(here.link.as_deref(), Some("https://example.com"), "the deleted run keeps its hyperlink"); + let (_, there) = run_with(p, "there"); + assert!(there.ins.is_some()); + assert_eq!(there.link, None, "inserted text takes the revised run's formatting (no link)"); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "click here now"); + let p = s.doc.body[0].as_para().unwrap(); + let (_, here) = run_with(p, "here"); + assert_eq!(here.link.as_deref(), Some("https://example.com"), "Reject restores the hyperlink at token level"); +} + +#[test] +fn first_run_hyperlink_does_not_leak_onto_inserted_text() { + let mut s = Session::new(Document::from_text("here click now")); + s.run("select.text", &json!({"text": "here"})).unwrap(); + s.run("insert.link", &json!({"url": "https://example.com"})).unwrap(); + s.run("review.compare", &json!({"text": "here there click now"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + let (_, here) = run_with(p, "here"); + assert_eq!(here.link.as_deref(), Some("https://example.com"), "the unchanged first run keeps its link"); + let (_, there) = run_with(p, "there"); + assert!(there.ins.is_some()); + assert_eq!(there.link, None, "the first run's link must not leak onto inserted text"); +} + +// --- reject restores formatting ----------------------------------------------------------------- + +#[test] +fn deleted_segment_keeps_formatting_so_reject_restores_it() { + let mut s = Session::new(Document::from_text("alpha beta gamma")); + s.run("select.text", &json!({"text": "alpha"})).unwrap(); + s.run("format.bold", &json!({})).unwrap(); + s.run("select.text", &json!({"text": "beta"})).unwrap(); + s.run("format.italic", &json!({})).unwrap(); + s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap(); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "alpha beta gamma"); + let p = s.doc.body[0].as_para().unwrap(); + let (_, alpha) = run_with(p, "alpha"); + assert_eq!(alpha.bold, Some(true)); + let (_, beta) = run_with(p, "beta"); + assert_eq!(beta.italic, Some(true), "the deleted token kept its italic, so Reject restores it at token level"); +} + +// --- text-only segmentation identity (goldens from the pre-fix binary) -------------------------- + +#[test] +fn text_only_segmentation_matches_pre_fix_golden() { + // (original, revised, level, expected (text, ins, del) runs) + let cases: &[(&str, &str, &str, &[(&str, bool, bool)])] = &[ + ("The dog sat.", "The cat sat.", "word", &[("The ", false, false), ("dog ", false, true), ("cat ", true, false), ("sat.", false, false)]), + ("a cat ran", "a dog ran", "word", &[("a ", false, false), ("cat ", false, true), ("dog ", true, false), ("ran", false, false)]), + ("colour", "color", "word", &[("colour", false, true), ("color", true, false)]), + ( + "zawarta w dniu 01.09.2026 pomiędzy:", + "zawarta w dniu 19.10.2026 pomiędzy:", + "word", + &[("zawarta w dniu ", false, false), ("01.09.2026 ", false, true), ("19.10.2026 ", true, false), ("pomiędzy:", false, false)], + ), + ("The dog sat.", "The cat sat.", "character", &[("The ", false, false), ("dog", false, true), ("cat", true, false), (" sat.", false, false)]), + ("a cat ran", "a dog ran", "character", &[("a ", false, false), ("cat", false, true), ("dog", true, false), (" ran", false, false)]), + ("colour", "color", "character", &[("colo", false, false), ("u", false, true), ("r", false, false)]), + ( + "zawarta w dniu 01.09.2026 pomiędzy:", + "zawarta w dniu 19.10.2026 pomiędzy:", + "character", + &[("zawarta w dniu ", false, false), ("01.09", false, true), ("19.10", true, false), (".2026 pomiędzy:", false, false)], + ), + ]; + for (orig, rev, level, want) in cases { + let mut s = Session::new(Document::from_text(orig)); + s.run("review.compare", &json!({"text": rev, "level": level})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + let want: Vec<(String, bool, bool)> = want.iter().map(|(t, i, d)| ((*t).to_string(), *i, *d)).collect(); + assert_eq!(run_sig(p), want, "{orig:?} -> {rev:?} [{level}]"); + } +} + +// --- paragraph mark and paragraph properties ---------------------------------------------------- + +#[test] +fn paragraph_mark_is_preserved() { + let mut s = Session::new(Document::from_text("alpha beta gamma")); + { + let mut p = s.doc.body[0].as_para().unwrap().clone(); + p.mark.bold = Some(true); + s.doc.body[0] = std::sync::Arc::new(Block::Para(p)); + } + s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + assert_eq!(p.mark.bold, Some(true), "the rebuilt paragraph keeps the original paragraph mark"); +} + +#[test] +fn paragraph_props_kept_when_revised_is_plain() { + let mut s = Session::new(Document::from_text("alpha beta gamma")); + s.run("para.style", &json!({"style": "Heading1"})).unwrap(); + s.run("para.alignCenter", &json!({})).unwrap(); + s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + assert_eq!(p.props.style.as_deref(), Some("Heading1"), "the original style survives a plain revised side"); + assert!(p.props.align.is_some(), "the original alignment survives a plain revised side"); +} + +// --- object pass-through (not flattened away by the rebuild) ------------------------------------- + +/// A session whose single paragraph is `alpha beta gamma` with a picture after "beta ", already +/// compared against `alpha delta gamma`: the picture's anchor sits in a deleted run. +fn compared_with_picture() -> Session { + let mut s = Session::new(Document::from_text("alpha beta gamma")); + s.run("caret.set", &json!({"pos": Pos::body(0, "alpha beta ".len())})).unwrap(); + let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; + s.run("insert.picture", &json!({"data": png})).unwrap(); + assert_eq!(s.doc.body[0].as_para().unwrap().objects.len(), 1, "the picture was inserted"); + s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap(); + s +} + +#[test] +fn picture_anchor_survives_a_changed_paragraph() { + let s = compared_with_picture(); + let p = s.doc.body[0].as_para().unwrap(); + assert_eq!(p.objects.len(), 1, "the changed paragraph's picture anchor survives the rebuild"); + let off = p.object_offsets().first().copied().expect("the picture anchor is in the text"); + assert!(p.props_of_char(off).del.is_some(), "the picture anchor sits in a deleted run"); +} + +#[test] +fn accepting_removes_the_deleted_picture_and_rejecting_restores_it() { + let mut accepted = compared_with_picture(); + accepted.run("review.acceptAll", &json!({})).unwrap(); + assert_eq!(accepted.doc.body[0].as_para().unwrap().objects.len(), 0, "accepting the deletion removes the picture"); + + let mut rejected = compared_with_picture(); + rejected.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(rejected.doc.body[0].as_para().unwrap().objects.len(), 1, "rejecting the deletion restores the picture"); +} + +// --- document revised side: unchanged tokens follow the revised formatting (#3749) -------------- + +#[test] +fn unchanged_word_takes_the_revised_formatting_document_path() { + let rev = Session::new(Document::from_text("Read the manual now.")); + let path = std::env::temp_dir().join(format!("wc-compare-s0-rev-bold-{}.docx", std::process::id())); + crate::io::save_path(&path, &rev.doc).unwrap(); + + let mut s = Session::new(Document::from_text("Read the manual today.")); + s.run("select.text", &json!({"text": "manual"})).unwrap(); + s.run("format.bold", &json!({})).unwrap(); + s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_file(&path); + + let p = s.doc.body[0].as_para().unwrap(); + let (_, manual) = run_with(p, "manual"); + assert_ne!(manual.bold, Some(true), "the unchanged word takes the revised side's formatting, not the original's bold"); + let (_, today) = run_with(p, "today."); + assert!(today.del.is_some(), "the removed word is deleted"); + let (_, now) = run_with(p, "now."); + assert!(now.ins.is_some(), "the added word is inserted"); + + s.run("review.acceptAll", &json!({})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + assert_eq!(p.plain_text(), "Read the manual now."); + let (_, manual) = run_with(p, "manual"); + assert_ne!(manual.bold, Some(true), "accepting leaves the revised (unbolded) formatting"); +} + +#[test] +fn paragraph_style_change_is_not_masked_document_path() { + let rev = Session::new(Document::from_text("Introduction to X")); + let path = std::env::temp_dir().join(format!("wc-compare-s0-style-{}.docx", std::process::id())); + crate::io::save_path(&path, &rev.doc).unwrap(); + + let mut s = Session::new(Document::from_text("Introduction")); + s.run("para.style", &json!({"style": "Heading1"})).unwrap(); + s.run("review.compare", &json!({"path": path.to_string_lossy(), "level": "character"})).unwrap(); + let _ = std::fs::remove_file(&path); + + let p = s.doc.body[0].as_para().unwrap(); + assert_ne!(p.props.style.as_deref(), Some("Heading1"), "the revised paragraph's empty properties win, so the style change isn't masked"); + assert!(p.run_ranges().any(|(_, c)| c.ins.is_some()), "the text was diffed, not wholesale replaced"); + let (_, intro) = run_with(p, "Introduction"); + assert!(intro.ins.is_none() && intro.del.is_none(), "the unchanged text survives unmarked"); + let (_, added) = run_with(p, " to X"); + assert!(added.ins.is_some(), "only the added text is insertion-marked"); +} + +#[test] +fn unchanged_word_gains_the_revised_formatting_document_path() { + let mut rev = Session::new(Document::from_text("Read the manual now.")); + rev.run("select.text", &json!({"text": "manual"})).unwrap(); + rev.run("format.bold", &json!({})).unwrap(); + let path = std::env::temp_dir().join(format!("wc-compare-s0-rev-gains-bold-{}.docx", std::process::id())); + crate::io::save_path(&path, &rev.doc).unwrap(); + + let mut s = Session::new(Document::from_text("Read the manual today.")); + s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_file(&path); + + let p = s.doc.body[0].as_para().unwrap(); + let (_, manual) = run_with(p, "manual"); + assert_eq!(manual.bold, Some(true), "the unchanged word takes the revised side's bold"); + let (_, today) = run_with(p, "today."); + assert!(today.del.is_some(), "the removed word is deleted"); + let (_, now) = run_with(p, "now."); + assert!(now.ins.is_some(), "the added word is inserted"); + + s.run("review.acceptAll", &json!({})).unwrap(); + let p = s.doc.body[0].as_para().unwrap(); + assert_eq!(p.plain_text(), "Read the manual now."); + let (_, manual) = run_with(p, "manual"); + assert_eq!(manual.bold, Some(true), "accepting leaves the revised (bolded) formatting"); +} + +#[test] +fn removed_hyperlink_on_an_unchanged_word_follows_the_revised_side_document_path() { + let rev = Session::new(Document::from_text("Read the manual now.")); + let path = std::env::temp_dir().join(format!("wc-compare-s0-link-{}.docx", std::process::id())); + crate::io::save_path(&path, &rev.doc).unwrap(); + + let mut s = Session::new(Document::from_text("Read the manual today.")); + s.run("select.text", &json!({"text": "manual"})).unwrap(); + s.run("insert.link", &json!({"url": "https://example.com"})).unwrap(); + s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_file(&path); + + let p = s.doc.body[0].as_para().unwrap(); + let (_, manual) = run_with(p, "manual"); + assert_eq!(manual.link, None, "the unchanged word takes the revised side's run, which dropped the link"); +} From abc04c1b418d8a58d900fecc5183580c38a62e66 Mon Sep 17 00:00:00 2001 From: Bardan Ghimire Date: Tue, 17 Nov 2026 11:35:55 +0545 Subject: [PATCH 49/99] =?UTF-8?q?geom:=20fix=20Rect=20collapse,=20sanitize?= =?UTF-8?q?=20deserialized=20Rect,=20accept=20non-ASCII=E2=80=A6=20(#5880)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/geom/src/lib.rs | 229 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 212 insertions(+), 17 deletions(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index eea58972dc..8912cd19a2 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -63,15 +63,21 @@ pub fn finite(v: f32) -> f32 { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Unit { + /// Inches (the default). #[default] Inches, + /// Centimetres. Centimeters, + /// Millimetres. Millimeters, + /// Points (1/72 inch). Points, + /// Picas (12 points). Picas, } impl Unit { + /// The suffix shown after a number in this unit (`"` for inches, ` cm`, ` pt`, …). pub fn suffix(self) -> &'static str { match self { Unit::Inches => "\"", @@ -81,6 +87,7 @@ impl Unit { Unit::Picas => " pi", } } + /// How many points one of this unit is. pub fn pt_per_unit(self) -> f32 { match self { Unit::Inches => PT_PER_IN, @@ -104,15 +111,34 @@ impl Unit { let s = format!("{v:.2}"); let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s }; let s = if s == "-0" { "0" } else { s }; - s.replace('.', &decimal.to_string()) + let mut buf = [0u8; 4]; + let sep: &str = decimal.encode_utf8(&mut buf); + s.replace('.', sep) + } +} + +/// Maps the digits and decimal separators of other scripts to their ASCII forms: Arabic-Indic +/// (`٠`–`٩`, `٫`), Extended Arabic-Indic (`۰`–`۹`) and full-width (`0`–`9`, `.`, `,`). +fn fold_digit(c: char) -> char { + match c { + '\u{0660}'..='\u{0669}' => char::from(b'0' + (c as u32 - 0x0660) as u8), + '\u{06F0}'..='\u{06F9}' => char::from(b'0' + (c as u32 - 0x06F0) as u8), + '\u{FF10}'..='\u{FF19}' => char::from(b'0' + (c as u32 - 0xFF10) as u8), + '\u{066B}' | '\u{FF0E}' => '.', + '\u{FF0C}' => ',', + other => other, } } /// Parse a measurement typed by a user: `1"`, `1 in`, `2.5cm`, `12pt`, `3 pi`, `10 mm`, `1.5 li` -/// (lines are 12 pt). A bare number is in `default`. Returns points. Either decimal separator -/// works (`2,5 cm` and `2.5 cm`), whatever the region. +/// (lines are 12 pt), `8 px` (pixels are 0.75 pt). A bare number is in `default`. Returns points, +/// or `None` for anything unreadable or whose result does not fit in an `f32`. +/// +/// Either decimal separator works (`2,5 cm` and `2.5 cm`), whatever the region, so a thousands +/// separator is *not* understood: `1,000 pt` is 1 pt, not 1000. Arabic-Indic and full-width digits +/// are accepted like ASCII ones. Scientific notation is not: the number ends at the `e`. pub fn parse_measure(s: &str, default: Unit) -> Option { - let t = s.trim().to_ascii_lowercase().replace('\u{2212}', "-"); + let t = s.trim().chars().map(fold_digit).collect::().to_ascii_lowercase().replace('\u{2212}', "-"); if t.is_empty() { return None; } @@ -142,50 +168,98 @@ pub fn parse_measure(s: &str, default: Unit) -> Option { /// A point in page space (points, y down). #[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct Point { + /// Distance from the left edge. pub x: f32, + /// Distance from the top edge. pub y: f32, } impl Point { + /// A point at (`x`, `y`). pub const fn new(x: f32, y: f32) -> Self { Point { x, y } } } -/// An axis-aligned rectangle (points, y down). `w`/`h` are never negative when built with [`Rect::new`]. +/// An axis-aligned rectangle (points, y down). `w`/`h` are finite and never negative, whether the +/// rectangle was built with [`Rect::new`] or deserialized (both go through the same checks). #[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(from = "RectRaw")] pub struct Rect { + /// Left edge. pub x: f32, + /// Top edge. pub y: f32, + /// Width. pub w: f32, + /// Height. pub h: f32, } +/// The unchecked shape of a [`Rect`] on the wire; converting it applies [`Rect::new`]'s rules. +#[derive(Deserialize)] +struct RectRaw { + x: f32, + y: f32, + w: f32, + h: f32, +} + +impl From for Rect { + fn from(r: RectRaw) -> Self { + Rect::new(r.x, r.y, r.w, r.h) + } +} + +/// Where two crossed edges meet: both land on their midpoint. +fn collapse(lo: f32, hi: f32) -> (f32, f32) { + if hi < lo { + let m = lo * 0.5 + hi * 0.5; + (m, m) + } else { + (lo, hi) + } +} + impl Rect { + /// A rectangle with NaN and infinities replaced by 0 and a negative size clamped to 0. pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self { Rect { x: finite(x), y: finite(y), w: finite(w).max(0.0), h: finite(h).max(0.0) } } + /// The right edge. pub fn right(&self) -> f32 { self.x + self.w } + /// The bottom edge. pub fn bottom(&self) -> f32 { self.y + self.h } + /// Whether `p` is inside or on the edge. Edges are *included*, unlike [`Rect::intersects`], + /// so a point on an edge shared by two rectangles is in both. pub fn contains(&self, p: Point) -> bool { p.x >= self.x && p.x <= self.right() && p.y >= self.y && p.y <= self.bottom() } + /// Whether the interiors overlap. Rectangles that only touch along an edge do *not* intersect. pub fn intersects(&self, o: &Rect) -> bool { self.x < o.right() && o.x < self.right() && self.y < o.bottom() && o.y < self.bottom() } + /// The smallest rectangle covering both. An empty rectangle still counts: `Rect::default()` + /// sits at the origin, so accumulating bounds from it always stretches to (0, 0). Start from + /// the first real rectangle instead. pub fn union(&self, o: &Rect) -> Rect { let x = self.x.min(o.x); let y = self.y.min(o.y); Rect::new(x, y, self.right().max(o.right()) - x, self.bottom().max(o.bottom()) - y) } + /// Shrunk by `l`, `t`, `r`, `b` on the left, top, right and bottom (grown for negative values). + /// If the edges cross, the result has zero size at the middle of where they crossed. pub fn inset(&self, l: f32, t: f32, r: f32, b: f32) -> Rect { - Rect::new(self.x + l, self.y + t, self.w - l - r, self.h - t - b) + let (l, t, r, b) = (finite(l), finite(t), finite(r), finite(b)); + let (x0, x1) = collapse(self.x + l, self.right() - r); + let (y0, y1) = collapse(self.y + t, self.bottom() - b); + Rect::new(x0, y0, x1 - x0, y1 - y0) } - /// Grown by `d` on every side (shrunk for negative `d`, down to zero size). + /// Grown by `d` on every side (shrunk for negative `d`, down to zero size at the centre). pub fn expand(&self, d: f32) -> Rect { self.inset(-d, -d, -d, -d) } @@ -206,8 +280,11 @@ pub fn normalize_degrees(deg: f32) -> f32 { /// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6). #[derive(Clone, Copy, Debug, PartialEq, Default)] pub struct Spin { + /// Clockwise rotation in degrees. pub deg: f32, + /// Mirrored left to right. pub flip_h: bool, + /// Mirrored top to bottom. pub flip_v: bool, } @@ -311,13 +388,15 @@ pub fn paper_by_name(name: &str) -> Option<(&'static str, f32, f32)> { /// How a page is placed on other paper when printing with "Scale to paper size" (#2108). #[derive(Clone, Copy, Debug, PartialEq)] pub struct PaperFit { - /// The sheet, turned to the page's orientation (points). + /// The sheet's width, turned to the page's orientation (points). pub paper_w: f32, + /// The sheet's height, turned to the page's orientation (points). pub paper_h: f32, /// Page points to sheet points. pub k: f32, - /// Where the page's top-left corner lands on the sheet (the page is centred). + /// Where the page's left edge lands on the sheet (the page is centred). pub dx: f32, + /// Where the page's top edge lands on the sheet (the page is centred). pub dy: f32, } @@ -327,7 +406,7 @@ pub struct PaperFit { /// page as it is (scale 1 on paper of its own size). pub fn fit_to_paper(page_w: f32, page_h: f32, paper_w: f32, paper_h: f32) -> PaperFit { let ok = |v: f32| v.is_finite() && v >= 1.0; - let as_is = PaperFit { paper_w: page_w, paper_h: page_h, k: 1.0, dx: 0.0, dy: 0.0 }; + let as_is = PaperFit { paper_w: finite(page_w), paper_h: finite(page_h), k: 1.0, dx: 0.0, dy: 0.0 }; if !(ok(page_w) && ok(page_h) && ok(paper_w) && ok(paper_h)) { return as_is; } @@ -345,6 +424,10 @@ pub fn fit_to_paper(page_w: f32, page_h: f32, paper_w: f32, paper_h: f32) -> Pap mod tests { use super::*; + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-3 + } + #[test] fn unit_round_trips() { assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits()); @@ -363,6 +446,7 @@ mod tests { assert_eq!(parse_measure("12pt", Unit::Inches), Some(12.0)); assert_eq!(parse_measure("2", Unit::Inches), Some(144.0)); assert_eq!(parse_measure("1,5 li", Unit::Inches), Some(18.0)); + assert_eq!(parse_measure("8 px", Unit::Inches), Some(6.0)); let cm = parse_measure("2.54 cm", Unit::Inches).unwrap(); assert!((cm - 72.0).abs() < 0.01); assert_eq!(parse_measure("abc", Unit::Inches), None); @@ -375,19 +459,29 @@ mod tests { assert_eq!(parse_measure("1.5\"", Unit::Centimeters), Some(108.0)); assert_eq!(parse_measure("\u{2212}1 in", Unit::Points), Some(-72.0)); assert_eq!(parse_measure("1,2,3", Unit::Inches), None); - // Overflowing values during unit conversion return None (#1359). + // A comma is a decimal separator, never a thousands separator. + assert_eq!(parse_measure("1,000 pt", Unit::Inches), Some(1.0)); + // Scientific notation is not accepted: the number stops at the `e`, leaving an unknown + // unit. (Overflow itself is covered by `parse_measure_rejects_overflow_to_infinity`.) + assert_eq!(parse_measure("1e3 pt", Unit::Points), None); assert_eq!(parse_measure("3.4e38 in", Unit::Points), None); - assert_eq!(parse_measure("-3.4e38 in", Unit::Points), None); - assert_eq!(parse_measure("3.4e38 cm", Unit::Points), None); - assert_eq!(parse_measure("3.4e38 mm", Unit::Points), None); - assert_eq!(parse_measure("3.4e38 pi", Unit::Points), None); - assert_eq!(parse_measure("3.4e38 li", Unit::Points), None); assert_eq!(parse_measure("3.4e38", Unit::Inches), None); - assert_eq!(parse_measure("1e39 pt", Unit::Points), None); assert_eq!(parse_measure("inf", Unit::Points), None); assert_eq!(parse_measure("nan", Unit::Points), None); } + #[test] + fn parses_digits_of_other_scripts() { + let two_cm = parse_measure("2 cm", Unit::Inches).unwrap(); + assert_eq!(parse_measure("\u{0662} cm", Unit::Inches), Some(two_cm)); // Arabic-Indic ٢ + assert_eq!(parse_measure("\u{06F2} cm", Unit::Inches), Some(two_cm)); // Extended ۲ + assert_eq!(parse_measure("\u{FF12} cm", Unit::Inches), Some(two_cm)); // Full-width 2 + let two_and_half = parse_measure("2.5 cm", Unit::Inches).unwrap(); + assert_eq!(parse_measure("\u{0662}\u{066B}\u{0665} cm", Unit::Inches), Some(two_and_half)); // ٢٫٥ + assert_eq!(parse_measure("\u{FF12}\u{FF0E}\u{FF15}cm", Unit::Inches), Some(two_and_half)); // 2.5 + assert_eq!(parse_measure("\u{0663}", Unit::Points), Some(3.0)); + } + #[test] fn parse_measure_rejects_overflow_to_infinity() { // Finite inputs whose scaled result overflows `f32` must be rejected, @@ -424,6 +518,10 @@ mod tests { assert_eq!(Unit::Inches.format_with(108.0, ','), "1,5\""); assert_eq!(Unit::Points.format_with(720.0, ','), "720 pt"); assert_eq!(Unit::Inches.format_with(f32::NAN, ','), "0\""); + // A tiny negative value must not print as "-0". + assert_eq!(Unit::Points.format(-0.001), "0 pt"); + // Any character can be the separator. + assert_eq!(Unit::Inches.number(108.0, '\u{066B}'), "1\u{066B}5"); } #[test] @@ -437,6 +535,102 @@ mod tests { assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0)); } + #[test] + fn rect_edges_are_in_contains_but_not_intersects() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(10.0, 0.0, 10.0, 10.0); // shares the edge x = 10 + assert!(!a.intersects(&b)); + assert!(a.contains(Point::new(10.0, 5.0)) && b.contains(Point::new(10.0, 5.0))); + } + + #[test] + fn inset_past_zero_collapses_to_center() { + let r = Rect::new(0.0, 0.0, 10.0, 10.0); + assert_eq!(r.inset(8.0, 8.0, 8.0, 8.0), Rect::new(5.0, 5.0, 0.0, 0.0)); + assert_eq!(r.expand(-8.0), Rect::new(5.0, 5.0, 0.0, 0.0)); + assert_eq!(r.expand(-20.0), Rect::new(5.0, 5.0, 0.0, 0.0)); + // Only one axis crosses: the other keeps its size. + assert_eq!(r.inset(0.0, 8.0, 0.0, 8.0), Rect::new(0.0, 5.0, 10.0, 0.0)); + // Growing still works, and hostile insets are ignored rather than poisoning the result. + assert_eq!(r.expand(1.0), Rect::new(-1.0, -1.0, 12.0, 12.0)); + assert_eq!(r.inset(f32::NAN, 0.0, 0.0, 0.0), r); + } + + #[test] + fn rect_from_raw_is_sanitised() { + // Deserialization goes through this conversion (`#[serde(from = "RectRaw")]`). + let r = Rect::from(RectRaw { x: f32::NAN, y: 1.0, w: -4.0, h: f32::INFINITY }); + assert_eq!(r, Rect::new(0.0, 1.0, 0.0, 0.0)); + let ok = Rect::from(RectRaw { x: 1.0, y: 2.0, w: 3.0, h: 4.0 }); + assert_eq!(ok, Rect::new(1.0, 2.0, 3.0, 4.0)); + } + #[test] + fn rects_are_cleaned_when_deserialized() { + use serde::de::value::{Error, MapDeserializer}; + let fields = [("x", f32::NAN), ("y", 1.0), ("w", -5.0), ("h", 2.0)]; + let parsed: Result = Rect::deserialize(MapDeserializer::new(fields.into_iter())); + assert!(parsed.is_ok()); + assert_eq!(parsed.unwrap_or_default(), Rect::new(0.0, 1.0, 0.0, 2.0)); + } + #[test] + fn spin_apply_and_unapply_are_inverse() { + for spin in [ + Spin::new(0.0, false, false), + Spin::new(37.0, false, false), + Spin::new(90.0, true, false), + Spin::new(215.0, false, true), + Spin::new(300.0, true, true), + ] { + let (x, y) = spin.apply(50.0, 40.0, 70.0, 10.0); + let (bx, by) = spin.unapply(50.0, 40.0, x, y); + assert!(close(bx, 70.0) && close(by, 10.0), "{spin:?}"); + } + } + + #[test] + fn a_quarter_turn_is_clockwise_in_page_space() { + // y points down, so the point to the right of the centre goes below it. + let (x, y) = Spin::new(90.0, false, false).apply(0.0, 0.0, 10.0, 0.0); + assert!(x.abs() < 1e-4 && (y - 10.0).abs() < 1e-4); + } + + #[test] + fn within_equals_applying_both_spins() { + let (outer, inner) = (Spin::new(30.0, true, false), Spin::new(75.0, false, true)); + let (ix, iy) = inner.apply(0.0, 0.0, 12.0, -7.0); + let (ex, ey) = outer.apply(0.0, 0.0, ix, iy); + let (bx, by) = inner.within(outer).apply(0.0, 0.0, 12.0, -7.0); + assert!(close(ex, bx) && close(ey, by)); + } + + #[test] + fn spin_matrix_agrees_with_apply() { + let spin = Spin::new(37.0, true, false); + let [a, b, c, d, e, f] = spin.matrix(50.0, 40.0); + let (x, y) = spin.apply(50.0, 40.0, 70.0, 10.0); + assert!(close(a * 70.0 + c * 10.0 + e, x) && close(b * 70.0 + d * 10.0 + f, y)); + // The centre stays where it is. + let (cx, cy) = spin.apply(50.0, 40.0, 50.0, 40.0); + assert!(close(cx, 50.0) && close(cy, 40.0)); + } + + #[test] + fn spin_bounds_and_identity() { + assert!(Spin::default().is_identity()); + assert!(Spin::new(360.0, false, false).is_identity()); + assert!(!Spin::new(0.0, true, false).is_identity()); + let b = Spin::new(90.0, false, false).bounds(Rect::new(0.0, 0.0, 10.0, 20.0)); + assert!(close(b.x, -5.0) && close(b.y, 5.0) && close(b.w, 20.0) && close(b.h, 10.0)); + } + + #[test] + fn normalises_degrees() { + assert_eq!(normalize_degrees(370.0), 10.0); + assert_eq!(normalize_degrees(-90.0), 270.0); + assert_eq!(normalize_degrees(f32::NAN), 0.0); + assert!((0.0..360.0).contains(&normalize_degrees(-1e-9))); + } + #[test] fn paper_names() { assert_eq!(paper_name(612.0, 792.0), Some("Letter")); @@ -472,6 +666,7 @@ mod tests { { let f = fit_to_paper(a, b, c, d); assert_eq!((f.k, f.dx, f.dy), (1.0, 0.0, 0.0)); + assert!(f.paper_w.is_finite() && f.paper_h.is_finite()); } assert!(fit_to_paper(1.0, 1.0, f32::MAX, f32::MAX).k.is_finite()); } From 224bfdb2a0bd7a153216373a52ef6bc2af64672a Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:04:39 +0100 Subject: [PATCH 50/99] Layout: Word 2003's indent rules start a line right after a float before the indent (#5939) (#5940) (#6905) Co-Authored-By: Claude Opus 5.5 Co-Authored-By: SenuraMalaka <19330762+SenuraMalaka@users.noreply.github.com> --- crates/doc/src/settings.rs | 7 +++ crates/layout/src/para/lines.rs | 47 ++++++++++++-- crates/layout/src/tests.rs | 107 ++++++++++++++++++++++++++++++++ docs/gaps.md | 5 +- docs/layout-parity.md | 5 +- 5 files changed, 163 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/settings.rs b/crates/doc/src/settings.rs index 3dd38116c7..3d18185921 100644 --- a/crates/doc/src/settings.rs +++ b/crates/doc/src/settings.rs @@ -137,6 +137,12 @@ pub struct Settings { /// Keep contextual paragraph spacing inside legacy table cells (`allowSpaceOfSameStyleInTable`). /// Word ignores the layout override in compatibility mode 15, but the flag still round-trips. pub allow_space_of_same_style_in_table: bool, + /// `w:doNotSuppressIndentation` (a `.doc`'s `Copts.fWW11IndentRules`): Word 2003's indent + /// rules beside floating objects. An unnumbered paragraph's line starts right after a floating + /// object before it on the line, its own indent ignored (ECMA-376 Part 4 §14.8.3.12). Word 2013's + /// layout (compatibility mode 15) does not use it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub do_not_suppress_indentation: bool, /// Drawing grid spacing in points, across and down (View › Gridlines); ECMA-376's default is 1/8 inch. pub grid_h: f32, pub grid_v: f32, @@ -319,6 +325,7 @@ impl Default for Settings { sum_paragraph_spacing: false, do_not_expand_shift_return: false, allow_space_of_same_style_in_table: false, + do_not_suppress_indentation: false, grid_h: DEFAULT_GRID, grid_v: DEFAULT_GRID, math: None, diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index 821132f6aa..f3f08f2328 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -27,6 +27,9 @@ struct Breaker<'e> { /// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its /// spaces (`space_room`); never on lines with tabs. shrink_spaces: bool, + /// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an + /// unnumbered paragraph: a row starts right after a floating object before the indent. + tight_indent: bool, /// Word stretches a justified line ending in a manual line break unless the document says not to. expand_break: bool, /// Hyphenation Options: the zone, and how many lines in a row may end with a hyphen. @@ -190,6 +193,13 @@ impl<'e> Breaker<'e> { hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None }, tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 }, shrink_spaces: rp.align == Align::Justify && settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT, + tight_indent: settings.do_not_suppress_indentation + && settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT + && level.is_none() + && pl.label.is_none() + // A drop cap sits at the indent: starting its lines at a float's edge would put + // them over the letter. + && pl.drop_cap.is_none(), expand_break: !settings.do_not_expand_shift_return, zone: Some(settings.hyphenation_zone).filter(|z| z.is_finite() && *z >= 0.0).unwrap_or(HYPHENATION_ZONE).min(1584.0), hyph_limit: settings.consecutive_hyphen_limit as usize, @@ -236,9 +246,12 @@ impl<'e> Breaker<'e> { let mut guard = 0; loop { let lo = self.row_left(pl); - match row_spans(self.exclusions, self.top, self.est_h, self.table_h, lo, self.base_right).map(|mut spans| (spans.pop_front(), spans)) { + let row = (self.top, self.est_h, self.table_h); + match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) { Ok((Some((a, b)), rest)) => { - let narrowed = !rest.is_empty() || a > lo || b < self.base_right; + // Under Word 2003's indent rules a row can start left of the indent too. + let moved = if self.tight_indent { (a - lo).abs() > 0.01 } else { a > lo }; + let narrowed = !rest.is_empty() || moved || b < self.base_right; self.row_rest = rest; self.row_first = self.lines.len(); return (a, b.max(a + MIN_LINE_WIDTH), narrowed); @@ -1064,6 +1077,23 @@ impl Scan { /// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one. const MIN_SPAN: f32 = 20.0; +/// Where a row starts under Word 2003's indent rules: right after the floating objects that end +/// at or before the indent `lo` on this row and let text past their right side (their outline's +/// right edge for Tight and Through wrapping), never left of the paragraph's own left edge (0) or +/// right of `lo`; `lo` if there are none. +fn tight_row_start(exclusions: &[Exclusion], (top, h, table_h): (f32, f32, f32), lo: f32) -> f32 { + exclusions + .iter() + .filter(|e| !e.top_bottom && e.side != WrapText::Left && e.right <= lo && e.intersects_row(top, h, table_h, f32::NEG_INFINITY, lo)) + .filter_map(|e| match &e.contour { + None => Some(e.right), + Some(c) => c.occupied(top - e.top, top + h - e.top).into_iter().map(|(_, b)| b + e.left).reduce(f32::max), + }) + .reduce(f32::max) + // A float out in the left margin doesn't pull the text into the margin after it. + .map_or(lo, |edge| edge.max(0.0).min(lo)) +} + /// How far below a line's top its baseline sits. Multiple spacing at or above single keeps the /// text at the top of the line and puts the extra leading below the baseline; below single it /// shrinks the whole box, ascent included (Word's output for docxide-pdf's fixtures: 1.15-spaced @@ -1078,8 +1108,17 @@ fn baseline_offset(spacing: LineSpacing, asc: f32, height: f32, desc: f32) -> f3 /// The spans of a row at `top` (about `h` tall) between `lo` and `hi` that text can use around /// the exclusions, left to right (Square wrapping uses both sides of an object). `Err(y)`: none -/// here, try again at `y` (below what's in the way). -fn row_spans(exclusions: &[Exclusion], top: f32, h: f32, table_h: f32, lo: f32, hi: f32) -> Result, f32> { +/// here, try again at `y` (below what's in the way). With `tight_indent` (Word 2003's indent +/// rules, `w:doNotSuppressIndentation`) a row starts right after a floating object that ends +/// before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented 1" tightly +/// wraps an object at 0.25"). +fn row_spans( + exclusions: &[Exclusion], + (top, h, table_h): (f32, f32, f32), + (lo, hi): (f32, f32), + tight_indent: bool, +) -> Result, f32> { + let lo = if tight_indent { tight_row_start(exclusions, (top, h, table_h), lo) } else { lo }; let here: Vec<&Exclusion> = exclusions.iter().filter(|e| e.intersects_row(top, h, table_h, lo, hi)).collect(); if let Some(below) = here.iter().filter(|e| e.top_bottom).map(|e| e.bottom).reduce(f32::max) { return Err(below); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 4f05f3f1a7..c1cc4c44a0 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -3809,6 +3809,113 @@ fn text_wraps_around_square_float() { assert!(l.pages[0].items.iter().any(|i| matches!(i, Placed::Shape { .. }))); } +/// The left edges of a paragraph's lines beside a 144 × 100 pt square-wrapped rectangle at the +/// column's top left (9 pt from text), and of its first line below the rectangle, in +/// compatibility `mode` with Word 2003's indent rules on or off. The paragraph is indented +/// 216 pt; `float` adjusts the object, `para` the paragraph, and `numbered` makes it a list item. +fn word_2003_indent_lefts( + mode: u32, + rules: bool, + float: &dyn Fn(&mut wordcraft_doc::para::Float), + numbered: bool, + para: &dyn Fn(&mut ParaProps), +) -> (Vec, Option) { + let mut d = Document::from_text(&"Words beside the picture here. ".repeat(20)); + d.settings.compat_mode = mode; + d.settings.do_not_suppress_indentation = rules; + let num = numbered.then(|| Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered)); + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| { + p.indent_left = Some(216.0); + p.indent_first = Some(0.0); + p.numbering = num.map(|num| wordcraft_doc::props::NumRef { num, level: 0 }); + para(p); + }) + .unwrap(); + let mut f = wordcraft_doc::para::Float { + wrap: wordcraft_doc::para::Wrap::Square, + h_rel: wordcraft_doc::para::Anchor::Column, + v_rel: wordcraft_doc::para::Anchor::Paragraph, + x: 0.0, + y: 0.0, + dist: 9.0, + ..Default::default() + }; + float(&mut f); + let shape = InlineObject::Shape { + kind: wordcraft_doc::para::ShapeKind::Rectangle, + w: 144.0, + h: 100.0, + fill: None, + stroke: None, + stroke_width: 1.0, + float: f, + story: None, + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + // After the first word, so a drop cap takes the paragraph's first letter. + d.insert_object(&Pos::body(0, 6), shape, &Default::default()).unwrap(); + let l = lay(&d); + let Placed::Lines { para, .. } = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. })).unwrap() else { + panic!() + }; + let beside = para.lines.iter().filter(|ln| ln.top < 100.0).map(|ln| ln.left).collect(); + let below = para.lines.iter().find(|ln| ln.top > 120.0).map(|ln| ln.left); + (beside, below) +} + +/// Word 2003's indent rules (`w:doNotSuppressIndentation`, a `.doc`'s `Copts.fWW11IndentRules`): an +/// unnumbered paragraph indented past a floating object on its left starts its lines right after +/// the object, its indent ignored (ECMA-376 Part 4 §14.8.3.12). In a Word 2003-mode `.doc` saved +/// by Word, empty paragraphs indented 216 pt sit right after a text box ending 165 pt into the +/// column, in the 71 pt gap before a second box where the indent would leave under 20 pt. Below +/// the object, and in Word 2013's layout, the indent applies. +#[test] +fn word_2003_indent_rules_start_lines_right_after_a_float_before_the_indent() { + let lefts = |mode: u32, rules: bool| word_2003_indent_lefts(mode, rules, &|_| {}, false, &|_| {}); + for mode in [11, 12, 14] { + let (beside, below) = lefts(mode, true); + assert!( + !beside.is_empty() && beside.iter().all(|x| (x - 153.0).abs() < 0.01), + "mode {mode}: lines start after the object and its 9 pt distance: {beside:?}" + ); + assert_eq!(below, Some(216.0), "mode {mode}: below the object the indent applies"); + } + assert_eq!(lefts(11, false).0[0], 216.0, "without the option the indent applies beside the object"); + assert_eq!(lefts(15, true).0[0], 216.0, "Word 2013's layout keeps the indent"); +} + +/// Under Word 2003's indent rules a line starts after a Tight or Through-wrapped object's outline +/// where the line meets it, not after the outline's widest point: here a right triangle, its +/// point at the top left, 144 pt wide (and 9 pt from text) only at its foot. +#[test] +fn word_2003_indent_rules_follow_a_tight_objects_outline() { + use wordcraft_doc::para::Wrap; + use wordcraft_doc::wrap::WrapPolygon; + let poly = WrapPolygon::new(true, [(0, 0), (0, 21_600), (21_600, 21_600)]).map(Arc::new); + for wrap in [Wrap::Tight, Wrap::Through] { + let (beside, _) = word_2003_indent_lefts(11, true, &|f| (f.wrap, f.wrap_polygon) = (wrap, poly.clone()), false, &|_| {}); + assert!(beside.len() > 2 && beside[0] < 60.0, "{wrap:?}: the first line starts near the point: {beside:?}"); + assert!(beside.windows(2).all(|w| w[0] < w[1]) && beside.iter().all(|&x| x <= 153.0 + 0.01), "{wrap:?}: each line further out: {beside:?}"); + } +} + +/// Word 2003's indent rules leave the indent alone for a numbered paragraph (its number sits at +/// the indent) and for one with a drop cap (the letter does), and never start a line left of the +/// paragraph's own edge after an object out in the margin. +#[test] +fn word_2003_indent_rules_keep_the_indent_where_they_do_not_apply() { + let (numbered, _) = word_2003_indent_lefts(11, true, &|_| {}, true, &|_| {}); + assert!(numbered.iter().all(|&x| x >= 216.0 - 0.01), "a numbered paragraph keeps its indent: {numbered:?}"); + let (dropped, _) = word_2003_indent_lefts(11, true, &|_| {}, false, &|p| p.drop_cap = Some(3)); + assert!(dropped.iter().all(|&x| x >= 216.0 - 0.01), "lines beside a drop cap stay right of it: {dropped:?}"); + // An object in the left margin, its right side and distance from text 44 pt short of the column. + let (margin, _) = word_2003_indent_lefts(11, true, &|f| f.x = -197.0, false, &|_| {}); + assert!(margin.iter().all(|&x| x >= -0.01), "no line starts in the margin: {margin:?}"); + assert!((margin[0] - 0.0).abs() < 0.01, "the line starts at the paragraph's edge: {margin:?}"); +} + #[test] fn a_lines_arrowheads_sit_at_its_ends() { // A line runs from its frame's top left to its bottom right (DrawingML's `line`, as it is diff --git a/docs/gaps.md b/docs/gaps.md index f41f200dee..dd855eb30a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ > **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** trivial (#5: a list item deleted whole under Track Changes shows its number as deleted text, #4828); previously trivial (clipboard: a copied picture now reaches the system clipboard as PNG, with HTML where the host writes it; a copy of only shapes still stays in WordCraft, #6205); previously trivial (#4501 refactor regressions restored, #4683; no ranked gap changed); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** trivial (gap 4: Word 2003's indent rules beside floating objects, #5939); previously trivial (#5: a list item deleted whole under Track Changes shows its number as deleted text, #4828); previously trivial (clipboard: a copied picture now reaches the system clipboard as PNG, with HTML where the host writes it; a copy of only shapes still stays in WordCraft, #6205); previously trivial (#4501 refactor regressions restored, #4683; no ranked gap changed); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -83,7 +83,7 @@ Page drawing indexes text-box warp lookups by paragraph and story for the curren |---|---|---|---|---|---|---| | 1 | **DOCX never tested on real-world files.** No corpus of files from Word, Google Docs, LibreOffice and Pages has been opened, rendered and round-tripped and compared with Word page by page | B | No corpus in the repo; `crates/docx/tests` are synthetic fixtures (including omitted/empty paragraph defaults and imported TOC range preservation); "DOCX fidelity corpus: not started" since 2026-10-06. Field reports fixed one by one: a cover page's theme-coloured shapes (#611), freeforms inside groups and text-box margins and Resize to fit (#743), shape gradients and transparency (#1500), cover-page positions relative to the page and freeforms drawn back to their start (#743), Word's text watermark in headers, read and written (#1290), VML freeform rule lines in headers, and `flowChartOr` drawn with its spokes (#1644); explicit DrawingML outline dashes and flat/square/round caps preserved; paragraph-relative header/footer/cell/text-box float origins corrected (cu20we, synthetic regressions) | Everyone: the files people receive are the files that break | 30–50 | [file-format-parity.md](file-format-parity.md) | | 3 | **Crashes and freezes in the field**: startup crash on Intel UHD Graphics (#170, open), a crash on macOS 12.7.6 Intel (#979, open) (lag on GPUs without a DirectX 12 driver fixed, #316; 32-bit Windows exited at launch because DirectX 12 graphics pipeline creation failed, now OpenGL), freezes (#59 Thai fonts and #31 font selector, both open; #77 closed), broken shape tool (#142, open); the Windows 11 no-write-without-admin (#218) and unmovable images (#82) reports are closed (pictures and shapes in Behind Text drag through the text over them, #1313); memory growth on every font change fixed (#848: the font list no longer loads each family it previews) | B | 197 open issues (2026-10-12), among them the crash and freeze reports #170, #979, #59 and #31 | Anyone hit loses work or trust; the never-crash standard covers panics, not hangs or GPU driver faults | 20–30 | [target-app-parity.md](target-app-parity.md) (Stability) | -| 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | In-line pictures raised or lowered (`w:position`) set their line's height as in Word, past their own height too (#3984, #5796). SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | +| 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | Word 2003's indent rules beside floating objects (`w:doNotSuppressIndentation`, a `.doc`'s `Copts.fWW11IndentRules`) are followed by the layout below compatibility mode 15 for unnumbered paragraphs; numbered paragraphs still keep their indent, and files turn the rules on only once craft-libs reads the setting (#5939). In-line pictures raised or lowered (`w:position`) set their line's height as in Word, past their own height too (#3984, #5796). SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250); one anchored right after a page break, before text, is drawn on the new page (#4262). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). Page break before now applies at a continuous section's mid-page top (#5287); the later-column case remains unmeasured in Word. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963); a hyphen before a slash and a letter is also a break opportunity (#3408), while a hyphen before a slash and a digit stays whole A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, so a TOC entry's page number keeps its leader (#1840). | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | @@ -236,6 +236,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-11-01 | trivial | Arrowheads keep their kind, width and length (DrawingML `a:headEnd`/`a:tailEnd` `type`/`w`/`len`, VML `startarrow`/`endarrow` with `…arrowwidth`/`…arrowlength`), read and written back, and are drawn 2, 3 or 5 times the line's width long and wide (small, medium, large), a line under 2 points as a 2-point one, as measured in Word for Windows; every kind is still drawn as a triangle; no ranked gap changed; readiness estimates unchanged | | 2026-11-04 | trivial | #19: ODT settings for what the standard leaves open removed: one choice for each case | | 2026-11-04 | trivial | #19: ODT element audit; files from other applications checked | +| 2026-11-14 | trivial | Pagination gap #4: Word 2003's indent rules beside floating objects (`w:doNotSuppressIndentation`, a `.doc`'s `Copts.fWW11IndentRules`) followed below compatibility mode 15 for unnumbered paragraphs (#5939); files turn them on only once craft-libs reads the setting | | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-11-01 | trivial | #19 narrowed: ODT read and written nearly whole on this branch (styles, tables, notes, comments, tracked changes including formatting, fields, indexes and marks, drawings, charts, embedded objects, forms, ruby, password protection, flat ODT), checked against LibreOffice; what's left listed; estimate 18–27 h → 10–16 h | | 2026-11-01 | trivial | #10 narrowed: text in a turned text box is drawn turned with it on screen and in PNG and PDF (upside down when flipped across, never mirrored); editing it still goes by its upright text; estimate unchanged | diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 6201b80436..55b72f4d9d 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** trivial (a deleted list item's number is drawn as deleted text, #4828); previously minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: cu20we: outline caps; previously trivial: cu20we: box float paragraph origin; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial: PAGE fields in a paragraph split across pages show the page they are on, #1352; previously trivial: a dragged floating object anchors in the column it lands in, #884; previously trivial: a paragraph ending on a page with footnotes keeps its space after above the separator, #1116; previously trivial: symbol-font text drawn as Unicode symbols, #776; previously trivial: large-table scrolling measured and fixed, #811; previously trivial: text boxes use their own margins; Resize shape to fit text never cuts text, #743; previously trivial: complex-script shaping and Myanmar line breaking, #604; previously trivial: body page totals, table-cell footnotes and bookmark link pages fixed, #450 #451 #455; previously major: first version; line breaking, pagination and object placement checked against Word's behaviour from the layout source on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** trivial (Word 2003's indent rules beside floating objects, `doNotSuppressIndentation`, #5939); previously trivial (a deleted list item's number is drawn as deleted text, #4828); previously minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously trivial: continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: cu20we: outline caps; previously trivial: cu20we: box float paragraph origin; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial: PAGE fields in a paragraph split across pages show the page they are on, #1352; previously trivial: a dragged floating object anchors in the column it lands in, #884; previously trivial: a paragraph ending on a page with footnotes keeps its space after above the separator, #1116; previously trivial: symbol-font text drawn as Unicode symbols, #776; previously trivial: large-table scrolling measured and fixed, #811; previously trivial: text boxes use their own margins; Resize shape to fit text never cuts text, #743; previously trivial: complex-script shaping and Myanmar line breaking, #604; previously trivial: body page totals, table-cell footnotes and bookmark link pages fixed, #450 #451 #455; previously major: first version; line breaking, pagination and object placement checked against Word's behaviour from the layout source on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -99,7 +99,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Hidden text excluded from breaking and hyphenation | ✅ | #173 | — | | Empty paragraph with a hidden mark (`w:pPr/w:rPr/w:vanish`) | ✅ | Synthetic DOCX observed in Word for Windows 16.0.20527: no room, no list number, and the number is still counted (`1.`, hidden item, `3.`), in the body and in table cells. `layout::tests::empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing`, #3982. Not observed in Word: when such a paragraph closes a section before a continuous one and holds only an in-line picture (or a note reference, or a legacy check box), the picture keeps its room and the next section starts below it instead of over it (`a_hidden_mark_with_an_inline_picture_keeps_its_room`, #5288). A paragraph with text and a hidden mark shown together with the next one (Word) is #3986 | - | | Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages | — | -| Compatibility modes (Word 2003/2007/2010 layout for old files: `w:compat` options) | 🟡 | `allowSpaceOfSameStyleInTable` supported in modes 11/12/14; mode 15 retains contextual suppression. `doNotExpandShiftReturn` keeps justified lines that end in a manual line break short (#3924). Most other legacy compat options remain ignored | 10–20 | +| Compatibility modes (Word 2003/2007/2010 layout for old files: `w:compat` options) | 🟡 | `allowSpaceOfSameStyleInTable` supported in modes 11/12/14; mode 15 retains contextual suppression. `doNotExpandShiftReturn` keeps justified lines that end in a manual line break short (#3924). `doNotSuppressIndentation` (Word 2003's indent rules; a `.doc`'s `Copts.fWW11IndentRules`): below mode 15 an unnumbered paragraph's line starts right after a floating object that ends before its indent, never in the margin, and not beside a drop cap (#5939); the numbered-paragraph half of the rule is not implemented, and files set it only once craft-libs reads it. Most other legacy compat options remain ignored | 10–20 | | Fields: STYLEREF in headers and footers (running chapter titles) | ✅ | Evaluated per page at layout time: the page's first (or with `\l` last) paragraph of the style, else the nearest before it; style name, id or heading level (a level finds the style named `heading N` whatever its id, so localized documents match, #1286); character styles; `\n \r \w \s \t \p` (`\r` treated as `\w`); body STYLEREF updated with the other fields (#775). Field results with right-to-left text (a Hebrew heading, "פרק א") are laid out with bidi reordering like ordinary text: the result is an isolate taking its first strong letter's direction (else the text's around the field), and each level run is shaped and mirrored in its own direction, so `{ PAGE }` in field-code view and `(Chapter 1)` keep their brackets in right-to-left paragraphs; this covers every field and note mark shown as text (#1670). Header paragraphs are cached on their per-page results, so typing in body text no STYLEREF shows doesn't lay the headers out again (#1286) | — | | Fields filled in for output: SEQ, STYLEREF, REF in the body | ✅ | PDF export, print jobs and page images lay out a copy whose unlocked SEQ, STYLEREF and REF fields show their current results, as Word does when printing or exporting with Update fields before printing off (measured in Word for Windows with stale stored results); a locked SEQ keeps its result but still counts, its `\r` too, and a SEQ in a tracked deletion keeps its result and doesn't count, with markup shown or hidden (measured in Word for Windows); NUMWORDS, FILENAME, the document properties and formulas keep their stored results, as in Word; REF fields with `\p`, `\r`, `\n` or `\w` (above or below, and paragraph numbers) keep theirs until those are computed, and so does a REF to a bookmark that ends in a later paragraph (Word shows its paragraphs as paragraphs of the result); SEQ numbers are filled in before the STYLEREF and REF fields that read them, so a STYLEREF to a heading holding a SEQ field shows its new number (after F9 too); SEQ fields in text boxes are numbered where their boxes are anchored, after F9 too, and a REF to a bookmark in a text box, header, footer, footnote, endnote or comment shows that text as stored, as in Word; a REF to a bookmark the document lacks prints "Error! Reference source not found."; the document is unchanged (`cmd::references::tests::output_shows_fresh_seq_styleref_and_ref_results`, `cmd::references::tests::output_numbers_text_box_captions_where_their_boxes_are_anchored`, `cmd::references::tests::output_shows_references_to_bookmarks_outside_the_body`, `cmd::references::tests::output_shows_words_error_for_a_reference_to_a_missing_bookmark`, `cmd::references::tests::output_counts_locked_seq_fields_and_not_deleted_ones`) | — | | Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers, PAGEREF in headers and footers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages; a PAGE field in a paragraph that runs onto a later page (a page break inside it, or a natural split) shows that page's number, the rest of the paragraph broken again for the wider result (#1352); PAGEREF in headers and footers shows its bookmark's page, filled in after pagination like their totals (#1477); in the body it keeps its result until fields are updated | — | @@ -321,6 +321,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-07 | trivial | A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Estimates unchanged. | | 2026-11-05 | trivial | PR #4545: eligible cell floats retain in-bounds offsets and touch the outer cell edge only on overflow, ignoring wrap distances for object placement. Front-of-text, turned-cell and outside-cell opt-outs remain. Synthetic geometry controls; native front/behind-text parity remains unqualified. | | 2026-11-05 | trivial | With multiple spacing a line of only in-line pictures is as tall as they reach, raised or lowered, and never less than its font's height (a list label's font counting too): a picture shorter than the font keeps the font's ascent and descent, as noted for ODT documents below; a taller one ends at the line's bottom with no descent under it. The spacing adds its share of the font's height, not of a lowered picture's. A legacy check box sizes its line as text of its size. Measured in Word with Arial at 10 and 20 pt, single, 1.15, 1.25 and 1.5 spacing, 156 synthetic lines (`tests::lowered_pictures_and_check_boxes_take_words_line_heights`). Known gap: a picture lowered further than its own height is limited to that height where Word's line keeps growing. | +| 2026-11-14 | trivial | Word 2003's indent rules beside floating objects (`w:doNotSuppressIndentation`, a `.doc`'s `Copts.fWW11IndentRules`): below compatibility mode 15 an unnumbered paragraph indented past a floating object on its left starts its lines right after the object, its indent ignored (ECMA-376 Part 4 §14.8.3.12), as in Word's PDF of a Word 2003-mode `.doc`; below the object and in mode 15 the indent applies (#5939, `layout::tests::word_2003_indent_rules_start_lines_right_after_a_float_before_the_indent`); files turn it on only once craft-libs reads the setting from `.doc` and `.docx` | | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-10-28 | trivial | Shared MATH construction records reuse variants and assembly data without changing glyph mappings or existing limits (#3630); readiness estimates unchanged | | 2026-10-29 | trivial | Page drawing indexes text-box warp lookups per paragraph (#3614); requested offsets only, bounded prefix traversal, original Linux display and persistence controls; readiness estimates unchanged | From 54e82f7131b73fea1868d68e6fa0f8ba835912b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Tue, 17 Nov 2026 13:26:11 +0700 Subject: [PATCH 51/99] Table Design: show Shading label beside the color menu arrow (#2016) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/ribbon/table.rs | 5 +- crates/ui-egui/src/ribbon/tests.rs | 149 ++++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/buttons.rs | 59 +++++++++- 4 files changed, 207 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/ribbon/table.rs b/crates/ui-egui/src/ribbon/table.rs index afae6cf104..80c06886f7 100644 --- a/crates/ui-egui/src/ribbon/table.rs +++ b/crates/ui-egui/src/ribbon/table.rs @@ -1,5 +1,5 @@ use super::common::{mi, stack}; -use super::{MeasureExt, Remember, Target, Ui, WordApp, big, group, json, menu_button, small, split, vec2}; +use super::{MeasureExt, Remember, Target, Ui, WordApp, big, group, json, menu_button, small, vec2}; pub(super) fn table_design(app: &mut WordApp, ui: &mut Ui) { let look = app.session.sel.focus.path.cell().and_then(|(tp, _, _)| app.session.doc.table(app.session.sel.focus.story, &tp).map(|t| t.props.look)); @@ -81,7 +81,8 @@ pub(super) fn table_design(app: &mut WordApp, ui: &mut Ui) { }, ); let sw = wordcraft_doc::Rgb::parse(&app.canvas.last_shading).map(crate::theme::c32); - split( + // Labelled, with its arrow on the same row (#1726). + crate::widgets::split_labeled( ui, app, "shadingNoBar", diff --git a/crates/ui-egui/src/ribbon/tests.rs b/crates/ui-egui/src/ribbon/tests.rs index ce05473951..e5e4f5b6b1 100644 --- a/crates/ui-egui/src/ribbon/tests.rs +++ b/crates/ui-egui/src/ribbon/tests.rs @@ -1092,3 +1092,152 @@ fn shape_and_chart_formats_leave_out_of_range_sizes_alone() { assert_eq!(before.0, Some((20.0, 2500.0))); assert_eq!(shown(a), before, "Chart Design shown, the chart untouched"); } + +fn table_design_harness(language: &str, theme: egui::Theme) -> egui_kittest::Harness<'static, WordApp> { + let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap(); + app.run("ui.language", json!({"value": language})).unwrap(); + app.run("ui.theme", json!({"value": if theme == egui::Theme::Dark { "dark" } else { "light" }})).unwrap(); + egui_kittest::Harness::builder().with_size(vec2(1600.0, 700.0)).with_theme(theme).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + assert_eq!(ctx.global_style().visuals.dark_mode, theme == egui::Theme::Dark, "the requested palette is active while drawing"); + ui.horizontal_top(|ui| table_design(app, ui)); + }, + app, + ) +} + +/// The Shading arrow's name: "Shading options", in the interface language (#3172). +fn shading_options() -> String { + crate::i18n::fmt(tl!("{name} options"), &[("name", tl!("Shading"))]) +} + +/// #1726: the text must actually be painted, and both hit targets must share one row in +/// Table Styles' vertical stack. Accessibility labels alone cannot prove visible text. +#[test] +fn table_shading_label_is_painted_beside_its_arrow() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + // Vietnamese and German labels need the embedded catalogs (CI has them); English always runs. + let languages: &[&str] = if crate::i18n::catalogs_embedded() { &["en", "vi", "de"] } else { &["en"] }; + for &language in languages { + for theme in [egui::Theme::Light, egui::Theme::Dark] { + let mut h = table_design_harness(language, theme); + h.run_steps(3); + let label = tl!("Shading"); + let main = h.get_by_role_and_label(Role::Button, label).rect(); + let arrow = h.get_by_role_and_label(Role::Button, &shading_options()).rect(); + assert!((main.top() - arrow.top()).abs() < 0.01 && (main.bottom() - arrow.bottom()).abs() < 0.01); + assert!((main.right() - arrow.left()).abs() < 0.01, "{language}: {main:?}, {arrow:?}"); + let text = h + .output() + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t), + _ => None, + }) + .expect("Shading is drawn as text, not just a hover tip"); + let text_rect = Rect::from_min_size(text.pos, text.galley.size()); + assert!(main.contains_rect(text_rect), "{language}: {text_rect:?} outside {main:?}"); + assert!(text_rect.left() >= main.left() + 24.0, "the label starts after the icon"); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); +} + +fn first_cell_shading(app: &WordApp) -> Option { + app.session.doc.body.iter().find_map(|b| b.as_table()).unwrap().rows[0].cells[0].props.shading +} + +fn painted_text_rect(output: &egui::FullOutput, text: &str) -> Option { + output.shapes.iter().find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(Rect::from_min_size(t.pos, t.galley.size())), + _ => None, + }) +} + +/// #1726: the arrow opens the real colour menu without applying the remembered colour; +/// picking a swatch remembers it, and the command half reapplies it after one-step undo. +#[test] +fn table_shading_split_keeps_palette_and_apply_separate() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut h = table_design_harness("en", egui::Theme::Light); + h.state_mut().canvas.last_shading = "0070C0".into(); + h.run_steps(3); + let original = first_cell_shading(h.state()); + h.get_by_role_and_label(Role::Button, &shading_options()).click(); + h.run(); + assert_eq!(first_cell_shading(h.state()), original, "opening the palette must not apply the last colour"); + assert!(painted_text_rect(h.output(), "No Color").is_some(), "the arrow opens the shading palette"); + // Swatches are drawn controls; locate the red standard swatch from its painted box. + let red = h + .output() + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.fill == egui::Color32::RED && r.rect.size() == vec2(15.0, 15.0) => Some(r.rect.center()), + _ => None, + }) + .expect("red standard colour is visible in the palette"); + h.hover_at(red); + h.drag_at(red); + h.drop_at(red); + h.run(); + assert_eq!(first_cell_shading(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0))); + assert_eq!(h.state().canvas.last_shading, "FF0000"); + assert!(painted_text_rect(h.output(), "No Color").is_none(), "a colour pick closes the palette"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(first_cell_shading(h.state()), original); + h.get_by_role_and_label(Role::Button, "Shading").click(); + h.run(); + assert_eq!(first_cell_shading(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0))); + assert!(painted_text_rect(h.output(), "No Color").is_none(), "the command half must not open the palette"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(first_cell_shading(h.state()), original); + h.get_by_role_and_label(Role::Button, "Shading").click(); + h.run(); + assert_eq!(first_cell_shading(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0))); + h.get_by_role_and_label(Role::Button, &shading_options()).click(); + h.run(); + let clear = painted_text_rect(h.output(), "No Color").expect("No Color is visible in the palette").center(); + h.hover_at(clear); + h.drag_at(clear); + h.drop_at(clear); + h.run(); + assert_eq!(first_cell_shading(h.state()), None); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(first_cell_shading(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0)), "No Color is undone in one step"); +} + +/// #1726 with #662: in a compact group the labelled split button drops its label and keeps only +/// its icon and arrow, as small buttons do; its name stays for the tooltip and screen readers. +#[test] +fn a_labelled_split_button_shows_only_its_icon_when_compact() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + for compact in [false, true] { + let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 100.0)).build_ui_state( + move |ui, app: &mut WordApp| { + crate::ribbon_fit::set_compact(ui.ctx(), compact); + let action = crate::widgets::ButtonAction::new("table.shading", json!({}), false); + crate::widgets::split_labeled(ui, app, "shadingNoBar", "Shading", action, None, |_, _| {}); + }, + app, + ); + h.run_steps(2); + let button = h.get_by_role_and_label(Role::Button, "Shading").rect(); + assert_eq!(painted_text_rect(h.output(), "Shading").is_some(), !compact, "compact: {compact}"); + if compact { + assert_eq!(button.width(), 24.0, "only the icon"); + } else { + assert!(button.width() > 30.0, "icon and label: {button:?}"); + } + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b898db6972..043bb8b750 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -14,7 +14,7 @@ mod tooltip; pub use buttons::{ BIG_ICON_Y, BIG_LABEL_Y, ButtonAction, CONTENT_H, DROPDOWN, LABEL_H, LABEL_LINE_H, LABEL_PITCH, MenuButtonOptions, big, big_toggle, enabled, - label_line, menu_button, menu_enabled, small, split, + label_line, menu_button, menu_enabled, small, split, split_labeled, }; pub(crate) use buttons::{bg, run_from_ribbon}; pub use combo::{ diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index 237f981cfa..ad70a53c8f 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -180,25 +180,74 @@ pub fn split( action: ButtonAction<'_>, swatch: Option, menu: impl FnOnce(&mut Ui, &mut WordApp), +) -> Response { + split_button(ui, app, icon, tip, action, SplitLook { swatch, labeled: false }, menu) +} + +/// A [`split`] button with its label beside the icon and the arrow on the same row, also in a +/// vertical ribbon stack (Table Design › Shading, #1726). A compact group shows only the icon. +pub fn split_labeled( + ui: &mut Ui, + app: &mut WordApp, + icon: &str, + label: &str, + action: ButtonAction<'_>, + swatch: Option, + menu: impl FnOnce(&mut Ui, &mut WordApp), +) -> Response { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + split_button(ui, app, icon, label, action, SplitLook { swatch, labeled: true }, menu) + }) + .inner +} + +/// A split button's look beyond its icon: the colour bar under it, and its name beside it. +struct SplitLook { + swatch: Option, + labeled: bool, +} + +fn split_button( + ui: &mut Ui, + app: &mut WordApp, + icon: &str, + tip: &str, + action: ButtonAction<'_>, + look: SplitLook, + menu: impl FnOnce(&mut Ui, &mut WordApp), ) -> Response { let ButtonAction { id, params, checked } = action; let tip = tl!(tip); let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click()); + let on = enabled(app, id); + // A compact group (#662) shows only the icon, as `small` does; the tooltip keeps the name. + let label = (look.labeled && !crate::ribbon_fit::compact(ui.ctx())) + .then(|| ui.painter().layout_no_wrap(tip.to_string(), regular(11.5), if on { t.text } else { t.text_disabled })); + let text_w = label.as_ref().map_or(0.0, |g| g.size().x + 6.0); + // What a compact group gives back, so the ribbon can plan it before drawing it compact. + crate::ribbon_fit::add_saving(ui.ctx(), text_w); + let (r, resp) = ui.allocate_exact_size(vec2(24.0 + text_w, 22.0), Sense::click()); keytip_badge(ui, r, id, tip); let (ar, aresp) = ui.allocate_exact_size(vec2(11.0, 22.0), Sense::click()); - let on = enabled(app, id); bg_if(ui, r, &resp, checked, &t, on); bg_if(ui, ar, &aresp, false, &t, on); - let ic = Rect::from_center_size(r.center(), vec2(17.0, 17.0)); + // The icon (and its colour bar) leads; a label follows it, mirrored in a right-to-left interface. + let rtl = crate::rtl::flows(ui); + let ic = Rect::from_center_size(pos2(crate::rtl::lead_x(rtl, r, 12.0), r.center().y), vec2(17.0, 17.0)); let (c, a) = if on { (t.icon, t.accent) } else { (t.text_disabled, t.text_disabled) }; icons::paint(ui.painter(), ic, icon, c, a); - if let Some(sw) = swatch { + if let Some(sw) = look.swatch { let sw = if on { sw } else { t.text_disabled }; - let bar = Rect::from_min_max(pos2(r.min.x + 4.0, r.max.y - 5.0), pos2(r.max.x - 4.0, r.max.y - 2.0)); + let left = crate::rtl::lead_left(rtl, r, 4.0, 16.0); + let bar = Rect::from_min_max(pos2(left, r.max.y - 5.0), pos2(left + 16.0, r.max.y - 2.0)); ui.painter().rect_filled(bar, 0.0, sw); ui.painter().rect_stroke(bar, 0.0, Stroke::new(0.5, t.border), egui::StrokeKind::Inside); } + if let Some(g) = label { + let y = r.center().y - g.size().y / 2.0; + ui.painter().galley(pos2(crate::rtl::lead_left(rtl, r, 24.0, g.size().x), y), g, t.text); + } icons::paint(ui.painter(), Rect::from_center_size(ar.center(), vec2(DROPDOWN, DROPDOWN)), "dropdown", c, a); let resp = tooltip(app, resp, tip, id); command_menu(&resp, app, id); From 4e2a5c2b8f3c6abb85be0ec02af1ecd2b86117d5 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 17 Nov 2026 07:42:09 +0100 Subject: [PATCH 52/99] Table borders no longer look blue and uneven (#6048) Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/lib.rs | 33 +++++++++- crates/render/src/tests.rs | 25 ++++++++ crates/ui-egui/src/canvas.rs | 14 ++--- crates/ui-egui/src/canvas/pages.rs | 78 ++++++++++++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 97 ++++++++++++++++++++++++++++++ 5 files changed, 238 insertions(+), 9 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 74f1ca9ac7..0fecbb23b2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -703,12 +703,43 @@ fn draw_line(ctx: &mut RenderContext, fr: &Frame, it: &Draw) { stroke_segment(ctx, (x0, y0, x1, y1), (-nx, -ny)); } _ => { + let (st, off) = match snap_rule(fr.view, (x0, y0, x1, y1), w) { + Some((w_px, off)) => (kurbo::Stroke { width: w_px / fr.view.as_coeffs()[0], ..st }, off), + None => (st, (0.0, 0.0)), + }; ctx.set_stroke(st); - stroke_segment(ctx, (x0, y0, x1, y1), (0.0, 0.0)); + stroke_segment(ctx, (x0, y0, x1, y1), off); } } } +/// Snap a horizontal or vertical rule to the device pixel grid so every border of one nominal +/// width covers the same number of pixels at any zoom (#5967). Returns the stroke width in device +/// pixels and the offset, in points, that moves the line onto the snapped spot; `None` for slanted +/// lines or a view that rotates or skews. +fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -> Option<(f64, (f64, f64))> { + if !is_upright(view) { + return None; + } + let [k, _, _, _, tx, ty] = view.as_coeffs(); + if y0 == y1 && x0 != x1 { + let (w_px, c) = snap_hairline(y0 * k + ty, width * k); + Some((w_px, (0.0, (c - ty) / k - y0))) + } else if x0 == x1 && y0 != y1 { + let (w_px, c) = snap_hairline(x0 * k + tx, width * k); + Some((w_px, ((c - tx) / k - x0, 0.0))) + } else { + None + } +} + +/// A line `width_px` wide centred at device coordinate `centre`, moved so both edges fall on whole +/// pixels. Returns the width, made a whole number of pixels (at least one), and the new centre. +fn snap_hairline(centre: f64, width_px: f64) -> (f64, f64) { + let w = width_px.round().max(1.0); + (w, (centre - w / 2.0).round() + w / 2.0) +} + /// Stroke the line from (`x0`, `y0`) to (`x1`, `y1`), moved by (`ox`, `oy`). fn stroke_segment(ctx: &mut RenderContext, (x0, y0, x1, y1): (f64, f64, f64, f64), (ox, oy): (f64, f64)) { let mut p = BezPath::new(); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index eeb41b22b2..ad8f6aa8f3 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1938,6 +1938,31 @@ fn paths_far_past_every_canvas_are_not_flattened() { assert!(!path_extent_ok(Affine::IDENTITY, &line(f64::NAN))); } +#[test] +fn rules_of_one_width_cover_the_same_whole_pixels_at_every_zoom() { + for zoom in [0.5, 0.6, 0.75] { + for ppp in [1.0, 1.25] { + let k = zoom * ppp * 96.0 / 72.0; + let view = Affine::new([k, 0.0, 0.0, k, 37.3, 12.9]); + let mut widths = Vec::new(); + for i in 0..20 { + let pos = 10.0 + f64::from(i) * 17.37; + let (w_h, (_, oy)) = snap_rule(view, (5.0, pos, 400.0, pos), 0.5).unwrap(); + let (w_v, (ox, _)) = snap_rule(view, (pos, 5.0, pos, 400.0), 0.5).unwrap(); + widths.push(w_h); + widths.push(w_v); + for (w, centre) in [(w_h, (pos + oy) * k + 12.9), (w_v, (pos + ox) * k + 37.3)] { + let edge = centre - w / 2.0; + assert!((edge - edge.round()).abs() < 1e-9, "zoom {zoom} ppp {ppp}: edge {edge} is off the pixel grid"); + } + } + assert!(widths.iter().all(|w| *w == widths[0] && *w >= 1.0 && w.fract() == 0.0), "zoom {zoom} ppp {ppp}: {widths:?}"); + } + } + assert!(snap_rule(Affine::rotate(0.3), (0.0, 0.0, 9.0, 0.0), 0.5).is_none()); + assert!(snap_rule(Affine::scale(2.0), (0.0, 0.0, 9.0, 4.0), 0.5).is_none()); +} + /// The same three pictures that don't draw as in the PDF test: each stays a grey box, and the page's /// pixels are what they were before strict export existed (#6005). #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1fea2a08ad..8e4b54bf6f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -64,7 +64,7 @@ use navigation::{scrollbar_page_tip, viewed_page}; use pages::{DRAWING_GRID_MAX_LINES, DRAWING_GRID_MIN_PX}; pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options}; use pages::{ - drawing_grid, drawing_grid_step, gridline_cells, page_image, page_key, page_render_options, page_shows, shown_layout, texel_aligned_rect, + drawing_grid, drawing_grid_step, gridline_segments, page_image, page_key, page_render_options, page_shows, shown_layout, texel_aligned_rect, view_key, visible_tiles, }; pub(crate) use reading::turn_read_page; @@ -1278,14 +1278,12 @@ fn paint_pages(pass: PagePaint<'_>) -> PagePaintOutput { } draw_page_gridlines(app, &painter, t, page, visual_sr, page_scale); // The current header/footer's cells have editing guides; explicit View Gridlines - // still outlines every table. Neither kind of guide is part of the document. + // still outlines every table. Both are drawn only where no border is (#5967), and + // neither kind of guide is part of the document. if app.session.view.table_gridlines || grid_story.is_some() { - for rect in gridline_cells(page, app.session.view.table_gridlines, grid_story) { - let r = Rect::from_min_size( - pos2(visual_sr.min.x + rect.x * page_scale, visual_sr.min.y + rect.y * page_scale), - vec2(rect.w * page_scale, rect.h * page_scale), - ); - painter.rect_stroke(r, 0.0, Stroke::new(0.5, t.blue.linear_multiply(0.6)), egui::StrokeKind::Middle); + let at = |p: wordcraft_geom::Point| pos2(visual_sr.min.x + p.x * page_scale, visual_sr.min.y + p.y * page_scale); + for (a, b) in gridline_segments(page, app.session.view.table_gridlines, grid_story) { + painter.line_segment([at(a), at(b)], Stroke::new(0.5, t.blue.linear_multiply(0.6))); } } } diff --git a/crates/ui-egui/src/canvas/pages.rs b/crates/ui-egui/src/canvas/pages.rs index 5fbc819330..e268cf2618 100644 --- a/crates/ui-egui/src/canvas/pages.rs +++ b/crates/ui-egui/src/canvas/pages.rs @@ -171,6 +171,84 @@ pub(super) fn gridline_cells(page: &Page, all: bool, editing: Option) }) } +/// The table gridline segments to draw on a page, in document points: the edges of the +/// [`gridline_cells`] minus the parts a printed border already draws. Word shows gridlines only +/// where a cell has no border; drawn over a border, the thin blue guide tinted every bordered +/// table blue and made its lines look uneven when zoomed out (#5967). +pub(super) fn gridline_segments(page: &Page, all: bool, editing: Option) -> Vec<(wordcraft_geom::Point, wordcraft_geom::Point)> { + use wordcraft_geom::Point; + // A rule this close to a cell edge (points) is drawn on it. + const ON_EDGE: f32 = 0.25; + // Rules by the line they run along (horizontal or not, coordinate in quarter points), so + // each cell edge looks only at the rules on its own line. Body rules cannot cover header or + // footer cells, so they are left out when only those are outlined, as in `gridline_cells`. + let key = |c: f32| (c * 4.0).round() as i64; + let body = if all { page.items.as_slice() } else { &[] }; + let mut rules: std::collections::HashMap<(bool, i64), Vec<(f32, f32, f32)>> = std::collections::HashMap::new(); + for it in body.iter().chain(&page.header).chain(&page.footer) { + let Placed::Rule { x0, y0, x1, y1, border } = it else { continue }; + if !border.is_visible() { + continue; + } + let (horizontal, c0, c1, s0, s1) = if (y0 - y1).abs() <= ON_EDGE { (true, *y0, *y1, *x0, *x1) } else { (false, *x0, *x1, *y0, *y1) }; + if (c0 - c1).abs() <= ON_EDGE && c0.is_finite() { + rules.entry((horizontal, key(c0))).or_default().push((c0, s0.min(s1), s0.max(s1))); + } + } + // The rules covering the line at `at`, sorted and merged into disjoint spans. Cells share their + // edges, so each distinct line is sorted once (not once per cell edge) and every edge then + // binary-searches its start. + let mut merged: std::collections::HashMap<(bool, u32), Vec<(f32, f32)>> = std::collections::HashMap::new(); + // The parts of [a, b] along a line at `at` that no rule on the same line covers; `horizontal` + // picks rules running along x at y = `at`, otherwise along y at x = `at`. + let mut uncovered = |horizontal: bool, at: f32, a: f32, b: f32| -> Vec<(f32, f32)> { + let covers = merged.entry((horizontal, at.to_bits())).or_insert_with(|| { + let k = key(at); + let mut covers: Vec<(f32, f32)> = (k - 1..=k + 1) + .filter_map(|k| rules.get(&(horizontal, k))) + .flatten() + .filter(|(c, _, _)| (c - at).abs() <= ON_EDGE) + .map(|&(_, s0, s1)| (s0, s1)) + .collect(); + covers.sort_by(|p, q| p.0.total_cmp(&q.0)); + let mut spans: Vec<(f32, f32)> = Vec::with_capacity(covers.len()); + for (c0, c1) in covers { + match spans.last_mut() { + Some(last) if c0 <= last.1 + ON_EDGE => last.1 = last.1.max(c1), + _ => spans.push((c0, c1)), + } + } + spans + }); + let mut out = Vec::new(); + let mut from = a; + for &(c0, c1) in &covers[covers.partition_point(|s| s.1 < a)..] { + if c0 > from + ON_EDGE { + out.push((from, c0.min(b))); + } + from = from.max(c1); + if from >= b { + break; + } + } + if from + ON_EDGE < b { + out.push((from, b)); + } + out + }; + let mut segs = Vec::new(); + for r in gridline_cells(page, all, editing) { + let (l, t, rt, bt) = (r.x, r.y, r.x + r.w, r.y + r.h); + for y in [t, bt] { + segs.extend(uncovered(true, y, l, rt).into_iter().map(|(a, b)| (Point::new(a, y), Point::new(b, y)))); + } + for x in [l, rt] { + segs.extend(uncovered(false, x, t, bt).into_iter().map(|(a, b)| (Point::new(x, a), Point::new(x, b)))); + } + } + segs +} + /// The drawing grid's spacing in points at a screen scale: the document's spacing (`w:drawingGrid*Spacing`; /// ECMA-376's 1/8 inch when it doesn't say), doubled until the lines are at least /// [`DRAWING_GRID_MIN_PX`] apart on screen. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index abdc32a3c1..3889e46798 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1,3 +1,4 @@ +use super::pages::gridline_cells; use super::*; use crate::table_resize::tests::{H, cell, screen, steps, table_window}; @@ -3563,6 +3564,102 @@ fn table_gridlines_include_header_and_footer_tables() { assert!(ys(None).is_empty(), "closing header/footer editing removes the automatic guides"); } +/// #5967: gridlines show only where a cell has no printed border, as in Word; drawn over the +/// border they tinted every bordered table blue. +#[test] +fn table_gridlines_skip_edges_a_border_draws() { + use wordcraft_geom::Point; + let cell = Placed::Cell { + rect: wordcraft_geom::Rect::new(0.0, 0.0, 10.0, 20.0), + covered: false, + table: Default::default(), + row: 0, + cell: 0, + story: StoryRef::Body, + clip: false, + }; + let rule = |x0, y0, x1, y1, border| Placed::Rule { x0, y0, x1, y1, border }; + let line = wordcraft_doc::props::Border::single(0.5); + let none = wordcraft_doc::props::Border::single(0.0); + let page = Page { + items: vec![ + // Top border over the whole edge (run on past the corners, as layout draws it). + rule(-0.25, 0.0, 10.25, 0.0, line), + // Left border over the top half only. + rule(0.0, 0.0, 0.0, 10.0, line), + // A zero-width border draws nothing, so the right edge keeps its gridline. + rule(10.0, 0.0, 10.0, 20.0, none), + cell, + ], + ..Default::default() + }; + // Overlapping rules out of order on one line leave only the gap between them: the bottom + // edge keeps 4..6 alone. + let mut gapped = page.clone(); + gapped.items.extend([ + rule(5.0, 20.0, 10.0, 20.0, line), + rule(-0.25, 20.0, 3.0, 20.0, line), + rule(1.0, 20.0, 4.0, 20.0, line), + rule(6.0, 20.0, 5.5, 20.0, line), + ]); + assert_eq!(gridline_segments(&gapped, true, None).first(), Some(&(Point::new(4.0, 20.0), Point::new(5.0, 20.0)))); + assert_eq!(gridline_segments(&gapped, true, None).len(), 3); + let segs = gridline_segments(&page, true, None); + assert_eq!( + segs, + [ + (Point::new(0.0, 20.0), Point::new(10.0, 20.0)), // bottom: no border + (Point::new(0.0, 10.0), Point::new(0.0, 20.0)), // left: below the border + (Point::new(10.0, 0.0), Point::new(10.0, 20.0)), // right: invisible border + ] + ); +} + +/// #5967: the gridlines of a table with very many rows are found in one pass over the rules, not +/// by re-sorting every rule on a line for each cell edge on it (a long table repainted slowly). +#[test] +fn table_gridlines_of_a_many_row_table_are_fast() { + const ROWS: usize = 30_000; + let line = wordcraft_doc::props::Border::single(0.5); + let mut items = Vec::new(); + for i in 0..ROWS { + let y = i as f32 * 10.0; + items.push(Placed::Cell { + rect: wordcraft_geom::Rect::new(0.0, y, 10.0, 10.0), + covered: false, + table: Default::default(), + row: i, + cell: 0, + story: StoryRef::Body, + clip: false, + }); + // One border piece per row on each side, so both vertical lines carry a rule per row. + for x in [0.0, 10.0] { + items.push(Placed::Rule { x0: x, y0: y, x1: x, y1: y + 10.0, border: line }); + } + } + let page = Page { items, ..Default::default() }; + let start = std::time::Instant::now(); + let segs = gridline_segments(&page, true, None); + // Both sides are covered; the top and bottom of every cell are not. + assert_eq!(segs.len(), 2 * ROWS); + assert!(segs.iter().all(|(a, b)| a.y == b.y)); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "took {:?}", start.elapsed()); +} + +/// #5967: a new table has borders on every edge, so it shows no gridline at all; with its +/// borders removed every edge shows one. +#[test] +fn a_bordered_table_shows_no_gridlines() { + let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default()); + a.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap(); + assert!(a.session.view.table_gridlines, "View Gridlines is on by default"); + let segs = |a: &mut WordApp| gridline_segments(&a.session.layout().pages[0], true, None).len(); + assert_eq!(segs(&mut a), 0); + a.run("table.borders", json!({"kind": "none"})).unwrap(); + assert_eq!(segs(&mut a), 6 * 4, "every edge of the six cells"); +} + #[test] fn drawing_grid_starts_at_the_margins_and_stays_inside_them() { // Letter page with 1" margins: the text area is 468 x 648 pt from (72, 72). From ca075db4587bd5835435a3bb5fbaa2960bde5452 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:54:43 +0100 Subject: [PATCH 53/99] M14: report missing --cmd values before CLI options (#6686) --- apps/wordcraft-cli/src/main.rs | 7 ++++++- apps/wordcraft-cli/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/apps/wordcraft-cli/src/main.rs b/apps/wordcraft-cli/src/main.rs index 0bcf8377ea..b500db3293 100644 --- a/apps/wordcraft-cli/src/main.rs +++ b/apps/wordcraft-cli/src/main.rs @@ -603,6 +603,11 @@ fn run>(args: &[S]) -> Result<(), Failure> { write_stdout(|o| writeln!(o, "{r}")) } "run" => { + for (i, arg) in rest.iter().enumerate() { + if arg == "--cmd" && rest.get(i + 1).is_none_or(|value| value.starts_with("--")) { + return Err("--cmd needs a value".into()); + } + } validate_options("run", &rest, RUN_OPTIONS)?; let page = parse_page_arg("run", &rest)?; let scale = parse_scale_arg("run", &rest)?; @@ -636,7 +641,7 @@ fn run>(args: &[S]) -> Result<(), Failure> { let mut i = 0; while i < rest.len() { if rest.get(i).map(String::as_str) == Some("--cmd") { - let spec = rest.get(i + 1).ok_or("--cmd needs a value")?; + let spec = rest.get(i + 1).filter(|value| !value.starts_with("--")).ok_or("--cmd needs a value")?; let (id, params) = match spec.split_once('=') { Some((id, p)) => { (id.to_string(), serde_json::from_str::(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?) diff --git a/apps/wordcraft-cli/src/tests.rs b/apps/wordcraft-cli/src/tests.rs index c44143fb41..b22e4ffa05 100644 --- a/apps/wordcraft-cli/src/tests.rs +++ b/apps/wordcraft-cli/src/tests.rs @@ -497,6 +497,27 @@ fn command_line_template_wins_over_the_scripts_file() { assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE")); } +#[test] +fn cmd_value_missing_is_reported() { + let missing = std::env::temp_dir().join(format!( + "wc-cli-missing-cmd-{}-{}.docx", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos() + )); + assert!(!missing.exists()); + let missing = missing.to_string_lossy(); + for argv in [ + vec!["run", "--cmd"], + vec!["run", "--cmd", "--save", "out.docx"], + vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"], + vec!["run", "--cmd", "--bogus"], + vec!["run", "--cmd", "--file", &missing], + ] { + assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}"); + } + assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok()); +} + #[test] fn script_value_missing_is_reported() { let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string(); From caa4c4b11415a76f41c6ac91a53c50055b220bec Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 17 Nov 2026 08:10:58 +0100 Subject: [PATCH 54/99] Enter in a paragraph with a drop cap no longer copies the drop cap (#6793) Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/edit.rs | 17 ++++++++++++++- crates/doc/src/edit/tests.rs | 35 +++++++++++++++++++++++++++++++ crates/engine/src/tests/typing.rs | 22 +++++++++++++++++++ docs/typing-parity.md | 9 +++++++- 4 files changed, 81 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index 175210e031..14081425e1 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -727,9 +727,16 @@ impl Document { } /// Split the paragraph at `pos`; returns the start of the new (second) paragraph. + /// + /// A split after the first letters leaves the drop cap on the first paragraph only: the new + /// one is plain (Word: Enter makes a normal paragraph). A split at offset 0 is unchanged. + /// A drop cap that comes from a paragraph style, not the paragraph, is not cleared. pub fn split_paragraph(&mut self, pos: &Pos) -> Result { let i = pos.path.last(); - let tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?; + let mut tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?; + if pos.off > 0 { + clear_drop_cap(&mut tail.props); + } let bl = self.container_mut(pos.story, &pos.path)?; bl.insert((i + 1).min(bl.len()), para_block(tail)); Ok(Pos { story: pos.story, path: pos.path.with_last(i + 1), off: 0 }) @@ -1599,5 +1606,13 @@ impl Document { } } +/// Take the drop cap (and its options) off a paragraph's properties. +fn clear_drop_cap(props: &mut crate::props::ParaProps) { + props.drop_cap = None; + props.drop_cap_margin = None; + props.drop_cap_distance = None; + props.drop_cap_font = None; +} + #[cfg(test)] mod tests; diff --git a/crates/doc/src/edit/tests.rs b/crates/doc/src/edit/tests.rs index 0278396824..7b85dcc694 100644 --- a/crates/doc/src/edit/tests.rs +++ b/crates/doc/src/edit/tests.rs @@ -988,3 +988,38 @@ fn insert_fragment_remaps_conflicting_media_keys() { let remapped = para.objects.iter().find_map(|o| if let InlineObject::Image { media, .. } = o { Some(media.as_str()) } else { None }).unwrap(); assert_eq!(remapped, other_key); } + +/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first +/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged. +#[test] +fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() { + let drop_cap = |d: &Document, i: usize| { + let p = d.body.get(i).and_then(|b| b.as_para()).map(|p| p.props.clone()).unwrap_or_default(); + (p.drop_cap, p.drop_cap_margin, p.drop_cap_distance, p.drop_cap_font) + }; + let capped = |text: &str| { + let mut d = doc(&[text]); + if let Ok(p) = d.para_mut(StoryRef::Body, &Path::top(0)) { + p.props.drop_cap = Some(3); + p.props.drop_cap_margin = Some(true); + p.props.drop_cap_distance = Some(4.0); + p.props.drop_cap_font = Some("Serif".into()); + } + d + }; + let cap = (Some(3), Some(true), Some(4.0), Some("Serif".to_string())); + let plain = (None, None, None, None); + + let mut d = capped("Sugar and knowledge"); + d.split_paragraph(&Pos::body(0, 10)).unwrap(); + assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone())); + + let mut d = capped("Sugar"); + d.split_paragraph(&Pos::body(0, 5)).unwrap(); + assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone())); + + // At offset 0 nothing changes: both paragraphs keep the properties, as before. + let mut d = capped("Sugar"); + d.split_paragraph(&Pos::body(0, 0)).unwrap(); + assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap)); +} diff --git a/crates/engine/src/tests/typing.rs b/crates/engine/src/tests/typing.rs index 75fe31e744..3bab9d0bd2 100644 --- a/crates/engine/src/tests/typing.rs +++ b/crates/engine/src/tests/typing.rs @@ -4031,3 +4031,25 @@ fn issues_1281_1045_english_dialects_proof_typed_text() { let words: Vec<&str> = issues.as_array().unwrap().iter().filter(|i| i["kind"] == "spelling").filter_map(|i| i["text"].as_str()).collect(); assert_eq!(words, ["21th"]); } + +/// #6788: Enter in a paragraph with a drop cap makes a normal paragraph; only the first keeps +/// the cap (Word behaviour), for a dropped cap and one in the margin. +#[test] +fn enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph() { + for position in ["dropped", "margin"] { + let mut s = typed("Sugar and knowledge"); + run(&mut s, "insert.dropCap", json!({"position": position, "lines": 3, "distance": 4.0, "font": "Liberation Mono"})); + let first_has_cap = s.doc.body.first().and_then(|b| b.as_para()).is_some_and(|p| p.props.drop_cap == Some(3)); + assert!(first_has_cap, "{position}: the cap is set"); + run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 10}, "focus": {"block": 0, "off": 10}})); + run(&mut s, "text.newParagraph", json!({})); + let paras: Vec<_> = s.doc.body.iter().filter_map(|b| b.as_para()).collect(); + assert_eq!(paras.len(), 2, "{position}"); + let (first, second) = (¶s[0].props, ¶s[1].props); + assert_eq!(first.drop_cap, Some(3), "{position}: the first paragraph keeps its cap"); + assert_eq!(second.drop_cap, None, "{position}"); + assert_eq!(second.drop_cap_margin, None, "{position}"); + assert_eq!(second.drop_cap_distance, None, "{position}"); + assert_eq!(second.drop_cap_font, None, "{position}"); + } +} diff --git a/docs/typing-parity.md b/docs/typing-parity.md index ef72f3e2ec..f3e9551db1 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -1,6 +1,6 @@ # Typing parity with Word -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** trivial (Ctrl/Cmd+Shift+V pastes the formatting picked up with Ctrl/Cmd+Shift+C or the Format Painter, or text only when none was, #1537); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously trivial (Ctrl+K on a selection retypes it with a changed Text to display); previously trivial (equation `\int` + Space waits for its limits, `_x^y` then Space builds them and typing goes into the operand, and any character that can't continue `\name` corrects it, observed in Word for Windows on #4938, #4917); previously minor (English spelling by dialect from SCOWL 2026, CP2; previously trivial: a tracked heading or border-line AutoFormat replaces another author's formatting change; previously trivial: Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (highlight at a caret leaves the word alone, #4086); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial: tests and notes for the border-line, table, tab-indent and wide-space rules; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; previously trivial: a command that changes nothing is not an edit: no undo step, no unsaved changes, no relayout, and the redo stack survives it; previously trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** trivial (Enter in a paragraph with a drop cap makes a normal paragraph, #6788); previously trivial (Ctrl/Cmd+Shift+V pastes the formatting picked up with Ctrl/Cmd+Shift+C or the Format Painter, or text only when none was, #1537); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously trivial (Ctrl+K on a selection retypes it with a changed Text to display); previously trivial (equation `\int` + Space waits for its limits, `_x^y` then Space builds them and typing goes into the operand, and any character that can't continue `\name` corrects it, observed in Word for Windows on #4938, #4917); previously minor (English spelling by dialect from SCOWL 2026, CP2; previously trivial: a tracked heading or border-line AutoFormat replaces another author's formatting change; previously trivial: Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (highlight at a caret leaves the word alone, #4086); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial: tests and notes for the border-line, table, tab-indent and wide-space rules; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; previously trivial: a command that changes nothing is not an edit: no undo step, no unsaved changes, no relayout, and the redo stack survives it; previously trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 What Word does when you type, observed black-box (same keystrokes typed into Word and WordCraft, results read back paragraph by paragraph) and pinned by tests in @@ -611,10 +611,17 @@ two originally non-empty paragraphs retains the first paragraph's properties. Sy regressions cover body, header and cell containers, sections, outline/TOC membership, DOCX and Undo/Redo (Leaf #152). No new Word or native UI comparison was run. +## Enter in a drop cap paragraph + +| Keys | Word's result | Test | +|---|---|---| +| Enter after the first letters of a paragraph with a drop cap | the new paragraph is a normal paragraph without a drop cap; the cap stays on the first paragraph (#6788). Enter at offset 0 is left unchanged (not compared with Word). A drop cap that comes from a paragraph style is not cleared. | `enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph`, `split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only` | + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-15 | trivial | Enter in a paragraph with a drop cap: the new paragraph gets no drop cap (#6788); synthetic coverage, offset 0 unchanged and not compared with Word | | 2026-11-15 | trivial | Paste Formatting row: Ctrl/Cmd+Shift+V pastes the picked-up formatting, else text only; Ctrl/Cmd+Shift+C no longer arms the Format Painter (#1537, #4943); the chord's V release never pastes again (Shift up first); web text paste relies on the browser sending its paired Paste event, and the formatting paste drops that event only within about a second | | 2026-11-04 | trivial | Ctrl+K on a selection: a changed Text to display replaces the selected text before it is linked | | 2026-11-07 | trivial | Removing an already-empty paragraph preserves the following paragraph properties, mark and inline formatting. Delete, Backspace, selected marks, outline/TOC, DOCX and Undo/Redo have synthetic coverage (Leaf #152); no new Word or native acceptance run. | From a5753be57ed82dd42ab7f6cf488a2b0c1b2cb103 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 02:27:16 -0500 Subject: [PATCH 55/99] docs: prefer shared craft-libs implementations (#6862) --- AGENTS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 702f630871..698c64ef5b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,3 +138,7 @@ Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/targe - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. + +## Shared-library reuse + +Before implementing file formats, codecs, protocols or reusable UI components, check [storytold/craft-libs](https://github.com/storytold/craft-libs) and relevant open PRs; reuse or extend shared APIs instead of duplicating app-local implementations. Keep app-specific policy and adapters local, preserve behavior and format fidelity, security and resource limits, repository layering and regression tests, and document any shared-API gap rather than silently reducing functionality. From 221faf2901e3879fcdbe4af9932eb49fec53527a Mon Sep 17 00:00:00 2001 From: Michael Mu <69072633+MichaelMuClaude@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:40:33 +0800 Subject: [PATCH 56/99] KeyTips: two-letter command badges can be completed (#4498) (#4499) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/keytips.rs | 49 +++++++++++++++++++------- crates/ui-egui/src/keytips/tests.rs | 54 +++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/keytips.rs b/crates/ui-egui/src/keytips.rs index 9700c1859c..a6fc6c41fa 100644 --- a/crates/ui-egui/src/keytips.rs +++ b/crates/ui-egui/src/keytips.rs @@ -467,7 +467,10 @@ fn letters_for(app: &WordApp, tab: &str) -> Vec { out[i] = Some(c.to_string()); } } - // Pass 2: name-derived letters for everything still unassigned. + // Pass 2: name-derived letters for everything still unassigned. A control that finds no free + // letter is left for the two-letter pass below. + let mut named: Vec = Vec::new(); + let mut overflow: Vec = Vec::new(); for (i, ctl) in ctrls.iter().enumerate() { if out[i].is_some() { continue; @@ -481,21 +484,30 @@ fn letters_for(app: &WordApp, tab: &str) -> Vec { Some(c) => { used.push(c); out[i] = Some(c.to_string()); + named.push(i); } - None => { - // Two-letter badge fallback: a tab has at most ~20 controls, so this succeeds; - // the "?n" form keeps assignment total rather than panicking. - let two = ('A'..='Z').flat_map(|a| ('A'..='Z').map(move |b| format!("{a}{b}"))).find(|s| { - let mut ch = s.chars(); - let (a, b) = (ch.next().unwrap_or('?'), ch.next().unwrap_or('?')); - !out.iter().flatten().any(|o| o == s) && !reserved.contains(&a) && !reserved.contains(&b) - }); - let two = two.unwrap_or_else(|| format!("?{}", out.iter().flatten().count())); - used.extend(two.chars()); - out[i] = Some(two); - } + None => overflow.push(i), } } + // Pass 3: two-letter badges. No badge may be the start of another (Word's rule), or the short + // one runs the moment its letter is typed and the long one can never be completed (#4498). + // So the first letter of every two-letter badge is a letter no single-letter badge uses: the + // letters of the last name-derived badges are given up for that until the overflow fits. + let seconds: Vec = ('A'..='Z').filter(|c| !reserved.contains(c)).collect(); + let mut firsts: Vec = Vec::new(); + let mut two: Vec = overflow; + while !two.is_empty() && firsts.len() * seconds.len() < two.len() { + let Some(i) = named.pop() else { break }; + let letter = out[i].take().and_then(|l| l.chars().next()); + firsts.extend(letter); + two.push(i); + } + two.sort_unstable(); + let mut labels = firsts.iter().flat_map(|a| seconds.iter().map(move |b| format!("{a}{b}"))); + for i in two { + // "?n" keeps the assignment total, with nothing to run it, rather than panicking. + out[i] = Some(labels.next().unwrap_or_else(|| format!("?{i}"))); + } out.into_iter().map(Option::unwrap_or_default).collect() } @@ -639,6 +651,14 @@ pub fn handle_key(app: &mut WordApp, key: egui::Key) -> bool { let tab = app.ui.tab.clone(); let ls = letters_for(app, &tab); let ctrls = controls(&tab); + // Badges are never the start of one another, so a complete one is the one. + let name = format!("{}{name}", app.ui.keytip_prefix); + // The start of a two-letter badge: wait for its next letter, with + // KeyTips still on and only the badges it can complete showing (#4498). + if !ls.contains(&name) && ls.iter().any(|l| l.starts_with(&name)) { + app.ui.keytip_prefix = name; + return true; + } let mut hit: Option = None; for (ctl, l) in ctrls.into_iter().zip(ls) { if l == name { @@ -865,6 +885,9 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context, ui: &mut Ui) { return; } let cmds: Vec<(Rect, String)> = ui.data(|d| d.get_temp::>(rects_id())).unwrap_or_default(); + // After the start of a two-letter badge only the badges it can still complete show. + let prefix = app.ui.keytip_prefix.clone(); + let cmds = cmds.into_iter().filter(|(_, l)| app.ui.keytips != Phase::Commands || l.starts_with(&prefix)); for (r, l) in tabs.into_iter().chain(cmds) { badge(ui, r, &l); } diff --git a/crates/ui-egui/src/keytips/tests.rs b/crates/ui-egui/src/keytips/tests.rs index 582197669d..63926f7b7e 100644 --- a/crates/ui-egui/src/keytips/tests.rs +++ b/crates/ui-egui/src/keytips/tests.rs @@ -161,6 +161,60 @@ fn letters_are_unique_inside_every_tab() { } } +/// #4498: no badge is the start of another, on any tab, or the short one runs as soon as its +/// letter is typed and the long one can never be reached. +#[test] +fn no_badge_starts_another_badge() { + let mut a = app(); + a.run("insert.table", serde_json::json!({"rows": 2, "cols": 2})).unwrap(); + let (_, cmds) = letters(&a); + let mut two_letter = 0; + for (tab, ls) in &cmds { + for l in ls { + assert!(!l.is_empty() && !l.starts_with('?'), "{tab}: a control without a badge ({l:?})"); + two_letter += usize::from(l.chars().count() > 1); + let others = ls.iter().filter(|o| *o != l && o.starts_with(l.as_str())).count(); + assert_eq!(others, 0, "{tab}: badge {l} starts another badge in {ls:?}"); + } + } + assert!(two_letter > 0, "Home has more controls than letters, so some badges take two"); +} + +/// #4498: the first letter of a two-letter badge keeps KeyTips on and waits; the second runs +/// the command. A letter that completes nothing ends KeyTips and runs nothing. +#[test] +fn a_two_letter_badge_is_completed_by_its_second_letter() { + let key = |c: char| egui::Key::from_name(&c.to_string()).unwrap(); + let mut a = app(); + a.canvas.focused = false; + a.run("ui.tab", serde_json::json!({"tab": "Home"})).unwrap(); + let ls = letters_for(&a, "Home"); + let long: Vec<&String> = ls.iter().filter(|l| l.chars().count() == 2).collect(); + let target = *long.first().expect("Home has two-letter badges"); + let (first, second) = (target.chars().next().unwrap(), target.chars().nth(1).unwrap()); + let sibling = long.iter().find(|l| l.starts_with(first) && *l != &target).map(|l| l.chars().nth(1).unwrap()); + let before = a.session.doc.plain_text(wordcraft_doc::StoryRef::Body); + activate(&mut a); + assert!(handle_key(&mut a, egui::Key::H)); + assert_eq!(a.ui.keytips, Phase::Commands); + assert!(handle_key(&mut a, key(first))); + assert_eq!((a.ui.keytips, a.ui.keytip_prefix.as_str()), (Phase::Commands, first.to_string().as_str()), "waits for the second letter"); + assert!(handle_key(&mut a, key(second))); + assert_eq!(a.ui.keytips, Phase::Off, "the second letter completes it"); + assert!(a.ui.keytip_prefix.is_empty()); + assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before, "no letter reached the document"); + // The first letter then a second that completes nothing: off, and nothing runs. + let unused = ('A'..='Z').find(|c| !ls.contains(&format!("{first}{c}"))).unwrap(); + a.run("ui.tab", serde_json::json!({"tab": "Home"})).unwrap(); + activate(&mut a); + handle_key(&mut a, egui::Key::H); + handle_key(&mut a, key(first)); + assert!(handle_key(&mut a, key(unused))); + assert_eq!((a.ui.keytips, a.ui.keytip_prefix.as_str()), (Phase::Off, "")); + assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before); + assert!(sibling.is_none() || sibling != Some(second), "siblings of a prefix have distinct second letters"); +} + #[test] fn keytips_never_reuse_another_commands_shortcut_letter() { let a = app(); From aeb9704d823b18e804e0f16adfa9183f0848fe09 Mon Sep 17 00:00:00 2001 From: Bryan Mark Date: Tue, 17 Nov 2026 16:53:51 +0900 Subject: [PATCH 57/99] UI: CJK text gets an installed CJK font in builds without craft-fonts and craft-i18n (#4637) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tests.rs | 34 ++++++++++++++++++++ crates/ui-egui/src/theme.rs | 64 +++++++++++++++++++++++++++++++------ 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index d70823fb64..80d3c76920 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -357,6 +357,40 @@ fn non_latin_file_name_is_drawn_in_the_caption() { assert!(cjk.canvas.ime_faces.is_empty(), "CJK collections are not copied into the fallback list"); } +/// The CJK UI font a Japanese file name asks for is loaded and draws the name, also in a build +/// without craft-i18n's CJK catalogs and craft-fonts' CJK faces. There it was never loaded, and +/// the caption, like an input method's composition, showed boxes. +#[test] +fn a_japanese_file_name_is_drawn_in_the_caption() { + // A font to draw it with: an installed CJK font in a build without embedded CJK faces, or + // embedded faces that have the name's characters (embedded faces without them load no + // installed font for it). + let embedded = wordcraft_fonts::ui_cjk_fonts_for(false, false); + let drawable = if embedded.is_empty() { + wordcraft_fonts::system_cjk_ui_font_for(false, false, &[]).is_some() + } else { + wordcraft_fonts::ui_uncovered_cjk(&["日本語"], &embedded).is_empty() + }; + // macOS and Windows always have one (Hiragino, Yu Gothic), and CI runs these tests on both (the + // Print job), so there a missing font fails instead of hiding a regression. + assert!(drawable || cfg!(not(any(target_os = "macos", windows))), "macOS and Windows have a CJK font, but none draws 日本語"); + if !drawable { + eprintln!("skipped: no CJK font draws 日本語"); + return; + } + let ctx = egui::Context::default(); + let frame = |app: &mut WordApp| { + ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx())).drop_without_applying_deltas(); + }; + let mut a = app(); + a.session.path = Some("日本語.docx".into()); + // The fonts the name asks for load from the next frame. + frame(&mut a); + frame(&mut a); + assert!(a.want_system_cjk); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&crate::theme::semibold(13.0), "日本語")), "the caption draws the name"); +} + /// File › Recover draws the recovered documents' names with the interface faces: a Chinese /// name there was a row of boxes because nothing asked for the CJK UI font. (The Recent list /// has its own, `ensure_recent_fonts`.) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index a67814261f..03a040c658 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -695,7 +695,8 @@ fn system_arabic_font() -> Option<&'static wordcraft_fonts::SystemUiFont> { /// The installed CJK interface font for a Chinese (`hans`) or other interface, chosen once: /// `None` when the embedded faces already cover the interface text /// ([`cjk_font_text`](crate::i18n::Lang::cjk_font_text)). The font is picked for the catalogs' -/// missing characters, or for the language names when only those are missing. +/// missing characters, or for the language names when only those are missing; see +/// [`system_cjk_needed`]. #[cfg(not(target_arch = "wasm32"))] fn system_cjk_font(hans: bool, korean: bool) -> Option<&'static wordcraft_fonts::SystemUiFont> { static ZH: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -711,19 +712,41 @@ fn system_cjk_font(hans: bool, korean: bool) -> Option<&'static wordcraft_fonts: .get_or_init(|| { let embedded = wordcraft_fonts::ui_cjk_fonts_for(hans, korean); let (catalogs, names) = crate::i18n::Lang::cjk_font_text_for(hans, korean); - let mut needed = wordcraft_fonts::ui_uncovered_cjk(&catalogs, &embedded); - if needed.is_empty() { - needed = wordcraft_fonts::ui_uncovered_cjk(&[&names], &embedded); - if needed.is_empty() { - return None; - } - } + let needed = system_cjk_needed(&catalogs, &names, &embedded)?; log::debug!("interface: {} CJK characters lack an embedded glyph", needed.len()); - wordcraft_fonts::system_cjk_ui_font_for(hans, korean, &needed) + let found = wordcraft_fonts::system_cjk_ui_font_for(hans, korean, &needed); + if found.is_none() && needed.is_empty() && !hans && !korean { + // No Japanese or Chinese font installed: a Korean one (NanumGothic alone on Linux) + // still draws Korean document text. + return wordcraft_fonts::system_cjk_ui_font_for(false, true, &needed); + } + found }) .as_ref() } +/// The CJK characters an installed interface font is picked for: those of the catalogs, or of +/// the language names, that the embedded faces lack. `None` when the embedded faces draw them all. +/// +/// The interface asks for this font only when CJK is on screen: the interface language, or CJK +/// document text drawn as interface text (an input method's composition, a file name in the +/// caption). A build with neither craft-i18n's CJK catalogs nor craft-fonts' CJK faces has no CJK +/// text of its own to measure, and that text drew as boxes. It gets the font picked for the +/// language's own characters (an empty list: [`wordcraft_fonts::system_cjk_ui_font_for`] probes +/// one, `の` for a Japanese or other interface), or failing that a Korean font. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn system_cjk_needed(catalogs: &[&str], names: &str, embedded: &[&wordcraft_fonts::CraftFont]) -> Option> { + let needed = wordcraft_fonts::ui_uncovered_cjk(catalogs, embedded); + if !needed.is_empty() { + return Some(needed); + } + let needed = wordcraft_fonts::ui_uncovered_cjk(&[names], embedded); + if !needed.is_empty() { + return Some(needed); + } + embedded.is_empty().then(Vec::new) +} + #[cfg(not(target_arch = "wasm32"))] fn system_hant_font() -> Option<&'static wordcraft_fonts::SystemUiFont> { static HANT: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -1160,6 +1183,29 @@ mod tests { assert!(semi.iter().any(|n| n.starts_with("fallback ")), "the caption is painted with semibold"); } + /// A build without craft-i18n's CJK catalogs and craft-fonts' CJK faces has no CJK interface + /// text of its own, so the CJK UI font that CJK document text asks for (a composition, a file + /// name, a comment) was never loaded, and that text drew as boxes. It is now picked for the + /// language's own characters. + #[test] + fn cjk_text_gets_an_installed_cjk_font_in_a_build_without_one() { + assert_eq!(super::system_cjk_needed(&[], "English", &[]), Some(Vec::new()), "picked for the language's own characters"); + assert_eq!(super::system_cjk_needed(&["ファイル"], "English", &[]), Some(vec!['ァ', 'イ', 'フ', 'ル'])); + assert_eq!(super::system_cjk_needed(&[], "English 日本語", &[]), Some(vec!['日', '本', '語'])); + let embedded = wordcraft_fonts::ui_cjk_fonts_for(false, false); + if !embedded.is_empty() { + assert_eq!(super::system_cjk_needed(&[], "English", &embedded), None, "the embedded faces draw CJK"); + } else { + // macOS and Windows always have one, and CI runs these tests on both (the Print job). + let installed = wordcraft_fonts::system_cjk_ui_font_for(false, false, &[]).is_some(); + assert!(installed || cfg!(not(any(target_os = "macos", windows))), "macOS and Windows have a CJK font"); + if installed { + let defs = super::font_definitions_language(false, false, false, true); + assert!(defs.font_data.keys().any(|n| n.starts_with("system ")), "the installed CJK font follows the interface fonts"); + } + } + } + /// #656: dialog primary buttons, the Discord pill, the table eraser and the Navigation search /// highlight take their colours from the theme, not fixed light-theme values. #[test] From d7215f4441ee9371442fcd6343c8e85ab74d1348 Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Tue, 17 Nov 2026 16:06:43 +0800 Subject: [PATCH 58/99] fix(ui): allow Start at 0 in Page Number Format (#4911) (#4927) --- .../docx/tests/it/section_page_number_type.rs | 14 ++-- .../src/dialogs/dialogs_layout/page.rs | 4 +- .../src/dialogs/dialogs_layout/tests.rs | 66 +++++++++++++++++++ 3 files changed, 78 insertions(+), 6 deletions(-) diff --git a/crates/docx/tests/it/section_page_number_type.rs b/crates/docx/tests/it/section_page_number_type.rs index 461f1581f7..a11e965fc8 100644 --- a/crates/docx/tests/it/section_page_number_type.rs +++ b/crates/docx/tests/it/section_page_number_type.rs @@ -30,10 +30,16 @@ fn page_number_type_is_kept_even_when_it_only_repeats_the_defaults() { #[test] fn page_number_type_with_a_start_and_format_still_round_trips() { - let body = r#"One"#; - let d = wordcraft_docx::read(&docx(body)).unwrap(); - let xml = document_xml(&wordcraft_docx::write(&d).unwrap()); - assert!(xml.contains(r#"w:fmt="upperRoman""#) && xml.contains(r#"w:start="3""#), "{xml}"); + for (format, start) in [("decimal", 0), ("upperRoman", 3)] { + let page_number_type = format!(r#""#); + let body = format!(r#"One{page_number_type}"#); + let d = wordcraft_docx::read(&docx(&body)).unwrap(); + assert_eq!(d.last_section.page_num_start, Some(start)); + let saved = wordcraft_docx::write(&d).unwrap(); + let xml = document_xml(&saved); + assert!(xml.contains(&page_number_type), "{xml}"); + assert_eq!(wordcraft_docx::read(&saved).unwrap().last_section.page_num_start, Some(start)); + } } #[test] diff --git a/crates/ui-egui/src/dialogs/dialogs_layout/page.rs b/crates/ui-egui/src/dialogs/dialogs_layout/page.rs index 3c3b8381b4..9e530e9c6b 100644 --- a/crates/ui-egui/src/dialogs/dialogs_layout/page.rs +++ b/crates/ui-egui/src/dialogs/dialogs_layout/page.rs @@ -240,7 +240,7 @@ impl PageNumbersForm { section: wordcraft_engine::cmd::page::section_index_of_focus(&app.session), format: sp.page_num_format.ooxml().to_string(), cont: sp.page_num_start.is_none(), - start: sp.page_num_start.unwrap_or(1).clamp(1, 100_000), + start: sp.page_num_start.unwrap_or(1).min(100_000), } } @@ -275,7 +275,7 @@ pub(super) fn page_numbers_ui(app: &mut WordApp, ui: &mut Ui, f: &mut PageNumber ui.radio_value(&mut f.cont, true, tl!("Continue from previous section")); ui.horizontal(|ui| { ui.radio_value(&mut f.cont, false, tl!("Start at:")); - ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000)); + ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(0..=100_000)); }); }); let (ok, cancel) = buttons(ui, "OK", true); diff --git a/crates/ui-egui/src/dialogs/dialogs_layout/tests.rs b/crates/ui-egui/src/dialogs/dialogs_layout/tests.rs index ff35ed322a..671a106b4f 100644 --- a/crates/ui-egui/src/dialogs/dialogs_layout/tests.rs +++ b/crates/ui-egui/src/dialogs/dialogs_layout/tests.rs @@ -93,6 +93,72 @@ fn page_numbers_dialog_sets_the_format_and_start() { assert_eq!((f.section, f.format.as_str(), f.start), (1, "lowerRoman", 9)); } +/// #4911: zero is an explicit start, distinct from continuing the previous section. +#[test] +fn page_numbers_dialog_preserves_zero_and_continue() { + let mut a = app(); + a.run("ui.dialog", json!({"name": "pageNumbers"})).unwrap(); + let LayoutDialog::PageNumbers(f) = form(&mut a) else { panic!("page numbers") }; + assert!(f.cont); + assert_eq!(f.start, 1, "unspecified numbering still defaults to one"); + for start in [0, 1, 100_000] { + a.run("layout.pageNumberFormat", json!({"start": start})).unwrap(); + assert_eq!(a.session.doc.last_section.page_num_start, Some(start)); + a.run("ui.dialog", json!({"name": "pageNumbers"})).unwrap(); + let LayoutDialog::PageNumbers(f) = form(&mut a) else { panic!("page numbers") }; + assert!(!f.cont); + assert_eq!(f.start, start); + assert_eq!(f.params()["start"], json!(start)); + a.run("layout.pageNumberFormat", f.params()).unwrap(); + assert_eq!(a.session.doc.last_section.page_num_start, Some(start)); + a.run("ui.dialog", json!({"name": "pageNumbers"})).unwrap(); + let LayoutDialog::PageNumbers(mut f) = form(&mut a) else { panic!("page numbers") }; + assert!(!f.cont); + assert_eq!(f.start, start, "reopening preserves the explicit start"); + f.cont = true; + assert_eq!(f.params()["start"], serde_json::Value::Null); + a.run("layout.pageNumberFormat", f.params()).unwrap(); + assert_eq!(a.session.doc.last_section.page_num_start, None); + a.run("ui.dialog", json!({"name": "pageNumbers"})).unwrap(); + let LayoutDialog::PageNumbers(f) = form(&mut a) else { panic!("page numbers") }; + assert!(f.cont); + assert_eq!(f.start, 1, "continuing does not become an explicit zero"); + } +} + +/// #4911: typing zero in Start at and pressing OK restarts numbering from zero. +#[test] +fn page_numbers_dialog_accepts_typed_zero() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + + let mut a = app(); + a.run("ui.language", json!({"value": "en"})).unwrap(); + a.run("ui.dialog", json!({"name": "pageNumbers"})).unwrap(); + // The dialog's existing numeric input and format picker lack accessible names. + let mut h = egui_kittest::Harness::builder().with_accessibility_check(false).with_size(egui::vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + a, + ); + h.run_steps(4); + h.get_by_label("Start at:").click(); + h.run_steps(2); + h.get_by_role(Role::SpinButton).click(); + h.run_steps(2); + h.get_by_role(Role::SpinButton).type_text("0"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.doc.last_section.page_num_start, None, "typing does not apply before OK"); + + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "OK closes the dialog"); + assert_eq!(h.state().session.doc.last_section.page_num_start, Some(0)); +} + /// #755: the Line Numbers "From text" distance and the Hyphenation zone follow the /// File › Options unit (centimeters here); `params` sends points whatever the unit. #[test] From 8fa2895202f0c69da5a6a4138e77df8969ede95b Mon Sep 17 00:00:00 2001 From: naxvog Date: Tue, 17 Nov 2026 09:26:57 +0100 Subject: [PATCH 59/99] Layout: pin the leading-float space-before rule's edge cases (follow-up to #5440) (#5999) --- crates/layout/src/tests/float_top.rs | 122 +++++++++++++++++++++------ 1 file changed, 94 insertions(+), 28 deletions(-) diff --git a/crates/layout/src/tests/float_top.rs b/crates/layout/src/tests/float_top.rs index fb555de219..de0b095e12 100644 --- a/crates/layout/src/tests/float_top.rs +++ b/crates/layout/src/tests/float_top.rs @@ -3,36 +3,59 @@ //! the same place for 0 pt and 12 pt before. use super::lay; -use crate::{Arc, Placed, StoryRef}; +use crate::{Arc, DocLayout, LayoutCache, LayoutOptions, Placed, StoryRef, ViewMode, layout}; use wordcraft_doc::para::{Anchor, InlineObject}; use wordcraft_doc::props::TableFloat; use wordcraft_doc::{Block, Document, Paragraph, Table, para_block}; -/// Where the lines of body block `block` start on page one. -fn line_y(d: &Document, block: u32) -> f32 { - lay(d).pages[0] - .items - .iter() - .find_map(|i| match i { - Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y), - _ => None, - }) - .unwrap() +/// Positions are compared to a hundredth of a point; a kept 12 pt space before shows as at least +/// 11.99 pt more. +const EPS: f32 = 0.01; +const KEPT: f32 = 12.0 - EPS; + +/// What the paragraph after the table holds. +enum Content<'a> { + Empty, + /// Nothing but this zero-width marker. + Marker(&'a InlineObject), + Text(&'static str), } -/// `table` (a floating one) or nothing, then a paragraph of `text` with `before`, then "After". -fn document(table: bool, text: &str, before: f32) -> Document { - let mut p = Paragraph::with_text(text, Default::default()); - // "#" stands for a bookmark, a zero-width marker. - if text == "#" { - p = Paragraph::new(); - p.insert_object(0, InlineObject::BookmarkStart { name: "_GoBack".into() }, &Default::default()).unwrap(); - } +/// The page and top of body block `block`'s lines. +fn line_at(l: &DocLayout, block: u32) -> (usize, f32) { + l.pages + .iter() + .enumerate() + .find_map(|(pi, pg)| { + pg.items.iter().find_map(|i| match i { + Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some((pi, *y)), + _ => None, + }) + }) + .unwrap_or_else(|| panic!("no lines laid out for body block {block}")) +} + +/// Where body block `block`'s lines start (on whatever page). +fn line_y(d: &Document, block: u32) -> f32 { + line_at(&lay(d), block).1 +} + +/// A floating table `table` wide (or none), then a paragraph of `content` with `before`, then "After". +fn document(table: Option, content: &Content<'_>, before: f32) -> Document { + let mut p = match content { + Content::Empty => Paragraph::new(), + Content::Text(text) => Paragraph::with_text(text, Default::default()), + Content::Marker(obj) => { + let mut p = Paragraph::new(); + p.insert_object(0, (*obj).clone(), &Default::default()).unwrap(); + p + } + }; p.props.space_before = Some(before); let mut d = Document::new(); d.body = vec![para_block(p), para_block(Paragraph::with_text("After", Default::default()))]; - if table { - let mut t = Table::new(1, 1, 200.0); + if let Some(w) = table { + let mut t = Table::new(1, 1, w); t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("Table", Default::default()))]; t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() }); d.body.insert(0, Arc::new(Block::Table(t))); @@ -42,12 +65,55 @@ fn document(table: bool, text: &str, before: f32) -> Document { #[test] fn an_empty_paragraph_after_a_floating_table_at_the_page_top_takes_no_space_before() { - let empty = line_y(&document(true, "", 12.0), 2); - let plain = line_y(&document(false, "", 0.0), 1); - assert!((empty - plain).abs() < 0.01, "after the empty anchor at {empty}, with no table nor space before at {plain}"); - // A bookmark alone doesn't make it a paragraph with text. - assert!((line_y(&document(true, "#", 12.0), 2) - plain).abs() < 0.01); + let empty = line_y(&document(Some(200.0), &Content::Empty, 12.0), 2); + let plain = line_y(&document(None, &Content::Empty, 0.0), 1); + assert!((empty - plain).abs() < EPS, "after the empty anchor at {empty}, with no table nor space before at {plain}"); // One with text keeps it, and so does an empty first paragraph with no table before it. - assert!(line_y(&document(true, "Text", 12.0), 2) > empty + 11.99); - assert!(line_y(&document(false, "", 12.0), 1) > plain + 11.99); + assert!(line_y(&document(Some(200.0), &Content::Text("Text"), 12.0), 2) > empty + KEPT); + assert!(line_y(&document(None, &Content::Empty, 12.0), 1) > plain + KEPT); +} + +#[test] +fn a_paragraph_of_markers_only_after_the_leading_float_takes_no_space_before() { + let empty = line_y(&document(Some(200.0), &Content::Empty, 12.0), 2); + let markers = [ + InlineObject::BookmarkStart { name: "_GoBack".into() }, + InlineObject::CommentStart { id: 1 }, + InlineObject::PermStart { id: 1, group: "everyone".into(), editor: String::new() }, + ]; + for m in markers { + let y = line_y(&document(Some(200.0), &Content::Marker(&m), 12.0), 2); + assert!((y - empty).abs() < EPS, "{m:?}: after it at {y}, after an empty anchor at {empty}"); + } +} + +#[test] +fn an_empty_paragraph_below_a_full_width_leading_float_takes_no_space_before() { + // Not checked against Word (no fixture has it): the rule doesn't look at whether the paragraph + // sits beside the table, so below one as wide as the text it drops its space before too. + let full = |before| line_y(&document(Some(468.0), &Content::Empty, before), 2); + assert!((full(12.0) - full(0.0)).abs() < EPS, "after it with 12 pt before at {}, with none at {}", full(12.0), full(0.0)); +} + +#[test] +fn web_view_and_a_floating_table_on_a_later_page_keep_the_space_before() { + // Web view lays floating tables out in the text: the paragraph after one keeps its space before. + let web = |before| { + let opts = LayoutOptions { view: ViewMode::Web, web_width: 500.0, ..Default::default() }; + line_at(&layout(&document(Some(200.0), &Content::Empty, before), &mut LayoutCache::new(), &opts), 2).1 + }; + assert!(web(12.0) > web(0.0) + KEPT, "web view: after it with 12 pt before at {}, with none at {}", web(12.0), web(0.0)); + // A filler paragraph whose space after leaves less room than the table needs: the table goes to + // the top of page two with its empty anchor, which isn't the document's leading float. + let body_h = lay(&Document::new()).pages[0].body.h; + let later = |before| { + let mut d = document(Some(200.0), &Content::Empty, before); + let mut filler = Paragraph::with_text("Filler", Default::default()); + filler.props.space_after = Some(body_h - 20.0); + d.body.insert(0, para_block(filler)); + let l = lay(&d); + assert_eq!(line_at(&l, 2).0, 1, "the empty anchor is on page two"); + line_at(&l, 3).1 + }; + assert!(later(12.0) > later(0.0) + KEPT, "later page: after it with 12 pt before at {}, with none at {}", later(12.0), later(0.0)); } From ebe2f430d8b63229e158a348fec07e87117018ed Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Tue, 17 Nov 2026 05:40:28 -0300 Subject: [PATCH 60/99] UI: Invalidate Home Styles preview textures on font changes (#5957) (#6029) Co-authored-by: Shabir Ahmad --- crates/ui-egui/src/previews.rs | 24 +++++++++++++++++----- crates/ui-egui/src/previews/tests.rs | 30 ++++++++++++++++++++++++++++ docs/ui-parity.md | 1 + 3 files changed, 50 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/previews.rs b/crates/ui-egui/src/previews.rs index 1ff99e1073..e618034cf8 100644 --- a/crates/ui-egui/src/previews.rs +++ b/crates/ui-egui/src/previews.rs @@ -180,13 +180,20 @@ fn font_key(name: &str, ppp: f32) -> String { } impl Previews { + /// Ensure the cached family lists and style preview textures match the current font generation. + fn check_fonts(&mut self) { + let generation = wordcraft_fonts::FontDb::global().generation(); + if self.font_gen != generation { + self.fonts_changed(); + } + } + /// The font list: installed families, each by its name in the interface language when it has /// one (宋体 for SimSun in Chinese, #505), like Word's. pub fn families(&mut self) -> Vec { + self.check_fonts(); let lang = crate::i18n::current().code(); - let generation = wordcraft_fonts::FontDb::global().generation(); - if self.families.as_ref().is_none_or(|(l, _)| *l != lang) || self.font_gen != generation { - self.font_gen = generation; + if self.families.as_ref().is_none_or(|(l, _)| *l != lang) { let db = wordcraft_fonts::FontDb::global(); let mut f: Vec = db.families_in(lang).into_iter().filter(|f| !f.starts_with('.')).collect(); for w in [wordcraft_doc::styles::BODY_FONT, wordcraft_doc::styles::HEADING_FONT] { @@ -237,11 +244,15 @@ impl Previews { self.english_names.get(shown).cloned().unwrap_or_else(|| shown.to_string()) } - /// Fonts were added or removed: list the families again. The font menus' entries see the - /// change themselves ([`FontAtlas`]), in every window. + /// Fonts were added or removed: list the families again and clear cached style preview + /// textures so any style rendered with a fallback face refreshes with newly available fonts. + /// The font menus' entries see the change themselves ([`FontAtlas`]), in every window. pub fn fonts_changed(&mut self) { self.families = None; self.east_asian = None; + // Style previews may have been rasterised with a fallback face before a font was installed. + self.tex.clear(); + self.font_gen = wordcraft_fonts::FontDb::global().generation(); } /// A closure drawing a font-menu entry in its own face, from the fonts' atlas. @@ -299,7 +310,10 @@ impl Previews { }) } + /// Look up a cached preview texture under `key`, or render and insert it if missing. + /// Invalidates the cache first if the font generation has changed. pub(crate) fn get_or(&mut self, ctx: &egui::Context, key: &str, make: impl FnOnce() -> Option) -> Option { + self.check_fonts(); if let Some(t) = self.tex.get(key) { return Some(t.clone()); } diff --git a/crates/ui-egui/src/previews/tests.rs b/crates/ui-egui/src/previews/tests.rs index 7a56434542..271196437b 100644 --- a/crates/ui-egui/src/previews/tests.rs +++ b/crates/ui-egui/src/previews/tests.rs @@ -64,6 +64,36 @@ fn gallery_style(name: &str) -> wordcraft_doc::styles::Style { wordcraft_doc::styles::Style { id: "Backfill".into(), name: name.into(), quick: true, priority: Some(0), ..Default::default() } } +/// Seeded style preview textures are invalidated when fonts change so that newly available +/// faces replace fallback fonts used in earlier renders (#5957). +#[test] +fn font_changes_invalidate_cached_style_preview_textures() { + let ctx = egui::Context::default(); + let mut previews = Previews::default(); + let texture = ctx.load_texture("test-style-preview", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), egui::TextureOptions::LINEAR); + previews.tex.insert("style:Normal:cached".into(), texture); + previews.fonts_changed(); + assert!(previews.tex.is_empty(), "a new font can replace the fallback used by cached style previews"); +} + +/// Previews instances (such as other open windows) that missed an active `watch_fonts` call +/// invalidate their cached preview textures on their next lookup once the font generation advances (#5957). +#[test] +fn stale_previews_invalidate_on_next_lookup() { + let ctx = egui::Context::default(); + let mut previews = Previews::default(); + let texture = ctx.load_texture("test-style-preview", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), egui::TextureOptions::LINEAR); + previews.tex.insert("style:Normal:cached".into(), texture); + // Simulate this Previews instance having rendered at an older font generation. + previews.font_gen = wordcraft_fonts::FontDb::global().generation().wrapping_sub(1); + let mut made = false; + let _ = previews.get_or(&ctx, "style:Normal:cached", || { + made = true; + Some(egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE])) + }); + assert!(made, "the cached preview was invalidated and re-rendered because the font generation changed"); +} + /// Regression test for #2: a style gallery label longer than its tile was painted at full width /// and ran into the neighbouring tiles; it is now cut with an ellipsis to fit the tile. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2fb2379831..c4b899b397 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -134,6 +134,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-11-14 | trivial | Save As and Export (also the formats on the Print page) offer Browse in WordCraft… on Linux/BSD, as Open does; exporting there lists Export's formats as the types, whose extension replaces a known document extension on the name; an export refusal or failure shows on the Export page, as Save As's does (#3535) | | 2026-11-16 | trivial | Language dialog whole-document OK: Do not check sent only when clicked; `review.language` document scope returns the caret result with `scope`; glossary skipped while tracking formatting (result says `glossarySkipped`) (#3518) | | 2026-11-14 | trivial | Language dialog: Apply to the whole document sets the proofing language or Do not check for every story (body, headers, footers, notes, comments, text boxes, tables, glossary) in one undo step; `review.language` takes `scope: "document"` (#3518) | +| 2026-11-10 | trivial | Home Styles gallery previews invalidate cached raster textures when the font database changes (#5957) | | 2026-10-26 | trivial | Dialog sections: 13 dialogs group related controls in theme-aware panels with indented settings; tall dialogs scroll only when needed (#4035, #4038) | | 2026-11-12 | trivial | Clipboard: a copied picture is published as PNG (and HTML where the host writes it); WordCraft's own paste still keeps the original fragment, and a copy of only shapes carries no HTML or RTF (#6205). Native external-app paste remains untested. | | 2026-11-07 | trivial | Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word, instead of jumping to that position in the document (#5853) | From a216825578993f63a334f8bfd3932afb14b1b483 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:57:16 +0100 Subject: [PATCH 61/99] M14: keep selected file names intact in the built-in browser (#6777) --- crates/ui-egui/src/file_browser.rs | 80 +++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_browser.rs b/crates/ui-egui/src/file_browser.rs index 897db5b3a9..48b79efed8 100644 --- a/crates/ui-egui/src/file_browser.rs +++ b/crates/ui-egui/src/file_browser.rs @@ -144,6 +144,8 @@ pub(crate) struct FileBrowser { listing: Result, /// The highlighted entry. selected: Option, + /// The highlighted entry was a folder when it was selected. + selected_is_dir: bool, note: Note, focus_name: bool, } @@ -182,6 +184,7 @@ impl FileBrowser { exports, listing: Ok(Listing::default()), selected: None, + selected_is_dir: false, note: Note::None, focus_name: true, }; @@ -199,6 +202,7 @@ impl FileBrowser { self.location = dir.to_string_lossy().into_owned(); self.dir = dir; self.selected = None; + self.selected_is_dir = false; self.note = Note::None; } @@ -222,11 +226,13 @@ impl FileBrowser { /// pick. Save adds the chosen type's extension to a name without one (an export replaces a /// known document extension with the type's) and asks once more before replacing a file; Open wants a file that exists. pub(crate) fn accept(&mut self) -> Step { - if let Some(dir) = self.selected.take().filter(|p| p.is_dir()) { + if let Some(dir) = self.selected.clone().filter(|p| p.is_dir()) { self.navigate(dir); return Step::Stay; } - let Some(mut path) = resolve(&self.dir, &self.name) else { return Step::Stay }; + // A removed folder remains a folder selection, not a proposed file name. + let selected_file = self.selected.clone().filter(|_| !self.selected_is_dir); + let Some(mut path) = selected_file.or_else(|| resolve(&self.dir, &self.name)) else { return Step::Stay }; if path.is_dir() { self.name.clear(); self.navigate(path); @@ -262,6 +268,7 @@ impl FileBrowser { /// A click on an entry: highlight it, and a file's name goes into the file name field. fn select(&mut self, e: &Entry) { self.selected = Some(e.path.clone()); + self.selected_is_dir = e.dir; if !e.dir { self.name = e.name.clone(); } @@ -490,6 +497,7 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option> } if r.changed() { b.selected = None; + b.selected_is_dir = false; b.note = Note::None; } let before = b.filter; @@ -602,6 +610,74 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A selected file keeps its exact name for Open and both steps of Save's replacement check. + #[test] + fn selecting_a_file_preserves_leading_spaces() { + let dir = scratch("selected-path"); + let selected = dir.join(" report.docx"); + let sibling = dir.join("report.docx"); + std::fs::write(&selected, b"selected original").unwrap(); + std::fs::write(&sibling, b"sibling original").unwrap(); + for save in [false, true] { + let req = if save { + FileDialogRequest::Save { name: "Draft.docx".into(), dir: None } + } else { + FileDialogRequest::Open { purpose: "document".into() } + }; + let mut browser = FileBrowser::new(req, AfterPick::OpenDocument { document: 0 }, dir.clone(), false); + let entry = browser.listing.as_ref().unwrap().entries.iter().find(|entry| entry.path == selected).unwrap().clone(); + browser.select(&entry); + if save { + assert_eq!(browser.accept(), Step::Stay, "Save still asks before replacing the selected file"); + assert_eq!(browser.note, Note::Replace(selected.clone())); + } + assert_eq!(browser.accept(), Step::Pick(selected.clone())); + assert_eq!(std::fs::read(&selected).unwrap(), b"selected original"); + assert_eq!(std::fs::read(&sibling).unwrap(), b"sibling original"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// A folder selection keeps its kind even if the folder disappears before Save. + #[test] + fn a_selected_folder_never_replaces_the_typed_save_name() { + for removed in [false, true] { + let dir = scratch(if removed { "selected-folder-removed" } else { "selected-folder-live" }); + let folder = dir.join("Drafts"); + std::fs::create_dir(&folder).unwrap(); + let req = FileDialogRequest::Save { name: "chapter.docx".into(), dir: None }; + let mut browser = FileBrowser::new(req, AfterPick::OpenDocument { document: 0 }, dir.clone(), false); + let entry = browser.listing.as_ref().unwrap().entries.iter().find(|entry| entry.path == folder).unwrap().clone(); + browser.select(&entry); + assert_eq!(browser.name, "chapter.docx"); + if removed { + std::fs::remove_dir(&folder).unwrap(); + assert_eq!(browser.accept(), Step::Pick(dir.join("chapter.docx"))); + assert!(!dir.join("Drafts.docx").exists()); + } else { + assert_eq!(browser.accept(), Step::Stay); + assert_eq!(browser.dir, folder); + } + let _ = std::fs::remove_dir_all(&dir); + } + } + + /// A selected file still names the exact Save target after external deletion. + #[test] + fn a_removed_selected_file_keeps_its_exact_save_path() { + let dir = scratch("removed-selected-file"); + let selected = dir.join(" report.docx"); + std::fs::write(&selected, b"original").unwrap(); + let req = FileDialogRequest::Save { name: "Draft.docx".into(), dir: None }; + let mut browser = FileBrowser::new(req, AfterPick::OpenDocument { document: 0 }, dir.clone(), false); + let entry = browser.listing.as_ref().unwrap().entries.iter().find(|entry| entry.path == selected).unwrap().clone(); + browser.select(&entry); + std::fs::remove_file(&selected).unwrap(); + assert_eq!(browser.accept(), Step::Pick(selected)); + assert_eq!(browser.note, Note::None); + let _ = std::fs::remove_dir_all(&dir); + } + /// The host can't show a system dialog (#576): Save As carries on in the built-in browser, /// and its answer saves the document. #[test] From de694152a97983fe61266c81b5c71bbb29a97f3e Mon Sep 17 00:00:00 2001 From: keithcsqueensu <92232107+keithcsqueensu@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:13:06 -0500 Subject: [PATCH 62/99] Equations: an empty shown n-ary limit survives linear text (#6076) (#6085) --- crates/doc/src/math.rs | 5 +++-- crates/doc/tests/linear_empty_limits.rs | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 crates/doc/tests/linear_empty_limits.rs diff --git a/crates/doc/src/math.rs b/crates/doc/src/math.rs index adf66a6236..568bd1c668 100644 --- a/crates/doc/src/math.rs +++ b/crates/doc/src/math.rs @@ -610,11 +610,12 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) { } MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => { s.push(*chr); - if !sub_hide && !sub.is_empty() { + // A shown limit is written even when empty (`_()`): left out, it reads back hidden (#6076). + if !sub_hide { s.push('_'); lin_script(sub, s, depth); } - if !sup_hide && !sup.is_empty() { + if !sup_hide { s.push('^'); lin_script(sup, s, depth); } diff --git a/crates/doc/tests/linear_empty_limits.rs b/crates/doc/tests/linear_empty_limits.rs new file mode 100644 index 0000000000..208e22849a --- /dev/null +++ b/crates/doc/tests/linear_empty_limits.rs @@ -0,0 +1,24 @@ +//! An n-ary operator's empty but shown limit survives linear text (#6076): half-typed `∑_` has an +//! empty lower limit that is shown, and `to_linear` writes it as `_()`. Left out, it reads back as a +//! hidden limit. + +use wordcraft_doc::math::{MNode, MRun, parse_linear, to_linear}; + +#[test] +fn an_empty_shown_limit_prints_back_the_same() { + for s in ["∑_", "∑^", "∫_0^▒x", "∑_()^n▒i"] { + let n = parse_linear(s); + assert_eq!(parse_linear(&to_linear(&n)), n, "{s} → {}", to_linear(&n)); + } +} + +#[test] +fn hidden_and_filled_limits_print_as_before() { + let nary = |sub_hide, sup_hide, sub: &str, sup: &str| { + let arg = |t: &str| if t.is_empty() { Vec::new() } else { vec![MNode::Run(MRun::new(t))] }; + vec![MNode::Nary { chr: '∑', lim_loc: None, grow: false, sub_hide, sup_hide, sub: arg(sub), sup: arg(sup), e: arg("x") }] + }; + assert_eq!(to_linear(&nary(true, true, "", "")), "∑▒x"); + assert_eq!(to_linear(&nary(false, false, "i", "n")), "∑_i^n▒x"); + assert_eq!(to_linear(&nary(false, true, "", "")), "∑_()▒x"); +} From 8fced5d045bc85c6a75931e6ed7704172e02509c Mon Sep 17 00:00:00 2001 From: Senura Dissanayake Date: Tue, 17 Nov 2026 10:24:06 +0100 Subject: [PATCH 63/99] Compare: "Show changes at:" keeps its labels on one line (#6046) (#6145) --- crates/ui-egui/src/dialogs/dialogs_review.rs | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/ui-egui/src/dialogs/dialogs_review.rs b/crates/ui-egui/src/dialogs/dialogs_review.rs index d5977dbadb..be3d084533 100644 --- a/crates/ui-egui/src/dialogs/dialogs_review.rs +++ b/crates/ui-egui/src/dialogs/dialogs_review.rs @@ -256,6 +256,9 @@ fn compare_ui(app: &mut WordApp, ui: &mut Ui, f: &mut CompareForm) -> bool { crate::rtl::Table::new("compare_show").columns(2).spacing(vec2(24.0, 2.0)).top().show(ui, |t| { t.row(|r| { r.cell(|ui| { + // Not the grid's last column: it starts at the grid's minimum cell width, so + // text that wraps would wrap to that and keep the column that narrow (#6046). + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); crate::rtl::vertical(ui, |ui| { heading(ui, "Show changes at:"); ui.radio_value(&mut f.character_level, false, tl!("Word level")); @@ -916,6 +919,35 @@ mod tests { assert!(texts(&h).iter().any(|t| t.contains("(none)")), "no matches: the hint shows"); } + /// #6046: Compare › More shows "Show changes at:" and its two choices each on one line. The + /// column is not the grid's last, so it first gets the grid's minimum cell width; wrapped to + /// that, its text broke after every few letters and the column stayed that narrow. + #[test] + fn compare_more_keeps_the_show_changes_at_column_on_one_line() { + use egui_kittest::kittest::Queryable; + let mut app = app("Original text."); + app.run("review.compare", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h.get_by_label("More >>").click(); + h.run_steps(4); + let one_line = h.get_by_label("New document").rect().height(); + for label in ["Show changes at:", "Word level", "Character level"] { + let r = h.get_by_label(label).rect(); + assert!(r.height() <= one_line + 1.0, "{label} wraps: {r:?}, one line is {one_line}"); + } + // The next column starts after the widest of them. + let (left, right) = (h.get_by_label("Character level").rect(), h.get_by_label("Show changes in:").rect()); + assert!(right.left() >= left.right(), "the columns overlap: {left:?} {right:?}"); + } + /// #2848 through the real dialog: tick "Add a period with double-space" on the AutoFormat As /// You Type tab, press OK, and a double Space typed in the page makes a period. #[test] From 53e05c242031a574af1af82efe38ba1e32ddaa2e Mon Sep 17 00:00:00 2001 From: Ahmad Bagheri Date: Tue, 17 Nov 2026 13:10:08 +0330 Subject: [PATCH 64/99] Linux: draw on the GPU that drives the screen (#6016) (#6158) --- apps/wordcraft/src/linux_gpu.rs | 298 ++++++++++++++++++++++++++++ apps/wordcraft/src/linux_gpu/drm.rs | 237 ++++++++++++++++++++++ apps/wordcraft/src/main.rs | 9 + 3 files changed, 544 insertions(+) create mode 100644 apps/wordcraft/src/linux_gpu.rs create mode 100644 apps/wordcraft/src/linux_gpu/drm.rs diff --git a/apps/wordcraft/src/linux_gpu.rs b/apps/wordcraft/src/linux_gpu.rs new file mode 100644 index 0000000000..198708f366 --- /dev/null +++ b/apps/wordcraft/src/linux_gpu.rs @@ -0,0 +1,298 @@ +//! Linux: draw on the GPU that drives the screen. +//! +//! egui-wgpu picks the discrete GPU by default (`PowerPreference::HighPerformance`). On a laptop +//! whose integrated GPU drives the panel, every frame drawn on the discrete one is copied across +//! to it, and the discrete GPU leaves its idle state whenever the window redraws: on an Intel HD +//! 530 + NVIDIA Quadro M4000M laptop, from 7 W at P8 to over 20 W at P0/P1. Forcing the integrated +//! GPU instead breaks desktops whose screen is on the discrete card (storytold/pdfcraft#96), and a +//! desktop with a monitor on each card needs the discrete one (storytold/pdfcraft#445). So the +//! choice follows the connected displays, as in craft-anything (storytold/craft-anything#571): +//! +//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`, +//! `none`), when set, decide; +//! 2. a connected built-in panel: the GPU behind it; +//! 3. displays on only one GPU: that GPU; +//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as before. + +mod drm; + +use drm::DisplayCard; +use eframe::wgpu::{DeviceType, PowerPreference}; + +/// What we know of one adapter wgpu offers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Candidate { + pub name: String, + pub vendor: u32, + pub device: u32, + /// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL). + pub pci_slot: String, + pub device_type: DeviceType, + pub gl: bool, +} + +/// What the person asked for through wgpu's environment variables. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Asked { + pub adapter_name: Option, + pub power: Option, +} + +/// Why an adapter was chosen, for the log. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Why { + AskedByName, + AskedPower, + BuiltInPanel, + OnlyGpuWithDisplays, + Fallback, +} + +/// The index of the adapter to draw with, and why; `None` when there is none. +pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> { + if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) { + // As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice. + if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) { + return Some((i, Why::AskedByName)); + } + log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name"); + } + if let Some(power) = asked.power { + return by_kind(candidates, power).map(|i| (i, Why::AskedPower)); + } + let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect(); + let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect(); + let target = if !panels.is_empty() { + Some((panels, Why::BuiltInPanel)) + } else if with_displays.len() == 1 { + Some((with_displays, Why::OnlyGpuWithDisplays)) + } else { + None + }; + if let Some((wanted, why)) = target { + // Vulkan before GL for the same card; otherwise wgpu's order. + let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl); + if let Some((i, _)) = found { + return Some((i, why)); + } + } + by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback)) +} + +/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by +/// PCI ids, which count only when no other card has the same ids (two cards of one model); GL +/// gives only a vendor, which counts only when no other card has that vendor. +fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool { + if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() { + return adapter.pci_slot == card.pci_slot; + } + if adapter.device != 0 { + return adapter.vendor == card.vendor + && adapter.device == card.device + && all.iter().filter(|c| c.vendor == card.vendor && c.device == card.device).count() == 1; + } + adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1 +} + +/// The first adapter in wgpu's own order for that power preference. +fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option { + let rank = |t: DeviceType| match (power, t) { + (PowerPreference::None, _) => 0, + (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1, + (_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2, + (_, DeviceType::Other) => 3, + (_, DeviceType::VirtualGpu) => 4, + (_, DeviceType::Cpu) => 5, + }; + candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i) +} + +#[cfg(target_os = "linux")] +impl Candidate { + fn of(info: &eframe::wgpu::AdapterInfo) -> Self { + Candidate { + name: info.name.clone(), + vendor: info.vendor, + device: info.device, + pci_slot: info.device_pci_bus_id.to_ascii_lowercase(), + device_type: info.device_type, + gl: info.backend == eframe::wgpu::Backend::Gl, + } + } +} + +#[cfg(target_os = "linux")] +impl Asked { + fn from_env() -> Self { + Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() } + } +} + +/// The adapter that draws the window, among those that can draw to it. +#[cfg(target_os = "linux")] +pub(crate) fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result { + let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect(); + let candidates: Vec = usable.iter().map(|a| Candidate::of(&a.get_info())).collect(); + let cards = drm::display_cards(); + let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why))); + match picked { + Some((a, why)) => { + log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info()); + Ok(a.clone()) + } + None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0"); + const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0"); + const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0"); + + fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate { + Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false } + } + + fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate { + Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true } + } + + fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard { + DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel } + } + + /// What wgpu offers on a laptop whose AMD iGPU drives the panel, in its order (Vulkan, then GL). + fn laptop_adapters() -> Vec { + vec![ + vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu), + vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu), + gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu), + ] + } + + /// The iGPU drives the panel; egui-wgpu's default drew on the discrete GPU. + #[test] + fn a_laptop_draws_on_the_gpu_behind_its_panel() { + let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)]; + assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel))); + // The same with the discrete GPU listed first. + let mut swapped = laptop_adapters(); + swapped.swap(0, 1); + assert_eq!(choose(&swapped, &cards, &Asked::default()), Some((1, Why::BuiltInPanel))); + } + + /// The panel's GPU stays the choice with an external monitor on the discrete card as well. + #[test] + fn the_panel_wins_over_a_monitor_on_the_other_card() { + let cards = [card(NVIDIA, 1, false), card(AMD, 1, true)]; + assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel))); + } + + /// A desktop with its monitor on the discrete card and the iGPU left on (a low-power default + /// draws on the iGPU there, and the window can't start: the case the panel rule must not break). + #[test] + fn a_desktop_draws_on_the_only_card_with_a_monitor() { + let adapters = + [vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)]; + let cards = [card(INTEL, 0, false), card(NVIDIA, 1, false)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays))); + // And on the iGPU when that's where the only monitor is. + let cards = [card(INTEL, 2, false), card(NVIDIA, 0, false)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((0, Why::OnlyGpuWithDisplays))); + } + + /// A desktop with a monitor on each card: the discrete GPU, as before (an iGPU choice there + /// lost its surface as soon as it was set up). + #[test] + fn monitors_on_two_cards_keep_the_discrete_gpu() { + let adapters = + [vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)]; + let cards = [card(INTEL, 1, false), card(NVIDIA, 1, false)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::Fallback))); + } + + /// Nothing readable (no `/sys`, or a card the drivers don't name): the discrete GPU, as before. + #[test] + fn without_display_facts_the_old_choice_stands() { + assert_eq!(choose(&laptop_adapters(), &[], &Asked::default()), Some((1, Why::Fallback))); + let unknown = [card((0x1234, 0x1, "0000:09:00.0"), 1, true)]; + assert_eq!(choose(&laptop_adapters(), &unknown, &Asked::default()), Some((1, Why::Fallback))); + assert_eq!(choose(&[], &[card(AMD, 1, true)], &Asked::default()), None); + } + + /// The environment variables still decide: prime-run style requests reach the NVIDIA card. + #[test] + fn wgpu_environment_variables_decide_when_set() { + let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)]; + let asked = |name: Option<&str>, power: Option| Asked { adapter_name: name.map(Into::into), power }; + assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))), Some((2, Why::AskedByName))); + // A name nothing has: the usual choice, not a failure. + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel))); + assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some(""), None)), Some((0, Why::BuiltInPanel))); + } + + /// Under `WGPU_BACKEND=gl` there's no PCI address or device id: the vendor alone finds the + /// card, but only when no other card shares it. + #[test] + fn gl_adapters_are_matched_by_vendor_only_when_unambiguous() { + let adapters = + [gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)]; + let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel))); + // Two AMD cards: the vendor can't tell them apart, so the old choice stands. + let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)]; + let adapters = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)]; + assert_eq!(choose(&adapters, &two_amd, &Asked::default()), Some((1, Why::Fallback))); + } + + /// Two adapters for the panel's card (Vulkan and GL): Vulkan, whatever the order. + #[test] + fn vulkan_comes_before_gl_for_the_same_card() { + let adapters = [ + gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu), + vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu), + ]; + assert_eq!(choose(&adapters, &[card(AMD, 1, true)], &Asked::default()), Some((1, Why::BuiltInPanel))); + } + + /// A laptop with the lid closed and a monitor on the NVIDIA card: the switched-off panel isn't + /// read as one (`drm` skips it), so the card with the monitor draws. + #[test] + fn a_closed_laptop_draws_on_the_card_with_the_monitor() { + let cards = [card(NVIDIA, 1, false), card(AMD, 0, false)]; + assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays))); + } + + /// Two cards of one model have the same PCI ids: only the PCI address tells them apart. Without + /// one from the driver the display rule gives way to the old choice instead of guessing. + #[test] + fn identical_cards_are_told_apart_only_by_pci_address() { + const SECOND: (u32, u32, &str) = (0x10de, 0x25a2, "0000:02:00.0"); + let cards = [card(NVIDIA, 0, false), card(SECOND, 1, false)]; + let with_slots = [vulkan("NVIDIA A", NVIDIA, DeviceType::DiscreteGpu), vulkan("NVIDIA B", SECOND, DeviceType::DiscreteGpu)]; + assert_eq!(choose(&with_slots, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays))); + let without: Vec = with_slots.iter().cloned().map(|c| Candidate { pci_slot: String::new(), ..c }).collect(); + assert_eq!(choose(&without, &cards, &Asked::default()), Some((0, Why::Fallback))); + } + + /// The laptop this was measured on: Intel HD 530 behind the panel (`card2-eDP-1`), a Quadro + /// M4000M with nothing connected, and the Quadro offered first by wgpu. + #[test] + fn an_intel_and_nvidia_laptop_draws_on_intel() { + const HD530: (u32, u32, &str) = (0x8086, 0x191b, "0000:00:02.0"); + const M4000M: (u32, u32, &str) = (0x10de, 0x13f9, "0000:01:00.0"); + let adapters = [ + vulkan("Quadro M4000M", M4000M, DeviceType::DiscreteGpu), + vulkan("Intel(R) HD Graphics 530 (SKL GT2)", HD530, DeviceType::IntegratedGpu), + ]; + let cards = [card(M4000M, 0, false), card(HD530, 1, true)]; + assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel))); + } +} diff --git a/apps/wordcraft/src/linux_gpu/drm.rs b/apps/wordcraft/src/linux_gpu/drm.rs new file mode 100644 index 0000000000..cee58e0bb0 --- /dev/null +++ b/apps/wordcraft/src/linux_gpu/drm.rs @@ -0,0 +1,237 @@ +//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`). +//! +//! A window drawn on one card and shown on a screen attached to another is copied across on every +//! frame, so the app draws on the card that drives the screen (see the parent module). + +use std::io::Read as _; +use std::path::Path; + +/// A graphics card and the displays connected to it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct DisplayCard { + /// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel. + pub vendor: u32, + /// PCI device id. + pub device: u32, + /// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one. + pub pci_slot: String, + /// Connected displays that are switched on, of any kind, built-in panel included. + pub displays: u32, + /// A connected, switched-on built-in panel (eDP, LVDS or DSI): this card drives a laptop's + /// own screen. + pub built_in_panel: bool, +} + +/// Connector kinds that are a computer's own screen rather than a monitor plugged into it. +const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"]; + +/// At most this many entries are read from the DRM folder. +const MAX_ENTRIES: usize = 512; + +/// At most this many bytes are read from one sysfs file. +const MAX_FILE: u64 = 4096; + +/// The graphics cards on this computer and what's connected to them. Empty where the system +/// doesn't say (a sandbox without `/sys`). +#[cfg(target_os = "linux")] +pub(crate) fn display_cards() -> Vec { + display_cards_in(Path::new("/sys/class/drm")) +} + +/// [`display_cards`] read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per +/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN--` entry per +/// connector, with `connected` or `disconnected` in its `status` and, where the kernel gives it, +/// `enabled` or `disabled` in its `enabled`. Cards without PCI ids (a firmware framebuffer) are +/// left out. +pub(crate) fn display_cards_in(drm: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(drm) else { + return Vec::new(); + }; + let mut names: Vec = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect(); + names.sort(); + let cards = names.iter().filter(|n| is_card(n)); + cards + .filter_map(|card| { + let uevent = read_small(&drm.join(card).join("device").join("uevent"))?; + let (vendor, device) = pci_ids(&uevent)?; + let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase(); + let prefix = format!("{card}-"); + let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false }; + for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) { + let dir = drm.join(format!("{prefix}{connector}")); + let status = read_small(&dir.join("status")).unwrap_or_default(); + // A panel can be connected but switched off (a closed lid with a monitor in use): + // `enabled` then reads `disabled`, and it drives nothing. No `enabled`: as before. + let enabled = read_small(&dir.join("enabled")).unwrap_or_default(); + if status.trim() != "connected" || enabled.trim() == "disabled" { + continue; + } + out.displays = out.displays.saturating_add(1); + if BUILT_IN_PANELS.contains(&connector_kind(connector)) { + out.built_in_panel = true; + } + } + Some(out) + }) + .collect() +} + +/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node. +fn is_card(name: &str) -> bool { + name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + +/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number. +fn connector_kind(connector: &str) -> &str { + match connector.rsplit_once('-') { + Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind, + _ => connector, + } +} + +/// `PCI_ID=1002:1638` → (0x1002, 0x1638). +fn pci_ids(uevent: &str) -> Option<(u32, u32)> { + let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?; + Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?)) +} + +fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> { + uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim) +} + +fn read_small(path: &Path) -> Option { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?; + Some(text) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// A folder of its own under the system's temporary folder, removed when dropped. + struct TempDir(PathBuf); + + impl TempDir { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("wordcraft-drm-test-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + TempDir(dir) + } + + fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + /// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as + /// (name, status). + fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> TempDir { + let dir = TempDir::new(); + for (card, id, slot) in cards { + let device = dir.path().join(card).join("device"); + fs::create_dir_all(&device).expect("card folder"); + fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).expect("uevent"); + } + for (connector, status) in connectors { + let c = dir.path().join(connector); + fs::create_dir_all(&c).expect("connector folder"); + fs::write(c.join("status"), format!("{status}\n")).expect("status"); + } + fs::create_dir_all(dir.path().join("renderD128")).expect("render node"); + fs::write(dir.path().join("version"), "drm 1.1.0\n").expect("version"); + dir + } + + /// A laptop whose AMD iGPU drives the panel, with an NVIDIA card that has no outputs. + #[test] + fn a_laptop_panel_is_found_on_the_integrated_gpu() { + let d = drm( + &[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")], + &[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")], + ); + let cards = display_cards_in(d.path()); + assert_eq!( + cards, + vec![ + DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false }, + DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true }, + ] + ); + } + + /// A desktop with a monitor on each card: displays on both, no built-in panel. + #[test] + fn monitors_on_two_cards_are_counted_on_each() { + let d = drm( + &[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")], + &[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")], + ); + let cards = display_cards_in(d.path()); + assert_eq!(cards.iter().map(|c| (c.displays, c.built_in_panel)).collect::>(), vec![(1, false), (2, false)]); + } + + /// `card10` is a different card from `card1`, and its connectors aren't `card1`'s. + #[test] + fn card_numbers_are_not_prefixes_of_each_other() { + let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]); + let cards = display_cards_in(d.path()); + assert_eq!(cards.iter().map(|c| (c.vendor, c.displays)).collect::>(), vec![(0x1002, 0), (0x10de, 1)]); + } + + /// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number. + #[test] + fn built_in_panels_are_told_from_monitors_by_connector_kind() { + assert_eq!(connector_kind("eDP-1"), "eDP"); + assert_eq!(connector_kind("HDMI-A-1"), "HDMI-A"); + assert_eq!(connector_kind("DSI-12"), "DSI"); + assert_eq!(connector_kind("Virtual"), "Virtual"); + let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]); + assert!(display_cards_in(d.path()).iter().all(|c| c.built_in_panel)); + } + + /// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped, never a panic. + #[test] + fn what_cant_be_read_is_left_out() { + let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]); + fs::create_dir_all(d.path().join("card2")).expect("card without device"); + fs::create_dir_all(d.path().join("card")).expect("bare name"); + assert!(display_cards_in(d.path()).is_empty()); + assert!(display_cards_in(&d.path().join("missing")).is_empty()); + assert_eq!(pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2))); + assert_eq!(pci_ids("PCI_IDX=10de:25a2"), None); + } + + /// A status of `unknown` (some virtual outputs) isn't a connected display. + #[test] + fn only_connected_counts() { + let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]); + assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0)); + } + + /// A laptop with its lid closed and a monitor on the discrete card: the panel still reads + /// `connected` but is switched off, so it neither counts nor marks its card as the panel's. + #[test] + fn a_switched_off_panel_does_not_count() { + let d = drm( + &[("card0", "10de:25a2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")], + &[("card0-HDMI-A-1", "connected"), ("card1-eDP-1", "connected")], + ); + fs::write(d.path().join("card0-HDMI-A-1").join("enabled"), "enabled\n").expect("enabled"); + fs::write(d.path().join("card1-eDP-1").join("enabled"), "disabled\n").expect("enabled"); + let cards = display_cards_in(d.path()); + assert_eq!(cards.iter().map(|c| (c.vendor, c.displays, c.built_in_panel)).collect::>(), vec![(0x10de, 1, false), (0x1002, 0, false)]); + } +} diff --git a/apps/wordcraft/src/main.rs b/apps/wordcraft/src/main.rs index 302b97d4f7..7f81caa91e 100644 --- a/apps/wordcraft/src/main.rs +++ b/apps/wordcraft/src/main.rs @@ -20,6 +20,8 @@ mod default_apps; mod file_dialogs; #[cfg(any(target_os = "windows", target_os = "macos", test))] mod graphics; +#[cfg(any(target_os = "linux", test))] +mod linux_gpu; mod logging; #[cfg(all(unix, not(target_os = "macos")))] mod portal_save; @@ -685,6 +687,13 @@ fn main() -> eframe::Result { })); } } + // egui-wgpu draws on the discrete GPU by default; on a laptop whose integrated GPU drives the + // panel, that wakes the discrete GPU whenever the window redraws. Draw on the GPU that drives + // the screen; `WGPU_ADAPTER_NAME` and `WGPU_POWER_PREF` still decide (see linux_gpu.rs). + #[cfg(target_os = "linux")] + if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup { + setup.native_adapter_selector = Some(std::sync::Arc::new(linux_gpu::pick_adapter)); + } // Registered before the event loop starts, so it catches the Finder event that launched us as // well as later ones. Lives until the event loop returns; the app creator only borrows it. #[cfg(target_os = "macos")] From c99dd5cc6e34cc2e974a66a217a0dde88e0df428 Mon Sep 17 00:00:00 2001 From: tpawley2001 Date: Tue, 17 Nov 2026 01:56:37 -0800 Subject: [PATCH 65/99] References: TOC, index, table of figures and page cross-references use the section's page number format (#3856) (#5971) --- crates/engine/src/cmd/citations.rs | 1 + crates/engine/src/cmd/citations/cross_refs.rs | 54 +++- crates/engine/src/cmd/citations/generated.rs | 22 +- crates/engine/src/cmd/citations/tests.rs | 65 +++++ crates/engine/src/cmd/index.rs | 18 +- crates/engine/src/cmd/references.rs | 1 + crates/engine/src/cmd/references/fields.rs | 51 +++- crates/engine/src/cmd/references/toc.rs | 9 +- crates/engine/src/tests.rs | 1 + .../src/tests/page_number_formats_in_lists.rs | 260 ++++++++++++++++++ 10 files changed, 440 insertions(+), 42 deletions(-) create mode 100644 crates/engine/src/tests/page_number_formats_in_lists.rs diff --git a/crates/engine/src/cmd/citations.rs b/crates/engine/src/cmd/citations.rs index 87e83fac77..f889790a56 100644 --- a/crates/engine/src/cmd/citations.rs +++ b/crates/engine/src/cmd/citations.rs @@ -19,6 +19,7 @@ mod sources; mod styles; use cross_refs::cross_ref; +pub(crate) use cross_refs::leading_breaks; pub use cross_refs::{caption_labels, ref_targets}; #[cfg(test)] use generated::ENTRY_STYLE; diff --git a/crates/engine/src/cmd/citations/cross_refs.rs b/crates/engine/src/cmd/citations/cross_refs.rs index 265a73fabc..6c35c27797 100644 --- a/crates/engine/src/cmd/citations/cross_refs.rs +++ b/crates/engine/src/cmd/citations/cross_refs.rs @@ -1,5 +1,5 @@ -use super::generated::page_of; use super::{CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p}; +use crate::cmd::references::page_label; pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult { let to = p::str(v, "to").unwrap_or("heading"); @@ -10,9 +10,10 @@ pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult { let find = |ts: Vec<(String, Pos)>| ts.into_iter().find(|(t, _)| t == target || t.starts_with(target)); let (text, pos) = find(targets).ok_or_else(|| CmdError::Params(format!("no {to} `{target}`")))?; let show = p::str(v, "show").unwrap_or("text"); - let page = page_of(s, &pos); let result = match show { - "page" => page.to_string(), + // The page the target's text starts on (after its leading page breaks), as its footer + // shows it. + "page" => page_label(s, &Pos { off: leading_breaks(&s.doc, &pos), ..pos.clone() }), "number" => text.split(':').next().unwrap_or(&text).trim().to_string(), "aboveBelow" => { if pos < s.sel.focus { @@ -152,6 +153,23 @@ pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> { targets } +/// The offset just past the page breaks at the start of the paragraph at `pos`, skipping bookmark +/// marks among them (a `_Ref` bookmark may start before the breaks): its text starts there. +pub(crate) fn leading_breaks(doc: &Document, pos: &Pos) -> usize { + let Some(p) = doc.para(pos.story, &pos.path) else { return 0 }; + let mut after = 0; + for (i, c) in p.text.char_indices() { + if c == '\u{0C}' { + after = i.saturating_add(c.len_utf8()); + } else if c != wordcraft_doc::para::OBJ + || !matches!(p.object_at(i), Some(InlineObject::BookmarkStart { .. } | InlineObject::BookmarkEnd { .. })) + { + break; + } + } + after +} + /// The hidden `_Ref` bookmark around the target paragraph at `pos` (its label and number only /// when `number_only`), reusing one already there. Returns its name and `at` moved past the /// bookmark marks inserted before it. @@ -159,16 +177,22 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R const MARK: usize = wordcraft_doc::para::OBJ.len_utf8(); let para = s.doc.para(pos.story, &pos.path).ok_or_else(|| CmdError::Params("cross-reference target is gone".into()))?; let end = if number_only { para.text.find(':').unwrap_or(para.len()) } else { para.len() }; - if let Some(InlineObject::BookmarkStart { name }) = para.object_at(0) - && name.starts_with("_Ref") - { - // Reuse it when it covers the same extent: up to the colon, or the whole paragraph. - let same = para.object_offsets().into_iter().any(|o| { - matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name) - && para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() }) - }); - if same { - return Ok((name.clone(), at)); + // The bookmark starts after the leading page breaks, so `PAGEREF` reads the page the text is on. + let start = leading_breaks(&s.doc, pos).min(end); + // Reuse one that starts there or at the paragraph's start (before the breaks): the field's + // result still reads the page the text is on. + for from in [start, 0] { + if let Some(InlineObject::BookmarkStart { name }) = para.object_at(from) + && name.starts_with("_Ref") + { + // Reuse it when it covers the same extent: up to the colon, or the whole paragraph. + let same = para.object_offsets().into_iter().any(|o| { + matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name) + && para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() }) + }); + if same { + return Ok((name.clone(), at)); + } } } let next = @@ -176,11 +200,11 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R let name = format!("_Ref{next:09}"); let props = CharProps::default(); s.doc.insert_object(&Pos { off: end, ..pos.clone() }, InlineObject::BookmarkEnd { name: name.clone() }, &props)?; - s.doc.insert_object(&Pos { off: 0, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?; + s.doc.insert_object(&Pos { off: start, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?; if at.story == pos.story && at.path == pos.path { if at.off >= end { at.off = at.off.saturating_add(2 * MARK); - } else if at.off > 0 { + } else if at.off > start { at.off = at.off.saturating_add(MARK); } } diff --git a/crates/engine/src/cmd/citations/generated.rs b/crates/engine/src/cmd/citations/generated.rs index 60b0b89882..b234948c68 100644 --- a/crates/engine/src/cmd/citations/generated.rs +++ b/crates/engine/src/cmd/citations/generated.rs @@ -6,7 +6,9 @@ use super::{ Block, CharProps, CmdError, CmdResult, Document, FieldCode, InlineObject, Paragraph, Path, Pos, Session, SortKey, StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, heading_letter, p, sel_result, sort_key, }; +use crate::cmd::references::{page_at, page_formats, page_text}; use std::sync::Arc; +use wordcraft_doc::section::NumFormat; /// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "

` is an indented paragraph, not the Quote style, #1270); previously trivial: every table style part round-trips, #714; previously trivial: VML freeforms read and kept on save; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: `flowChartOr` draws its circle and cross spokes, as in Word; previously trivial: RTF: Mac OS Roman and DOS text, #1653; previously trivial: VML text boxes keep their internal margins, fit to their text and vertical alignment; hidden drawings not shown; previously trivial: PDF export draws horizontal and vertical lines inside groups, #1474; previously trivial: symbol-font text exported as Unicode, #776; previously trivial: text-box margins, Resize shape to fit text and freeforms in groups, #743; previously trivial: formatted paste from the system clipboard's HTML and RTF, #687; previously trivial: independent complex-script formatting inheritance and round-trip regression tests; previously trivial: import/export fixes for TXT, RTF, ODT, HTML and LaTeX, #433–#440; previously major: first version; every format Word reads or writes, measured from the readers and writers on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4, plus Word for Windows' extra formats +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** trivial (a rounded rectangle without a corner size of its own takes the preset's default, a sixth of its shorter side, #6546); previously trivial (DOCX section line numbering: `w:lnNumType` without a positive `w:countBy` stays off, #6209); previously trivial (ODT: a paragraph default style that names no font keeps the document's default font, #4683); previously trivial (ODT columns stating only their shares); previously trivial (ODT font size for every script); previously trivial (ODT text turning off what its style turns on); previously trivial (ODT custom styles with an outline level); previously trivial (ODT pictures keep the size their file gives); previously trivial (ODT frames keep the page they are anchored to); previously trivial (ODT: a document's language kept when its styles are written from the model); previously trivial (ODT table and row backgrounds); previously trivial (ODT row: how tab stops are saved, corrected); previously trivial (RTF footnotes, endnotes and comments, #1053); previously trivial (XML line ends in text normalised, #5897); previously trivial (ODT pictures offered in several formats); previously trivial (ODT heading text of another size); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (ODT: no settings for what the standard leaves open); previously trivial (picture brightness, contrast and transparency); previously trivial (ODT paragraph groups kept as read); previously trivial (ODT paragraphs with charts kept as read); previously trivial (ODT sections in cells and at empty paragraphs); previously trivial (ODT element audit); previously trivial (ODT reference marks written as such); previously trivial (ODT hidden sections stay hidden; lists kept as read); previously trivial (ODT manifest lists every file); previously trivial (ODT paragraphs with bookmarks, notes, objects and page-anchored frames written as read); previously trivial (ODT paragraphs with text boxes written as read); previously trivial (ODT paragraphs with comments and tracked changes written as read); previously trivial (ODT paragraphs with pictures and shapes written as read); previously trivial (ODT sections inside text boxes); previously trivial (ODT definitions sharing a name, sections around tables, chart replacement pictures, note citations, stacking order); previously trivial (ODT form definitions and indexes written as read); previously trivial (ODT gradient angles by the file's version; deviation documented); previously minor (ODT: unedited tables, pages, sections, properties and declarations written as read; no-edit loss gate); previously minor (ODT: unedited paragraphs and style definitions written as read); previously trivial (ODT author fields said not fixed); previously trivial (ODT default text colour; covered cells' content); previously trivial (ODT widow control profile case; tabs from the indent kept); previously trivial (ODT span kerning; note reference formatting; notes starting with a tab); previously trivial (ODT fixed and sender fields); previously trivial (ODT: table styles saved into their cells; ODT tables carry no Word table style; section column balance); previously trivial (ODT interpretation profile: the standard is law, what it leaves open (including unstated page margins) follows WordCraft, LibreOffice or custom settings); previously trivial (ODT form controls keep their place on the line and text areas their lines; custom shapes keep their geometry); previously trivial (ODT in-line frames placed against the text; in-line pictures saved standing on the baseline); previously trivial (ODT charts written back as they were while unchanged; frames' drawn outline; default header height); previously trivial (ODT header rows only where they repeat); previously trivial (ODT padding without a border; unequal columns; column breaks); previously trivial (ODT lines of only pictures laid out as LibreOffice does; default page without a layout); previously trivial (ODT pictures alone in a paragraph keep its size; in-line frames raised under an inherited paragraph relation); previously trivial (ODT tables fit the margins and keep their space above and below; header spacing kept); previously trivial (ODT frames anchored and placed by their style); previously trivial (ODT default font size saved; page-anchored frames placed from the page; text box paragraph styles kept; empty paragraphs keep their size); previously trivial (ODT default font size; locale-ordered dates); previously trivial (ODT page background pictures); previously trivial (ODT tables fixed layout; tables starting a page); previously trivial (emphasis marks: model, layout, DOCX `w:em`, ODT `style:text-emphasize`, `format.emphasisMark`); previously trivial (ODT variables as SET/REF fields; character styles keep what they turn off); previously trivial (ODT styles keep what they turn off; WMF/EMF pictures kept; pictures in text boxes shown by LibreOffice); previously trivial (ODT unstated page margins are LibreOffice's 2 cm; drawings outside a paragraph join the next one); previously trivial (ODT placeholders as content controls, template dates, user name fields, unsized pages, style-only templates, found with LibreOffice's own templates); previously trivial (ODT hidden form controls kept; `.ott` templates opened and saved); previously trivial (ODT fidelity re-estimated at ~90%; a kept form control made another kind is saved as that kind); previously trivial (ODT form control sizes and buttons kept); previously trivial (ODT turned text in cells and text boxes); previously trivial (ODT macros and unknown package parts kept); previously trivial (ODT table cell formulas as formula fields); previously trivial (ODT custom shapes drawn from their own geometry); previously trivial (ODT bibliography marks as citations of sources); previously trivial (ODT linked text boxes); previously trivial (ODT picture crops and contour wrapping); previously trivial (ODT fidelity re-estimated at ~85%); previously trivial (ODT custom document properties and user fields as DOCPROPERTY); previously trivial (ODT connectors read and written glued); previously trivial (ODT borders around text read and written); previously trivial (ODT index marks read and written as XE fields; an index held around its entries updates); previously trivial (ODT ruby read and written); previously trivial (ODT page breaks after a paragraph, kept lines, widow control, hyphenation, table alignment and width and row heights); previously trivial (in-line drawings raised or lowered by their run's position; ODT in-line frames keep their place on the baseline; leading's space after the last line; text box borders shown by LibreOffice); previously trivial (ODT form controls opened and saved as content controls); previously trivial (password-protected ODT opened and saved); previously trivial (ODT headers and footers keep their shapes, text boxes, charts and embedded objects on save); previously trivial (ODT embedded spreadsheets and OLE objects kept whole instead of lost; flat ODT sub-documents valid `office:document`s); previously trivial (ODT charts in drawing groups drawn on open); previously trivial (ODT charts opened and saved as editable charts; flat ODT sub-documents no longer end the body); previously trivial (ODT leading read as an at-least spacing); previously trivial (ODT tracked formatting changes; changed regions named by `xml:id`); previously trivial (ODT drop caps; tab stops no longer drop a paragraph's background); previously trivial (flat ODT `.fodt` opened and saved; ODT fidelity re-estimated at ~80%); previously trivial (ODT page settings; a footnote no longer takes a footer's text); previously trivial (ODT dates in their formats, sequences, chapters and references); previously trivial (ODT bookmarks over text); previously trivial (ODT tables of contents and indexes; ODT fidelity re-estimated); previously trivial (ODT polygons, polylines and paths); previously trivial (ODT arrowheads, dashes and gradients); previously trivial (ODT groups of shapes and pictures); previously trivial (ODT rotated and mirrored shapes and pictures); previously trivial (ODT drawing shapes read and written); previously trivial (ODT text box frames keep their line, fill, padding and fit); previously trivial (ODT Asian and complex-script fonts); previously trivial (ODT right-to-left paragraphs); previously trivial (ODT text boxes kept); previously trivial (ODT unnumbered headings detached from the outline); previously trivial (ODT contextual spacing and layout settings); previously trivial (ODT custom character styles kept); previously trivial (ODT list level positions); previously trivial (ODT custom paragraph styles kept); previously trivial (ODT equations written as formula objects); previously trivial (ODT numbered headings written as headings); previously trivial (ODT floating pictures); previously trivial (ODT paragraph borders and background); previously trivial (ODT heading numbering); previously trivial (ODT font-face names); previously trivial (ODT table cell borders and padding); previously trivial (ODT heading, title, quote and preformatted styles keep their look); previously trivial (ODT tab stops read and written); previously trivial (ODT character formatting read and written); previously trivial (ODT lists keep their number formats, bullets and identity); previously trivial (ODT comments read and written); previously trivial (ODT footnotes and endnotes read and written); previously trivial (ODT headers, footers and text fields written; fields read); previously trivial (ODT paragraph spacing, indents and line spacing read and written); previously trivial (Replace and Remove Table of Contents treat Word's title above a section break as Word does, #4041); previously trivial (a password-protected .docx opened from the file manager asks for its password also when the startup document was replaced, #5299); previously minor (`w:altChunk` brought in on open; MHT opens; HTML style sheets, paragraph margins and Word's web-page defaults; broader corpus qualification and readiness estimates unchanged); previously trivial (a VML horizontal rule (`o:hr`) is drawn across its line at Word's measured width and kept on save, with rotation and flips, #3956); previously trivial (soft edges on a see-through solid fill fade from the fill's own opacity, #1600); previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (a list inside a Markdown block quote is written back inside the quote); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (.doc: the default font is the stylesheet's standard font (Aptos in Word 365 files), #5066); previously trivial (a paragraph naming an undefined style is formatted as Normal, as in Word, #5077); previously trivial (a hyperlinked TOC writes its page numbers as `PAGEREF _Toc… \h` fields, as Word does, #5097); previously trivial (HTML import ends the empty comments and at once, #5040); previously trivial (chart and SmartArt text the font lacks is drawn in a fallback face, so Chinese labels no longer show boxes, #4720); previously trivial (bibliography sources keep a corporate author (`b:Corporate`): read, written, cited and listed whole, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (note conversion preserves content with an ordered reference/run walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (built-in heading styles have their outline level without `w:outlineLvl`, #4696); previously trivial (DOCX comment ranges inside footnotes and endnotes are kept on read, #4548); previously trivial (RTF import and export keep Windows and Enhanced Metafile pictures (`\wmetafile`, `\emfblip`), #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (DOCX parts stored under another casing keep their embedded fonts through a save, and a private save of a kept glossary escapes the attribute values it rewrites; previously trivial: the `.doc` reader logs what its copy budget leaves out, once a kind per document; importers bound hostile expansion: font names, links, ODS repeats, LaTeX wrappers, Markdown delimiters, #3692/#3713; previously trivial: repeated DOCX style IDs: save/reopen regression; previously trivial: Markdown code spans keep line-broken text literal, #3738; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: localized TOC style ids read as the TOC styles, and a TOC in columns keeps its layout through Update Table, #3889; previously trivial: cu20we: outline caps; previously trivial: a relationship the markup names without the prefix is read as it wrote: an unqualified `id` on an element that carries a relationship names that relationship, and the writer keeps the attribute with the id the new package holds the part under; an ordinary `id` — a VML shape's, a drawing's — names no part; previously trivial: the reader takes the relationship ids the markup refers to from the relationship attributes of the main document it has already parsed, so a document with many relationships opens in the time its part takes, #3411; previously trivial: a table cell span from a `.json` file stays within 63 columns through Insert Column and Merge Cells, #3637; previously trivial: the file commands that change the document are checked on a protected document, the protection of a protected document needs an explicit stop, the session author can't change through `file.setAuthor` under protection (the CLI's `--author` uses the same protection check), and the post-check compares the settings and the metadata; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: `majorBidi`/`minorBidi` theme fonts follow the settings' theme font language, as measured in Word; previously trivial: Word signature lines are kept on save, still signable; previously trivial: Times New Roman keeps Liberation Serif under the roman-font rule; previously trivial: shape gradients and transparency, #1500; previously trivial: a folder that keeps no Unix modes, such as a NAS share mounted by GVFS, still takes a save, #3003; previously trivial: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: table style band sizes written, a style without them unbanded as in Word, #3415; previously trivial: HTML export writes ruby (furigana, phonetic guides) and HTML import reads it back, #1681; previously trivial: RTF import decodes the East Asian multibyte code pages, #1653; previously trivial: PDF export: lam-alef drawn as two glyphs at one x extracts in reading order, #2310; previously trivial: native .json stores pictures and kept parts as base64, #586 follow-up; previously trivial: ODT headers and footers read from each master page, #863; previously trivial: RTF import compares heading and code formatting with the file's stylesheet; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: Word XML and web pages saved as `.doc` open by what they hold, #2853; previously trivial: a VML shape in a header cell is always placed on the page, user-checked in Word for Mac, #1775; previously trivial: `w:sym` characters keep their symbol font when the text's font changes and are written back as `w:sym`, #2036; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: two lines in one and horizontal in vertical (`w:eastAsianLayout`) kept on save; previously trivial: PDF outline targets follow leading page breaks; previously trivial: positional tabs `w:ptab` read and kept on save, #2367; previously trivial: DOCX: mixed right-to-left runs split and marked `w:rtl` with their language, #1543; previously trivial: `w:doNotTrackMoves` round-trips and turns move tracking off; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: DOCX glossary documents (building blocks) read, kept and written; previously trivial: cached field results keep their visible run formatting; previously trivial: cached REF results retain hyperlink destinations; previously trivial: CLI conversions can explicitly refresh fields; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: a pasted HTML `
` is an indented paragraph, not the Quote style, #1270); previously trivial: every table style part round-trips, #714; previously trivial: VML freeforms read and kept on save; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: `flowChartOr` draws its circle and cross spokes, as in Word; previously trivial: RTF: Mac OS Roman and DOS text, #1653; previously trivial: VML text boxes keep their internal margins, fit to their text and vertical alignment; hidden drawings not shown; previously trivial: PDF export draws horizontal and vertical lines inside groups, #1474; previously trivial: symbol-font text exported as Unicode, #776; previously trivial: text-box margins, Resize shape to fit text and freeforms in groups, #743; previously trivial: formatted paste from the system clipboard's HTML and RTF, #687; previously trivial: independent complex-script formatting inheritance and round-trip regression tests; previously trivial: import/export fixes for TXT, RTF, ODT, HTML and LaTeX, #433–#440; previously major: first version; every format Word reads or writes, measured from the readers and writers on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4, plus Word for Windows' extra formats > **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. > **Legacy form update:** 2026-10-22 · trivial: field names and selected drop-down labels decode numeric XML character references once. @@ -130,7 +130,7 @@ Measured by grepping `crates/docx/src/read` and `src/write` for the OOXML elemen | Legacy font effects (`w:outline`, `w:shadow`, `w:emboss`, `w:imprint` in `w:rPr`) | ✅ | ✅ | Drawn on screen and in PDFs as Word's PDFs show them (#2534): hollow outlined letters; a sharp grey copy down-right (shadow, emboss) or up-left (imprint); WordArt effects on the same run win; tracked insertions and deletions keep them. Not drawn on colour emoji, or on top-to-bottom text with upright East Asian characters. Emboss and imprint are approximations (no highlight edge) | | OpenType ligatures (`w14:ligatures` in `w:rPr`: runs, styles, document defaults) | ✅ | ✅ | All 16 values; an unknown value is ignored; nothing is written when the document has none | | DrawingML outline caps (`a:ln/@cap`) | ✅ | ✅ | Flat/default, square (`sq`) and round (`rnd`) imported, saved and applied in raster/PDF; missing or unknown caps are flat. Synthetic read/save, endpoint-pixel and PDF-content tests (cu20we); theme inheritance unverified. | -| DrawingML shapes and text boxes (`wps:`) | ✅ | ✅ | Preset geometries subset (callouts and flowchart boxes drawn as the nearest shape, #611); `flowChartOr` draws a circle with horizontal and vertical spokes; rounded rectangles keep their own corner (`roundRect` `adj`: read, written back, drawn on screen and in PDF, #1476); fill and outline from the shape or from the theme through its style references (`a:fillRef`/`a:lnRef`, #611), scheme, preset, system, scRGB and HSL colours; rotation and flips (`a:xfrm` `rot`/`flipH`/`flipV`, pictures and groups too, #332), the effect extent covering the rotated bounds; `wps:bodyPr` `vert` and `anchor`, internal margins (`lIns`/`tIns`/`rIns`/`bIns`) and Resize shape to fit text (`a:spAutoFit`: the text is never cut, #743), linked text boxes (`wps:txbx/@id`, `wps:linkedTxbx` `id`/`seq`, #369); text warps (`a:prstTxWarp` with adjust values, all 41 presets kept; unknown ones dropped), connectors (`straightConnector1`, `bentConnector2`–`5`, `curvedConnector2`–`5` read; 3-segment forms written) with glued ends (`wps:cNvCnPr` `a:stCxn`/`a:endCxn`; the glued shapes keep their drawing ids) and arrowheads (`a:headEnd`/`a:tailEnd` with their `type`, `w` and `len` kept; drawn as triangles 2, 3 or 5 times the line's width long and wide, as Word does), including custom-geometry paths (#416); fills with transparency (`a:alpha`) and gradients (`a:gradFill`: up to 10 stops each with its transparency, `a:lin` angle and `scaled`, `a:path` circle/rect/shape with `fillToRect`, `tileRect`, `rotWithShape`, `flip`) read and written as stated, also through the theme's fill styles (`a:fillRef` 1–999 `a:fillStyleLst`, 1001+ `a:bgFillStyleLst`, `phClr` in the reference's colour; written as the resolved fill), outline gradients kept (drawn in their middle stop) (#1500). Drawn: linear and circular; rectangular and shape-following paths drawn circular; `tileRect`/`flip` not drawn; pattern fills drawn and saved as their foreground colour. Hidden drawings (`wp:docPr/@hidden`, a group member's `cNvPr/@hidden`) are kept and saved but neither drawn nor laid out, nor exported to other formats, as in Word for Windows; `.doc` and RTF shapes don't read their hidden flag yet | +| DrawingML shapes and text boxes (`wps:`) | ✅ | ✅ | Preset geometries subset (callouts and flowchart boxes drawn as the nearest shape, #611); `flowChartOr` draws a circle with horizontal and vertical spokes; rounded rectangles keep their own corner (`roundRect` `adj`: read, written back, drawn on screen and in PDF, #1476), and one without its own takes the preset's default of 16667, a sixth of the shorter side (#6546, `doc::connector::tests::corner_radius_follows_the_shorter_side`); fill and outline from the shape or from the theme through its style references (`a:fillRef`/`a:lnRef`, #611), scheme, preset, system, scRGB and HSL colours; rotation and flips (`a:xfrm` `rot`/`flipH`/`flipV`, pictures and groups too, #332), the effect extent covering the rotated bounds; `wps:bodyPr` `vert` and `anchor`, internal margins (`lIns`/`tIns`/`rIns`/`bIns`) and Resize shape to fit text (`a:spAutoFit`: the text is never cut, #743), linked text boxes (`wps:txbx/@id`, `wps:linkedTxbx` `id`/`seq`, #369); text warps (`a:prstTxWarp` with adjust values, all 41 presets kept; unknown ones dropped), connectors (`straightConnector1`, `bentConnector2`–`5`, `curvedConnector2`–`5` read; 3-segment forms written) with glued ends (`wps:cNvCnPr` `a:stCxn`/`a:endCxn`; the glued shapes keep their drawing ids) and arrowheads (`a:headEnd`/`a:tailEnd` with their `type`, `w` and `len` kept; drawn as triangles 2, 3 or 5 times the line's width long and wide, as Word does), including custom-geometry paths (#416); fills with transparency (`a:alpha`) and gradients (`a:gradFill`: up to 10 stops each with its transparency, `a:lin` angle and `scaled`, `a:path` circle/rect/shape with `fillToRect`, `tileRect`, `rotWithShape`, `flip`) read and written as stated, also through the theme's fill styles (`a:fillRef` 1–999 `a:fillStyleLst`, 1001+ `a:bgFillStyleLst`, `phClr` in the reference's colour; written as the resolved fill), outline gradients kept (drawn in their middle stop) (#1500). Drawn: linear and circular; rectangular and shape-following paths drawn circular; `tileRect`/`flip` not drawn; pattern fills drawn and saved as their foreground colour. Hidden drawings (`wp:docPr/@hidden`, a group member's `cNvPr/@hidden`) are kept and saved but neither drawn nor laid out, nor exported to other formats, as in Word for Windows; `.doc` and RTF shapes don't read their hidden flag yet | | Freeform shapes (`a:custGeom`: `a:moveTo`, `a:lnTo`, Bézier curves flattened) and WordCraft ink | ✅ | ✅ | Ink is written as a freeform `wps:wsp` in a `wp:anchor` (round caps, alpha for highlighter) and recognised again by its drawing name (#307). It is saved as a custom-geometry shape, not as Word's own ink (InkML in `w14:contentPart`), so Word shows WordCraft ink as a freeform shape it can move and recolour but not erase with its ink eraser; arcs drawn straight | | Group shapes (`wpg:`), drawing canvas (`wpc:`) | ✅ | ✅ | Groups (#267) and canvases (#344) with pictures, shapes, freeforms (custom geometry, #743; a path drawn back to its start without `a:close` is filled, as in Word) and text boxes; nested groups flattened; members' `a:grpFill` takes their group's fill, and a canvas background (`wpc:bg`) may be a gradient or transparent (#1500). The canvas schema has no transform, so a turned or flipped canvas keeps its turn in our own `wpc:extLst` extension (`urn:wordcraft:canvas-xfrm`; Word shows it unturned). Legacy VML canvases (`v:group editas="canvas"`) aren't read as canvases | | VML (`w:pict`, `v:shape`, `v:textbox`) | 🟡 | 🟡 | Pictures, text boxes, lines (with arrowheads, their kind, width and length kept), rectangles and ovals, best effort (#242, #611); `v:fill` opacity and gradients (`type="gradient"`/`gradientRadial`, `color2`, `colors`, `angle`, `focus`, `focusposition`, `o:opacity2`), saved as DrawingML (#1500). Preset shapes (`v:shape` whose `o:spt`, own or from its `v:shapetype`, or Word's shapetype id `_x0000_tNN`, names a preset; [MS-ODRAW] §2.4.24 numbers) are drawn and saved like the DrawingML preset of the same shape: exactly for rectangle, rounded rectangle, ellipse, diamond, isosceles triangle, five-point star, right arrow, line and straight connector, heart, text box, and the flowchart process, decision and connector; the others as their nearest shape, as for DrawingML (left/up/down arrows as the arrow, right triangle as the triangle, callouts as their box). Picture frames without a picture aren't drawn. Fill, outline and size come from the shape, else its shapetype; text inside keeps the shape around it (#1377). Adjust values (`adj`) aren't read: presets use WordCraft's proportions. Text boxes keep their internal margins (`inset`, unless `o:insetmode="auto"`), Resize shape to fit text (`mso-fit-shape-to-text`) and vertical alignment (`v-text-anchor`). Hidden shapes (`visibility:hidden`, like DrawingML's `wp:docPr/@hidden`) are kept and saved but neither drawn nor laid out, as in Word for Windows (Word for Mac draws them). Picture `gain` and `blacklevel` on `v:imagedata` (Word's picture watermark "Washout") are read as brightness and contrast (#1711). Saving as DOCX writes them as DrawingML `a:lum`; saving as Word 2003 XML writes them back as VML `gain`/`blacklevel` (transparency has no place on `v:imagedata` and is dropped there). Text-box text direction is read as Word reads it: `mso-layout-flow-alt:bottom-to-top` as `vert270` whatever `layout-flow` says, else `layout-flow:vertical` or `vertical-ideographic` as `vert`, else horizontal (#5193). Word's text watermark (a `v:textpath` shape in a header or footer, recognised by Word's `PowerPlusWaterMarkObject` id or by being centred on the page both ways) becomes the document's watermark: text, font, fill colour, semitransparent (`v:fill` `opacity`) and diagonal (any turn); drawn with WordCraft's own size and angle, on every page even when only some sections' headers (or only the first-page header) have it (#1290). Saving writes the watermark back the same way: a `v:textpath` shape centred on the margins, behind the text, at the start of every header's first paragraph; a section whose pages would show no header gets a header holding only the watermark (default, and first-page or even-page ones when those are on), while sections linked to an earlier header stay linked. Freeforms (`v:shape` with its own `path`: moves, lines, Béziers and closes in its `coordsize`/`coordorigin` space, `nf`/`ns`, `v:stroke` opacity) are read as freeforms and saved as DrawingML custom geometry; fill opacity kept (no fill at 0); arcs are drawn straight; shapes whose path uses formulas (`@n`) and paths inherited from a `v:shapetype` aren't read. Word signature lines (Insert › Signature Line: a VML picture with an `o:signatureline`) are shown as their picture and saved back whole with it, at the size set in WordCraft, so they stay signable in Word instead of becoming plain pictures. Other VML is written only for OLE object pictures and signature lines. Other VML WordArt (Word 2007's: `v:textpath` in the body, or a header logo) becomes a text box without fill or outline holding its `string`, in the textpath's font, the shape's fill colour and a size from the shape's height; its WordArt shape (`o:spt` 136–175) becomes the DrawingML text warp of the same shape (#2875). Its outline, shadow and 3-D effects aren't read | @@ -339,6 +339,7 @@ For field results, the engine parser treats a backslash in quoted arguments as e | Date | Change | Summary | |---|---|---| +| 2026-11-13 | trivial | A rounded rectangle without a corner size of its own (`roundRect` with an empty `a:avLst`) takes the preset's default `adj` of 16667, a sixth of its shorter side; it was drawn with 16%. Measured in Word for Windows: such a shape of 300 x 100 pt has corners of 16.67 pt, one of 300 x 40 pt of 6.67 pt and one of 60 x 150 pt of 10 pt (#6546) (`doc::connector::tests::corner_radius_follows_the_shorter_side`). | | 2026-11-04 | trivial | ODT: a later paragraph default style that names no font no longer clears the document's default font; a regression from the #4501 refactor (#4683) | | 2026-11-08 | trivial | ODT row corrected: a file whose tab stops are measured from the indent is saved measuring from it, not always from the margin (the 2026-11-03 change); the default stops are counted from the indent | | 2026-11-05 | trivial | ODT: a table's columns stating only their share (`style:rel-column-width`, as LibreOffice's CV template does) keep their proportions; they opened and saved as equal columns. An aligned table's stated width is what they divide, columns with only a width take it first, and the default style can give a share. In an aligned table whose every column has a share, the shares win over any widths stated with them, as LibreOffice 26.8 reads them, and a share too small for a column gives the narrowest one (6 pt) instead of losing the grid. A table in a cell, frame or narrower column with widths stated as well as shares, or with nothing to divide, splits equally as before. | From c7e84ae43dc9f638a83132310d6618d335786b16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Tue, 17 Nov 2026 18:22:13 +0700 Subject: [PATCH 71/99] #6282: print preview follows FILENAME text, fonts, texture limit and exact size (#6478) --- crates/ui-egui/src/print_page.rs | 149 +++++++++++++++++++++++++++---- 1 file changed, 131 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/print_page.rs b/crates/ui-egui/src/print_page.rs index ee0b9a51c7..826c58e23d 100644 --- a/crates/ui-egui/src/print_page.rs +++ b/crates/ui-egui/src/print_page.rs @@ -3,7 +3,7 @@ //! Page range and parity shape the PDF. Native printer settings and copy collation go to //! the shared spooler; browser printing and saved print PDFs retain copies in the PDF. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use egui::{Rect, Sense, Stroke, TextureHandle, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -118,38 +118,56 @@ fn choice_named(ui: &mut Ui, salt: &str, current: &mut String, items: &[(&str, & changed } -/// The output layout, kept while the document and Print Markup setting are unchanged. +/// What the preview's layout is made from besides the document's text: the revision, Print +/// Markup, the file name and path FILENAME fields show (#6282: Save As and Rename change them +/// without an edit), and the font database generation the app has seen (#6283: +/// `WordApp::watch_fonts` moves it when fonts are added or removed). +type LayoutKey = (u64, bool, (String, String), u64); + +/// The [`LayoutKey`] now. +fn layout_key(app: &WordApp) -> LayoutKey { + (app.session.rev(), app.session.prefs.print_markup, app.session.resolved_filenames(), app.font_generation) +} + +/// The output layout, kept while what it is made from ([`LayoutKey`]) is unchanged. fn layout_of(app: &WordApp, ctx: &egui::Context) -> Arc { let id = egui::Id::unique("print_page_layout"); - let rev = app.session.rev(); - let markup = app.session.prefs.print_markup; - if let Some((r, m, l)) = ctx.data(|d| d.get_temp::<(u64, bool, Arc)>(id)) - && r == rev - && m == markup + let key = layout_key(app); + if let Some((k, l)) = ctx.data(|d| d.get_temp::<(LayoutKey, Arc)>(id)) + && k == key { return l; } - let l = app.session.export_layout_with(markup); - ctx.data_mut(|d| d.insert_temp(id, (rev, markup, l.clone()))); + let l = app.session.export_layout_with(app.session.prefs.print_markup); + ctx.data_mut(|d| d.insert_temp(id, (key, l.clone()))); l } -/// A bounded per-cell texture cache, refreshed when the page, scale or Print Markup changes. -fn page_texture(app: &WordApp, ctx: &egui::Context, lay: &DocLayout, page: usize, cache_slot: usize, width: f32) -> Option { +/// What a preview texture was drawn from: the layout, the page and the render scale's bits. +type TextureKey = (Weak, usize, u32); + +/// A bounded per-cell texture cache, drawn again when the layout, the page or the scale changes. +fn page_texture(app: &WordApp, ctx: &egui::Context, lay: &Arc, page: usize, cache_slot: usize, width: f32) -> Option { let id = egui::Id::unique(("print_page_texture", cache_slot)); - let key = (app.session.rev(), app.session.prefs.print_markup, page, width as u32, (ctx.pixels_per_point() * 100.0) as u32); - if let Some((k, t)) = ctx.data(|d| d.get_temp::<((u64, bool, usize, u32, u32), TextureHandle)>(id)) - && k == key - { - return Some(t); - } let pg = lay.pages.get(page)?; // Zoomed in, the texture stays within what the GPU takes and is stretched beyond that. let max_side = ctx.input(|i| i.max_texture_side) as f32 / pg.w.max(pg.h).max(1.0); let scale = (width / pg.w.max(1.0) * ctx.pixels_per_point()).clamp(0.05, 4.0).min(max_side); + // Keyed on what the page is drawn from: the layout, so whatever lays the page out again + // draws it again (held weakly: no later layout can take its address while the key holds + // it), the page, and the exact scale (#6285), which also follows the GPU's texture limit + // (#6284). + if let Some(((l, p, s), t)) = ctx.data(|d| d.get_temp::<(TextureKey, TextureHandle)>(id)) + && std::ptr::eq(l.as_ptr(), Arc::as_ptr(lay)) + && p == page + && s == scale.to_bits() + { + return Some(t); + } let img = wordcraft_render::render_page(&app.session.doc, pg, scale, &Default::default()); let color = egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.to_straight()); let tex = ctx.load_texture("print_page_preview", color, egui::TextureOptions::LINEAR); + let key: TextureKey = (Arc::downgrade(lay), page, scale.to_bits()); ctx.data_mut(|d| d.insert_temp(id, (key, tex.clone()))); Some(tex) } @@ -395,7 +413,7 @@ fn zoom_step(z: f32, up: bool) -> f32 { /// The preview (#1156): the page fills the pane, a bar below pages through the document and /// zooms; zoomed in, the page scrolls both ways. -fn preview(app: &mut WordApp, ui: &mut Ui, lay: &DocLayout) { +fn preview(app: &mut WordApp, ui: &mut Ui, lay: &Arc) { let t = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); let sheets = match wordcraft_engine::print::sheets(&app.ui.print.params(), lay, app.session.current_pages(lay)) { @@ -592,4 +610,99 @@ mod tests { assert_eq!(app.session.dirty, dirty); } } + + /// A one-page synthetic document in a fresh preview. + fn synthetic_app() -> (WordApp, egui::Context) { + let session = Session::new(wordcraft_doc::Document::from_text("Synthetic print preview")); + (WordApp::new(session, Services::default()), egui::Context::default()) + } + + /// Rename (and Save As) change what a FILENAME field shows without an edit (#6282): the + /// preview lays the page out and draws it again. + #[test] + fn preview_follows_the_name_a_filename_field_shows() { + let mut doc = wordcraft_doc::Document::new(); + let mut p = wordcraft_doc::Paragraph::new(); + let field = wordcraft_doc::InlineObject::Field { + instr: "FILENAME".into(), + result: String::new(), + locked: false, + dirty: false, + code: false, + form: String::new(), + }; + p.insert_object(0, field, &Default::default()).unwrap(); + doc.body = vec![wordcraft_doc::para_block(p)]; + let mut app = WordApp::new(Session::new(doc), Services::default()); + let ctx = egui::Context::default(); + let shown = |l: &DocLayout| -> String { + l.pages[0] + .items + .iter() + .filter_map(|it| { + if let wordcraft_layout::Placed::Lines { para, .. } = it { + Some(para.shown.iter().map(|s| s.1.as_str()).collect::()) + } else { + None + } + }) + .collect() + }; + let before = layout_of(&app, &ctx); + assert_eq!(shown(&before), app.session.resolved_filenames().0, "the untitled document's name"); + let texture = page_texture(&app, &ctx, &before, 0, 0, 300.0).unwrap().id(); + let rev = app.session.rev(); + app.session.run("file.rename", &json!({"name": "Quarterly report"})).unwrap(); + assert_eq!(app.session.rev(), rev, "renaming is no edit"); + let after = layout_of(&app, &ctx); + assert_eq!(shown(&after), "Quarterly report"); + assert_ne!(page_texture(&app, &ctx, &after, 0, 0, 300.0).unwrap().id(), texture); + } + + /// Fonts added or removed change the layout without an edit (#6283): once the app has seen the + /// font database move, the preview lays the page out and draws it again. + #[test] + fn preview_follows_the_fonts() { + let (mut app, ctx) = synthetic_app(); + let before = layout_of(&app, &ctx); + let texture = page_texture(&app, &ctx, &before, 0, 0, 300.0).unwrap().id(); + // What `watch_fonts` records when a font is added: not the shared database itself, which + // tests running alongside change. + app.font_generation = app.font_generation.wrapping_add(1); + let after = layout_of(&app, &ctx); + assert!(!Arc::ptr_eq(&before, &after), "laid out again with the new fonts"); + assert!(Arc::ptr_eq(&after, &layout_of(&app, &ctx)), "and kept while the fonts stay"); + assert_ne!(page_texture(&app, &ctx, &after, 0, 0, 300.0).unwrap().id(), texture); + } + + /// The GPU's texture limit changes with the GPU, as when the window moves to a display on + /// another one (#6284): a page drawn under the old limit is drawn again under the new one. + #[test] + fn preview_texture_follows_the_gpu_texture_limit() { + let (app, ctx) = synthetic_app(); + let layout = layout_of(&app, &ctx); + let wide = page_texture(&app, &ctx, &layout, 0, 0, 1200.0).unwrap(); + assert!(wide.size()[1] > 1024, "{:?}", wide.size()); + // 1024: egui's font atlas takes no less. + ctx.run_pass(egui::RawInput { max_texture_side: Some(1024), ..Default::default() }, |_| {}).textures_delta.clear(); + let capped = page_texture(&app, &ctx, &layout, 0, 0, 1200.0).unwrap(); + assert!(capped.size().iter().all(|side| *side <= 1024), "{:?}", capped.size()); + } + + /// The texture is keyed on the exact width and pixels per point (#6285): a fraction of a point + /// wider, or a slightly denser display, draws the page again at its own resolution. + #[test] + fn preview_texture_follows_the_exact_width_and_pixels_per_point() { + let (app, ctx) = synthetic_app(); + let layout = layout_of(&app, &ctx); + let texture = |width: f32| page_texture(&app, &ctx, &layout, 0, 0, width).unwrap(); + assert_ne!(texture(300.2).id(), texture(300.8).id(), "less than a point wider"); + assert_eq!(texture(300.5).size()[0], 301); + let mut input = egui::RawInput::default(); + input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { native_pixels_per_point: Some(1.004), ..Default::default() }); + ctx.run_pass(input, |_| {}).textures_delta.clear(); + let ppp = ctx.pixels_per_point(); + assert!(ppp > 1.0 && ppp < 1.01, "{ppp}"); + assert_eq!(texture(300.5).size()[0], (300.5 * ppp).ceil() as usize, "drawn for {ppp} pixels per point"); + } } From b7b528fbcfa1134ac91150582c9f21de9bff273e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Tue, 17 Nov 2026 18:34:29 +0700 Subject: [PATCH 72/99] Layout: the automatic space after a Latin run beside East Asian text follows the Latin face (#6589) --- crates/fonts/src/fontdb/face.rs | 5 ++ crates/fonts/src/fontdb/names.rs | 18 +++- crates/fonts/src/fontdb/tests/sysfonts.rs | 18 ++++ crates/layout/src/para/grid.rs | 52 ++++++++--- crates/layout/src/tests/autospace.rs | 100 ++++++++++++++++------ 5 files changed, 153 insertions(+), 40 deletions(-) diff --git a/crates/fonts/src/fontdb/face.rs b/crates/fonts/src/fontdb/face.rs index d3e9e01add..8ac99eef54 100644 --- a/crates/fonts/src/fontdb/face.rs +++ b/crates/fonts/src/fontdb/face.rs @@ -67,6 +67,11 @@ pub struct FontFace { /// values). pub cap_height: f64, pub x_height: f64, + /// Average character width in font units (`OS/2.xAvgCharWidth`), half the em for an East + /// Asian font, whose average a platform's text metrics report as its half-width cell rather + /// than the full-width figure in the table. Word's automatic spacing between East Asian and + /// Latin text is half of it (see `wordcraft_layout::para::grid::auto_space`). + pub avg_char_width: f64, pub shaper: harfrust::ShaperData, /// Variable fonts: the named instance's axis settings (user units; empty = default instance), /// the normalised location and the shaper's view of it. diff --git a/crates/fonts/src/fontdb/names.rs b/crates/fonts/src/fontdb/names.rs index 4d9458594a..efa66719ee 100644 --- a/crates/fonts/src/fontdb/names.rs +++ b/crates/fonts/src/fontdb/names.rs @@ -14,6 +14,20 @@ pub(super) fn east_asian_font(f: &skrifa::FontRef<'_>) -> bool { } } +/// The font's average character width in font units: `OS/2.xAvgCharWidth`, or half the em when +/// the table is missing or says nothing. An East Asian font gets half the em whatever its table +/// says, because a platform's text metrics report a double-byte font's average as the width of +/// its half-width cell, not the full-width figure the table carries (Yu Gothic says 1972 of +/// 2048, and Word spaces it as 1024). +fn avg_char_width(f: &skrifa::FontRef<'_>, upem: f64) -> f64 { + use skrifa::raw::TableProvider; + let half = upem / 2.0; + if east_asian_font(f) { + return half; + } + f.os2().ok().map(|t| f64::from(t.x_avg_char_width())).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(half).min(upem) +} + /// A family name in another language, from a font's `name` table. #[derive(Clone, Debug, PartialEq)] pub struct LocalName { @@ -371,6 +385,7 @@ pub(super) fn make_face( .map(|v| v >= 0.5) .or(axis(b"slnt").map(|v| v.abs() > 0.1)) .unwrap_or(!matches!(a.style, skrifa::attribute::Style::Normal) || style_italic(&style)); + let upem = m.units_per_em.max(1) as f64; Some(FontFace { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), family, @@ -381,11 +396,12 @@ pub(super) fn make_face( postscript: coords.is_empty().then(|| name(&f, &[StringId::POSTSCRIPT_NAME])).flatten(), weight, italic, - upem: m.units_per_em.max(1) as f64, + upem, ascent: m.ascent as f64, descent: -(m.descent as f64), cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72), x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5), + avg_char_width: avg_char_width(&f, upem), shaper, coords, location, diff --git a/crates/fonts/src/fontdb/tests/sysfonts.rs b/crates/fonts/src/fontdb/tests/sysfonts.rs index 4507c19de1..7502c360ee 100644 --- a/crates/fonts/src/fontdb/tests/sysfonts.rs +++ b/crates/fonts/src/fontdb/tests/sysfonts.rs @@ -579,6 +579,24 @@ fn east_asian_fonts_are_listed_for_the_asian_text_font_box() { assert_eq!(listed(&db), 1); } +#[test] +fn an_east_asian_faces_average_character_width_is_its_half_width_cell() { + // #6583: Word's automatic space beside East Asian text is half the average character width + // of the face before it, and a platform's text metrics report a double-byte font's average + // as the width of its half-width cell, not the full-width figure its OS/2 table carries. The + // two faces here share one OS/2 table and differ only in their code pages. + let dir = font_dir("avgcharwidth"); + let song = with_family_names("SourceSans3-Regular.ttf", &[(0x0409, "Songti Width")]); + std::fs::write(dir.join("song.ttf"), with_code_pages(&song, 1 << 18)).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let latin = db.face(FAMILY, "Regular"); + let asian = db.face("Songti Width", "Regular"); + assert!(latin.upem > 0.0 && !latin.is_east_asian() && asian.is_east_asian()); + // The Latin face keeps the table's figure, which is not half the em. + assert!(latin.avg_char_width > latin.upem / 2.0, "{} of {}", latin.avg_char_width, latin.upem); + assert_eq!(asian.avg_char_width, asian.upem / 2.0); +} + /// #848: browsing the font list drew each family's name in its own face, loading every family /// shown for good (tens of megabytes per trip through the Font box). Preview faces are read for /// the preview alone: however many families are previewed, the database keeps no font data, and diff --git a/crates/layout/src/para/grid.rs b/crates/layout/src/para/grid.rs index df370aa27b..9d1d9d3458 100644 --- a/crates/layout/src/para/grid.rs +++ b/crates/layout/src/para/grid.rs @@ -1,5 +1,5 @@ use super::builder::Builder; -use super::model::ClKind; +use super::model::{ClKind, StyleRun}; use super::{Arc, CharProps, Document, WrapText}; /// The section's document grid as layout applies it (`w:docGrid`, ECMA-376 §17.6.5). @@ -73,19 +73,40 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) { } } -/// Automatic spacing (`w:autoSpaceDE`, `w:autoSpaceDN`): a quarter of the Asian character's font -/// size between Asian text and Latin text or digits that touch, across runs. Measured on Word's -/// PDF of a Chinese document at 16 pt (#2358), as JIS X 4051 asks. A field or note number is -/// classed by the text it shows. The room goes after the first of the two characters; returns it -/// by cluster index. +/// The room automatic spacing leaves after a Latin character drawn in `st`: half its face's +/// average character width, the figure a platform's text metrics report. Times New Roman gives +/// 0.199 of the font size, Calibri 0.258, Cambria 0.304 (see [`auto_space`]). A face that is +/// itself East Asian averages its half-width cell, so a digit set in SimSun gives a quarter of +/// the size like the East Asian text around it. +fn auto_space_room(st: &StyleRun) -> f32 { + let ratio = if st.face.upem > 0.0 { st.face.avg_char_width / st.face.upem } else { 0.5 }; + let ratio = if ratio.is_finite() { ratio.clamp(0.0, 1.0) as f32 } else { 0.5 }; + if st.size.is_finite() { (st.size * ratio / 2.0).clamp(0.0, 400.0) } else { 0.0 } +} + +/// Automatic spacing (`w:autoSpaceDE`, `w:autoSpaceDN`): room between Asian text and Latin text or +/// digits that touch, across runs. The room goes after the first of the two characters and takes +/// that character's own size: a quarter of it in front of a Latin run, half the Latin face's +/// average character width after it ([`auto_space_room`]). A field or note number is classed by +/// the text it shows. Returns the room by cluster index. +/// +/// The quarter in front is Word's PDF of a Chinese document at 16 pt (#2358), as JIS X 4051 asks. +/// The room after a Latin run was measured in Word 16.0.17932.21056 over 26 faces, both orders, +/// 10.5 to 400 pt, Japanese and Chinese (#6583), through +/// `Range.Information(wdHorizontalPositionRelativeToPage)` rather than a PDF, since +/// `ExportAsFixedFormat` hung: the room in front of a Latin run is a quarter of the font size +/// whatever face the Latin text uses, while the room after it follows that face — 0.1986 of the +/// size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New, +/// 0.3041 for Cambria — which is half each face's average character width. With different sizes +/// either side, the room after the Latin run takes the Latin size, not the Asian one. pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> { let mut out = Vec::new(); if !de && !dn { return out; } let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable(); - // The previous text cluster: index, its last character, its font size. - let mut prev: Option<(usize, char, f32)> = None; + // The previous text cluster: index and its last character. + let mut prev: Option<(usize, char)> = None; for k in 0..b.clusters.len() { let Some(c) = b.clusters.get(k) else { break }; match c.kind { @@ -105,18 +126,23 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec prev = None; continue; }; - let size = b.styles.get(c.style as usize).map_or(0.0, |st| st.size); - if let Some((pk, pc, psize)) = prev + if let Some((pk, pc)) = prev && let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn) { - let asian = if side == crate::kinsoku::AsianSide::Left { psize } else { size }; - let gap = if asian.is_finite() { (asian / 4.0).clamp(0.0, 400.0) } else { 0.0 }; + let style = b.clusters.get(pk).map(|p| p.style as usize); + let st = style.and_then(|i| b.styles.get(i)); + let gap = match side { + // In front of the Latin run the Asian character carries the room (#2358). + crate::kinsoku::AsianSide::Left => st.map_or(0.0, |st| if st.size.is_finite() { (st.size / 4.0).clamp(0.0, 400.0) } else { 0.0 }), + // After it the Latin character carries the room, so its own face decides (#6583). + crate::kinsoku::AsianSide::Right => st.map_or(0.0, auto_space_room), + }; if let Some(pc) = b.clusters.get_mut(pk) { pc.adv += gap; out.push((pk, gap)); } } - prev = Some((k, last, size)); + prev = Some((k, last)); } out } diff --git a/crates/layout/src/tests/autospace.rs b/crates/layout/src/tests/autospace.rs index a5f335fb4d..aa7a63803d 100644 --- a/crates/layout/src/tests/autospace.rs +++ b/crates/layout/src/tests/autospace.rs @@ -1,7 +1,20 @@ -//! Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`, -//! #2358). Word's PDF of the issue's file shows about a quarter of the font size between 院 and 94 -//! at 16 pt. Assertions compare a layout with the flags on to the same layout with them off, never -//! font metrics (fonts differ between machines; CJK glyphs may be missing). +//! Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`). +//! The room goes after the first of the two characters and takes that character's own size. +//! +//! - **In front of a Latin run** it is a quarter of the font size: Word's PDF of the #2358 file +//! shows about that between 院 and 94 at 16 pt, as JIS X 4051 asks. +//! - **After a Latin run** it is half the Latin face's average character width — 0.1986 of the +//! font size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New, +//! 0.3041 for Cambria. Measured in Word 16.0.17932.21056 over 26 faces, both orders, 10.5 to +//! 400 pt, Japanese and Chinese (#6583), from +//! `Range.Information(wdHorizontalPositionRelativeToPage)` rather than a PDF, because +//! `ExportAsFixedFormat` hung on the machine it was measured on. The room in front stayed a +//! quarter of the size whatever face the Latin text used, and the room after a Latin run of +//! several characters followed the last of them. +//! +//! Assertions compare a layout with the flags on to the same layout with them off, and read the +//! average character width from the face the layout actually drew with rather than naming a +//! figure (fonts differ between machines; CJK glyphs may be missing). use crate::para::ClKind; use crate::*; @@ -41,39 +54,74 @@ fn gaps(d: &Document) -> Vec { panic!("the layouts with and without the automatic space draw with other faces"); } -/// The default font size of `d`'s first paragraph, a quarter of it. +/// The default font size of `d`'s first paragraph, a quarter of it: the room in front of a Latin +/// run (#2358). fn quarter(d: &Document) -> f32 { let pl = first_para(&lay(d)); let size = pl.clusters.first().and_then(|c| pl.styles.get(c.style as usize)).unwrap().size; (size / 4.0 * 100.0).round() / 100.0 } -#[test] -fn digits_and_latin_beside_asian_text_get_a_quarter_of_the_font_size() { - crate::test_fonts(); - let mut d = Document::from_text("法院94年A字"); - let q = quarter(&d); - assert!(q > 0.0); - // 院|9 and 4|年 (DN), 年|A and A|字 (DE): the space follows the first of the two. - assert_eq!(gaps(&d), [0.0, q, 0.0, q, q, q, 0.0]); - para0(&mut d).props.auto_space_dn = Some(false); - assert_eq!(gaps(&d), [0.0, 0.0, 0.0, 0.0, q, q, 0.0], "numbers off"); - let p = para0(&mut d); - p.props.auto_space_dn = None; - p.props.auto_space_de = Some(false); - assert_eq!(gaps(&d), [0.0, q, 0.0, q, 0.0, 0.0, 0.0], "Latin off"); +/// Half the average character width of the face that draws the cluster starting at byte `at`: +/// the room after a Latin character (#6583). +fn after(d: &Document, at: usize) -> f32 { + let pl = first_para(&lay(d)); + let c = pl.clusters.iter().find(|c| c.start == at).unwrap(); + let st = pl.styles.get(c.style as usize).unwrap(); + let room = st.size * (st.face.avg_char_width / st.face.upem) as f32 / 2.0; + (room * 100.0).round() / 100.0 } #[test] -fn the_space_crosses_runs_and_takes_the_asian_size() { +fn digits_and_latin_beside_asian_text_get_a_quarter_in_front_and_the_latin_average_after() { + crate::test_fonts(); + let mut d = Document::from_text("法院94年A字"); + let q = quarter(&d); + // 4 is at byte 7, A at byte 11: the room after each follows the face that draws it. + let (a4, aa) = (after(&d, 7), after(&d, 11)); + assert!(q > 0.0 && a4 > 0.0 && aa > 0.0); + assert_ne!(a4, q, "the test face must not average half its em, or this proves nothing"); + // 院|9 and 4|年 (DN), 年|A and A|字 (DE): the room follows the first of the two. + assert_eq!(gaps(&d), [0.0, q, 0.0, a4, q, aa, 0.0]); + para0(&mut d).props.auto_space_dn = Some(false); + assert_eq!(gaps(&d), [0.0, 0.0, 0.0, 0.0, q, aa, 0.0], "numbers off"); + let p = para0(&mut d); + p.props.auto_space_dn = None; + p.props.auto_space_de = Some(false); + assert_eq!(gaps(&d), [0.0, q, 0.0, a4, 0.0, 0.0, 0.0], "Latin off"); +} + +#[test] +fn the_space_crosses_runs_and_takes_the_size_of_the_character_before_it() { crate::test_fonts(); let mut d = Document::from_text("漢A漢"); let size = |s: f32| move |c: &mut CharProps| c.size = Some(s); let p = para0(&mut d); p.format(0, 3, &size(20.0)).unwrap(); - p.format(3, 4, &size(10.0)).unwrap(); + p.format(3, 4, &size(12.0)).unwrap(); p.format(4, 7, &size(20.0)).unwrap(); - assert_eq!(gaps(&d), [5.0, 5.0, 0.0]); + // 漢|A takes a quarter of the 20 pt 漢. A|漢 takes the 12 pt A, not the 20 pt 漢: in Word a + // 100 pt digit before a 400 pt ideograph moved it 19.85 pt and a 400 pt digit before a + // 100 pt one moved it 80.65 pt, both the Latin figure at the Latin size (#6583). + let a = after(&d, 3); + assert!(a > 0.0 && a < 5.0); + assert_eq!(gaps(&d), [5.0, a, 0.0]); +} + +#[test] +fn the_room_after_a_latin_run_follows_the_latin_face() { + crate::test_fonts(); + // Two faces whose average character widths differ: the room after the digit differs with + // them, while the room in front of it stays a quarter of the size. + let mut rooms = Vec::new(); + for family in ["Source Sans 3", "JetBrains Mono"] { + let mut d = Document::from_text("漢9漢"); + para0(&mut d).format(3, 4, &|c: &mut CharProps| c.font = Some(family.to_string())).unwrap(); + let (q, a) = (quarter(&d), after(&d, 3)); + assert_eq!(gaps(&d), [q, a, 0.0], "{family}"); + rooms.push(a); + } + assert_ne!(rooms[0], rooms[1], "the two faces must differ in average character width"); } #[test] @@ -97,8 +145,9 @@ fn a_field_result_is_classed_by_the_text_it_shows() { assert!(pl.shown.iter().any(|s| s.0 == at && s.1 == "12"), "the field shows its result: {:?}", pl.shown); let q = quarter(&d); assert_eq!(pl.clusters[at].kind, ClKind::Text); - // 漢|1 and 2|漢: the field's first and last characters, not the object it stands for. - assert_eq!(gaps(&d), [q, q, 0.0]); + // 漢|1 and 2|漢: the field's first and last characters, not the object it stands for. The + // room after the field follows the face it draws its result in. + assert_eq!(gaps(&d), [q, after(&d, 3), 0.0]); } #[test] @@ -114,8 +163,7 @@ fn a_character_grid_the_paragraph_snaps_to_turns_it_off() { 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)] { - let q = quarter(&d); - assert_eq!(gaps(&d), [0.0, q, 0.0, q, 0.0]); + assert_eq!(gaps(&d), [0.0, quarter(&d), 0.0, after(&d, 7), 0.0]); } } From 40fd69b6d832110968cf496a5a192dc77d066429 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Tue, 17 Nov 2026 03:47:26 -0800 Subject: [PATCH 73/99] backstage: the side menu scrolls when the window is too short for it (#6639) (#6647) --- crates/ui-egui/src/backstage.rs | 116 ++++++++++++++----------- crates/ui-egui/src/backstage/tests.rs | 119 ++++++++++++++++++++++++++ 2 files changed, 187 insertions(+), 48 deletions(-) diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 7788db71c2..a49d2f755d 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -130,59 +130,79 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { app.canvas.want_focus = true; } ui.add_space(if mac { 12.0 } else { 6.0 }); - for (id, label, icon) in PAGES { - // No document open (#1129): Info, Save, Save As, Print and Export are greyed out. - let on = has_document || works_without_document(id); - let (r, resp) = ui.add_enabled_ui(on, |ui| ui.allocate_exact_size(vec2(200.0, 38.0), Sense::click())).inner; - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, tl!(label))); - let active = app.ui.backstage_page == id; - if active { - ui.painter().rect_filled(r, 0.0, egui::Color32::from_white_alpha(46)); - } else if on && resp.hovered() { - ui.painter().rect_filled(r, 0.0, egui::Color32::from_white_alpha(26)); - } - let ink = if on { egui::Color32::WHITE } else { egui::Color32::from_white_alpha(110) }; - icons::paint( - ui.painter(), - Rect::from_center_size(pos2(crate::rtl::lead_x(rtl, r, 31.0), r.center().y), vec2(18.0, 18.0)), - icon, - ink, - ink, - ); - ui.painter().text( - pos2(crate::rtl::lead_x(rtl, r, 52.0), r.center().y), - crate::rtl::lead_center(rtl), - tl!(label), - if active { semibold(14.0) } else { medium(14.0) }, - ink, - ); - if on - && app.ui.keytips == crate::keytips::Phase::Backstage - && let Some(letter) = keytip_letter(id) - { - crate::keytips::badge(ui, Rect::from_min_size(pos2(r.min.x + 16.0, r.min.y), vec2(20.0, 16.0)), letter); - } - if resp.clicked() { - go_to_page(app, id); - } - } - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - for (label, id) in bottom_links(app) { - let (r, resp) = ui.allocate_exact_size(vec2(200.0, 32.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!(label))); - if resp.hovered() { + // A window too short for the whole menu scrolls it below the back button (#6639). + // When the menu fits, About and the community link stay at the bottom. + let links = bottom_links(app); + let spacing = ui.spacing().item_spacing.y; + let links_h = (32.0 + spacing) * links.len() as f32 - spacing; + let fits = ui.available_height(); + egui::ScrollArea::vertical().id_salt("backstage_nav_scroll").auto_shrink([false, false]).show(ui, |ui| { + let top = ui.cursor().top(); + for (id, label, icon) in PAGES { + // No document open (#1129): Info, Save, Save As, Print and Export are greyed out. + let on = has_document || works_without_document(id); + let (r, resp) = ui.add_enabled_ui(on, |ui| ui.allocate_exact_size(vec2(200.0, 38.0), Sense::click())).inner; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, tl!(label))); + // A row reached with Tab scrolls into view. + if resp.gained_focus() { + resp.scroll_to_me(None); + } + let active = app.ui.backstage_page == id; + if active { + ui.painter().rect_filled(r, 0.0, egui::Color32::from_white_alpha(46)); + } else if on && resp.hovered() { ui.painter().rect_filled(r, 0.0, egui::Color32::from_white_alpha(26)); } - let at = pos2(crate::rtl::lead_x(rtl, r, 22.0), r.center().y); - ui.painter().text(at, crate::rtl::lead_center(rtl), tl!(label), regular(13.0), egui::Color32::WHITE); + let ink = if on { egui::Color32::WHITE } else { egui::Color32::from_white_alpha(110) }; + icons::paint( + ui.painter(), + Rect::from_center_size(pos2(crate::rtl::lead_x(rtl, r, 31.0), r.center().y), vec2(18.0, 18.0)), + icon, + ink, + ink, + ); + ui.painter().text( + pos2(crate::rtl::lead_x(rtl, r, 52.0), r.center().y), + crate::rtl::lead_center(rtl), + tl!(label), + if active { semibold(14.0) } else { medium(14.0) }, + ink, + ); + if on + && app.ui.keytips == crate::keytips::Phase::Backstage + && let Some(letter) = keytip_letter(id) + { + crate::keytips::badge(ui, Rect::from_min_size(pos2(r.min.x + 16.0, r.min.y), vec2(20.0, 16.0)), letter); + } if resp.clicked() { - if id == "discord" { - let _ = app.run("ui.discord", json!({})); - } else { - app.dialog = crate::dialogs::Dialog::open("about", app); - } + go_to_page(app, id); } } + let gap = top + fits - ui.cursor().top() - links_h; + if gap > 0.0 { + ui.add_space(gap); + } + ui.allocate_ui_with_layout(vec2(200.0, links_h), egui::Layout::bottom_up(egui::Align::Min), |ui| { + for (label, id) in links { + let (r, resp) = ui.allocate_exact_size(vec2(200.0, 32.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!(label))); + if resp.gained_focus() { + resp.scroll_to_me(None); + } + if resp.hovered() { + ui.painter().rect_filled(r, 0.0, egui::Color32::from_white_alpha(26)); + } + let at = pos2(crate::rtl::lead_x(rtl, r, 22.0), r.center().y); + ui.painter().text(at, crate::rtl::lead_center(rtl), tl!(label), regular(13.0), egui::Color32::WHITE); + if resp.clicked() { + if id == "discord" { + let _ = app.run("ui.discord", json!({})); + } else { + app.dialog = crate::dialogs::Dialog::open("about", app); + } + } + } + }); }); }); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.ribbon).inner_margin(egui::Margin::symmetric(0, 30))).show(ui, |ui| { diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index 3c3282dc2e..d67e8a7291 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -1511,6 +1511,125 @@ fn the_file_page_scrolls_with_the_wheel_at_the_window_edge() { assert!((bar.right() - 1432.0).abs() < 1.0, "expected the scrollbar at the window edge: {bar:?}"); } +/// The File page in a window `height` points tall, left to right or, with `rtl`, in a right-to-left +/// interface (a fixture catalog, so the test does not need the translations). With `mac`, the +/// File page covers the integrated macOS title bar. +fn file_page_harness(rtl: bool, mac: bool, height: f32) -> egui_kittest::Harness<'static, WordApp> { + let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default()); + a.integrated_titlebar = mac; + a.mac_titlebar = crate::chrome::MacTitleBar { height: 28.0, content_left: 70.0 }; + a.run("ui.backstage", json!({"value": true, "page": "home"})).unwrap(); + let ar = crate::i18n::fixture_lang("ar", "\tHome\tHome\n"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, height)).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + // Draw the File page in a fixture language even without embedded catalogs. + crate::i18n::set_current(if rtl { ar } else { crate::i18n::Lang::EN }); + crate::rtl::sync(&ctx); + assert_eq!(crate::rtl::on(), rtl); + super::show(app, ui); + crate::i18n::set_current(crate::i18n::Lang::EN); + }, + a, + ); + h.run_steps(4); + h +} + +/// The rectangle of the side menu's button named `label`, a 200 point wide row (the page itself +/// may have a control with the same name). +fn side_menu_button(h: &egui_kittest::Harness<'static, WordApp>, label: &str) -> egui::Rect { + let label = crate::i18n::t(label).to_string(); + h.query_all_by_label(&label) + .map(|n| n.rect()) + .find(|r| (r.width() - 200.0).abs() < 0.5) + .unwrap_or_else(|| panic!("the side menu's {label} button")) +} + +/// #6639: in a window too short for the File page's side menu, the wheel over the menu scrolls +/// it, so Options and About can be reached. Checked left to right and right to left, where the +/// menu is on the right. +#[test] +fn the_side_menu_scrolls_with_the_wheel_in_a_short_window() { + // Both directions run before the test fails, so each one's result is reported. + let mut misses = Vec::new(); + for (rtl, x) in [(false, 100.0), (true, 1340.0)] { + let language = if rtl { "right to left" } else { "left to right" }; + let height = 360.0; + // The harness keeps an 8 point margin, so the window's bottom edge is at y=352. + let bottom = height - 8.0; + let mut h = file_page_harness(rtl, false, height); + let menu = side_menu_button(&h, "Home"); + assert!(menu.min.x <= x && x <= menu.max.x, "{language}: the menu is under the pointer: {menu:?}"); + for label in ["Options", "About"] { + let r = side_menu_button(&h, label); + assert!(r.max.y > bottom, "{language}: {label} starts below the window's bottom edge: {r:?}"); + } + h.event(egui::Event::PointerMoved(egui::pos2(x, 200.0))); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -2000.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }); + h.run_steps(4); + for label in ["Options", "About"] { + let r = side_menu_button(&h, label); + if r.max.y > bottom + 0.5 { + misses.push(format!("{language}: the wheel did not bring {label} into the window: {r:?}")); + } + } + assert!(h.state().ui.backstage, "{language}: File stays open"); + } + assert!(misses.is_empty(), "{misses:#?}"); +} + +/// #6639: in a window too short for the side menu, Tab to About scrolls the menu so that About +/// is in the window, left to right and right to left. +#[test] +fn tab_to_about_scrolls_it_into_a_short_window() { + let mut misses = Vec::new(); + for rtl in [false, true] { + let language = if rtl { "right to left" } else { "left to right" }; + let bottom = 360.0 - 8.0; + let mut h = file_page_harness(rtl, false, 360.0); + let about_focused = |h: &egui_kittest::Harness<'static, WordApp>| { + h.query_all_by_label("About").find(|n| (n.rect().width() - 200.0).abs() < 0.5 && n.is_focused()).map(|n| n.rect()) + }; + let mut about = None; + for _ in 0..40 { + h.key_press(egui::Key::Tab); + h.run_steps(4); + about = about_focused(&h); + if about.is_some() { + break; + } + } + let Some(r) = about else { + panic!("{language}: Tab reaches the side menu's About button"); + }; + if r.max.y > bottom + 0.5 { + misses.push(format!("{language}: About has the focus below the window's bottom edge: {r:?}")); + } + } + assert!(misses.is_empty(), "{misses:#?}"); +} + +/// #6639: when the whole side menu fits, About stays at the menu's bottom, above its 12 point +/// margin, as it was before the menu could scroll, with and without the macOS title bar. +#[test] +fn about_stays_at_the_bottom_of_a_side_menu_that_fits() { + for (rtl, mac) in [(false, false), (true, false), (false, true), (true, true)] { + let language = if rtl { "right to left" } else { "left to right" }; + let h = file_page_harness(rtl, mac, 900.0); + let about = side_menu_button(&h, "About"); + let bottom = 900.0 - 8.0 - 12.0; + assert!((about.max.y - bottom).abs() < 0.5, "{language}, mac {mac}: About sits at the bottom of the menu: {about:?}"); + } +} + /// Recursively collects bounding rectangles and text entries from egui shapes. fn collect_shapes(shape: &egui::Shape, rects: &mut Vec, texts: &mut Vec<(String, egui::Pos2, f32)>) { match shape { From 24885e830c9a240f06042051b3d4f4789ee51b8c Mon Sep 17 00:00:00 2001 From: pakiat <49967840+pakiat@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:00:45 +0700 Subject: [PATCH 74/99] Recovery: removing a record's folder waits for files Windows is still deleting (#6666) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/recovery/desktop.rs | 19 +++++++++++- crates/engine/src/recovery/desktop/tests.rs | 34 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/recovery/desktop.rs b/crates/engine/src/recovery/desktop.rs index c0e12abfd5..9f411fe7d3 100644 --- a/crates/engine/src/recovery/desktop.rs +++ b/crates/engine/src/recovery/desktop.rs @@ -15,6 +15,9 @@ const MAX_FILES: usize = 16; const DISK_BUDGET: u64 = 2 << 30; /// Times a record lock held for a moment (by a process being started) is tried again. const LOCK_RETRIES: u32 = 10; +/// How many times, 10 ms apart, a record's emptied folder is removed again while it isn't empty +/// yet ([`remove_record_dir`]). +const REMOVE_RETRIES: u32 = 100; #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -347,11 +350,25 @@ impl Store { self.entries.remove(id); self.locks.remove(id); fs::remove_file(dir.join("owner.lock")).map_err(|e| e.to_string())?; - fs::remove_dir(&dir).map_err(|e| e.to_string())?; + remove_record_dir(&dir, |d| fs::remove_dir(d)).map_err(|e| e.to_string())?; sync_dir(&self.root).map_err(|e| e.to_string())?; Ok(()) } } +/// Removes a record's emptied folder `dir` with `remove`. On Windows a file just deleted stays in +/// its folder, pending deletion, while another process still has it open (an antivirus scanner +/// or a search indexer looking at a file just written), so the folder isn't empty yet and +/// removing it fails ("The directory is not empty", os error 145): wait that out, retrying +/// [`REMOVE_RETRIES`] times 10 ms apart, as [`Store::lock`] waits out a lock held for a moment. +fn remove_record_dir(dir: &Path, mut remove: impl FnMut(&Path) -> io::Result<()>) -> io::Result<()> { + for _ in 0..REMOVE_RETRIES { + match remove(dir) { + Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => std::thread::sleep(Duration::from_millis(10)), + done => return done, + } + } + remove(dir) +} struct Limited { inner: W, remaining: u64, diff --git a/crates/engine/src/recovery/desktop/tests.rs b/crates/engine/src/recovery/desktop/tests.rs index 5891b26d4d..537bfba572 100644 --- a/crates/engine/src/recovery/desktop/tests.rs +++ b/crates/engine/src/recovery/desktop/tests.rs @@ -619,3 +619,37 @@ fn finish_recovery_covers_every_open_document() { s.finish_recovery(); assert_eq!(records(&t.0), [dirty]); } + +/// Removing a record's emptied folder waits out a file Windows hasn't finished deleting (another +/// process, such as an antivirus scanner, still has it open, so the folder isn't empty yet: os +/// error 145), which made saving with a password, and discarding a closed document's copy, fail +/// now and then. It doesn't wait on other errors, nor forever. +#[test] +fn removing_a_record_folder_waits_for_files_still_being_deleted() { + let not_empty = || io::Error::from(io::ErrorKind::DirectoryNotEmpty); + let mut pending = 3; + let removed = remove_record_dir(Path::new("record"), |_| { + if pending > 0 { + pending -= 1; + Err(not_empty()) + } else { + Ok(()) + } + }); + assert!(removed.is_ok(), "{removed:?}"); + assert_eq!(pending, 0); + let mut calls = 0; + let stuck = remove_record_dir(Path::new("record"), |_| { + calls += 1; + Err(not_empty()) + }); + assert_eq!(stuck.map_err(|e| e.kind()), Err(io::ErrorKind::DirectoryNotEmpty)); + assert_eq!(calls, REMOVE_RETRIES + 1); + let mut calls = 0; + let denied = remove_record_dir(Path::new("record"), |_| { + calls += 1; + Err(io::Error::from(io::ErrorKind::PermissionDenied)) + }); + assert_eq!(denied.map_err(|e| e.kind()), Err(io::ErrorKind::PermissionDenied)); + assert_eq!(calls, 1); +} From 880cda902f55a1bb5352b0b6cfd9cb3b1448c5bc Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:16:17 +0100 Subject: [PATCH 75/99] M14: clarify finite positive CLI scale errors (#6691) --- apps/wordcraft-cli/src/main.rs | 2 +- apps/wordcraft-cli/src/tests.rs | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/apps/wordcraft-cli/src/main.rs b/apps/wordcraft-cli/src/main.rs index b500db3293..63d4abf3c2 100644 --- a/apps/wordcraft-cli/src/main.rs +++ b/apps/wordcraft-cli/src/main.rs @@ -266,7 +266,7 @@ fn parse_scale_arg(command: &str, args: &[String]) -> Result, String OptionArg::Value(val) => { let scale = val.parse::().map_err(|_| format!("{command}: invalid --scale `{val}`: not a number"))?; if !scale.is_finite() || scale <= 0.0 { - return Err(format!("{command}: invalid --scale `{val}`: scale must be a positive number")); + return Err(format!("{command}: invalid --scale `{val}`: scale must be a finite positive number")); } Ok(Some(scale)) } diff --git a/apps/wordcraft-cli/src/tests.rs b/apps/wordcraft-cli/src/tests.rs index b22e4ffa05..e22d4791fb 100644 --- a/apps/wordcraft-cli/src/tests.rs +++ b/apps/wordcraft-cli/src/tests.rs @@ -267,19 +267,19 @@ fn render_rejects_missing_or_invalid_page_and_scale() { assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into())); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])), - Err("render: invalid --scale `0`: scale must be a positive number".into()) + Err("render: invalid --scale `0`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])), - Err("render: invalid --scale `-2`: scale must be a positive number".into()) + Err("render: invalid --scale `-2`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])), - Err("render: invalid --scale `NaN`: scale must be a positive number".into()) + Err("render: invalid --scale `NaN`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])), - Err("render: invalid --scale `inf`: scale must be a positive number".into()) + Err("render: invalid --scale `inf`: scale must be a finite positive number".into()) ); // Duplicate options @@ -322,19 +322,19 @@ fn run_rejects_missing_or_invalid_page_and_scale() { ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])), - Err("run: invalid --scale `0`: scale must be a positive number".into()) + Err("run: invalid --scale `0`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])), - Err("run: invalid --scale `-1`: scale must be a positive number".into()) + Err("run: invalid --scale `-1`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])), - Err("run: invalid --scale `NaN`: scale must be a positive number".into()) + Err("run: invalid --scale `NaN`: scale must be a finite positive number".into()) ); assert_eq!( run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])), - Err("run: invalid --scale `inf`: scale must be a positive number".into()) + Err("run: invalid --scale `inf`: scale must be a finite positive number".into()) ); // Duplicate options From 1a56d041defe28f0d35de501ba7e40268a549d26 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Tue, 17 Nov 2026 04:24:29 -0800 Subject: [PATCH 76/99] Dependencies: take craft-libs main at 453b0da782 (#6886) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Dependencies: take craft-libs main at 3af2280ee3 Every craft-libs git dependency (the workspace's 25, ui-egui's 3, the app's craft-print, the web build's 2 and the krilla patch) moves to craft-libs main at 3af2280ee3 from the 8 revisions they were pinned at. Cargo.lock changes those sources, moves winprint and craft-winprint-gdi with craft-print, drops the second craft-tiff, and adds cap-primitives and its dependencies, which craft-font-store's Language pack recovery uses on native builds. - craft_print::Job has two new fields. WordCraft sets grey_pages to false, since it does not turn the spooled pages gray, and driver_settings to None. - DOCX text boxes, rectangles, rounded rectangles and ellipses are now written in mc:AlternateContent with a VML fallback that repeats the text box's text. Two tests that counted w:txbxContent elements, or the story text, now count the fallback copy as well. * Printing: the isolated print helper keeps the job's grey pages and driver settings The Windows print helper process rebuilt each job with grey_pages off and no driver settings, whatever the job carried. Its request now carries both: the driver settings travel as the printer's name and the DEVMODE in hex, and damaged settings are an error. The request file may now be up to 2 MiB larger, the size of the largest driver settings craft-print accepts, written as hex. Comments in Cargo.toml and apps/wordcraft/Cargo.toml now describe the shared craft-libs commit, and the shared-story text box test says where its two copies are written. * DOCX: open picture frame shapes and keep chart formatting from craft-libs At this craft-libs commit the DOCX reader returns a picture frame shape (`frame` preset) as its own shape kind, and charts carry series formatting and axis settings. WordCraft's model had neither: - A document with a picture frame shape failed to open with "unknown variant `frame`". The model bridge now reads it as a rectangle, as the earlier reader did. - The chart model drops nothing the shared chart model holds: series fill, line width, line and fill off, markers, smooth lines, data labels and number format, and the category and value axes. Before, saving a chart with any of these wrote the chart again without them. - A new scatter series is drawn as markers without a line, as before. Change Chart Type sets this when a chart becomes a scatter chart or stops being one, Edit Data keeps each replaced series' formatting, and Data Labels replaces each series' own label setting. * Charts: draw turned axis titles and keep stored scatter charts without lines At this craft-libs commit a chart's vertical axis title is a text item turned -90°. WordCraft's graphic text item now carries that angle, and the text is laid out along its box and drawn turned about the box's center. Scatter series saved in a .json document or a recovery snapshot before series formatting existed have no `noLine` value. They now read as markers without a line, as they were drawn when saved. * Charts: draw opened ODT scatter charts without lines The ODF reader at this craft-libs commit does not read a scatter chart's line setting, so a scatter chart saved as ODT and opened again was drawn with lines between its points. The ODF writer writes every scatter series as markers without a line, and the opened chart is now drawn that way. * Charts: set scatter series to markers only for opened ODF files alone Opened ODT, OTT and FODT files set their scatter series to markers without a line, since the ODF reader does not read a series' line setting. Other formats that go through the same import path keep their series as read. A series that arrives with its markers turned off gets them back, as Change Chart Type does, so it is still drawn. The test for an opened scatter chart now also covers flat ODT, checks the drawn items against the markers-only drawing, and checks that the chart's paragraph is still written as read. * Dependencies: take craft-libs main at 453b0da782 Every craft-libs dependency, and the craft-proof note in Cargo.toml, moves from 3af2280ee3 to 453b0da782. Cargo.lock adds craft-dds, which craft-image-codecs now uses; no crates.io version changes. - craft-xls builds its test fixtures only for tests and its test-support feature, and they return a Result. wordcraft-formats gets a test-support feature that turns it on; sheet::xls_fixture is behind it and returns Result, and wordcraft-engine's tests enable it. - craft_metafile::Picture has new report fields; the render tests' literals fill them with Default. - The docx tests follow the writer: the font table is kept as read, the flat OPC comparison allows a kept part without its XML declaration, and the bibliography store is related from the main part, once, after a second save too. * DOCX: gutter position Top is kept when a document is opened and saved craft-libs now reads w:gutterAtTop into its settings model instead of keeping it as unread XML, and WordCraft's settings had no field for it, so opening and saving a document dropped the setting. Settings gets gutter_at_top (off by default), which the document bridge carries both ways. Layout still puts the gutter on the left. * Charts: Change Chart Type gives a pie chart's value axis the new type's gridlines A pie or doughnut chart keeps a plain value axis (no gridlines, axis line on), and a new chart of any other type has gridlines and no axis line. Change Chart Type kept the old axis, so a pie chart changed to a column chart was drawn and saved without gridlines and with an axis line. Change Chart Type between a round chart and another type now sets the value axis to the new type's when it is still the old type's; an axis that was changed stays as it is. The progress log gets a line for the chart formatting, turned axis titles, picture frame shapes and gutter position this branch brings. The gutter_at_top doc comment states only what the field holds. --- Cargo.lock | 201 +++++++++---- Cargo.toml | 60 ++-- ROADMAP.md | 1 + apps/wordcraft-web/Cargo.toml | 4 +- apps/wordcraft/Cargo.toml | 4 +- apps/wordcraft/src/print.rs | 2 + apps/wordcraft/src/print/isolated.rs | 48 +++- crates/doc/src/chart.rs | 264 +++++++++++++++++- crates/doc/src/graphic.rs | 4 + crates/doc/src/settings.rs | 3 + crates/docx/src/model_bridge.rs | 113 ++++++++ .../tests/it/content_control_save_cost.rs | 2 + crates/docx/tests/it/roundtrip.rs | 58 +++- crates/docx/tests/it/text_boxes.rs | 4 +- crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/chart.rs | 48 +++- crates/engine/src/cmd/mailings/tests.rs | 3 +- crates/engine/src/io_ext.rs | 45 ++- crates/engine/src/tests.rs | 149 ++++++++++ crates/formats/Cargo.toml | 5 + crates/formats/src/sheet.rs | 5 +- crates/layout/src/display/objects.rs | 14 +- crates/layout/src/tests.rs | 42 +++ crates/layout/src/tests/missing_glyphs.rs | 1 + crates/pdf/src/tests.rs | 2 + crates/render/src/tests.rs | 6 +- crates/ui-egui/Cargo.toml | 6 +- 27 files changed, 961 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 152e056f71..527d0426dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -185,6 +185,12 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + [[package]] name = "android-activity" version = "0.6.1" @@ -739,6 +745,24 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cap-primitives" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix 1.1.5", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + [[package]] name = "cc" version = "1.6.0" @@ -1036,7 +1060,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "rustix 1.1.5", ] @@ -1044,17 +1068,25 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" + +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +dependencies = [ + "rayon", +] [[package]] name = "craft-doc-binary" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "chrono", "craft-cfb", @@ -1070,7 +1102,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "base64 0.23.1", "chrono", @@ -1090,7 +1122,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-xml", "kurbo", @@ -1101,7 +1133,7 @@ dependencies = [ [[package]] name = "craft-flow" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-wordmodel", "image", @@ -1111,19 +1143,24 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "fontique", + "harfrust 0.13.3", + "kurbo", "skrifa 0.47.0", "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", "windows-registry", ] [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ + "cap-primitives", "craft-atomic", "craft-font-catalog", "flate2", @@ -1142,12 +1179,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" [[package]] name = "craft-html" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-codepage", "craft-flow", @@ -1160,7 +1197,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1183,13 +1220,17 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ + "craft-dds", "craft-jpeg", "craft-metadata", + "craft-tiff", + "crc32fast", "exr", "flate2", "half", + "hayro-jpeg2000", "image", "image-webp", "jpeg-encoder", @@ -1206,7 +1247,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "thiserror 2.0.21", ] @@ -1214,7 +1255,7 @@ dependencies = [ [[package]] name = "craft-latex" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-flow", "craft-math", @@ -1225,7 +1266,7 @@ dependencies = [ [[package]] name = "craft-markdown" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-flow", "craft-html", @@ -1235,7 +1276,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-xml", "serde", @@ -1244,11 +1285,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "brotli-decompressor 6.3.1", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)", + "craft-tiff", "quick-xml 0.41.0", "serde", ] @@ -1256,7 +1297,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "encoding_rs", "image", @@ -1267,7 +1308,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "chardetng", "chrono", @@ -1278,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "aes", "base64 0.23.1", @@ -1304,7 +1345,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-odf", "craft-sheet", @@ -1315,7 +1356,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "aes", "base64 0.23.1", @@ -1332,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-xml", "craft-zip", @@ -1343,7 +1384,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "krilla", "thiserror 2.0.21", @@ -1352,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a3e0b5a9440d18f19422a9dca13516747b7d3181#a3e0b5a9440d18f19422a9dca13516747b7d3181" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-winprint-gdi", "log", @@ -1366,7 +1407,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=01315d9c92b5b0e69082d35ca56099461a1efd45#01315d9c92b5b0e69082d35ca56099461a1efd45" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1377,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-codepage", "craft-flow", @@ -1390,21 +1431,12 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "serde", "thiserror 2.0.21", @@ -1413,7 +1445,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1433,7 +1465,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "chrono", "dunce", @@ -1460,7 +1492,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "js-sys", "serde_json", @@ -1471,7 +1503,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "wasm-bindgen", "web-sys", @@ -1480,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "egui", "objc2 0.6.5", @@ -1491,7 +1523,7 @@ dependencies = [ [[package]] name = "craft-winprint-gdi" version = "0.1.0" -source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312" +source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f" dependencies = [ "windows-sys 0.61.2", ] @@ -1499,7 +1531,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "base64 0.23.1", "craft-math", @@ -1513,7 +1545,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-cfb", "craft-sheet", @@ -1526,7 +1558,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "craft-drawingml", "craft-opc", @@ -1538,16 +1570,17 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2325,6 +2358,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix 1.1.5", + "windows-sys 0.52.0", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -3195,6 +3239,28 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.52.0", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + [[package]] name = "ipnet" version = "2.12.2" @@ -3350,7 +3416,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3486,6 +3552,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + [[package]] name = "md-5" version = "0.10.6" @@ -4979,6 +5051,16 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix 1.1.5", +] + [[package]] name = "rustls" version = "0.23.46" @@ -7158,7 +7240,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", @@ -7173,6 +7255,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -7202,6 +7285,16 @@ version = "0.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags 2.13.2", + "windows-sys 0.52.0", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -7416,7 +7509,7 @@ name = "wordcraft-geom" version = "0.18.1" dependencies = [ "craft-image-codecs", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)", + "craft-tiff", "image", "serde", ] diff --git a/Cargo.toml b/Cargo.toml index a4876fdb72..880500f2fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,19 +24,19 @@ wordcraft-pdf = { path = "crates/pdf" } # Proofing is craft-libs' craft-proof (it was crates/proof); its Language data is craft-i18n's # language-data/, embedded from CRAFT_I18N_DIR (craft-i18n.rev). The package keeps the # `wordcraft-proof` name here so `wordcraft_proof::` paths are unchanged. -# craft-proof is storytold/craft-libs main at the merge of #590 (ca-ES-valencia reads the ca-valencia -# pack), after #589 (French elision suggestions first) and #497 (flag-based compounding), which also -# has #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font store's -# `language-pack` kind is #486 (CP4.1). -wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "01315d9c92b5b0e69082d35ca56099461a1efd45", version = "=0.1.0" } -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" } +# craft-proof is storytold/craft-libs main at 453b0da782. That commit has #590 (ca-ES-valencia +# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based +# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font +# store's `language-pack` kind is #486 (CP4.1). +wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } wordcraft-engine = { path = "crates/engine" } wordcraft-mcp = { path = "crates/mcp" } wordcraft-zotero = { path = "crates/zotero" } wordcraft-control-key = { path = "crates/control-key" } wordcraft-ui-egui = { path = "crates/ui-egui" } -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -67,28 +67,28 @@ wuff = "0.2.9" brotli-decompressor = "5" vello_cpu = "0.2" image = { version = "0.25", default-features = false } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", default-features = false, features = ["write"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["doc"] } -craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["text"] } -craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-html = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["flow"] } -craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-math = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["detect"] } -craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["doc"] } +craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["text"] } +craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-html = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["flow"] } +craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["detect"] } +craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } # zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates. miniz_oxide = "0.9" cfb = "0.15" @@ -153,7 +153,7 @@ debug = 0 # Required by craft-pdf: the backend rejects writers that failed during unwinding. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/ROADMAP.md b/ROADMAP.md index dd88207e56..39057e23fe 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -229,6 +229,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-11-02: ODT files follow their standard wherever it says something, and a setting wherever it doesn't (gap 19). File › Options › Advanced › OpenDocument files (and `file.options` `odf`) chooses between two display styles, Microsoft Word style (the default) and LibreOffice style, or custom values for each of twelve cases the standard leaves open: header heights and spacing, column gaps, shape colours and hairlines, where tab stops are measured from, frame relations the standard doesn't define, and lines of only pictures. A page layout that states no margins follows the setting too: 0 in Microsoft Word style (XSL's initial value), 2 cm for LibreOffice. Every case is listed in docs/odf-interpretation.md; Google Docs and ONLYOFFICE files checked, and neither needs a preset of its own yet. - 2026-11-02: ODT form controls keep their place on the line and multi-line text fields their lines; custom shapes keep their own geometry (LibreOffice draws its own shape after a save). In-line pictures placed against the text are raised from its size, and saved standing on the baseline. The corpus round-trip difference falls to 41k pixels, 90% below this morning's 408k; 42 of 125 documents round-trip pixel-identical (gap 19). Readiness unchanged. - 2026-11-02: ODT charts keep their whole look through a save: the chart object as read is written back while the chart is unchanged (edited, it's written from WordCraft's chart). Frames outlined by a drawn stroke keep it, and a header with no stated height is LibreOffice's 0.5 cm. The corpus round-trip difference falls to 47k pixels (408k this morning); 41 of 125 documents round-trip pixel-identical (gap 19). Readiness unchanged. +- 2026-11-17: DOCX charts keep each series' fill, line, markers, smooth lines, data labels and number format, and each axis's title, bounds, number format, gridlines, labels and line, through an open and a save; a vertical axis title is drawn turned. Change Chart Type between a pie or doughnut chart and another type gives the value axis the new type's gridlines and axis line unless it was changed. Picture frame shapes open as rectangles, and a gutter set at the top (`w:gutterAtTop`) is kept on save; layout does not move the gutter to the top. Readiness unchanged. - 2026-11-02: ODT: saving no longer makes a table's first row repeat on every page (a table style's header row had been taken for Repeat as header row), so LibreOffice's 16 agenda templates round-trip with their text the same; 91 of the 125 corpus documents now do, and the round-trip difference falls to 60k pixels (408k this morning) (gap 19). Readiness unchanged. - 2026-11-02: ODT documents open with LibreOffice's layout where it differs from Word (new `Settings::odf_layout`): a line of only pictures is as tall as they are, and a paragraph's padding without a border takes room. Unequal columns and column breaks are kept. The corpus round-trip difference falls to 82k pixels, 80% below this morning's 408k; LibreOffice's report templates and one-page résumé now round-trip almost pixel-identical (gap 19). Readiness unchanged. - 2026-11-02: ODT, from LibreOffice's report templates and agenda: tables filling the margins fit them, and a table's own space above and below is kept and laid out (new `TableProps::space_before`/`space_after`); a header's spacing stays below one taller than its band (new `SectionProps::header_gap`/`footer_gap`); a picture alone in a paragraph keeps the paragraph's size and its raise. The corpus round-trip difference falls from 241k to 155k pixels, 62% below this morning's 408k (gap 19). Readiness unchanged. diff --git a/apps/wordcraft-web/Cargo.toml b/apps/wordcraft-web/Cargo.toml index 8c42c988b1..382d35f566 100644 --- a/apps/wordcraft-web/Cargo.toml +++ b/apps/wordcraft-web/Cargo.toml @@ -18,8 +18,8 @@ wordcraft-engine = { workspace = true } wordcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.wordcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/wordcraft/Cargo.toml b/apps/wordcraft/Cargo.toml index c7768b0dae..8bd6f5b39c 100644 --- a/apps/wordcraft/Cargo.toml +++ b/apps/wordcraft/Cargo.toml @@ -84,9 +84,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfi clipboard-win = { version = "5.4", features = ["std"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# Pinned apart from craft-ui, which doesn't depend on it: `printer_queues`, the printer list that +# At the same craft-libs commit as the workspace's crates: `printer_queues`, the printer list that # asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622). -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a3e0b5a9440d18f19422a9dca13516747b7d3181" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } rfd = { workspace = true } # Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94); # rfd itself already depends on it. diff --git a/apps/wordcraft/src/print.rs b/apps/wordcraft/src/print.rs index 9465c4485c..7b8c98ca1c 100644 --- a/apps/wordcraft/src/print.rs +++ b/apps/wordcraft/src/print.rs @@ -89,9 +89,11 @@ pub fn submit() -> Submit { Duplex::Off => craft_print::Duplex::Off, }), grayscale: settings.grayscale, + grey_pages: false, scaling: craft_print::Scaling::ShrinkToFit, title: "WordCraft document".into(), options, + driver_settings: None, }; #[cfg(not(windows))] let sent = craft_print::submit_cancellable(&bytes, &job, &mut |_, _| {}, &token).map_err(|error| error.to_string()); diff --git a/apps/wordcraft/src/print/isolated.rs b/apps/wordcraft/src/print/isolated.rs index b2463b5d92..6d89b969fb 100644 --- a/apps/wordcraft/src/print/isolated.rs +++ b/apps/wordcraft/src/print/isolated.rs @@ -15,6 +15,8 @@ use serde::{Deserialize, Serialize}; const FLAG: &str = "--wordcraft-print-worker"; const PREFIX: &str = "WORDCRAFT_PRINT:"; const MAX_MESSAGE: u64 = 64 * 1024; +/// The job's options, and a driver's settings of up to 1 MiB written as hex. +const MAX_REQUEST: u64 = MAX_MESSAGE + 2 * 1024 * 1024; const MAX_PDF: u64 = 512 * 1024 * 1024; const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer"; @@ -32,9 +34,12 @@ struct Request { collate: bool, duplex: Option, grayscale: bool, + grey_pages: bool, shrink: bool, title: String, options: Vec<(String, String)>, + /// The printer the driver's settings were chosen for, and their DEVMODE as hex. + driver_settings: Option<(String, String)>, } impl Request { @@ -50,15 +55,21 @@ impl Request { craft_print::Duplex::ShortEdge => Duplex::ShortEdge, }), grayscale: job.grayscale, + grey_pages: job.grey_pages, shrink: job.scaling == craft_print::Scaling::ShrinkToFit, title: job.title.clone(), options: job.options.clone(), + driver_settings: job.driver_settings.as_ref().map(|settings| (settings.printer().to_owned(), settings.dev_mode().to_hex())), } } /// Restore the job without substituting printer defaults or changing copy semantics. - fn job(self) -> craft_print::Job { - craft_print::Job { + fn job(self) -> Result { + let driver_settings = match self.driver_settings { + Some((printer, hex)) => Some(craft_print::DriverSettings::new(printer, craft_print::rgb::DevMode::from_hex(&hex).map_err(error)?)), + None => None, + }; + Ok(craft_print::Job { printer: self.printer, copies: self.copies, collate: self.collate, @@ -68,10 +79,12 @@ impl Request { Duplex::ShortEdge => craft_print::Duplex::ShortEdge, }), grayscale: self.grayscale, + grey_pages: self.grey_pages, scaling: if self.shrink { craft_print::Scaling::ShrinkToFit } else { craft_print::Scaling::Exact }, title: self.title, options: self.options, - } + driver_settings, + }) } } @@ -166,7 +179,7 @@ impl Submission { return Err("the print PDF exceeds the 512 MiB helper limit".into()); } let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?; - if request.len() as u64 > MAX_MESSAGE { + if request.len() as u64 > MAX_REQUEST { return Err("the print settings exceed the helper message limit".into()); } let directory = tempfile::tempdir().map_err(error)?; @@ -323,10 +336,10 @@ fn helper( }) .map_err(error)?; let request: Request = - serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_MESSAGE)?).map_err(error)?; + serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_REQUEST)?).map_err(error)?; let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?; remove_inputs(directory)?; - let result = submit(&pdf, &request.job(), &cancel); + let result = submit(&pdf, &request.job()?, &cancel); emit(&Event::Done(result)) } @@ -463,21 +476,40 @@ mod tests { } #[test] - /// Job transport preserves every explicit setting, including Unicode and duplex direction. + /// Job transport preserves every explicit setting, including Unicode, duplex direction and the + /// driver's own settings. fn job_options_survive_the_process_boundary() { + // A DEVMODEW header of 156 bytes (`dmSize` at 68) and a 4-byte private part (`dmDriverExtra` at 70). + let mut dev_mode = vec![0u8; 160]; + dev_mode[68..70].copy_from_slice(&156u16.to_le_bytes()); + dev_mode[70..72].copy_from_slice(&4u16.to_le_bytes()); + dev_mode[156..].copy_from_slice(&[1, 2, 3, 4]); + let dev_mode = craft_print::rgb::DevMode::from_bytes(dev_mode).unwrap(); let expected = craft_print::Job { printer: Some("Office λ".into()), copies: 3, collate: false, duplex: Some(craft_print::Duplex::ShortEdge), grayscale: true, + grey_pages: true, scaling: craft_print::Scaling::ShrinkToFit, title: "A document".into(), options: vec![("media".into(), "iso_a4_210x297mm".into())], + driver_settings: Some(craft_print::DriverSettings::new("Office λ", dev_mode)), }; let bytes = serde_json::to_vec(&Request::from_job(&expected)).unwrap(); let received: Request = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(received.job(), expected); + assert_eq!(received.job(), Ok(expected)); + } + + #[test] + /// Damaged driver settings on the wire are an error, not a job printed with other settings. + fn damaged_driver_settings_are_refused() { + for hex in ["", "0", "zz", "00"] { + let mut request = Request::from_job(&job()); + request.driver_settings = Some(("Office".into(), hex.into())); + assert!(request.job().is_err(), "{hex:?}"); + } } #[test] diff --git a/crates/doc/src/chart.rs b/crates/doc/src/chart.rs index 6bbfeb8849..4132252af1 100644 --- a/crates/doc/src/chart.rs +++ b/crates/doc/src/chart.rs @@ -11,6 +11,8 @@ use serde::{Deserialize, Serialize}; +use crate::props::Rgb; + /// Most series in a chart. pub const MAX_SERIES: usize = 255; /// Most categories (points per series) in a chart. @@ -123,17 +125,119 @@ impl LegendPos { } } -/// One series: its name and a value per category (`None` = no value, a gap). +/// One series: its name, a value per category (`None` = no value, a gap) and how it is drawn: +/// fill, line, markers, smooth lines, its own data labels and number format. Unset fields follow +/// the chart's defaults. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChartSeries { pub name: String, #[serde(default)] pub values: Vec>, + /// Fill color; `None`: the chart's accent color for the series. + #[serde(default)] + pub fill: Option, + /// "None" fill: the series draws no fill. + #[serde(default)] + pub no_fill: bool, + /// Line width in points; `None`: the chart's default. + #[serde(default)] + pub line_w: Option, + /// "None" line: the series draws no line. + #[serde(default)] + pub no_line: bool, + /// Markers on points; `None`: unset (scatter charts draw them; a saved scatter series then has + /// no `c:marker`). + #[serde(default)] + pub markers: Option, + /// Draw the line as a smooth curve. + #[serde(default)] + pub smooth: bool, + /// Data labels for this series; `None`: follow the chart's setting. + #[serde(default)] + pub labels: Option, + /// Number format of this series's labels and values; `None`: linked to the source. + #[serde(default)] + pub fmt: Option, +} + +impl ChartSeries { + /// A new series of a `kind` chart: a scatter series is drawn as markers without a line. + pub fn new(kind: ChartType, name: String, values: Vec>) -> ChartSeries { + ChartSeries { name, values, no_line: kind == ChartType::Scatter, ..Default::default() } + } +} + +/// One chart axis: title, scale bounds, tick-label number format, gridlines, tick labels and the +/// axis line. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChartAxis { + /// `None`: no axis title; text cut to [`MAX_TEXT`] characters. + #[serde(default)] + pub title: Option, + /// Fixed lower bound; `None`: automatic. + #[serde(default)] + pub min: Option, + /// Fixed upper bound; `None`: automatic. + #[serde(default)] + pub max: Option, + /// Tick-label number format (`#,##0`, `0.00`, `0%`…); `None`: linked to the source data. + #[serde(default)] + pub fmt: Option, + /// Major gridlines drawn along this axis. + #[serde(default)] + pub gridlines: bool, + /// Tick labels; `false` hides them. + #[serde(default = "the_true")] + pub labels: bool, + /// The axis line. + #[serde(default = "the_true")] + pub line: bool, +} + +fn the_true() -> bool { + true +} + +impl Default for ChartAxis { + fn default() -> Self { + ChartAxis { title: None, min: None, max: None, fmt: None, gridlines: false, labels: true, line: true } + } +} + +/// The value axis as a new chart has it: gridlines, labels, no axis line. +pub fn value_axis() -> ChartAxis { + ChartAxis { gridlines: true, line: false, ..ChartAxis::default() } +} + +impl ChartAxis { + /// Make the axis safe to store: texts cleaned, bounds finite, `min` under `max` (an + /// impossible pair drops both), the format code cut to [`MAX_FMT`] characters. + pub fn sanitize(&mut self) { + self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty()); + self.min = self.min.filter(|v| v.is_finite()); + self.max = self.max.filter(|v| v.is_finite()); + if matches!((self.min, self.max), (Some(lo), Some(hi)) if lo >= hi) { + self.min = None; + self.max = None; + } + self.fmt = self.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty()); + } +} + +/// Longest axis number format kept, characters. +pub const MAX_FMT: usize = 128; + +/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`] +/// characters. +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::().trim_end().to_string() } /// A chart WordCraft can edit. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ChartSpec { #[serde(rename = "type")] @@ -151,6 +255,78 @@ pub struct ChartSpec { /// Show each point's value next to it. #[serde(default)] pub data_labels: bool, + /// The category axis (scatter charts: the x axis). + #[serde(default)] + pub cat_axis: ChartAxis, + /// The value axis (scatter charts: the y axis); gridlines on and no axis line in a new chart. + #[serde(default = "value_axis")] + pub val_axis: ChartAxis, +} + +/// A [`ChartSpec`] as stored. A scatter series saved without `noLine` (by a version without +/// series formatting) is drawn as markers without a line, as that version drew it. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredSpec { + #[serde(rename = "type")] + kind: ChartType, + #[serde(default)] + categories: Vec, + #[serde(default)] + series: Vec, + #[serde(default)] + title: Option, + #[serde(default)] + legend: Option, + #[serde(default)] + data_labels: bool, + #[serde(default)] + cat_axis: ChartAxis, + #[serde(default = "value_axis")] + val_axis: ChartAxis, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredSeries { + #[serde(default)] + no_line: Option, + #[serde(flatten)] + series: ChartSeries, +} + +impl<'de> Deserialize<'de> for ChartSpec { + fn deserialize>(deserializer: D) -> Result { + let s = StoredSpec::deserialize(deserializer)?; + let scatter = s.kind == ChartType::Scatter; + Ok(ChartSpec { + kind: s.kind, + categories: s.categories, + series: s.series.into_iter().map(|x| ChartSeries { no_line: x.no_line.unwrap_or(scatter), ..x.series }).collect(), + title: s.title, + legend: s.legend, + data_labels: s.data_labels, + cat_axis: s.cat_axis, + val_axis: s.val_axis, + }) + } +} + +impl Default for ChartSpec { + /// An empty chart whose value axis is the one a new chart (and a missing JSON field) has: + /// gridlines on, no axis line. + fn default() -> Self { + ChartSpec { + kind: ChartType::default(), + categories: Vec::new(), + series: Vec::new(), + title: None, + legend: None, + data_labels: false, + cat_axis: ChartAxis::default(), + val_axis: value_axis(), + } + } } impl ChartSpec { @@ -168,10 +344,14 @@ impl ChartSpec { ChartSpec { kind, categories: categories.into_iter().map(str::to_string).collect(), - series: series.into_iter().map(|(n, v)| ChartSeries { name: n.to_string(), values: v.into_iter().map(Some).collect() }).collect(), + series: series.into_iter().map(|(n, v)| ChartSeries::new(kind, n.to_string(), v.into_iter().map(Some).collect())).collect(), title: None, legend: Some(LegendPos::Bottom), data_labels: false, + cat_axis: ChartAxis::default(), + // Pie and doughnut charts have no axes: their axes stay plain, so the chart reads back + // as the same model. + val_axis: if kind.is_round() { ChartAxis::default() } else { value_axis() }, } } @@ -203,8 +383,12 @@ impl ChartSpec { *v = v.filter(|x| x.is_finite()); } s.values.resize(n, None); + s.fmt = s.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty()); + s.line_w = s.line_w.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 20.0)); } self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty()); + self.cat_axis.sanitize(); + self.val_axis.sanitize(); } /// The chart after `sanitize`. @@ -229,7 +413,11 @@ mod tests { let mut c = ChartSpec { categories: vec!["a".into(); MAX_POINTS + 10], series: (0..MAX_SERIES + 5) - .map(|i| ChartSeries { name: format!("{}\n{}", "x".repeat(400), i), values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)] }) + .map(|i| ChartSeries { + name: format!("{}\n{}", "x".repeat(400), i), + values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)], + ..Default::default() + }) .collect(), title: Some(" ".into()), ..Default::default() @@ -250,7 +438,7 @@ mod tests { fn short_categories_are_padded_to_the_longest_series() { let c = ChartSpec { categories: vec!["a".into()], - series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)] }], + series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)], ..Default::default() }], ..Default::default() } .sanitized(); @@ -258,4 +446,70 @@ mod tests { assert_eq!(ChartType::from_id("BARSTACKED"), Some(ChartType::BarStacked)); assert_eq!(LegendPos::from_id("top"), Some(LegendPos::Top)); } + + /// A scatter series stored without `noLine` reads as markers without a line; a stored value + /// and the other chart types keep theirs. + #[test] + fn stored_scatter_series_without_a_line_setting_draw_no_line() { + let read = |json: &str| -> Vec { serde_json::from_str::(json).unwrap().series.iter().map(|s| s.no_line).collect() }; + let series = r#"[{"name":"a","values":[1,null,2.5]},{"name":"b","values":[3],"noLine":false}]"#; + assert_eq!(read(&format!(r#"{{"type":"scatter","series":{series}}}"#)), [true, false]); + assert_eq!(read(&format!(r#"{{"type":"line","series":{series}}}"#)), [false, false]); + let c: ChartSpec = serde_json::from_str(&format!(r#"{{"type":"scatter","series":{series}}}"#)).unwrap(); + assert_eq!(c.series[0].values, [Some(1.0), None, Some(2.5)]); + // What this version writes reads back as itself. + for kind in ChartType::ALL { + let spec = ChartSpec::sample(kind); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&spec).unwrap()).unwrap(), spec, "{kind:?}"); + } + } + + #[test] + fn default_and_missing_json_axis_fields_agree() { + let from_json: ChartSpec = serde_json::from_str(r#"{"type":"column"}"#).unwrap(); + let d = ChartSpec::default(); + assert_eq!((d.cat_axis.clone(), d.val_axis.clone()), (from_json.cat_axis, from_json.val_axis)); + assert!(d.val_axis.gridlines && !d.val_axis.line); + } + + #[test] + fn axis_bounds_and_formats_are_cleaned() { + let mut a = ChartAxis { + title: Some(" Sales\n".into()), + min: Some(f64::NAN), + max: Some(50.0), + fmt: Some("x".repeat(MAX_FMT + 40)), + gridlines: true, + labels: false, + line: true, + }; + a.sanitize(); + assert_eq!(a.title.as_deref(), Some("Sales")); + assert_eq!(a.min, None); + assert_eq!(a.max, Some(50.0)); + assert_eq!(a.fmt.as_deref().map(|f| f.chars().count()), Some(MAX_FMT)); + + // min not under max drops the pair; a format of only spaces is no format. + let mut b = ChartAxis { min: Some(50.0), max: Some(50.0), fmt: Some(" ".into()), ..Default::default() }; + b.sanitize(); + assert_eq!((b.min, b.max), (None, None)); + assert_eq!(b.fmt, None); + + let mut spec = ChartSpec { + series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], ..Default::default() }], + categories: vec!["a".into()], + ..Default::default() + }; + spec.series[0].line_w = Some(f32::NAN); + spec.series[0].fmt = Some("0.00".into()); + spec.sanitize(); + assert_eq!(spec.series[0].line_w, None); + assert_eq!(spec.series[0].fmt.as_deref(), Some("0.00")); + let mut spec = ChartSpec { + series: vec![ChartSeries { name: "s".into(), values: vec![], line_w: Some(100.0), ..Default::default() }], + ..Default::default() + }; + spec.sanitize(); + assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt"); + } } diff --git a/crates/doc/src/graphic.rs b/crates/doc/src/graphic.rs index f0e87b52de..8efa0abc16 100644 --- a/crates/doc/src/graphic.rs +++ b/crates/doc/src/graphic.rs @@ -127,6 +127,10 @@ pub enum GraphicItem { align: TextAlign, #[serde(default)] font: Option, + /// Degrees clockwise the text turns about `rect`'s center as it is drawn (a chart's vertical + /// axis title is turned -90°). + #[serde(default)] + angle: f32, }, /// A picture (`Document::media` key) stretched into `rect`. Image { rect: [f32; 4], media: String }, diff --git a/crates/doc/src/settings.rs b/crates/doc/src/settings.rs index 3d18185921..b97019351c 100644 --- a/crates/doc/src/settings.rs +++ b/crates/doc/src/settings.rs @@ -80,6 +80,8 @@ pub struct Settings { pub default_tab: f32, pub even_odd_headers: bool, pub mirror_margins: bool, + /// The gutter is added to the top margin instead of the left one (`w:gutterAtTop`). + pub gutter_at_top: bool, pub auto_hyphenation: bool, /// Hyphenation zone (`w:hyphenationZone`), points: a line is hyphenated only when breaking /// it at a word boundary would leave more than this empty at its end. @@ -302,6 +304,7 @@ impl Default for Settings { default_tab: 36.0, even_odd_headers: false, mirror_margins: false, + gutter_at_top: false, auto_hyphenation: false, hyphenation_zone: DEFAULT_HYPHENATION_ZONE, hyphenate_caps: true, diff --git a/crates/docx/src/model_bridge.rs b/crates/docx/src/model_bridge.rs index 68931e75a5..b3e07601d0 100644 --- a/crates/docx/src/model_bridge.rs +++ b/crates/docx/src/model_bridge.rs @@ -94,6 +94,15 @@ fn object_value_from_shared( }; Ok(Target::Graphic { w, h, alt, float: convert(float)?, graphic }) } + // This model has no picture frame shape: DrawingML's `frame` preset is read as a + // rectangle, without the frame's border width. + mut shape @ Source::Shape { kind: craft_wordmodel::para::ShapeKind::Frame, .. } => { + if let Source::Shape { kind, extra, .. } = &mut shape { + *kind = craft_wordmodel::para::ShapeKind::Rectangle; + extra.corner = None; + } + convert(shape) + } Source::Group { w, h, float, ch_w, ch_h, children, canvas } => Ok(Target::Group { w, h, @@ -442,6 +451,110 @@ pub fn to_shared_model(source: &wordcraft_doc::Document) -> Result) -> craft_wordmodel::Document { + let mut source = craft_wordmodel::Document::new(); + let mut para = craft_wordmodel::para::Paragraph::new(); + para.objects = objects; + source.body = vec![Arc::new(craft_wordmodel::Block::Para(para))]; + source + } + + fn objects(doc: &wordcraft_doc::Document) -> Vec { + doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default() + } + + fn chart_object(spec: craft_wordmodel::chart::ChartSpec) -> craft_wordmodel::para::InlineObject { + let graphic = craft_wordmodel::graphic::Graphic { chart: Some(Arc::new(spec)), ..Default::default() }; + craft_wordmodel::para::InlineObject::Graphic { w: 100.0, h: 60.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) } + } + + fn charts(doc: &wordcraft_doc::Document) -> Vec> { + objects(doc) + .iter() + .filter_map(|o| match o { + wordcraft_doc::para::InlineObject::Graphic { graphic, .. } => Some(graphic.chart.as_deref().cloned()), + _ => None, + }) + .collect() + } + + /// A picture frame shape opens as a rectangle instead of failing the whole document. + #[test] + fn a_frame_shape_reads_as_a_rectangle() { + let shape = |kind| craft_wordmodel::para::InlineObject::Shape { + kind, + w: 40.0, + h: 30.0, + fill: None, + stroke: None, + stroke_width: 1.0, + float: Default::default(), + story: None, + freeform: None, + effects: Default::default(), + extra: craft_wordmodel::connector::ShapeExtra { corner: Some(2604), ..Default::default() }, + }; + let doc = from_shared_model(doc_with(vec![shape(craft_wordmodel::para::ShapeKind::Frame)])).expect("from_shared_model"); + let found = objects(&doc); + let [wordcraft_doc::para::InlineObject::Shape { kind, w, extra, .. }] = found.as_slice() else { panic!("{found:?}") }; + assert_eq!((*kind, *w, extra.corner), (wordcraft_doc::para::ShapeKind::Rectangle, 40.0, None)); + } + + /// A chart's series formatting and axis settings survive the trip through this model, so + /// saving writes the chart part the reader read. + #[test] + fn chart_formatting_survives_the_bridge() { + use craft_wordmodel::chart::{ChartSpec, ChartType}; + let mut formatted = ChartSpec::sample(ChartType::Line); + formatted.series[0].fill = Some(craft_wordmodel::props::Rgb(0x12, 0x34, 0x56)); + formatted.series[0].line_w = Some(2.5); + formatted.series[1].smooth = true; + formatted.series[1].markers = Some(true); + formatted.series[2].labels = Some(true); + formatted.series[2].fmt = Some("0.0".into()); + formatted.val_axis.title = Some("Sales".into()); + formatted.val_axis.min = Some(0.0); + formatted.cat_axis.gridlines = true; + let mut scatter_lines = ChartSpec::sample(ChartType::Scatter); + scatter_lines.series[0].no_line = false; + let all = [formatted, ChartSpec::sample(ChartType::Scatter), ChartSpec::sample(ChartType::Pie), scatter_lines]; + let doc = from_shared_model(doc_with(all.iter().cloned().map(chart_object).collect())).expect("from_shared_model"); + assert!(charts(&doc).iter().all(Option::is_some)); + let back = to_shared_model(&doc).expect("to_shared_model"); + let back: Vec = back + .body + .first() + .and_then(|b| b.as_para()) + .map(|p| { + p.objects + .iter() + .filter_map(|o| match o { + craft_wordmodel::para::InlineObject::Graphic { graphic, .. } => graphic.chart.as_deref().cloned(), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + assert_eq!(back, all); + } + + /// A scatter chart this model makes is written as markers without lines, the same part the + /// shared model writes for its own new scatter chart. + #[test] + fn a_new_scatter_chart_is_written_without_lines() { + let local = wordcraft_doc::chart::ChartSpec::sample(wordcraft_doc::chart::ChartType::Scatter); + assert!(!local.series.is_empty() && local.series.iter().all(|s| s.no_line)); + assert_eq!( + crate::chart_xml(&local), + craft_docx::chart_xml(&craft_wordmodel::chart::ChartSpec::sample(craft_wordmodel::chart::ChartType::Scatter)).into_bytes() + ); + for kind in wordcraft_doc::chart::ChartType::ALL { + let local = wordcraft_doc::chart::ChartSpec::sample(kind); + let shared: craft_wordmodel::chart::ChartSpec = convert_ref(&local).expect("convert"); + assert_eq!(shared, craft_wordmodel::chart::ChartSpec::sample(shared.kind), "{kind:?}"); + } + } + #[test] fn bridges_nested_stories_and_moves_media_both_directions() { let mut source = craft_wordmodel::Document::new(); diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index 0859ad1a4d..c61268e96c 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -217,6 +217,8 @@ const PINNED_PARTS: &[&str] = &[ "word/styles.xml", "word/settings.xml", "word/theme/theme1.xml", + // The fonts the document uses, with their families: it brings no font table of its own. + "word/fontTable.xml", "docProps/core.xml", "docProps/app.xml", ]; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 970804d4cd..649d70e66f 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -989,7 +989,8 @@ fn toc_field_skips_nested_stories() { let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap(); let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap(); let boxes: Vec<(usize, usize)> = xml.match_indices("").map(|(a, _)| (a, a + xml[a..].find("").unwrap())).collect(); - assert_eq!(boxes.len(), 2, "{xml}"); + // Each text box is written twice: in the drawing and in its VML fallback. + assert_eq!(boxes.len(), 4, "{xml}"); let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i)); for kind in ["begin", "separate", "end"] { let at: Vec = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect(); @@ -997,7 +998,7 @@ fn toc_field_skips_nested_stories() { assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}"); } let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap()); - assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("").unwrap(), "{xml}"); + assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("").unwrap(), "{xml}"); } #[test] @@ -1567,6 +1568,29 @@ fn attached_template_and_link_styles_round_trip() { assert!(!plain.settings.link_styles); } +/// Gutter position Top (`w:gutterAtTop`) is kept when a document is opened and saved again, and +/// is not written when it is off. +#[test] +fn gutter_at_top_survives_open_and_save() { + let settings_xml = |bytes: &[u8]| { + let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap(); + String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap() + }; + let mut d = Document::new(); + d.settings.gutter_at_top = true; + let first = wordcraft_docx::write(&d).expect("write"); + assert_eq!(settings_xml(&first).matches("").count(), 1); + + let opened = wordcraft_docx::read(&first).expect("read"); + assert!(opened.settings.gutter_at_top); + let saved = wordcraft_docx::write(&opened).expect("write again"); + assert_eq!(settings_xml(&saved).matches("").count(), 1); + assert!(wordcraft_docx::read(&saved).expect("read again").settings.gutter_at_top); + + let plain = wordcraft_docx::write(&Document::new()).expect("write plain"); + assert!(!settings_xml(&plain).contains("gutterAtTop")); +} + /// #995: the zoom a document was saved at (`w:zoom`), One Page (`fullPage`) included, is read /// and written back. #[test] @@ -1922,8 +1946,21 @@ fn flat_opc_round_trip_equals_docx() { assert!(text.starts_with("")); assert!(text.contains("pkg:name=\"/word/document.xml\"") && text.contains("")); assert_eq!(wordcraft_docx::sniff_xml(&xml), wordcraft_docx::XmlKind::FlatOpc); - let back = wordcraft_docx::read_xml(&xml).expect("read flat"); - assert_eq!(back, rt(&d)); + let mut back = wordcraft_docx::read_xml(&xml).expect("read flat"); + // `pkg:xmlData` inlines a part without its XML declaration, so a kept XML part (the font + // table) comes back without one; the markup is the same. + let mut want = rt(&d); + for doc in [&mut back, &mut want] { + for v in doc.passthrough.values_mut() { + if let Some(rest) = + v.strip_prefix(b"').map(|e| r[e + 1..].trim_ascii_start().to_vec())) + { + *v = Arc::new(rest); + } + } + } + assert!(back.passthrough.contains_key("word/fontTable.xml")); + assert_eq!(back, want); assert_eq!(back.media.len(), 1); } @@ -2398,6 +2435,10 @@ fn bibliography_sources_round_trip() { assert_bibliography_parts(&bytes); assert_bibliography_sources_round_trip(&bytes); + // Saved again after reading, the store keeps one relationship, from the main part. + let again = wordcraft_docx::write(&wordcraft_docx::read(&bytes).expect("read")).expect("write again"); + assert_bibliography_parts(&again); + assert_eq!(wordcraft_docx::read(&again).expect("read again").sources.len(), d.sources.len()); } /// #4848: a corporate author saves as Word's `b:Corporate`, in place of a name list (a role holds @@ -2438,9 +2479,12 @@ fn assert_bibliography_parts(bytes: &[u8]) { assert!(zip.contains("customXml/itemProps1.xml")); assert!(zip.contains("customXml/_rels/item1.xml.rels")); - let rels_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap(); - assert!(rels_xml.contains("relationships/customXml"), "{rels_xml}"); - assert!(rels_xml.contains("Target=\"customXml/item1.xml\""), "{rels_xml}"); + // The sources' data store is related from the main part's relationships only. + let rels_xml = String::from_utf8(zip.read("word/_rels/document.xml.rels", 16 << 20).unwrap().unwrap()).unwrap(); + assert_eq!(rels_xml.matches("relationships/customXml\"").count(), 1, "{rels_xml}"); + assert!(rels_xml.contains("Target=\"../customXml/item1.xml\""), "{rels_xml}"); + let root_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap(); + assert!(!root_xml.contains("relationships/customXml\""), "{root_xml}"); let ct_xml = String::from_utf8(zip.read("[Content_Types].xml", 16 << 20).unwrap().unwrap()).unwrap(); assert!(ct_xml.contains("PartName=\"/customXml/item1.xml\""), "{ct_xml}"); diff --git a/crates/docx/tests/it/text_boxes.rs b/crates/docx/tests/it/text_boxes.rs index 30b752cda3..32b8d0e386 100644 --- a/crates/docx/tests/it/text_boxes.rs +++ b/crates/docx/tests/it/text_boxes.rs @@ -261,5 +261,7 @@ fn story_shared_by_many_shapes_is_written_once() { } let xml = document_xml(&wordcraft_docx::write(&d).unwrap()); assert!(xml.len() < 2_000_000, "document.xml is {} bytes", xml.len()); - assert_eq!(xml.matches(text.as_str()).count(), 1); + // The story is written for the first shape only: in its drawing and in that drawing's VML + // fallback. The other shapes do not repeat it. + assert_eq!(xml.matches(text.as_str()).count(), 2); } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index ad546f0b86..a3049aa21a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -59,6 +59,7 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } [dev-dependencies] wordcraft-doc = { workspace = true, features = ["test-support"] } +wordcraft-formats = { workspace = true, features = ["test-support"] } encoding_rs = { workspace = true } craft-zip = { workspace = true } cfb = { workspace = true } diff --git a/crates/engine/src/cmd/chart.rs b/crates/engine/src/cmd/chart.rs index 79a16560e7..83a02368c5 100644 --- a/crates/engine/src/cmd/chart.rs +++ b/crates/engine/src/cmd/chart.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use serde_json::{Value, json}; -use wordcraft_doc::chart::{ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES}; +use wordcraft_doc::chart::{ChartAxis, ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES, value_axis}; use wordcraft_doc::graphic::{Graphic, GraphicKind}; use wordcraft_doc::para::{Float, InlineObject}; use wordcraft_doc::props::Rgb; @@ -33,6 +33,23 @@ pub fn specs() -> Vec { CommandSpec::new("chart.type", "Change Chart Type", "Chart Design › Type", |s, v| { let kind = chart_type(v)?.ok_or_else(|| CmdError::Params(format!("`type` is required: {TYPES}")))?; edit(s, |c| { + // A scatter series is drawn as markers without a line; the other types draw it. + if (c.kind == ChartType::Scatter) != (kind == ChartType::Scatter) { + for series in &mut c.series { + series.no_line = kind == ChartType::Scatter; + if series.no_line && series.markers == Some(false) { + series.markers = None; + } + } + } + // Pie and doughnut charts have a plain value axis and the other types a new + // chart's value axis; an axis left as the old type had it takes the new type's. + if c.kind.is_round() != kind.is_round() { + let (from, to) = if kind.is_round() { (value_axis(), ChartAxis::default()) } else { (ChartAxis::default(), value_axis()) }; + if c.val_axis == from { + c.val_axis = to; + } + } c.kind = kind; Ok(()) }) @@ -52,7 +69,15 @@ pub fn specs() -> Vec { c.categories = cats.clone(); } if let Some(series) = &series { - c.series = series.clone(); + // Each series keeps the formatting of the one it replaces. + c.series = series + .iter() + .enumerate() + .map(|(i, (name, values))| match c.series.get(i) { + Some(old) => ChartSeries { name: name.clone(), values: values.clone(), ..old.clone() }, + None => ChartSeries::new(c.kind, name.clone(), values.clone()), + }) + .collect(); } Ok(()) }) @@ -99,6 +124,10 @@ pub fn specs() -> Vec { let on = p::bool(v, "on").or_else(|| p::bool(v, "value")); edit(s, move |c| { c.data_labels = on.unwrap_or(!c.data_labels); + // The chart's setting replaces each series' own. + for series in &mut c.series { + series.labels = None; + } Ok(()) }) }) @@ -152,7 +181,14 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult { let mut spec = ChartSpec::sample(kind); if let Some(d) = v.get("data") { spec.categories = d.get("categories").map(categories).transpose()?.unwrap_or_default(); - spec.series = d.get("series").map(series_list).transpose()?.unwrap_or_default(); + spec.series = d + .get("series") + .map(series_list) + .transpose()? + .unwrap_or_default() + .into_iter() + .map(|(name, values)| ChartSeries::new(kind, name, values)) + .collect(); if spec.series.is_empty() { return Err(CmdError::Params(format!("`data.series` needs at least one series: {DATA}"))); } @@ -220,8 +256,8 @@ fn cell_text(v: &Value) -> String { } } -/// Series from JSON: `[{"name", "values": [number|null|numeric string]}]`. -fn series_list(v: &Value) -> Result, CmdError> { +/// Series names and values from JSON: `[{"name", "values": [number|null|numeric string]}]`. +fn series_list(v: &Value) -> Result>)>, CmdError> { let a = v.as_array().ok_or_else(|| CmdError::Params(format!("`series`: {DATA}")))?; a.iter() .take(MAX_SERIES) @@ -232,7 +268,7 @@ fn series_list(v: &Value) -> Result, CmdError> { None | Some(Value::Null) => Vec::new(), Some(_) => return Err(CmdError::Params("`values`: an array of numbers (null for none)".into())), }; - Ok(ChartSeries { name, values }) + Ok((name, values)) }) .collect() } diff --git a/crates/engine/src/cmd/mailings/tests.rs b/crates/engine/src/cmd/mailings/tests.rs index f8f1c60455..013200681e 100644 --- a/crates/engine/src/cmd/mailings/tests.rs +++ b/crates/engine/src/cmd/mailings/tests.rs @@ -617,7 +617,8 @@ fn recipients_from_an_xls_workbook() { let book = wordcraft_formats::sheet::xls_fixture(&[( "收件人", vec![row(&["姓名", "城市", "数量"]), row(&["张三", "北京", "12"]), row(&["李四", "上海", "2"])], - )]); + )]) + .unwrap(); let mut s = Session::new(Document::new()); let r = s.run("mailings.recipients", &json!({"path": "名单.xls", "data": b64(&book)})).unwrap(); assert_eq!(r, json!({"fields": ["姓名", "城市", "数量"], "records": 2, "sheet": "收件人"})); diff --git a/crates/engine/src/io_ext.rs b/crates/engine/src/io_ext.rs index 16c8136f8f..f46d2f50ff 100644 --- a/crates/engine/src/io_ext.rs +++ b/crates/engine/src/io_ext.rs @@ -16,10 +16,11 @@ pub fn open(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Opti // that state no size. other => wordcraft_formats::import_on(other, bytes, page).map(|r| { r.map(|mut doc| { - if !matches!(other, "odt" | "ott" | "fodt") { + let odf = matches!(other, "odt" | "ott" | "fodt"); + if !odf { crate::io::fit_pictures(&mut doc); } - draw_charts(&mut doc); + draw_charts(&mut doc, odf); doc }) }), @@ -27,8 +28,9 @@ pub fn open(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Opti } /// Draw the charts a reader left undrawn (ODT charts come as their chart model alone): in the -/// document's theme colours, at their size. -fn draw_charts(doc: &mut Document) { +/// document's theme colours, at their size. With `odf`, scatter series are set to markers without +/// a line first (see `markers_only_scatter`). +pub(crate) fn draw_charts(doc: &mut Document, odf: bool) { use wordcraft_doc::para::InlineObject; /// Groups nest at most this deep here (the readers flatten deeper ones). const DEPTH: usize = 16; @@ -39,16 +41,41 @@ fn draw_charts(doc: &mut Document) { _ => false, } } - fn draw(o: &mut InlineObject, theme: &[wordcraft_doc::Rgb], depth: usize) { + fn draw(o: &mut InlineObject, theme: &[wordcraft_doc::Rgb], odf: bool, depth: usize) { match o { - InlineObject::Group { children, .. } if depth < DEPTH => children.iter_mut().for_each(|c| draw(&mut c.obj, theme, depth + 1)), - o if undrawn(o, depth) => crate::cmd::chart::redraw(o, theme), + InlineObject::Group { children, .. } if depth < DEPTH => children.iter_mut().for_each(|c| draw(&mut c.obj, theme, odf, depth + 1)), + o if undrawn(o, depth) => { + if odf { + markers_only_scatter(o); + } + crate::cmd::chart::redraw(o, theme) + } _ => {} } } + // The ODF reader does not read a scatter chart's line setting, so every scatter series of an + // opened ODF file is set to markers without a line, as the ODF writer writes them. A series + // with its markers turned off gets them back, as Change Chart Type does, so it is still drawn. + fn markers_only_scatter(o: &mut InlineObject) { + if let InlineObject::Graphic { graphic, .. } = o + && let Some(spec) = graphic.chart.as_deref() + && spec.kind == wordcraft_doc::chart::ChartType::Scatter + && spec.series.iter().any(|s| !s.no_line || s.markers == Some(false)) + { + let mut spec = spec.clone(); + for series in &mut spec.series { + series.no_line = true; + if series.markers == Some(false) { + series.markers = None; + } + } + std::sync::Arc::make_mut(graphic).chart = Some(std::sync::Arc::new(spec)); + } + } let theme = doc.settings.theme_colors.clone(); - // (Drawing them doesn't change the document: markup kept as read for them still is.) - doc.fill_objects(&|o| undrawn(o, 0), &mut |o| draw(o, &theme, 0)); + // (Markup kept as read for these charts is still written as read after they are drawn, + // scatter charts included.) + doc.fill_objects(&|o| undrawn(o, 0), &mut |o| draw(o, &theme, odf, 0)); } /// Save to a format other than plain text / JSON. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 136b2685c7..42922bf7dc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7764,6 +7764,81 @@ fn chart_edits_are_one_undo_step_each() { assert_eq!((*w, graphic.w, graphic.h), (300.0, 300.0, 150.0)); } +/// Scatter series are drawn as markers without a line: inserted with data, changed to scatter +/// and back, and added by Edit Data. Edit Data keeps each replaced series' formatting. +#[test] +fn scatter_chart_series_have_no_line_and_edit_data_keeps_formatting() { + let no_lines = |s: &Session| first_chart(&s.doc).unwrap().series.iter().map(|x| x.no_line).collect::>(); + let mut s = s(); + run(&mut s, "insert.chart", json!({"type": "scatter", "data": {"categories": [1, 2], "series": [{"name": "A", "values": [1, 2]}]}})); + assert_eq!(no_lines(&s), [true]); + run(&mut s, "chart.type", json!({"type": "line"})); + assert_eq!(no_lines(&s), [false]); + run(&mut s, "chart.type", json!({"type": "scatter"})); + assert_eq!(no_lines(&s), [true]); + + // Formatting read from a file, set on the chart's model. + let set = |s: &mut Session, f: &dyn Fn(&mut wordcraft_doc::chart::ChartSpec)| { + let mut spec = first_chart(&s.doc).unwrap(); + f(&mut spec); + let pos = Pos::body(0, 0); + let p = s.doc.para_mut(pos.story, &pos.path).unwrap(); + let off = p.object_offsets()[0]; + if let Some(wordcraft_doc::para::InlineObject::Graphic { graphic, .. }) = p.object_at_mut(off) { + std::sync::Arc::make_mut(graphic).chart = Some(std::sync::Arc::new(spec)); + } + }; + + // A series' formatting stays through Edit Data; a new series gets the type's default. + set(&mut s, &|c| c.series[0].fill = Some(wordcraft_doc::props::Rgb(0x12, 0x34, 0x56))); + run(&mut s, "chart.editData", json!({"data": {"series": [{"name": "B", "values": [3, 4]}, {"name": "C", "values": [5, 6]}]}})); + let c = first_chart(&s.doc).unwrap(); + assert_eq!(c.series[0].fill, Some(wordcraft_doc::props::Rgb(0x12, 0x34, 0x56))); + assert_eq!((c.series[0].name.as_str(), c.series[1].name.as_str()), ("B", "C")); + assert_eq!(no_lines(&s), [true, true]); + + // A line-only series made a scatter series again gets its markers back, so it stays visible. + set(&mut s, &|c| c.series[0].markers = Some(false)); + run(&mut s, "chart.type", json!({"type": "line"})); + run(&mut s, "chart.type", json!({"type": "scatter"})); + assert_eq!(first_chart(&s.doc).unwrap().series[0].markers, None); + + // The chart's Data Labels setting replaces a series' own. + set(&mut s, &|c| c.series[1].labels = Some(true)); + run(&mut s, "chart.dataLabels", json!({"on": false})); + let c = first_chart(&s.doc).unwrap(); + assert!(!c.data_labels && c.series.iter().all(|x| x.labels.is_none())); +} + +/// A pie chart changed to a column chart gets a new column chart's value axis, and back; an +/// axis that was changed stays as it is. +#[test] +fn chart_type_between_round_and_axis_charts_sets_the_value_axis() { + use wordcraft_doc::chart::{ChartAxis, value_axis}; + let mut s = s(); + run(&mut s, "insert.chart", json!({"type": "pie"})); + assert_eq!(first_chart(&s.doc).unwrap().val_axis, ChartAxis::default()); + run(&mut s, "chart.type", json!({"type": "column"})); + assert_eq!(first_chart(&s.doc).unwrap().val_axis, value_axis()); + run(&mut s, "chart.type", json!({"type": "doughnut"})); + assert_eq!(first_chart(&s.doc).unwrap().val_axis, ChartAxis::default()); + + let mut s = self::s(); + run(&mut s, "insert.chart", json!({"type": "column"})); + let pos = Pos::body(0, 0); + let p = s.doc.para_mut(pos.story, &pos.path).unwrap(); + let off = p.object_offsets()[0]; + if let Some(wordcraft_doc::para::InlineObject::Graphic { graphic, .. }) = p.object_at_mut(off) { + let g = std::sync::Arc::make_mut(graphic); + let mut spec = (**g.chart.as_ref().unwrap()).clone(); + spec.val_axis.max = Some(50.0); + g.chart = Some(std::sync::Arc::new(spec)); + } + run(&mut s, "chart.type", json!({"type": "pie"})); + run(&mut s, "chart.type", json!({"type": "bar"})); + assert_eq!(first_chart(&s.doc).unwrap().val_axis, ChartAxis { max: Some(50.0), ..value_axis() }); +} + #[test] fn hostile_chart_data_is_capped() { use wordcraft_doc::chart::{MAX_CELLS, MAX_POINTS, MAX_SERIES, MAX_TEXT}; @@ -13169,6 +13244,80 @@ fn an_odt_charts_paragraph_is_written_as_read_after_drawing_it() { assert!(content.contains(r#"draw:name="Chart1""#) && !content.contains("wcChart"), "{content}"); } +/// A scatter chart saved as ODT (or flat ODT) and opened again is still drawn as markers without +/// lines, and its paragraph is still written as read. +#[test] +fn an_odt_scatter_chart_reopens_without_lines() { + use wordcraft_doc::para::InlineObject; + let mut s = Session::new(wordcraft_doc::Document::new()); + run(&mut s, "insert.chart", json!({"type": "scatter"})); + let odt = wordcraft_formats::odt::export(&s.doc).unwrap(); + let fodt = wordcraft_formats::odt::export_flat(&s.doc).unwrap(); + for (name, bytes) in [("t.odt", odt), ("t.fodt", fodt)] { + let doc = crate::io::open_bytes(name, &bytes).unwrap(); + let c = first_chart(&doc).expect("the chart has its model"); + assert_eq!(c.kind, wordcraft_doc::chart::ChartType::Scatter); + assert!(!c.series.is_empty() && c.series.iter().all(|x| x.no_line), "{name}: {:?}", c.series); + // The drawn items are the markers-only drawing, not the one with lines between points. + let p = doc.para_at(&Pos::body(0, 0)).unwrap(); + let (items, w, h) = p + .object_offsets() + .into_iter() + .find_map(|off| match p.object_at(off) { + Some(InlineObject::Graphic { graphic, w, h, .. }) if graphic.chart.is_some() => Some((graphic.items.clone(), *w, *h)), + _ => None, + }) + .expect("the chart is drawn"); + let theme = &doc.settings.theme_colors; + assert_eq!(items, crate::cmd::chart::chart_graphic(c.clone(), theme, w, h).items, "{name}"); + let mut lines = c.clone(); + lines.series.iter_mut().for_each(|x| x.no_line = false); + assert_ne!(items, crate::cmd::chart::chart_graphic(lines, theme, w, h).items, "{name}"); + } + let doc = crate::io::open_bytes("t.odt", &wordcraft_formats::odt::export(&s.doc).unwrap()).unwrap(); + let again = wordcraft_formats::odt::export(&doc).unwrap(); + let mut z = craft_zip::Archive::open(&again, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap(); + let content = String::from_utf8(z.read("content.xml", 16 << 20).unwrap().unwrap()).unwrap(); + assert!(content.contains(r#"draw:name="Chart1""#) && !content.contains("wcChart"), "{content}"); +} + +/// An undrawn scatter series with its markers turned off is not left with neither a line nor +/// markers when an opened ODF file's scatter charts are set to markers only; other formats keep +/// their series as read. +#[test] +fn an_opened_odf_scatter_series_keeps_its_markers() { + use std::sync::Arc; + use wordcraft_doc::para::InlineObject; + let mut s = Session::new(wordcraft_doc::Document::new()); + run(&mut s, "insert.chart", json!({"type": "scatter"})); + let undrawn = |doc: &wordcraft_doc::Document| { + let mut doc = doc.clone(); + doc.fill_objects(&|o| matches!(o, InlineObject::Graphic { graphic, .. } if graphic.chart.is_some()), &mut |o| { + if let InlineObject::Graphic { graphic, .. } = o { + let g = Arc::make_mut(graphic); + if let Some(spec) = g.chart.as_deref() { + let mut spec = spec.clone(); + for series in &mut spec.series { + series.no_line = false; + series.markers = Some(false); + } + g.chart = Some(Arc::new(spec)); + } + g.items.clear(); + } + }); + doc + }; + let mut odf = undrawn(&s.doc); + crate::io_ext::draw_charts(&mut odf, true); + let c = first_chart(&odf).expect("the chart has its model"); + assert!(!c.series.is_empty() && c.series.iter().all(|x| x.no_line && x.markers.is_none()), "{:?}", c.series); + let mut other = undrawn(&s.doc); + crate::io_ext::draw_charts(&mut other, false); + let c = first_chart(&other).expect("the chart has its model"); + assert!(c.series.iter().all(|x| !x.no_line && x.markers == Some(false)), "{:?}", c.series); +} + /// A picture an OpenDocument file makes wider than the text (a rule across the whole page) stays /// that wide, and its paragraph is written as read: opening a file changes nothing in it. #[test] diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 9db1a9ec7b..d2bc45fe7d 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -8,6 +8,11 @@ description = "WordCraft import/export: plain text, Markdown, HTML, RTF, OpenDoc [lints] workspace = true +[features] +# `sheet::xls_fixture`, the binary workbook builder other crates' tests share; turned on only as a +# dev-dependency, so never built into the app. +test-support = ["craft-xls/test-support"] + [dependencies] wordcraft-doc = { workspace = true } wordcraft-docx = { workspace = true } diff --git a/crates/formats/src/sheet.rs b/crates/formats/src/sheet.rs index b8bafa7a17..7a19c92ba5 100644 --- a/crates/formats/src/sheet.rs +++ b/crates/formats/src/sheet.rs @@ -109,9 +109,10 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec, Vec>)]) -> Vec { - craft_xls::testing::workbook(sheets) +pub fn xls_fixture(sheets: &[(&str, Vec>)]) -> Result, String> { + craft_xls::testing::workbook(sheets).map_err(|e| e.to_string()) } pub fn field_names(row: &[String]) -> Vec { diff --git a/crates/layout/src/display/objects.rs b/crates/layout/src/display/objects.rs index ee574e735e..10d5aa326f 100644 --- a/crates/layout/src/display/objects.rs +++ b/crates/layout/src/display/objects.rs @@ -35,6 +35,18 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32) cap: Default::default(), }) } + GraphicItem::Text { rect: r, angle, .. } if angle.is_finite() && angle.rem_euclid(360.0) != 0.0 => { + // Turned text is laid out level in its box turned the same way, then turned about + // the box's center. + let at = inside(r); + let (cx, cy) = (at.x + at.w / 2.0, at.y + at.h / 2.0); + let quarter = ((angle / 90.0).round() as i64).rem_euclid(2) == 1; + let level = if quarter { Rect::new(cx - at.h / 2.0, cy - at.w / 2.0, at.h, at.w) } else { at }; + let items = text_glyphs(doc, level, it, alpha, k); + if !items.is_empty() { + out.push(Draw::Rotated { cx, cy, spin: Spin::new(*angle, false, false), items }); + } + } GraphicItem::Text { rect: r, .. } => out.extend(text_glyphs(doc, inside(r), it, alpha, k)), GraphicItem::Image { rect: r, media } => out.push(Draw::Image { rect: inside(r), @@ -280,7 +292,7 @@ pub fn seg_path(segs: &[PathSeg]) -> BezPath { /// or the item's rectangle or size isn't a finite number (a degenerate scale: `r` itself is always /// finite, as [`Rect::new`] makes it). fn text_glyphs(doc: &Document, r: Rect, it: &GraphicItem, alpha: f32, k: f32) -> Vec { - let GraphicItem::Text { rect, text, size, color, bold, align, font } = it else { return Vec::new() }; + let GraphicItem::Text { rect, text, size, color, bold, align, font, .. } = it else { return Vec::new() }; let size = *size * k; if !rect.iter().chain([&size]).all(|v| v.is_finite()) { return Vec::new(); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index f3a2a50ed9..c1c51083e2 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -8211,6 +8211,7 @@ fn graphic_items_draw_inside_the_object() { bold: false, align: TextAlign::Center, font: None, + angle: 0.0, }, ]; let mut d = Document::from_text("Chart"); @@ -8241,6 +8242,7 @@ fn graphic_text_in_a_degenerate_rectangle_is_not_drawn() { bold: false, align: TextAlign::Center, font: None, + angle: 0.0, }; let items = vec![text([f32::NAN, 0.0, 10.0, 10.0], 10.0), text([0.0, 0.0, f32::INFINITY, 10.0], 10.0), text([0.0, 0.0, 10.0, 10.0], f32::NAN)]; let graphic = Graphic { kind: GraphicKind::Diagram, items, ..Default::default() }; @@ -8251,6 +8253,45 @@ fn graphic_text_in_a_degenerate_rectangle_is_not_drawn() { assert!(!draws.iter().any(|x| matches!(x, display::Draw::Glyphs { text, .. } if text == "Q1"))); } +/// A chart's vertical axis title (text turned -90°) is laid out along its tall box and drawn +/// turned about the box's center. +#[test] +fn turned_graphic_text_is_drawn_turned_about_its_box() { + crate::test_fonts(); + use wordcraft_doc::graphic::{Graphic, GraphicItem, GraphicKind, TextAlign}; + use wordcraft_doc::props::Rgb; + let items = vec![GraphicItem::Text { + rect: [0.0, 20.0, 20.0, 100.0], + text: "Sales".into(), + size: 10.0, + color: Rgb::BLACK, + bold: false, + align: TextAlign::Center, + font: None, + angle: -90.0, + }]; + let graphic = Graphic { kind: GraphicKind::Chart, items, ..Default::default() }; + let obj = InlineObject::Graphic { w: 216.0, h: 144.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }; + let mut d = Document::from_text("Chart"); + d.insert_object(&Pos::body(0, 0), obj, &Default::default()).unwrap(); + let draws = flat(display::page_display(&d, &lay(&d).pages[0], &Default::default())); + let turned = draws + .iter() + .find_map(|x| match x { + display::Draw::Rotated { cx, cy, spin, items } => Some((*cx, *cy, *spin, items)), + _ => None, + }) + .expect("the title is turned"); + let (cx, cy, spin, items) = turned; + assert_eq!(spin.deg, 270.0); + let Some(display::Draw::Glyphs { glyphs, text, .. }) = items.first() else { panic!("{items:?}") }; + assert_eq!(text, "Sales"); + // Laid out level across the box's 100 pt height, centered on the box's center. + let (first, last) = (glyphs[0].1, glyphs[glyphs.len() - 1].1); + assert!(first > cx - 50.0 && last < cx + 50.0 && first < cx && last > cx, "{first} {last} about {cx}"); + assert!((glyphs[0].2 - cy).abs() < 10.0, "baseline {} near {cy}", glyphs[0].2); +} + #[test] fn chart_text_the_font_lacks_is_drawn_in_a_fallback_face() { crate::test_fonts(); @@ -8271,6 +8312,7 @@ fn chart_text_the_font_lacks_is_drawn_in_a_fallback_face() { bold: false, align: TextAlign::Center, font: None, + angle: 0.0, }]; let graphic = Graphic { kind: GraphicKind::Chart, items, ..Default::default() }; let obj = InlineObject::Graphic { w: 216.0, h: 144.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }; diff --git a/crates/layout/src/tests/missing_glyphs.rs b/crates/layout/src/tests/missing_glyphs.rs index 3777fee569..106ab635e8 100644 --- a/crates/layout/src/tests/missing_glyphs.rs +++ b/crates/layout/src/tests/missing_glyphs.rs @@ -51,6 +51,7 @@ fn chart_with(d: &mut Document, label: &str) { bold: false, align: TextAlign::Center, font: None, + angle: 0.0, }]; let graphic = Graphic { kind: GraphicKind::Chart, items, ..Default::default() }; let obj = InlineObject::Graphic { w: 216.0, h: 144.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }; diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 3c6779157f..19f183d62f 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -982,6 +982,7 @@ fn inline_chart_is_a_figure_with_its_text_inside_it() { bold: false, align: TextAlign::Center, font: None, + angle: 0.0, }]; let graphic = Graphic { kind: GraphicKind::Chart, items, ..Default::default() }; let obj = InlineObject::Graphic { w: 216.0, h: 144.0, alt: "Sales by quarter".into(), float: Default::default(), graphic: Arc::new(graphic) }; @@ -3216,6 +3217,7 @@ fn chart_and_equation_text_keep_their_pdf_bytes() { bold: false, align: TextAlign::Center, font: None, + angle: 0.0, }]; let graphic = Graphic { kind: GraphicKind::Chart, items, ..Default::default() }; let obj = InlineObject::Graphic { w: 216.0, h: 144.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ad8f6aa8f3..de00204a30 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -2009,7 +2009,7 @@ fn undecodable_pictures_keep_their_grey_box_pixels() { fn geometry_bytes_counts_pattern_tiles_and_clips_once() { use craft_metafile::{ClipPath, Tile}; let segs = |n: usize| vec![Seg::Line(0.0, 0.0); n]; - let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 }; + let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, ..Default::default() }; let base = crate::media::geometry_bytes(&pic(vec![])); let tile = Arc::new(Tile { width: 1000, height: 1000, rgba: vec![0; 4_000_000], cell: [1.0, 1.0], origin: [0.0, 0.0] }); let pattern = |tile: &Arc| Item::Pattern { segs: segs(1000), even_odd: false, tile: tile.clone(), region: None, clips: vec![] }; @@ -2042,7 +2042,7 @@ fn geometry_bytes_counts_pattern_tiles_and_clips_once() { #[test] fn geometry_bytes_charges_the_capacity_of_segment_and_dash_vectors() { use craft_metafile::LineStyle; - let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 }; + let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, ..Default::default() }; let path = |segs: Vec, dash: Vec| Item::Path { segs, fill: None, @@ -2066,7 +2066,7 @@ fn geometry_bytes_charges_the_capacity_of_segment_and_dash_vectors() { #[test] fn geometry_bytes_counts_dash_arrays_and_text_records() { use craft_metafile::{Font, HAlign, LineStyle, Text, VAlign}; - let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 }; + let pic = |items: Vec| Picture { width: 10.0, height: 10.0, items, ..Default::default() }; let path = |dash: usize| Item::Path { segs: vec![Seg::Line(0.0, 0.0); 2], fill: None, diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 7b160e0e84..20386d13c1 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -9,14 +9,14 @@ description = "WordCraft egui front end (Word-style ribbon UI); swappable: nothi workspace = true [dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } # Interface translations: lookup, fallback, plurals and system-locale matching over the craft-i18n # catalogs that `build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, pinned in # `craft-i18n.rev`). Same craft-libs rev as craft-ui; it brings lazy per-locale parsing # (storytold/craft-libs#247), ICU4X plural rules and bidi isolates around inserted values. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } # One native window per open document: the window list, the Window menu and the egui viewports. -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } From 83f18db12dfdd6b20f3bd72b2bc6c27b9dd5a07e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Tue, 17 Nov 2026 21:29:27 +0700 Subject: [PATCH 77/99] =?UTF-8?q?#2786:=20Home=20=E2=80=BA=20Bullets:=20De?= =?UTF-8?q?fine=20New=20Bullet=E2=80=A6=20dialog=20and=20Change=20List=20L?= =?UTF-8?q?evel=20=E2=80=BA=20(#2860)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/lists.rs | 98 +++++ crates/engine/src/cmd/tools/specs.rs | 7 +- crates/engine/src/tests.rs | 77 ++++ crates/ui-egui/src/dialogs.rs | 25 +- crates/ui-egui/src/dialogs/chrome.rs | 16 +- crates/ui-egui/src/dialogs/dialogs_bullet.rs | 370 ++++++++++++++++++ crates/ui-egui/src/dialogs/dialogs_insert.rs | 10 +- .../src/dialogs/dialogs_insert/symbol.rs | 72 +++- crates/ui-egui/src/dialogs/dispatch.rs | 3 + crates/ui-egui/src/dialogs/font.rs | 42 ++ crates/ui-egui/src/dialogs/tests.rs | 82 ++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/previews.rs | 26 ++ crates/ui-egui/src/ribbon/home.rs | 18 + 14 files changed, 828 insertions(+), 19 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/dialogs_bullet.rs diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index 987e9fd537..3a68a4003f 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -157,6 +157,104 @@ fn default_level(i: usize) -> Level { levels_for(ListKind::Numbered).into_iter().nth(i).unwrap_or_default() } +/// Define New Bullet (#2786): the selected paragraphs go into a list of their own whose bullet is +/// `char`, drawn in `font` (with `size`, `bold`, `italic` and `color` when given) and aligned by +/// `align` at every level they use. A list of its own, so +/// no other list using the same character changes, and it never toggles a bullet off the way +/// `para.bullets` does. Each paragraph keeps its level (level 1 when it wasn't in a list). +pub fn define_bullet(s: &mut Session, v: &Value) -> CmdResult { + let ch = match v.get("char") { + None => '★', + Some(c) => { + let c = c.as_str().ok_or_else(|| CmdError::Params("char must be one character".into()))?; + let mut it = c.chars(); + match (it.next(), it.next()) { + (Some(c), None) if !c.is_control() => c, + _ => return Err(CmdError::Params("char must be one character".into())), + } + } + }; + let font = match v.get("font") { + None => None, + Some(f) => { + let f = f.as_str().map(str::trim).ok_or_else(|| CmdError::Params("font must be a family name".into()))?; + if f.len() > 128 { + return Err(CmdError::Params("font name too long".into())); + } + (!f.is_empty()).then(|| f.to_string()) + } + }; + let size = match v.get("size") { + None => None, + Some(n) => match n.as_f64() { + Some(pt) if (1.0..=1638.0).contains(&pt) => Some(pt as f32), + _ => return Err(CmdError::Params("size must be 1 to 1638 points".into())), + }, + }; + let flag = |k: &str| -> Result, CmdError> { + match v.get(k) { + None => Ok(None), + Some(b) => b.as_bool().map(Some).ok_or_else(|| CmdError::Params(format!("{k} must be true or false"))), + } + }; + let (bold, italic) = (flag("bold")?, flag("italic")?); + let color = match v.get("color") { + None => None, + Some(c) => { + let c = c.as_str().ok_or_else(|| CmdError::Params("color must be RRGGBB or auto".into()))?; + Some(TextColor::parse(c).ok_or_else(|| CmdError::Params("color must be RRGGBB or auto".into()))?) + } + }; + let align = match p::str(v, "align") { + None if v.get("align").is_none() => None, + Some("left") => Some(Align::Left), + Some("center") => Some(Align::Center), + Some("right") => Some(Align::Right), + _ => return Err(CmdError::Params("align must be left, center or right".into())), + }; + // A paragraph's level, from its own numbering or its style's (List Bullet 2 numbers its + // paragraphs at level 2 without any of their own). + let styles = s.doc.styles.clone(); + let level_of = |pp: &wordcraft_doc::props::ParaProps| styles.resolve_para(pp).numbering.filter(|n| n.num != 0).map_or(0, |n| n.level); + let story = s.sel.focus.story; + let used: std::collections::BTreeSet = + super::selected_paths(s).iter().filter_map(|p| s.doc.para(story, p)).map(|x| level_of(&x.props)).collect(); + let mut levels = levels_for(ListKind::BulletChar(ch)); + for l in used { + if let Some(lv) = levels.get_mut(usize::from(l)) { + lv.text = ch.to_string(); + lv.chr.font = font.clone(); + if size.is_some() { + lv.chr.size = size; + } + if bold.is_some() { + lv.chr.bold = bold; + } + if italic.is_some() { + lv.chr.italic = italic; + } + if color.is_some() { + lv.chr.color = color; + } + if let Some(a) = align { + lv.align = a; + } + } + } + let num = Arc::make_mut(&mut s.doc.numbering).try_add_levels(None, levels)?; + super::para::fmt(s, &|pp| { + let level = level_of(pp); + pp.numbering = Some(NumRef { num, level }); + pp.indent_left = None; + pp.indent_first = None; + pp.indent_left_chars = None; + pp.indent_first_chars = None; + if pp.style.is_none() || pp.style.as_deref() == Some("Normal") { + pp.style = Some("ListParagraph".into()); + } + }) +} + fn get(s: &mut Session, v: &Value) -> CmdResult { let num = p::u64(v, "num").map(|n| n.min(u32::MAX as u64) as u32).or_else(|| caret_list(s)).ok_or_else(|| CmdError::Failed("not in a list".into()))?; diff --git a/crates/engine/src/cmd/tools/specs.rs b/crates/engine/src/cmd/tools/specs.rs index 2eee21614d..e622e2064e 100644 --- a/crates/engine/src/cmd/tools/specs.rs +++ b/crates/engine/src/cmd/tools/specs.rs @@ -316,10 +316,9 @@ pub fn specs() -> Vec { sel_result(s) }) .params(r#"{"value": n}"#), - CommandSpec::new("para.defineBullet", "Define New Bullet", "Home › Paragraph › Bullets", |s, v| { - s.run("para.bullets", &json!({"kind": p::str(v, "char").unwrap_or("★")})) - }) - .params(r#"{"char": string}"#), + CommandSpec::new("para.defineBullet", "Define New Bullet", "Home › Paragraph › Bullets", crate::cmd::lists::define_bullet).params( + r#"{"char"?: one character (default ★), "font"?: family (the bullet's own font; "" = the text's), "size"?: pt, "bold"?: bool, "italic"?: bool, "color"?: "RRGGBB" | "auto", "align"?: "left|center|right"} (the selected paragraphs get a list of their own; each keeps its level)"#, + ), CommandSpec::new("para.defineNumber", "Define New Number Format", "Home › Paragraph › Numbering", |s, v| { let fmt = wordcraft_doc::section::NumFormat::from_ooxml(p::str(v, "format").unwrap_or("decimal")); let text = p::str(v, "text").unwrap_or("%1.").to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 42922bf7dc..6ea3c4f71a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8548,6 +8548,83 @@ fn colour_commands_take_any_custom_hex() { assert_eq!(s.doc.settings.page_color, wordcraft_doc::Rgb::parse("123ABC")); } +/// #2786: Define New Bullet puts the selection in a list of its own: the character, its font and +/// its alignment at the levels the paragraphs use, each paragraph keeping its level. A list that +/// already uses the same character is left alone, defining again never toggles the bullet off, +/// it survives a DOCX round trip, and bad params are errors that change nothing. +#[test] +fn define_bullet_gives_the_selection_a_bullet_of_its_own() { + use wordcraft_doc::props::Align; + let mut s = Session::new(wordcraft_doc::Document::from_text("One\nTwo\nThree")); + let num_at = |s: &Session, i: usize| s.doc.para_at(&Pos::body(i, 0)).unwrap().props.numbering.unwrap(); + // "Three" already has a ♦ list, defined the ordinary way. + s.sel = crate::Selection::caret(Pos::body(2, 0)); + run(&mut s, "para.bullets", json!({"kind": "♦"})); + let other = num_at(&s, 2).num; + let other_level = s.doc.numbering.level(other, 0).unwrap().clone(); + // "Two" sits at level 2 of a bulleted list before the definition. + s.sel = crate::Selection::caret(Pos::body(1, 0)); + run(&mut s, "para.bullets", json!({})); + run(&mut s, "para.listLevel", json!({"level": 1})); + s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(1, 3) }; + run(&mut s, "para.defineBullet", json!({"char": "♦", "font": "Segoe UI Symbol", "align": "center"})); + let (one, two) = (num_at(&s, 0), num_at(&s, 1)); + assert_eq!(one.num, two.num, "one list for the selection"); + assert_ne!(one.num, other, "not the existing ♦ list"); + assert_eq!((one.level, two.level), (0, 1), "each paragraph keeps its level"); + for lvl in [0, 1] { + let l = s.doc.numbering.level(one.num, lvl).unwrap(); + assert_eq!((l.text.as_str(), l.chr.font.as_deref(), l.align), ("♦", Some("Segoe UI Symbol"), Align::Center), "level {lvl}"); + } + assert_eq!(s.doc.numbering.level(other, 0).unwrap(), &other_level, "the other ♦ list is unchanged"); + // Defining the same bullet again keeps it (para.bullets would toggle it off). + run(&mut s, "para.defineBullet", json!({"char": "♦"})); + assert_eq!(s.doc.numbering.level(num_at(&s, 0).num, 0).unwrap().text, "♦"); + // DOCX keeps the character, its font and the alignment. + run(&mut s, "para.defineBullet", json!({"char": "✓", "font": "Segoe UI Symbol", "align": "right", "size": 14, "bold": true, "color": "C00000"})); + let back = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap(); + let n = back.para_at(&Pos::body(0, 0)).unwrap().props.numbering.unwrap(); + let l = back.numbering.level(n.num, 0).unwrap(); + assert_eq!((l.text.as_str(), l.chr.font.as_deref(), l.align), ("✓", Some("Segoe UI Symbol"), Align::Right)); + // The Font dialog's size, bold and colour reach the bullet too. + assert_eq!((l.chr.size, l.chr.bold), (Some(14.0), Some(true))); + assert_eq!(l.chr.color, wordcraft_doc::props::TextColor::parse("C00000")); + // A paragraph numbered only by its style keeps the style's level (review of #2860). + let mut s2 = Session::new(wordcraft_doc::Document::from_text("Styled")); + let styled = Arc::make_mut(&mut s2.doc.numbering).try_add_list(wordcraft_doc::ListKind::Bullet).unwrap(); + Arc::make_mut(&mut s2.doc.styles).get_mut("ListParagraph").unwrap().para.numbering = Some(wordcraft_doc::props::NumRef { num: styled, level: 1 }); + s2.doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props.style = Some("ListParagraph".into()); + assert!(s2.doc.para_at(&Pos::body(0, 0)).unwrap().props.numbering.is_none(), "no numbering of its own"); + s2.sel = crate::Selection::caret(Pos::body(0, 0)); + run(&mut s2, "para.defineBullet", json!({"char": "♦"})); + let n = s2.doc.para_at(&Pos::body(0, 0)).unwrap().props.numbering.unwrap(); + assert_eq!(n.level, 1, "the style's level is kept"); + assert_eq!(s2.doc.numbering.level(n.num, 1).unwrap().text, "♦"); + // No params: ★, as before. + s.sel = crate::Selection::caret(Pos::body(2, 0)); + run(&mut s, "para.defineBullet", json!({})); + assert_eq!(s.doc.numbering.level(num_at(&s, 2).num, 0).unwrap().text, "★"); + let doc = s.doc.clone(); + let long = "x".repeat(200); + for junk in [ + json!({"char": ""}), + json!({"char": "ab"}), + json!({"char": 5}), + json!({"char": "\u{7}"}), + json!({"char": "•", "align": "middle"}), + json!({"char": "•", "align": 1}), + json!({"char": "•", "font": 3}), + json!({"char": "•", "font": long}), + json!({"char": "•", "size": 0}), + json!({"char": "•", "size": "big"}), + json!({"char": "•", "bold": "yes"}), + json!({"char": "•", "color": "purple"}), + ] { + assert!(s.run("para.defineBullet", &junk).is_err(), "{junk}"); + } + assert_eq!(s.doc, doc); +} + /// #4685: Home › Paragraph › Shading on text selected inside a paragraph shades that text, as in /// Word, so No Color takes off a text shading a file gave it (an orange "highlight" from a .docx is /// `w:shd`, which Text Highlight Color › No Color leaves, in Word too). A caret or a whole diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c9872347a9..178f6f5c7a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -42,6 +42,7 @@ pub(crate) use find::swallow_shortcut_text; pub use find::{FindExtra, FindTab, GoToWhat}; #[cfg(test)] use find::{command_matches, goto_page}; +pub use font::font_for_bullet; #[cfg(test)] use font::{apply_font, preview_size}; use font::{east_asian_char, font_props}; @@ -97,6 +98,11 @@ pub enum Dialog { /// alone stays as it is. #[serde(skip)] start: serde_json::Map, + /// Formatting a bullet for Define New Bullet (#2786): OK hands the font, size, bold, + /// italic and colour back to that dialog instead of formatting the text, and Cancel goes + /// back to it unchanged. + #[serde(skip)] + bullet: Option>, }, Paragraph { /// Right-to-left reading order (Direction in Word's Paragraph dialog). @@ -488,14 +494,27 @@ pub enum Dialog { } impl Dialog { + /// The Define New Bullet form a Font or Symbol dialog opened from it carries (#2786). + fn bullet_form(&mut self) -> Option { + match self { + Dialog::Font { bullet, .. } => bullet.take().map(|b| *b), + Dialog::Insert(i) => match i.as_mut() { + crate::dialogs_insert::InsertDialog::Symbol(f) => f.bullet.take().map(|b| *b), + _ => None, + }, + _ => None, + } + } + /// Whether the dialog blocks the rest of the window while it is open. As in Word for Mac - /// (16.114.1, #3859), all are but those you keep working beside. + /// (16.114.1, #3859), all are but those you keep working beside. Symbol opened from Define + /// New Bullet picks the bullet for it, so it blocks the window as that dialog does (#2786). pub fn is_modal(&self) -> bool { use crate::dialogs_insert::InsertDialog; use crate::dialogs_refs::RefsDialog; match self { Dialog::Find { .. } | Dialog::InsertMergeField { .. } => false, - Dialog::Insert(d) => !matches!(**d, InsertDialog::Symbol(_)), + Dialog::Insert(d) => !matches!(&**d, InsertDialog::Symbol(f) if f.bullet.is_none()), Dialog::Refs(d) => !matches!(**d, RefsDialog::MarkEntry(_) | RefsDialog::CrossRef(_)), _ => true, } @@ -634,6 +653,7 @@ impl Dialog { kern: kern.map(|k| k > 0.0), kern_at: kern.filter(|k| *k > 0.0).unwrap_or(12.0) as f32, start: serde_json::Map::new(), + bullet: None, }; let props = font_props(&d); if let Dialog::Font { start, .. } = &mut d { @@ -905,6 +925,7 @@ impl Dialog { } } +pub mod dialogs_bullet; pub mod dialogs_chart; pub mod dialogs_controls; pub mod dialogs_insert; diff --git a/crates/ui-egui/src/dialogs/chrome.rs b/crates/ui-egui/src/dialogs/chrome.rs index bb708daaae..90b09f33ec 100644 --- a/crates/ui-egui/src/dialogs/chrome.rs +++ b/crates/ui-egui/src/dialogs/chrome.rs @@ -261,7 +261,14 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) { }); } count_dialog_frame(ctx, id); - close |= crate::window_close::show(ctx, &shown.response, &Tokens::get(ctx)); + if crate::window_close::show(ctx, &shown.response, &Tokens::get(ctx)) && !close { + close = true; + // The title bar's close box is Cancel: a dialog opened from Define New Bullet goes + // back to it, as its Cancel button does (#2786). + if back_to_bullet(app, &mut d) { + return; + } + } // A file browser it opened (Attach…, Browse…) stays above it. if d.is_modal() && !close && !app.file_browser_open() { block_behind(app, ctx, &shown.response); @@ -278,6 +285,13 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) { } } +/// Back to Define New Bullet from a Font or Symbol dialog it opened, when `d` is one (#2786). +fn back_to_bullet(app: &mut WordApp, d: &mut Dialog) -> bool { + let Some(form) = d.bullet_form() else { return false }; + app.dialog = Some(Dialog::Insert(Box::new(crate::dialogs_insert::InsertDialog::DefineBullet(form)))); + true +} + /// Cancel key for dialogs: Escape everywhere, plus ⌘. (Command+Period) on macOS. pub(crate) fn cancel_key_pressed(ui: &Ui) -> bool { ui.input(|i| i.key_pressed(egui::Key::Escape) || (cfg!(target_os = "macos") && i.modifiers.command && i.key_pressed(egui::Key::Period))) diff --git a/crates/ui-egui/src/dialogs/dialogs_bullet.rs b/crates/ui-egui/src/dialogs/dialogs_bullet.rs new file mode 100644 index 0000000000..3a26957136 --- /dev/null +++ b/crates/ui-egui/src/dialogs/dialogs_bullet.rs @@ -0,0 +1,370 @@ +//! Define New Bullet (Home › Paragraph › Bullets, #2786): the bullet character (picked in the +//! Symbol dialog), its font (in the app's Font dialog) and its alignment, with a preview. It +//! ends in one command, `para.defineBullet`, so agents get the same result without the dialog. + +use egui::{Ui, vec2}; +use serde::Serialize; +use serde_json::json; +use wordcraft_doc::props::Align; + +use crate::WordApp; +use crate::dialogs::Dialog; +use crate::dialogs_insert::{InsertDialog, SymbolForm}; +use crate::theme::{Tokens, regular, semibold}; + +/// The alignments the dialog offers: `para.defineBullet`'s `align` and their names. +pub const ALIGNMENTS: [(&str, &str); 3] = [("left", "Left"), ("center", "Center"), ("right", "Right")]; + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DefineBulletForm { + /// The bullet character. + pub ch: String, + /// The bullet's own font; empty = the text's. + pub font: String, + /// The bullet's size in points; empty = the text's. + pub size: String, + pub bold: bool, + pub italic: bool, + /// `RRGGBB`; empty or `auto` = the text's colour. + pub color: String, + /// `left`, `center` or `right`. + pub align: String, +} + +impl DefineBulletForm { + /// Starts from the bullet the caret's paragraph has (its level's character, font and + /// alignment), or a plain • when it has none. + pub fn new(app: &WordApp) -> DefineBulletForm { + let doc = &app.session.doc; + let level = doc + .para_at(&app.session.sel.focus) + .and_then(|p| doc.styles.resolve_para(&p.props).numbering) + .filter(|n| n.num != 0) + .and_then(|n| doc.numbering.level(n.num, n.level)) + .filter(|l| l.format == wordcraft_doc::section::NumFormat::Bullet && l.text.chars().count() == 1); + match level { + Some(l) => DefineBulletForm { + ch: l.text.clone(), + font: l.chr.font.clone().unwrap_or_default(), + size: l.chr.size.map(|s| s.to_string()).unwrap_or_default(), + bold: l.chr.bold.unwrap_or(false), + italic: l.chr.italic.unwrap_or(false), + color: match l.chr.color { + Some(wordcraft_doc::props::TextColor::Rgb(c)) => c.hex(), + _ => String::new(), + }, + align: match l.align { + Align::Center => "center", + Align::Right => "right", + _ => "left", + } + .into(), + }, + None => DefineBulletForm::plain("•"), + } + } + + /// A bullet `ch` in the text's own formatting, left aligned. + pub fn plain(ch: &str) -> DefineBulletForm { + DefineBulletForm { + ch: ch.into(), + font: String::new(), + size: String::new(), + bold: false, + italic: false, + color: String::new(), + align: "left".into(), + } + } + + /// The bullet's formatting as the preview draws it, at [`Self::preview_pt`]. + pub fn chr(&self) -> wordcraft_doc::props::CharProps { + wordcraft_doc::props::CharProps { + size: Some(self.preview_pt()), + font: (!self.font.is_empty()).then(|| self.font.clone()), + bold: self.bold.then_some(true), + italic: self.italic.then_some(true), + color: wordcraft_doc::Rgb::parse(&self.color).map(wordcraft_doc::props::TextColor::Rgb), + ..Default::default() + } + } + + /// The bullet's size in the preview, in points: its own size, or the text's (11 pt) when it + /// has none, kept to what the preview's rows can show (4–20 pt). + pub fn preview_pt(&self) -> f32 { + let pt = self.size.trim().parse::().ok().filter(|pt| pt.is_finite() && (1.0..=1638.0).contains(pt)).unwrap_or(11.0); + pt.clamp(4.0, 20.0) + } + + /// The `para.defineBullet` params this form stands for. + pub fn params(&self) -> serde_json::Value { + let mut v = json!({"char": self.ch, "font": self.font, "align": self.align, "bold": self.bold, "italic": self.italic}); + // No size is the text's size; anything else goes to the command, which rejects a bad one. + let size = self.size.trim(); + if !size.is_empty() { + v["size"] = match size.parse::() { + Ok(pt) if pt.is_finite() => json!(pt), + _ => json!(size), + }; + } + v["color"] = json!(if wordcraft_doc::Rgb::parse(&self.color).is_some() { self.color.as_str() } else { "auto" }); + v + } +} + +/// Draws the dialog; returns true to close it (OK, Cancel, or Symbol… / Font…, which hand the +/// dialog over to the Symbol or Font dialog and get it back when it closes). +pub fn body(app: &mut WordApp, ui: &mut Ui, f: &mut DefineBulletForm) -> bool { + let t = Tokens::get(ui.ctx()); + ui.set_width(340.0); + ui.label(egui::RichText::new(tl!("Bullet character")).font(semibold(12.0))); + ui.add_space(4.0); + let (mut to_symbol, mut to_font) = (false, false); + ui.horizontal(|ui| { + to_symbol = ui.button(tl!("Symbol…")).clicked(); + to_font = ui.button(tl!("Font…")).clicked(); + }); + if to_symbol { + let form = f.clone(); + app.dialog = Some(Dialog::Insert(Box::new(InsertDialog::Symbol(SymbolForm::for_bullet(app, form))))); + return true; + } + if to_font { + // The app's own Font dialog, formatting the bullet and handing it back. + if let Some(d) = crate::dialogs::font_for_bullet(app, f.clone()) { + app.dialog = Some(d); + return true; + } + } + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.label(tl!("Alignment:")); + ui.add_space(6.0); + for (k, n) in ALIGNMENTS { + ui.radio_value(&mut f.align, k.to_string(), tl!(n)); + } + }); + ui.add_space(8.0); + ui.label(egui::RichText::new(tl!("Preview")).font(regular(12.0)).color(t.text_dim)); + preview(app, ui, f); + ui.add_space(6.0); + let (ok, cancel) = crate::dialogs_insert::buttons(ui, "OK", "Cancel", f.ch.chars().count() == 1); + if ok && let Err(e) = app.run("para.defineBullet", f.params()) { + // A bad setting (a size out of range…) keeps the dialog open to correct it. + app.status(e); + return false; + } + ok || cancel +} + +/// The preview, drawn like Define New Multilevel List's: two plain lines of text, three bulleted +/// ones and two plain lines again, as grey bars on a white page. The bullet sits at the first +/// level's aligned-at position (18 pt), aligned there as chosen, and its text starts at the text +/// indent (36 pt); the bullet itself is laid out by the layout engine, so a symbol font shows the +/// character the page will. +fn preview(app: &mut WordApp, ui: &mut Ui, f: &DefineBulletForm) { + let t = Tokens::get(ui.ctx()); + let row = 17.0; + let (rect, _) = ui.allocate_exact_size(vec2(340.0, row * 7.0 + 10.0), egui::Sense::hover()); + let p = ui.painter_at(rect); + p.rect_filled(rect, 2.0, egui::Color32::WHITE); + p.rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border_strong), egui::StrokeKind::Inside); + // Positions in points, scaled so 4.5 inches fit, as in Define New Multilevel List. + let scale = (rect.width() - 16.0) / 324.0; + let left = rect.left() + 8.0; + let (aligned_at, text_at) = (left + 18.0 * scale, left + 36.0 * scale); + let bar = |y: f32, from: f32, gray: u8| { + let r = egui::Rect::from_min_max(egui::pos2(from, y - 2.0), egui::pos2(rect.right() - 8.0, y + 2.0)); + p.rect_filled(r, 1.0, egui::Color32::from_gray(gray)); + }; + // Room for the character at its size (`previews::glyph` draws it at `chr`'s size). + let chr = wordcraft_doc::props::CharProps { size: Some(f.preview_pt() * scale), ..f.chr() }; + let glyph = f.preview_pt() * scale / 0.7; + for i in 0..7 { + let y = rect.top() + 5.0 + row * i as f32 + row / 2.0; + if !(2..5).contains(&i) { + bar(y, left, 205); + continue; + } + let x = match f.align.as_str() { + "center" => aligned_at - glyph / 2.0, + "right" => aligned_at - glyph, + _ => aligned_at, + }; + let r = egui::Rect::from_min_size(egui::pos2(x, y - glyph / 2.0), vec2(glyph, glyph)); + crate::previews::glyph(app, ui, r, &f.ch, &chr, egui::Color32::WHITE); + bar(y, text_at.max(r.right() + 2.0), 120); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui_kittest::kittest::Queryable; + use wordcraft_engine::Session; + + /// The interface fonts take effect from the frame after they're installed: the first frame + /// installs them and draws nothing. + fn fonts_ready(ui: &Ui) -> bool { + let id = egui::Id::unique("define_bullet_test_fonts"); + let ready = ui.ctx().data(|d| d.get_temp::(id)).unwrap_or(false); + if !ready { + crate::theme::install_fonts(ui.ctx()); + ui.ctx().data_mut(|d| d.insert_temp(id, true)); + } + ready + } + + fn app_with_bullet() -> WordApp { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("One\nTwo")), crate::Services::default()); + a.run("para.bullets", json!({"kind": "▪"})).unwrap(); + a + } + + fn level_at(app: &WordApp, i: usize) -> wordcraft_doc::numbering::Level { + let doc = &app.session.doc; + let n = doc.para_at(&wordcraft_doc::Pos::body(i, 0)).unwrap().props.numbering.unwrap(); + doc.numbering.level(n.num, n.level).unwrap().clone() + } + + /// The form starts from the caret's bullet; OK ends in `para.defineBullet` with the + /// character, its font and the alignment. + #[test] + fn ok_defines_the_bullet_the_form_shows() { + let app = app_with_bullet(); + let f = DefineBulletForm::new(&app); + let font = level_at(&app, 0).chr.font.unwrap_or_default(); + assert_eq!((f.ch.as_str(), f.font.as_str(), f.align.as_str()), ("▪", font.as_str(), "left")); + let mut h = egui_kittest::Harness::builder().with_size(vec2(500.0, 500.0)).build_ui_state( + |ui, (app, f): &mut (WordApp, DefineBulletForm)| { + if fonts_ready(ui) { + body(app, ui, f); + } + }, + (app, DefineBulletForm { font: "Segoe UI Symbol".into(), align: "right".into(), ..DefineBulletForm::plain("†") }), + ); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + let l = level_at(&h.state().0, 0); + assert_eq!((l.text.as_str(), l.chr.font.as_deref(), l.align), ("†", Some("Segoe UI Symbol"), Align::Right)); + } + + /// #2786 review: a size the command rejects (not a number, out of range) is an error OK + /// reports, keeping the dialog open and the list as it was; no size is the text's size. + #[test] + fn ok_with_a_bad_size_keeps_the_dialog_open() { + assert!(DefineBulletForm::plain("†").params().get("size").is_none(), "no size: the text's size"); + for bad in ["abc", "5000", "0"] { + let app = app_with_bullet(); + let before = level_at(&app, 0); + let form = DefineBulletForm { size: bad.into(), ..DefineBulletForm::plain("†") }; + let mut h = egui_kittest::Harness::builder().with_size(vec2(500.0, 500.0)).build_ui_state( + |ui, (app, f, closed): &mut (WordApp, DefineBulletForm, bool)| { + if fonts_ready(ui) && body(app, ui, f) { + *closed = true; + } + }, + (app, form, false), + ); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(!h.state().2, "{bad}: the dialog stays open"); + assert_eq!(level_at(&h.state().0, 0).text, before.text, "{bad}: the list is unchanged"); + } + } + + /// #2786 review: the preview draws the bullet at its own size, the text's when it has none, + /// within what the rows can show. + #[test] + fn the_preview_draws_the_bullets_size() { + let at = |size: &str| DefineBulletForm { size: size.into(), ..DefineBulletForm::plain("•") }.preview_pt(); + assert_eq!(at(""), 11.0); + assert_eq!(at("16"), 16.0); + assert!(at("8") < at("11") && at("11") < at("18")); + assert_eq!(at("72"), 20.0, "kept to the rows"); + assert_eq!(at("abc"), 11.0); + // The preview draws the character with these props: `previews::glyph` keeps their size. + let f = DefineBulletForm { size: "16".into(), ..DefineBulletForm::plain("•") }; + assert_eq!(f.chr().size, Some(16.0)); + } + + /// Symbol… hands the form to the Symbol dialog, whose OK brings it back with the character + /// picked there; Cancel brings it back unchanged. + #[test] + fn symbol_picks_the_character_and_returns() { + let form = DefineBulletForm { align: "center".into(), ..DefineBulletForm::plain("▪") }; + let mut h = egui_kittest::Harness::builder().with_size(vec2(500.0, 500.0)).build_ui_state( + |ui, (app, f): &mut (WordApp, DefineBulletForm)| { + if fonts_ready(ui) { + body(app, ui, f); + } + }, + (app_with_bullet(), form.clone()), + ); + h.run_steps(2); + h.get_by_label("Symbol…").click(); + h.run_steps(2); + let mut app = std::mem::replace(&mut h.state_mut().0, app_with_bullet()); + drop(h); + let Some(dialog) = app.dialog.take() else { panic!("the Symbol dialog is open") }; + // Picking the bullet, it blocks the window as Define New Bullet does (#3859). + assert!(dialog.is_modal(), "the bullet's Symbol dialog is modal"); + let Dialog::Insert(d) = dialog else { panic!("the Symbol dialog is open") }; + let InsertDialog::Symbol(mut sym) = *d else { panic!("the Symbol dialog is open") }; + assert_eq!(sym.bullet.as_deref().map(|b| b.align.as_str()), Some("center"), "it carries the form"); + sym.selected = Some('†'); + let mut h = egui_kittest::Harness::builder().with_size(vec2(700.0, 700.0)).build_ui_state( + |ui, (app, d): &mut (WordApp, InsertDialog)| { + if fonts_ready(ui) { + crate::dialogs_insert::body(app, ui, d); + } + }, + (app, InsertDialog::Symbol(sym)), + ); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + let back = match h.state_mut().0.dialog.take() { + Some(Dialog::Insert(d)) => match *d { + InsertDialog::DefineBullet(f) => f, + _ => panic!("back to Define New Bullet"), + }, + _ => panic!("back to Define New Bullet"), + }; + assert_eq!((back.ch.as_str(), back.align.as_str()), ("†", "center")); + // Nothing was inserted into the text. + assert_eq!(h.state().0.session.doc.para_at(&wordcraft_doc::Pos::body(0, 0)).unwrap().text, "One"); + } + + /// The Symbol dialog's title-bar close box goes back to Define New Bullet, as Cancel does. + #[test] + fn closing_the_symbol_dialog_returns_to_the_bullet() { + let mut app = app_with_bullet(); + let form = DefineBulletForm { align: "center".into(), ..DefineBulletForm::plain("▪") }; + let sym = SymbolForm::for_bullet(&app, form); + app.dialog = Some(Dialog::Insert(Box::new(InsertDialog::Symbol(sym)))); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut WordApp| { + if fonts_ready(ui) { + let ctx = ui.ctx().clone(); + crate::dialogs::show(app, &ctx); + } + }, + app, + ); + h.run_steps(3); + h.get_by_label("Close").click(); + h.run_steps(3); + let back = match h.state_mut().dialog.take() { + Some(Dialog::Insert(d)) => match *d { + InsertDialog::DefineBullet(f) => f, + _ => panic!("back to Define New Bullet"), + }, + _ => panic!("back to Define New Bullet"), + }; + assert_eq!((back.ch.as_str(), back.align.as_str()), ("▪", "center")); + } +} diff --git a/crates/ui-egui/src/dialogs/dialogs_insert.rs b/crates/ui-egui/src/dialogs/dialogs_insert.rs index a175138238..aa574c9e23 100644 --- a/crates/ui-egui/src/dialogs/dialogs_insert.rs +++ b/crates/ui-egui/src/dialogs/dialogs_insert.rs @@ -38,6 +38,7 @@ pub enum InsertDialog { SmartArt(crate::dialogs_smart_art::SmartArtForm), ChartType(crate::dialogs_chart::ChartTypeForm), ChartData(crate::dialogs_chart::ChartDataForm), + DefineBullet(crate::dialogs_bullet::DefineBulletForm), DropCap(DropCapForm), } @@ -53,6 +54,7 @@ impl InsertDialog { InsertDialog::ChartType(f) if f.change => "changeChartType", InsertDialog::ChartType(_) => "insertChart", InsertDialog::ChartData(_) => "chartData", + InsertDialog::DefineBullet(_) => "defineBullet", InsertDialog::DropCap(_) => "dropCap", } } @@ -68,14 +70,16 @@ impl InsertDialog { InsertDialog::ChartType(f) if f.change => "Change Chart Type", InsertDialog::ChartType(_) => "Insert Chart", InsertDialog::ChartData(_) => "Edit Data", + InsertDialog::DefineBullet(_) => "Define New Bullet", InsertDialog::DropCap(_) => "Drop Cap", } } } /// The dialog `ui.dialog` opens by `name`: `columns`, `symbol`, `specialCharacters`, `field`, -/// `insertChart`, `changeChartType` or `chartData` (the last two for the selected chart), or -/// `insertSmartArt`, or `dropCap` (Drop Cap Options…, where the paragraph can take one). +/// `insertChart`, `changeChartType` or `chartData` (the last two for the selected chart), +/// `insertSmartArt`, `defineBullet` (Home › Bullets › Define New Bullet…), or `dropCap` (Drop Cap +/// Options…, where the paragraph can take one). pub fn open(name: &str, app: &WordApp) -> Option { Some(match name { "dateTime" => InsertDialog::DateTime(DateTimeForm::new(app)), @@ -87,6 +91,7 @@ pub fn open(name: &str, app: &WordApp) -> Option { "insertChart" => InsertDialog::ChartType(crate::dialogs_chart::ChartTypeForm::new(app, false)?), "changeChartType" => InsertDialog::ChartType(crate::dialogs_chart::ChartTypeForm::new(app, true)?), "chartData" => InsertDialog::ChartData(crate::dialogs_chart::ChartDataForm::new(app)?), + "defineBullet" => InsertDialog::DefineBullet(crate::dialogs_bullet::DefineBulletForm::new(app)), "dropCap" => InsertDialog::DropCap(DropCapForm::read(app)?), _ => return None, }) @@ -102,6 +107,7 @@ pub fn body(app: &mut WordApp, ui: &mut Ui, d: &mut InsertDialog) -> bool { InsertDialog::SmartArt(f) => crate::dialogs_smart_art::picker_ui(app, ui, f), InsertDialog::ChartType(f) => crate::dialogs_chart::type_ui(app, ui, f), InsertDialog::ChartData(f) => crate::dialogs_chart::data_ui(app, ui, f), + InsertDialog::DefineBullet(f) => crate::dialogs_bullet::body(app, ui, f), InsertDialog::DropCap(f) => drop_cap_ui(app, ui, f), } } diff --git a/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs b/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs index 797d6aef72..0905cd85c6 100644 --- a/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs +++ b/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs @@ -131,6 +131,10 @@ pub struct SymbolForm { /// Scroll the grid to this row on the next frame. #[serde(skip)] scroll_to: Option, + /// Picking a bullet for Define New Bullet (#2786): OK hands the character and its font back + /// to that dialog instead of inserting it, and Cancel goes back to it unchanged. + #[serde(skip)] + pub bullet: Option>, } /// Grid geometry. @@ -151,12 +155,45 @@ impl SymbolForm { let recent = app.ui.recent_symbols.first().cloned(); let font = recent.as_ref().map(|r| r.font.clone()).unwrap_or_default(); let selected = recent.and_then(|r| r.ch.chars().next()); - let mut f = - SymbolForm { tab, font, selected, code: String::new(), special: 0, text_font, chars: Vec::new(), chars_of: None, scroll_to: None }; + let mut f = SymbolForm { + tab, + font, + selected, + code: String::new(), + special: 0, + text_font, + chars: Vec::new(), + chars_of: None, + scroll_to: None, + bullet: None, + }; f.sync_code(); f } + /// The Symbol dialog picking `form`'s bullet: it opens on the bullet's font and character. + pub fn for_bullet(app: &WordApp, form: crate::dialogs_bullet::DefineBulletForm) -> SymbolForm { + let mut f = SymbolForm::new(app, 0); + f.font = form.font.clone(); + f.selected = form.ch.chars().next(); + f.load(); + f.sync_code(); + f.scroll_to = f.selected.and_then(|c| f.row_of(c)); + f.bullet = Some(Box::new(form)); + f + } + + /// Back to Define New Bullet, with `picked` (a character and its font) when one was chosen. + fn back_to_bullet(&mut self, app: &mut WordApp, picked: Option<(String, String)>) -> bool { + let Some(mut form) = self.bullet.take() else { return false }; + if let Some((ch, font)) = picked { + form.ch = ch; + form.font = font; + } + app.dialog = Some(crate::dialogs::Dialog::Insert(Box::new(super::InsertDialog::DefineBullet(*form)))); + true + } + /// The font the grid shows: the chosen one, or the text's. pub fn shown_font(&self) -> &str { if self.font.is_empty() { &self.text_font } else { &self.font } @@ -269,11 +306,16 @@ fn symbol_cell(app: &mut WordApp, ui: &mut Ui, font: &str, c: char, selected: bo pub(super) fn symbol_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SymbolForm) -> bool { let t = Tokens::get(ui.ctx()); ui.set_width(GRID_COLS as f32 * CELL + 24.0); - let names = [tl!("Symbols").to_string(), tl!("Special Characters").to_string()]; - if let Some(k) = crate::widgets::dialog_tabs(ui, &names, f.tab as usize) { - f.tab = k as u8; + if f.bullet.is_some() { + // A bullet is one character in a font: the Special Characters tab has nothing for it. + f.tab = 0; + } else { + let names = [tl!("Symbols").to_string(), tl!("Special Characters").to_string()]; + if let Some(k) = crate::widgets::dialog_tabs(ui, &names, f.tab as usize) { + f.tab = k as u8; + } + ui.add_space(6.0); } - ui.add_space(6.0); let mut insert: Option<(Value, String, String)> = None; if f.tab == 1 { if special_ui(app, ui, f, &mut insert, &t) { @@ -326,8 +368,10 @@ pub(super) fn symbol_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SymbolForm) -> b let rows = f.chars.len().div_ceil(GRID_COLS); let mut area = egui::ScrollArea::vertical().id_salt("symbol_grid").max_height(CELL * GRID_ROWS as f32).auto_shrink([false, false]); if let Some(row) = f.scroll_to.take() { - // Keep the row in view: it lands on the grid's second row when there is room. - area = area.vertical_scroll_offset(row.saturating_sub(1) as f32 * CELL); + // Keep the row in view: it lands on the grid's second row when there is room. Rows + // are `CELL` plus the item spacing apart (`show_rows` adds it between rows). + let pitch = CELL + ui.spacing().item_spacing.y; + area = area.vertical_scroll_offset(row.saturating_sub(1) as f32 * pitch); } let font = f.shown_font().to_string(); let chars = f.chars.clone(); @@ -398,15 +442,23 @@ pub(super) fn symbol_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SymbolForm) -> b if double && let Some(p) = f.params() { insert = Some((p, f.selected.map(String::from).unwrap_or_default(), f.font.clone())); } - // The Insert button. - let (ok, close) = buttons(ui, "Insert", "Close", f.selected.is_some()); + // The Insert button (OK while picking a bullet). + let (ok_label, close_label) = if f.bullet.is_some() { ("OK", "Cancel") } else { ("Insert", "Close") }; + let (ok, close) = buttons(ui, ok_label, close_label, f.selected.is_some()); if ok && let Some(p) = f.params() { insert = Some((p, f.selected.map(String::from).unwrap_or_default(), f.font.clone())); } if close { + f.back_to_bullet(app, None); return true; } } + if f.bullet.is_some() + && let Some((_, ch, font)) = insert + { + remember_symbol(app, &ch, &font); + return f.back_to_bullet(app, Some((ch, font))); + } if let Some((params, ch, font)) = insert { // Special characters with their own command insert through it (non-breaking hyphen…). let r = match params.get("command").and_then(Value::as_str) { diff --git a/crates/ui-egui/src/dialogs/dispatch.rs b/crates/ui-egui/src/dialogs/dispatch.rs index 4d682cc315..18693522de 100644 --- a/crates/ui-egui/src/dialogs/dispatch.rs +++ b/crates/ui-egui/src/dialogs/dispatch.rs @@ -247,6 +247,9 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden); }); let (ok, cancel) = buttons(ui, tl!("OK")); + if (ok || cancel) && super::font::hand_back_bullet(app, d, ok) { + return true; + } if ok { apply_font(app, d); } diff --git a/crates/ui-egui/src/dialogs/font.rs b/crates/ui-egui/src/dialogs/font.rs index 672829ab8b..eec09022ab 100644 --- a/crates/ui-egui/src/dialogs/font.rs +++ b/crates/ui-egui/src/dialogs/font.rs @@ -167,6 +167,48 @@ pub(super) fn east_asian_char(c: char) -> bool { matches!(u32::from(c), 0x1100..=0x11FF | 0x2E80..=0x9FFF | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xF900..=0xFAFF | 0xFE30..=0xFE4F | 0xFF00..=0xFFEF | 0x20000..=0x3FFFF) } +/// The Font dialog formatting Define New Bullet's bullet (#2786): it opens on the bullet's font, +/// size, bold, italic and colour, and carries the form back (see `Dialog::Font::bullet`). +pub fn font_for_bullet(app: &mut WordApp, form: crate::dialogs_bullet::DefineBulletForm) -> Option { + let mut d = Dialog::open("font", app)?; + if let Dialog::Font { font, font_was, size, bold, italic, color, .. } = &mut d { + if !form.font.is_empty() { + *font = app.previews.font_shown(&form.font); + *font_was = font.clone(); + } + *size = form.size.clone(); + *bold = form.bold; + *italic = form.italic; + *color = form.color.clone(); + } + let props = font_props(&d); + if let Dialog::Font { start, bullet, .. } = &mut d { + *start = props; + *bullet = Some(Box::new(form)); + } + Some(d) +} + +/// The Font dialog's OK or Cancel while it formats Define New Bullet's bullet (#2786): back to +/// that dialog, with the font (its stored English name, and only when the user changed it, so a +/// bullet in the text's font keeps following the text), size, bold, italic and colour on OK. +/// False when the dialog isn't formatting a bullet. +pub(super) fn hand_back_bullet(app: &mut WordApp, d: &mut Dialog, ok: bool) -> bool { + let Dialog::Font { bullet, font, font_was, size, bold, italic, color, .. } = d else { return false }; + let Some(mut form) = bullet.take() else { return false }; + if ok { + if font.trim() != font_was.trim() { + form.font = app.previews.font_stored(font.trim()); + } + form.size = size.trim().to_string(); + form.bold = *bold; + form.italic = *italic; + form.color = color.clone(); + } + app.dialog = Some(Dialog::Insert(Box::new(crate::dialogs_insert::InsertDialog::DefineBullet(*form)))); + true +} + /// The Font dialog's OK: one formatting step that sets only the properties the user changed, so /// formatting the dialog can't show or left alone stays as it is. Fonts are set by their stored /// (English) names, the Latin font for Persian/Arabic text too (as `format.font`). diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c3e9d99258..a1ea146d36 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -895,6 +895,88 @@ fn modify_style_font_box_finds_the_family() { assert_eq!(rc.font, wordcraft_doc::styles::HEADING_FONT); } +/// #2786: Define New Bullet's Font… is this Font dialog, opened on the bullet's formatting. OK +/// hands the font, size and bold back to Define New Bullet without formatting the text; +/// Cancel, and the title bar's close box, go back with the form as it was. +#[test] +fn font_dialog_formats_a_bullet_and_hands_it_back() { + use crate::dialogs_bullet::DefineBulletForm; + use crate::dialogs_insert::InsertDialog; + use egui_kittest::kittest::Queryable; + let back = |button: &str| -> (DefineBulletForm, wordcraft_doc::props::CharProps) { + let mut app = app_with("Example"); + let _ = app.run("para.bullets", json!({"kind": "▪"})); + let form = DefineBulletForm { font: "Arial".into(), ..DefineBulletForm::plain("▪") }; + app.dialog = font_for_bullet(&mut app, form); + let Some(Dialog::Font { size, bold, bullet, .. }) = &mut app.dialog else { panic!("the Font dialog is open") }; + assert!(bullet.is_some(), "it carries the form"); + assert!(!*bold && size.is_empty(), "it shows the bullet's formatting, not the text's"); + *size = "16".into(); + *bold = true; + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + if fonts { + show(app, &ctx); + } else { + crate::theme::install_fonts_for(&ctx, false); + fonts = true; + } + }, + app, + ); + h.run_steps(3); + h.get_by_label(button).click(); + h.run_steps(3); + let app = h.state_mut(); + let Some(Dialog::Insert(d)) = app.dialog.take() else { panic!("back to Define New Bullet") }; + let InsertDialog::DefineBullet(f) = *d else { panic!("back to Define New Bullet") }; + let text = app.session.doc.para_at(&wordcraft_doc::Pos::body(0, 0)).map(|p| p.props_of_char(0).clone()).unwrap_or_default(); + (f, text) + }; + let (f, text) = back("OK"); + assert_eq!((f.ch.as_str(), f.font.as_str(), f.size.as_str(), f.bold), ("▪", "Arial", "16", true)); + assert_ne!(text.bold, Some(true), "the text isn't formatted"); + assert_ne!(text.size, Some(16.0), "the text isn't formatted"); + for button in ["Cancel", "Close"] { + let (f, _) = back(button); + assert_eq!((f.font.as_str(), f.size.as_str(), f.bold), ("Arial", "", false), "{button} keeps the form"); + } + // A bullet in the text's font (no font of its own) keeps it when OK doesn't change the + // font box, though the box shows the text's font (review of #2860). + let mut app = app_with("Example"); + let _ = app.run("para.bullets", json!({"kind": "▪"})); + let Some(mut d) = font_for_bullet(&mut app, DefineBulletForm::plain("▪")) else { panic!("the Font dialog opens") }; + if let Dialog::Font { font, .. } = &d { + assert!(!font.is_empty(), "the box shows the text's font"); + } + if let Dialog::Font { bullet: Some(b), font, font_was, .. } = &mut d { + assert_eq!(font, font_was); + assert!(b.font.is_empty()); + } + app.dialog = Some(d); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + if fonts { + show(app, &ctx); + } else { + crate::theme::install_fonts_for(&ctx, false); + fonts = true; + } + }, + app, + ); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + let Some(Dialog::Insert(d)) = h.state_mut().dialog.take() else { panic!("back to Define New Bullet") }; + let InsertDialog::DefineBullet(f) = *d else { panic!("back to Define New Bullet") }; + assert_eq!(f.font, "", "still the text's font"); +} + /// A dialog was pinned by its anchor, so dragging its title bar did nothing (#732). #[test] fn dragging_a_dialog_title_bar_moves_it() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 357f141b9f..09dc4d7c13 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -91,6 +91,7 @@ use serde_json::{Value, json}; use wordcraft_engine::Session; pub use control::ControlRequest; +pub use dialogs::dialogs_bullet; pub use dialogs::dialogs_chart; pub use dialogs::dialogs_controls; pub use dialogs::dialogs_insert; diff --git a/crates/ui-egui/src/previews.rs b/crates/ui-egui/src/previews.rs index e618034cf8..6af6d6a212 100644 --- a/crates/ui-egui/src/previews.rs +++ b/crates/ui-egui/src/previews.rs @@ -556,6 +556,32 @@ fn snippet_blocks(base: &Document, blocks: Vec, options: SnippetOptions) Some(egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &px)) } +/// One character formatted by `chr` (at its size, or fitted to `r` without one), centred in `r` +/// and drawn with `tint`: +/// laid out like document text, so symbol fonts show what the page will (Define New Bullet, #2786). +pub fn glyph(app: &mut WordApp, ui: &mut Ui, r: Rect, ch: &str, chr: &CharProps, tint: egui::Color32) { + let ppp = ui.ctx().pixels_per_point(); + let key = format!("glyph:{ch}:{chr:?}:{ppp}:{}x{}", r.width(), r.height()); + let tex = app.previews.get_or(ui.ctx(), &key, || { + let chr = CharProps { size: Some(chr.size.unwrap_or(r.height() * 0.7)), ..chr.clone() }; + let mut p = Paragraph::with_text(ch, chr); + p.props.align = Some(wordcraft_doc::props::Align::Center); + p.props.space_before = Some(0.0); + p.props.space_after = Some(0.0); + snippet_blocks( + &Document::new(), + vec![Block::Para(p)], + SnippetOptions { width: r.width(), height: r.height(), pixels_per_point: ppp, margin: 0.0, paper: None, dark: false }, + ) + }); + if let Some(hd) = tex { + let sz = hd.size_vec2() / ppp; + let ir = Rect::from_min_size(r.min, sz.min(r.size())); + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2((ir.width() / sz.x).min(1.0), (ir.height() / sz.y).min(1.0))); + ui.painter().with_clip_rect(r).image(hd.id(), ir, uv, tint); + } +} + /// Manage Styles' preview of one style (`ty`: the `styles.manage` type), `size` points wide and /// tall: a line of sample text, or a small table for a table style. pub fn style_preview(app: &mut WordApp, ui: &mut Ui, id: &str, ty: &str, size: egui::Vec2) { diff --git a/crates/ui-egui/src/ribbon/home.rs b/crates/ui-egui/src/ribbon/home.rs index 54581154d5..5cb359457e 100644 --- a/crates/ui-egui/src/ribbon/home.rs +++ b/crates/ui-egui/src/ribbon/home.rs @@ -26,6 +26,23 @@ pub(super) fn painter_double_click(app: &mut WordApp) { let _ = app.run("edit.formatPainter", json!({"sticky": true})); } +/// Change List Level › and Define New Bullet… at the foot of the Bullets drop-down (#2786). +/// Change List Level is for a paragraph in a list of its own numbering, the one `para.listLevel` +/// changes (a style's numbering it leaves alone). +fn bullet_list_items(ui: &mut Ui, app: &mut WordApp) { + ui.separator(); + let in_list = app.session.doc.para_at(&app.session.sel.focus).and_then(|p| p.props.numbering).is_some_and(|n| n.num != 0); + ui.add_enabled_ui(in_list, |ui| { + ui.menu_button(tl!("Change List Level"), |ui| { + for level in 0..9u8 { + let label = format!("{} {}", tl!("Level"), level + 1); + mi_text(ui, app, &label, "para.listLevel", json!({"level": level})); + } + }); + }); + mi(ui, app, "Define New Bullet…", "ui.dialog", json!({"name": "defineBullet"})); +} + pub(super) fn home(app: &mut WordApp, ui: &mut Ui) { let st = app.session.run("format.state", &json!({})).unwrap_or_default(); let flag = |k: &str| st.get(k).and_then(Value::as_bool).unwrap_or(false); @@ -196,6 +213,7 @@ pub(super) fn home(app: &mut WordApp, ui: &mut Ui) { } }); mi(ui, app, "None", "para.bullets", json!({"off": true})); + bullet_list_items(ui, app); }); split( ui, From 5c8a6e1d75fac66baedc1dee0c9b45d72c4feb3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Tue, 17 Nov 2026 21:45:51 +0700 Subject: [PATCH 78/99] =?UTF-8?q?#3917:=20Text=20Outline=20and=20Shape=20O?= =?UTF-8?q?utline=20=E2=80=BA=20Weight=20show=20a=20line=20sample=20for=20?= =?UTF-8?q?each=20weight=20(#3933)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/cmd/wordart.rs | 4 +- crates/ui-egui/src/ribbon.rs | 1 + crates/ui-egui/src/ribbon/common.rs | 34 ++++++++++++- crates/ui-egui/src/ribbon/shape.rs | 33 ++++++++---- crates/ui-egui/src/ribbon/tests.rs | 62 ++++++++++++++++++++++ crates/ui-egui/src/wordart_menus.rs | 79 +++++++++++++++++++++++++---- 6 files changed, 189 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/wordart.rs b/crates/engine/src/cmd/wordart.rs index 2f92679311..de9dcb61ea 100644 --- a/crates/engine/src/cmd/wordart.rs +++ b/crates/engine/src/cmd/wordart.rs @@ -47,8 +47,8 @@ fn theme(s: &Session) -> Vec { } /// The text box story the selection formats as a whole: the selected shape's, or the one the -/// caret is in. -fn box_story(s: &Session) -> Option { +/// caret is in. The ribbon reads the current effects from the same place. +pub fn box_story(s: &Session) -> Option { if let Some((_, InlineObject::Shape { story: Some(id), .. })) = super::objects::object_selection(s) { return Some(*id); } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index ebdcd26cde..813d239e4e 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -35,6 +35,7 @@ use charts::{chart_design, smart_art_design}; pub(crate) use common::mi; #[cfg(test)] pub(crate) use common::size_menu; +pub(crate) use common::weight_menu; use common::{custom_groups, edge_cue}; use design::design; #[cfg(test)] diff --git a/crates/ui-egui/src/ribbon/common.rs b/crates/ui-egui/src/ribbon/common.rs index da7c640bdd..84c092c4d6 100644 --- a/crates/ui-egui/src/ribbon/common.rs +++ b/crates/ui-egui/src/ribbon/common.rs @@ -1,5 +1,5 @@ use super::language::mi_check; -use super::{Align2, MeasureExt, Rect, Sense, Tokens, Ui, Value, WordApp, big, group, json, small, vec2}; +use super::{Align2, MeasureExt, Rect, Sense, Stroke, Tokens, Ui, Value, WordApp, big, group, json, pos2, small, vec2}; /// Custom groups (Customize Ribbon, #379): up to three commands as large buttons, more as small /// labelled buttons in columns of three. Each shows the command's own icon and label. @@ -145,6 +145,38 @@ pub(crate) fn size_menu(ui: &mut Ui, app: &mut WordApp) { mi(ui, app, crate::dialogs::PAPER_LABELS.more, "ui.dialog", json!({"name": "pageSetup"})); } +/// The outline weights Word offers, in points: Text Outline, Shape Outline and the border dialogs. +const OUTLINE_WEIGHTS: [f32; 9] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.25, 3.0, 4.5, 6.0]; + +/// An outline's Weight submenu (#3917): each weight as its label and a line sample drawn at that +/// weight, the `current` one highlighted. Choosing one runs `id` with `params(weight)`. +pub(crate) fn weight_menu(ui: &mut Ui, app: &mut WordApp, id: &str, current: Option, params: impl Fn(f32) -> Value) { + let enabled = crate::widgets::enabled(app, id); + let t = Tokens::get(ui.ctx()); + let color = if enabled { t.text } else { t.text_disabled }; + // A hairline under a device pixel would vanish, so the thinnest samples get one. + let pixel = 1.0 / ui.ctx().pixels_per_point(); + let labels = OUTLINE_WEIGHTS.map(|w| crate::i18n::fmt(tl!("{n} pt"), &[("n", &w.to_string())])); + // The samples start a short gap after the widest label and end as far from the right edge as + // the labels start from the left one. + let font = egui::TextStyle::Button.resolve(ui.style()); + let widest = labels.iter().map(|l| ui.painter().layout_no_wrap(l.clone(), font.clone(), color).size().x).fold(0.0, f32::max); + let pad = ui.spacing().button_padding.x; + for (w, label) in OUTLINE_WEIGHTS.into_iter().zip(&labels) { + let checked = current.is_some_and(|c| (c - w).abs() < 0.01); + let resp = ui.add_enabled(enabled, egui::Button::new(label.as_str()).selected(checked).min_size(vec2(200.0, 22.0))); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, checked, label)); + let r = resp.rect; + let y = r.center().y; + let (x0, x1) = (r.left() + pad + widest + 12.0, r.right() - pad); + ui.painter().line_segment([pos2(x0, y), pos2(x1, y)], Stroke::new(w.max(pixel), color)); + if resp.clicked() { + crate::widgets::run_from_ribbon(app, id, params(w)); + ui.close(); + } + } +} + pub(crate) fn mi(ui: &mut Ui, app: &mut WordApp, label: &str, id: &str, params: Value) { mi_text(ui, app, tl!(label), id, params); } diff --git a/crates/ui-egui/src/ribbon/shape.rs b/crates/ui-egui/src/ribbon/shape.rs index c5c971ac60..c08644f773 100644 --- a/crates/ui-egui/src/ribbon/shape.rs +++ b/crates/ui-egui/src/ribbon/shape.rs @@ -1,5 +1,5 @@ use super::arrange::{align_menu, rotate_menu, rotation_field, wrap_menu}; -use super::common::{mi, size_field, stack}; +use super::common::{mi, size_field, stack, weight_menu}; use super::language::mi_check; use super::{Target, Ui, WordApp, big, group, json, menu_button, small, vec2}; @@ -43,12 +43,28 @@ pub(crate) fn gradient_menu(ui: &mut Ui, app: &mut WordApp, fill: Option<&wordcr } } +/// The outline (colour, width) Shape Outline changes: the selected shape's, or the selected +/// drawing canvas's border. +pub(super) fn selected_outline(s: &wordcraft_engine::Session) -> Option<(wordcraft_doc::Rgb, f32)> { + match wordcraft_engine::cmd::objects::selected(s)?.1 { + wordcraft_doc::para::InlineObject::Shape { stroke, stroke_width, .. } => stroke.map(|c| (c, stroke_width)), + o => o.canvas_style().and_then(|c| c.stroke.map(|stroke| (stroke, c.stroke_width))), + } +} + +/// Shape Outline › Weight: a new weight keeps the outline's colour (black when it has none). +pub(super) fn shape_weight_menu(ui: &mut Ui, app: &mut WordApp) { + let outline = selected_outline(&app.session); + let color = outline.map_or(wordcraft_doc::Rgb::BLACK, |o| o.0).hex(); + weight_menu(ui, app, "shape.outline", outline.map(|o| o.1), |w| json!({"color": color, "width": w})); +} + /// Shape Format: fill, outline and effects of the selected shape, and its arrangement. pub(super) fn shape_format(app: &mut WordApp, ui: &mut Ui) { - let (stroke, glow_size, fill) = match wordcraft_engine::cmd::objects::selected(&app.session) { - Some((_, wordcraft_doc::para::InlineObject::Shape { stroke, effects, fill, .. })) => (stroke, effects.glow.map(|g| g.size), fill), - Some((_, o)) => (None, None, o.canvas_style().and_then(|c| c.fill.clone())), - _ => (None, None, None), + let (glow_size, fill) = match wordcraft_engine::cmd::objects::selected(&app.session) { + Some((_, wordcraft_doc::para::InlineObject::Shape { effects, fill, .. })) => (effects.glow.map(|g| g.size), fill), + Some((_, o)) => (None, o.canvas_style().and_then(|c| c.fill.clone())), + _ => (None, None), }; let theme = app.session.doc.settings.theme_colors.clone(); group(ui, "Shape Styles", None, app, |ui, app| { @@ -72,12 +88,7 @@ pub(super) fn shape_format(app: &mut WordApp, ui: &mut Ui) { mi(ui, app, "No Color", "shape.outline", json!({"color": null})); crate::colors::menu(ui, app, &theme, Target::cmd("shape.outline")); ui.separator(); - ui.menu_button(tl!("Weight"), |ui| { - let color = stroke.unwrap_or(wordcraft_doc::Rgb::BLACK).hex(); - for w in [0.25, 0.5, 0.75, 1.0, 1.5, 2.25, 3.0, 4.5, 6.0] { - mi(ui, app, &format!("{w} pt"), "shape.outline", json!({"color": color, "width": w})); - } - }); + ui.menu_button(tl!("Weight"), |ui| shape_weight_menu(ui, app)); }, ); menu_button( diff --git a/crates/ui-egui/src/ribbon/tests.rs b/crates/ui-egui/src/ribbon/tests.rs index e5e4f5b6b1..256db700c3 100644 --- a/crates/ui-egui/src/ribbon/tests.rs +++ b/crates/ui-egui/src/ribbon/tests.rs @@ -199,6 +199,68 @@ fn design_style_set_gallery_reads_from_the_right_in_rtl() { } } +/// #3917: an outline's Weight submenu offers Word's nine weights, each a named entry with a +/// line sample drawn at its weight; the current weight is highlighted, and choosing one sets it. +#[test] +fn weight_menu_draws_each_weight_and_applies_it() { + use egui::accesskit::Toggled; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default()); + a.run("select.all", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 400.0)).build_ui_state( + |ui, app: &mut WordApp| { + let current = crate::wordart_menus::current_outline(app).map(|c| c.1); + weight_menu(ui, app, "format.textEffects", current, |w| json!({"outline": {"color": "1F4E79", "width": w}})); + }, + a, + ); + h.run_steps(2); + let labels = ["0.25 pt", "0.5 pt", "0.75 pt", "1 pt", "1.5 pt", "2.25 pt", "3 pt", "4.5 pt", "6 pt"]; + for label in labels { + let node = h.get_by_label(label); + assert_eq!(node.accesskit_node().toggled(), Some(Toggled::False), "{label} not highlighted with no outline set"); + } + // One line sample per weight, at that weight. + let widths: Vec = h + .output() + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::LineSegment { stroke, .. } => Some(stroke.width), + _ => None, + }) + .collect(); + assert_eq!(widths, [0.25, 0.5, 0.75, 1.0, 1.5, 2.25, 3.0, 4.5, 6.0].map(|w: f32| w.max(1.0)), "samples, a pixel at least"); + let outline = |h: &egui_kittest::Harness<'_, WordApp>| crate::wordart_menus::current_outline(h.state()); + for (label, width) in [("6 pt", 6.0), ("0.25 pt", 0.25)] { + h.get_by_label(label).click(); + h.run_steps(2); + assert_eq!(outline(&h), Some((wordcraft_doc::Rgb::parse("1F4E79").unwrap(), width)), "{label}"); + assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True), "{label} is highlighted once chosen"); + assert_eq!(h.get_by_label("1 pt").accesskit_node().toggled(), Some(Toggled::False)); + } +} + +/// #3917 review: Shape Outline › Weight on a drawing canvas reads the canvas's border, so its +/// weight is highlighted and a new weight keeps the border's colour instead of turning it black. +#[test] +fn shape_outline_weight_keeps_a_canvas_borders_colour() { + use super::shape::{selected_outline, shape_weight_menu}; + use egui::accesskit::Toggled; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + a.run("insert.canvas", json!({})).unwrap(); + a.run("shape.outline", json!({"color": "1F4E79", "width": 1.5})).unwrap(); + let blue = wordcraft_doc::Rgb::parse("1F4E79"); + assert_eq!(selected_outline(&a.session), blue.map(|c| (c, 1.5)), "the canvas's border"); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 400.0)).build_ui_state(|ui, app: &mut WordApp| shape_weight_menu(ui, app), a); + h.run_steps(2); + assert_eq!(h.get_by_label("1.5 pt").accesskit_node().toggled(), Some(Toggled::True), "the border's weight"); + h.get_by_label("3 pt").click(); + h.run_steps(2); + assert_eq!(selected_outline(&h.state().session), blue.map(|c| (c, 3.0)), "a new weight keeps the border blue"); +} + /// #2738: Home › Underline's drop-down: every line sample is a named entry (assistive /// technology, tooltips) that applies its own style; Words only, None and Underline Color › /// Automatic do what they say. diff --git a/crates/ui-egui/src/wordart_menus.rs b/crates/ui-egui/src/wordart_menus.rs index 78f51761d9..25ef63f3ea 100644 --- a/crates/ui-egui/src/wordart_menus.rs +++ b/crates/ui-egui/src/wordart_menus.rs @@ -132,9 +132,7 @@ pub fn outline_menu(ui: &mut Ui, app: &mut WordApp, theme: &[Rgb], current: Opti ui.separator(); ui.menu_button(crate::tl!("Weight"), |ui| { let color = current.map_or(Rgb::BLACK, |c| c.0).hex(); - for w in [0.25, 0.5, 0.75, 1.0, 1.5, 2.25, 3.0] { - mi(ui, app, &format!("{w} pt"), "format.textEffects", json!({"outline": {"color": color, "width": w}})); - } + crate::ribbon::weight_menu(ui, app, "format.textEffects", current.map(|c| c.1), |w| json!({"outline": {"color": color, "width": w}})); }); } @@ -209,14 +207,75 @@ pub fn transform_menu(ui: &mut Ui, app: &mut WordApp) { }); } -/// The selected shape's text outline (colour, width), for the Weight menu. +/// The text outline (colour, width) Text Outline would change, for its Weight menu: read where +/// `format.textEffects` applies, so choosing a weight keeps that text's colour. A selected shape, +/// or a caret in a text box, formats the box's whole text, read from its start; otherwise the +/// selection, read as typing reads it (the first selected character, or the caret's). pub fn current_outline(app: &WordApp) -> Option<(Rgb, f32)> { - let story = match wordcraft_engine::cmd::objects::object_selection(&app.session) { - Some((_, wordcraft_doc::InlineObject::Shape { story: Some(id), .. })) => wordcraft_doc::StoryRef::Part(*id), - _ => app.session.sel.focus.story, + let s = &app.session; + let props = match wordcraft_engine::cmd::wordart::box_story(s) { + Some(id) => s.doc.para_at(&s.doc.start_of(wordcraft_doc::StoryRef::Part(id)))?.props_at(0).clone(), + None => s.typing_props(), }; - let start = app.session.doc.start_of(story); - let para = app.session.doc.para_at(&start)?; - let fx = para.props_at(0).text_effects.as_deref()?; + let fx = props.text_effects.as_deref()?; fx.outline.and_then(|o| o.color.map(|c| (c, o.width))) } + +#[cfg(test)] +mod tests { + use super::*; + use wordcraft_engine::Session; + + fn outline_at(app: &WordApp, para: usize) -> Option<(Rgb, f32)> { + let p = app.session.doc.para_at(&wordcraft_doc::Pos::body(para, 0))?; + let fx = p.props_of_char(0).text_effects.as_deref()?; + fx.outline.and_then(|o| o.color.map(|c| (c, o.width))) + } + + /// #3917 review: the Weight menu reads the outline where Text Outline applies, the selection, + /// not the first character of the story. Its highlight is the selected text's weight, and a + /// new weight keeps that text's colour and leaves other paragraphs alone. + #[test] + fn the_weight_menu_reads_and_keeps_the_selected_texts_outline() { + use egui::accesskit::Toggled; + use egui_kittest::kittest::{NodeT, Queryable}; + let rgb = |h: &str| Rgb::parse(h); + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Red line\nBlue line")), crate::Services::default()); + a.run("select.text", json!({"text": "Red line"})).unwrap(); + a.run("format.textEffects", json!({"outline": {"color": "C00000", "width": 1.0}})).unwrap(); + a.run("select.text", json!({"text": "Blue line"})).unwrap(); + a.run("format.textEffects", json!({"outline": {"color": "1F4E79", "width": 3.0}})).unwrap(); + assert_eq!(current_outline(&a), rgb("1F4E79").map(|c| (c, 3.0)), "the selection's outline, not the first paragraph's"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(500.0, 700.0)).build_ui_state( + |ui, app: &mut WordApp| { + let theme = app.session.doc.settings.theme_colors.clone(); + let current = current_outline(app); + outline_menu(ui, app, &theme, current); + }, + a, + ); + h.run_steps(2); + h.get_by_label("Weight").hover(); + h.run(); + h.get_by_label("Weight").click(); + h.run(); + assert_eq!(h.get_by_label("3 pt").accesskit_node().toggled(), Some(Toggled::True), "the selected text's weight"); + assert_eq!(h.get_by_label("1 pt").accesskit_node().toggled(), Some(Toggled::False)); + h.get_by_label("6 pt").click(); + h.run_steps(2); + assert_eq!(outline_at(h.state(), 1), rgb("1F4E79").map(|c| (c, 6.0)), "the new weight keeps the selected text's colour"); + assert_eq!(outline_at(h.state(), 0), rgb("C00000").map(|c| (c, 1.0)), "the other paragraph is untouched"); + } + + /// A caret in a text box formats the box's whole text, so its outline is read from the box's + /// start; back in the body, the body text's (none here). + #[test] + fn a_caret_in_a_text_box_reads_the_boxs_outline() { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Body")), crate::Services::default()); + a.run("insert.textBox", json!({"text": "Boxed words"})).unwrap(); + a.run("format.textEffects", json!({"outline": {"color": "00B050", "width": 2.25}})).unwrap(); + assert_eq!(current_outline(&a), Rgb::parse("00B050").map(|c| (c, 2.25))); + a.run("caret.set", json!({"pos": wordcraft_doc::Pos::body(0, 2)})).unwrap(); + assert_eq!(current_outline(&a), None, "the body text has no outline"); + } +} From 65212d68567ea59af6f790f9b3237720b39a741c Mon Sep 17 00:00:00 2001 From: pakiat <49967840+pakiat@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:59:23 +0700 Subject: [PATCH 79/99] Shapes: lines move by their body and resize by their ends (#4393) Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 2 + crates/engine/src/cmd/connectors.rs | 30 +++++-- crates/engine/src/cmd/objects/arrange.rs | 5 +- crates/engine/src/cmd/objects/tests.rs | 105 +++++++++++++++++++++++ crates/engine/src/tests/wordart.rs | 57 ++++++++++++ crates/ui-egui/src/objects.rs | 28 ++++-- crates/ui-egui/src/objects/tests.rs | 103 ++++++++++++++++++++++ docs/ui-parity.md | 3 +- 8 files changed, 315 insertions(+), 18 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 39057e23fe..ff34d391e8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -339,6 +339,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-10-22: The desktop window works with several open documents (one window per document comes next). View › Window › Switch Windows lists them and shows the one chosen, back where it was left; New, Open and the mailings open beside unsaved work instead of asking about it; File › Close shows the next document; quitting asks about every document with unsaved changes, one at a time, and Cancel keeps the app open. - 2026-10-22: Several open documents in one session (engine part of one window per document). File › New opens a new document beside the open ones; File › Open opens beside them too, replaces a blank document nobody has used, and shows a file that is already open instead of opening it twice. Each document keeps its own text, selection, undo history, find state, view and recovery copy. View › Window › Switch Windows (`view.switchWindows`) lists the open documents and switches between them; `file.closeDocument` closes one where no window asks about unsaved changes (agents, headless sessions). Envelopes, Labels, Finish & Merge and New from Template open their result as a new document and leave the main document open as it was. Document ids are unique in the process. The desktop app still shows one document per window; the windows come next. - 2026-10-22: Legacy form names and selected drop-down labels decode numeric XML references, including saved whitespace, without decoding escaped reference text twice. +- 2026-10-26: Lines on the page: a selected floating line shows a handle at each end, as a connector does and as in Word, and dragging one moves that end (lines don't glue to shapes); pressing anywhere else on it moves it. A level line (0 high, as Word files store a rule) used to show the frame's top and bottom handles on itself, so pressing it in the middle resized it into a slant; and moving any object no longer re-applies the minimum size to a size the move doesn't change, which gave a level line a 4 pt height. A turned line's or connector's ends are where they are drawn. - 2026-10-25: Interface catalogs are still the shared storytold/craft-i18n ones embedded from `craft-i18n.rev` (`9205108c…`): 27 WordCraft languages with English fallback for missing strings, and the equation “Delete Around Caret in Equation” translation preserved. Native-speaker review remains human. - 2026-10-25: Input methods (egui 0.37): character- and byte-counted surrounding deletions, a fresh composition after body/equation replacement, rejection of queued stale replacements before mutation, transactional equation deletes and one undo group, with tracked and placeholder length mapping. Synthetic regressions document these paths; managed CI passed, and native IME acceptance (#155–#164) plus browser IME behavior remain open. - 2026-10-25: Justified and distributed lines keep the width of the spaces before their first character, as Word does: Thai official letters indent paragraphs with a run of spaces, and their first line no longer moves right by the line's slack (86 pt in a measured case). A distributed line's text reaches the margin even when the line ends with the space it wrapped at. @@ -1062,6 +1063,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-10-22 | trivial | Progress log: several open documents in the desktop window | | 2026-10-22 | trivial | Progress log: several open documents in one session | | 2026-10-22 | trivial | Decode numeric XML references once in legacy form names and drop-down labels | +| 2026-10-26 | trivial | Progress log: floating lines move by their body and resize by their ends, and a level line stays level | | 2026-10-25 | trivial | Progress log: egui 0.37 migration records the `craft-i18n.rev` catalog pin (9205108…; 27 languages) and the input-method handling; managed CI passed; native acceptance and native-speaker review remain open | | 2026-10-25 | trivial | Progress log: justified and distributed lines keep the width of the spaces before their first character | | 2026-10-17 | trivial | Progress log: Standard-encrypted (AES) Word files open (gap 9) | diff --git a/crates/engine/src/cmd/connectors.rs b/crates/engine/src/cmd/connectors.rs index 2912859081..b530ee858d 100644 --- a/crates/engine/src/cmd/connectors.rs +++ b/crates/engine/src/cmd/connectors.rs @@ -20,9 +20,12 @@ pub const SNAP: f32 = 12.0; /// Largest offset a routed connector gets, points. const MAX_OFFSET: f32 = 4000.0; +/// `shape.connect` is offered for what it runs on: a floating connector or line in the body text. fn has_connector(s: &Session) -> Option<&'static str> { match super::objects::selected(s) { - Some((_, InlineObject::Shape { kind, .. })) if kind.is_connector() => None, + Some((pos, InlineObject::Shape { kind, float, .. })) if kind.is_open() => { + (pos.story != StoryRef::Body || float.wrap == Wrap::Inline).then_some("only floating connectors in the body text can be glued") + } _ => Some("select a connector first"), } } @@ -31,7 +34,7 @@ pub fn specs() -> Vec { vec![ CommandSpec::new("shape.connect", "Connect Shapes", "Shape Format › Insert Shapes", connect) .params( - r#"{"start"?: end, "end"?: end} end: {"path": [..], "off": n, "site"?: n} (glue to that body shape's connection site; nearest one when omitted) | {"x": pt, "y": pt, "page"?: n} (drag the end there: it glues to a shape's site within 12 pt, else stays free there) | null (unglue)"#, + r#"{"start"?: end, "end"?: end} end: {"path": [..], "off": n, "site"?: n} (glue to that body shape's connection site; nearest one when omitted) | {"x": pt, "y": pt, "page"?: n} (drag the end there: it glues to a shape's site within 12 pt, else stays free there) | null (unglue). A plain line's ends only move to points: lines don't glue"#, ) .when(has_connector), ] @@ -186,13 +189,23 @@ fn ensure_id(s: &mut Session, pos: &Pos) -> Result { Ok(id) } -/// `shape.connect`: glue, move or unglue the selected connector's ends. +/// A floating line or connector's start and end on its page: its frame's ends (flips +/// included), turned with the frame by `deg` about its centre. +pub fn page_ends(r: wordcraft_geom::Rect, flip_h: bool, flip_v: bool, deg: f32) -> ((f32, f32), (f32, f32)) { + let (a, b) = ends(r.x, r.y, r.w, r.h, flip_h, flip_v); + let turn = wordcraft_geom::Spin::new(deg, false, false); + let (cx, cy) = (r.x + r.w / 2.0, r.y + r.h / 2.0); + (turn.apply(cx, cy, a.0, a.1), turn.apply(cx, cy, b.0, b.1)) +} + +/// `shape.connect`: glue, move or unglue the selected connector's ends, or move a line's. fn connect(s: &mut Session, v: &Value) -> CmdResult { let (pos, obj) = super::objects::selected(s).ok_or_else(|| CmdError::Disabled("select a connector first".into()))?; let InlineObject::Shape { kind, float, .. } = &obj else { return Err(CmdError::Disabled("select a connector first".into())) }; - if !kind.is_connector() { + if !kind.is_open() { return Err(CmdError::Disabled("select a connector first".into())); } + let line = !kind.is_connector(); if pos.story != StoryRef::Body || float.wrap == Wrap::Inline { return Err(CmdError::Disabled("only floating connectors in the body text can be glued".into())); } @@ -200,7 +213,7 @@ fn connect(s: &mut Session, v: &Value) -> CmdResult { let layout = s.layout(); let hit = layout.object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the connector isn't laid out".into()))?; let r = hit.rect; - let (mut p0, mut p1) = ends(r.x, r.y, r.w, r.h, fh, fv); + let (mut p0, mut p1) = page_ends(r, fh, fv, hit.spin.deg); let mut glue: [Option>; 2] = [None, None]; for (i, key) in ["start", "end"].into_iter().enumerate() { let Some(e) = v.get(key) else { continue }; @@ -209,6 +222,9 @@ fn connect(s: &mut Session, v: &Value) -> CmdResult { continue; } let here = if i == 0 { p0 } else { p1 }; + if line && e.get("path").is_some() { + return Err(CmdError::Params(format!("`{key}`: a line's ends move to points; lines don't glue to shapes"))); + } let (target, site) = if e.get("path").is_some() { let at = body_pos(e).ok_or_else(|| CmdError::Params(format!("`{key}`: no shape there")))?; let th = layout @@ -234,9 +250,9 @@ fn connect(s: &mut Session, v: &Value) -> CmdResult { if page != hit.page { return Err(CmdError::Params("a connector's ends stay on its page".into())); } - // The nearest site of a shape (not a connector) within reach. + // The nearest site of a shape (not a connector) within reach; a line's end stays free. let mut best: Option<(Pos, u32, f32)> = None; - if let Some(pg) = layout.pages.get(page) { + if !line && let Some(pg) = layout.pages.get(page) { for it in &pg.items { let wordcraft_layout::Placed::Object { rect, spin, story: StoryRef::Body, path, off, .. } = it else { continue }; let at = Pos { story: StoryRef::Body, path: path.clone(), off: *off }; diff --git a/crates/engine/src/cmd/objects/arrange.rs b/crates/engine/src/cmd/objects/arrange.rs index bfae1b31d6..90fd2aa88d 100644 --- a/crates/engine/src/cmd/objects/arrange.rs +++ b/crates/engine/src/cmd/objects/arrange.rs @@ -21,8 +21,9 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult { } let (w0, h0) = obj_size(&obj); let min = min_size(&obj); - let w = p::f32(v, "width").unwrap_or(w0).clamp(min, MAX_OFFSET); - let h = p::f32(v, "height").unwrap_or(h0).clamp(min, MAX_OFFSET); + // A size not given stays as it is: a move must not give a level line (0 high) a height. + let w = p::f32(v, "width").map_or(w0, |w| w.clamp(min, MAX_OFFSET)); + let h = p::f32(v, "height").map_or(h0, |h| h.clamp(min, MAX_OFFSET)); if (w, h) != (w0, h0) { with_obj(s, |o| o.set_size(w, h))?; } diff --git a/crates/engine/src/cmd/objects/tests.rs b/crates/engine/src/cmd/objects/tests.rs index 1e71751ca5..86a2018a98 100644 --- a/crates/engine/src/cmd/objects/tests.rs +++ b/crates/engine/src/cmd/objects/tests.rs @@ -152,6 +152,111 @@ fn click_resize_and_drag(insert: &str, params: Value) { assert_eq!((object_area(&mut s).rect.x, object_area(&mut s).rect.y), (250.0, 300.0), "{insert}"); } +/// Moving keeps a size it isn't given: a level line (0 high, as Word files store a rule) +/// moved by its body stays level, though a height given to it is still at least the minimum. +#[test] +fn moving_a_level_line_keeps_it_level() { + let line = InlineObject::Shape { + kind: wordcraft_doc::para::ShapeKind::Line, + w: 200.0, + h: 0.0, + fill: None, + stroke: None, + stroke_width: 1.0, + float: wordcraft_doc::para::Float { wrap: Wrap::InFrontOfText, x: 50.0, y: 100.0, ..Default::default() }, + story: None, + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + let mut s = Session::new(wordcraft_doc::Document::new()); + s.doc.insert_object(&Pos::body(0, 0), line, &Default::default()).unwrap(); + s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, wordcraft_doc::para::OBJ.len_utf8())})).unwrap(); + s.run("arrange.bounds", &json!({"page": 0, "x": 150, "y": 300})).unwrap(); + let o = s.layout().object(&Pos::body(0, 0), 0).unwrap(); + assert_eq!((o.rect.x, o.rect.y, o.rect.w, o.rect.h), (150.0, 300.0, 200.0, 0.0)); + s.run("arrange.bounds", &json!({"height": 0})).unwrap(); + assert_eq!(s.layout().object(&Pos::body(0, 0), 0).unwrap().rect.h, min_size(&selected(&s).unwrap().1)); +} + +/// Connect Shapes is offered for the lines and connectors it moves: floating ones in the body +/// text, not one In Line with Text or in a header. +#[test] +fn connect_is_offered_only_for_floating_lines_in_the_body() { + use wordcraft_doc::para::ShapeKind; + let shape = |kind, wrap| InlineObject::Shape { + kind, + w: 200.0, + h: 0.0, + fill: None, + stroke: None, + stroke_width: 1.0, + float: wordcraft_doc::para::Float { wrap, x: 50.0, y: 100.0, ..Default::default() }, + story: None, + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + for kind in [ShapeKind::Line, ShapeKind::StraightConnector] { + for (wrap, offered) in [(Wrap::InFrontOfText, true), (Wrap::Inline, false)] { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.doc.insert_object(&Pos::body(0, 0), shape(kind, wrap), &Default::default()).unwrap(); + s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, wordcraft_doc::para::OBJ.len_utf8())})).unwrap(); + assert_eq!(s.why_disabled("shape.connect").is_none(), offered, "{kind:?} {wrap:?}"); + assert_eq!(s.run("shape.connect", &json!({"end": {"x": 300.0, "y": 150.0}})).is_ok(), offered, "{kind:?} {wrap:?}: runs when offered"); + } + } +} + +/// Moving one end of a slanted, flipped line leaves the other where the page shows it: the ends +/// `shape.connect` reads and writes are the drawn ones (checked on the rendered page). +#[test] +fn moving_an_end_of_a_flipped_slanted_line_keeps_the_other() { + use wordcraft_doc::para::ShapeKind; + // Flipped vertically, a line in the frame (300, 600) 100 × 100 runs from its bottom-left + // (300, 700) to its top-right (400, 600), as in Word. + let line = InlineObject::Shape { + kind: ShapeKind::Line, + w: 100.0, + h: 100.0, + fill: None, + stroke: Some(wordcraft_doc::props::Rgb::BLACK), + stroke_width: 3.0, + float: wordcraft_doc::para::Float { + wrap: Wrap::InFrontOfText, + h_rel: wordcraft_doc::para::Anchor::Page, + v_rel: wordcraft_doc::para::Anchor::Page, + x: 300.0, + y: 600.0, + flip_v: true, + ..Default::default() + }, + story: None, + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + let mut s = Session::new(wordcraft_doc::Document::new()); + s.doc.insert_object(&Pos::body(0, 0), line, &Default::default()).unwrap(); + s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, wordcraft_doc::para::OBJ.len_utf8())})).unwrap(); + let inked = |s: &Session, x: f32, y: f32| { + let l = s.export_layout(); + let r = wordcraft_render::render_page(&s.doc, &l.pages[0], 1.0, &Default::default()); + let dark = |px: i64, py: i64| { + let i = ((py * i64::from(r.width) + px) * 4) as usize; + r.pixels.get(i..i + 3).is_some_and(|p| p.iter().all(|&c| c < 128)) + }; + (-3..=3).any(|dx| (-3..=3).any(|dy| dark(x as i64 + dx, y as i64 + dy))) + }; + assert!(inked(&s, 302.0, 698.0) && inked(&s, 398.0, 602.0), "drawn from bottom-left to top-right"); + assert!(!inked(&s, 302.0, 602.0), "not from the top-left"); + // Its end goes to (450, 650): the start stays at (300, 700). + s.run("shape.connect", &json!({"end": {"x": 450.0, "y": 650.0}})).unwrap(); + assert!(inked(&s, 303.0, 699.0), "the start stays where it was drawn"); + assert!(inked(&s, 447.0, 651.0), "the end is where it was dragged"); + assert!(!inked(&s, 398.0, 602.0), "the end left its old place"); +} + /// Ctrl+drag: a copy lands where dropped and is selected; the original stays, the clipboard /// is untouched, and it is one undo step. #[test] diff --git a/crates/engine/src/tests/wordart.rs b/crates/engine/src/tests/wordart.rs index 1a07f1ddcc..d2359eb80c 100644 --- a/crates/engine/src/tests/wordart.rs +++ b/crates/engine/src/tests/wordart.rs @@ -141,6 +141,63 @@ fn dragging_a_connector_end_glues_it_to_the_nearest_site() { run(&mut s, "arrange.nudge", json!({"dx": 1})); } +/// A plain line's ends move to points the way a connector's free ends do, but never glue: not +/// even dropped on a shape's connection site, nor by reference. A turned line's ends are where +/// it is drawn, and moving one leaves the other there. +#[test] +fn dragging_a_line_end_moves_it_freely() { + let float = + |x: f32, y: f32, rot: f32| Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y, rot, ..Default::default() }; + let shape = |kind, w, h, float, extra| InlineObject::Shape { + kind, + w, + h, + fill: None, + stroke: None, + stroke_width: 1.0, + float, + story: None, + freeform: None, + effects: Default::default(), + extra, + }; + let mut p = Paragraph::with_text("Body ", CharProps::default()); + for o in [ + shape(ShapeKind::Rectangle, 72.0, 36.0, float(100.0, 200.0, 0.0), ShapeExtra { id: 1, ..Default::default() }), + shape(ShapeKind::Line, 200.0, 0.0, float(300.0, 300.0, 0.0), ShapeExtra::default()), + shape(ShapeKind::Line, 200.0, 0.0, float(300.0, 500.0, 90.0), ShapeExtra::default()), + ] { + let end = p.len(); + p.insert_object(end, o, &CharProps::default()).unwrap(); + } + let mut d = Document::new(); + d.body = vec![para_block(p)]; + let mut s = Session::new(d); + let line_ends = |s: &mut Session, off: usize| { + let pos = Pos::body(0, off); + let hit = s.layout().object(&pos, 0).unwrap(); + let Some(InlineObject::Shape { float, extra, .. }) = s.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).cloned() else { panic!() }; + let (a, b) = crate::cmd::connectors::page_ends(hit.rect, float.flip_h, float.flip_v, hit.spin.deg); + let round = |p: (f32, f32)| ((p.0 * 100.0).round() / 100.0, (p.1 * 100.0).round() / 100.0); + (round(a), round(b), extra) + }; + select(&mut s, 8); + run(&mut s, "shape.connect", json!({"end": {"x": 500.0, "y": 350.0}})); + assert_eq!(line_ends(&mut s, 8).0, (300.0, 300.0), "the start stays"); + assert_eq!(line_ends(&mut s, 8).1, (500.0, 350.0)); + // Right on the rectangle's left site (100, 218): a connector would glue; the line doesn't. + run(&mut s, "shape.connect", json!({"start": {"x": 101.0, "y": 217.0}})); + let (a, _, extra) = line_ends(&mut s, 8); + assert_eq!((a, extra.start, extra.end), ((101.0, 217.0), None, None)); + assert!(s.run("shape.connect", &json!({"end": {"path": [0], "off": 5}})).is_err(), "a line doesn't glue by reference"); + // Turned a quarter: drawn from (400, 400) to (400, 600). Its end moves down; its start stays. + select(&mut s, 11); + assert_eq!(line_ends(&mut s, 11).0, (400.0, 400.0)); + run(&mut s, "shape.connect", json!({"end": {"x": 400.0, "y": 650.0}})); + let (a, b, _) = line_ends(&mut s, 11); + assert_eq!((a, b), ((400.0, 400.0), (400.0, 650.0))); +} + #[test] fn wordart_is_inserted_styled_and_bent() { let mut s = Session::new(Document::new()); diff --git a/crates/ui-egui/src/objects.rs b/crates/ui-egui/src/objects.rs index 3228229ed0..da94d5e142 100644 --- a/crates/ui-egui/src/objects.rs +++ b/crates/ui-egui/src/objects.rs @@ -73,15 +73,21 @@ pub struct ObjectDrag { /// How near (screen points) a press must be to a connector's end to grab it. const END_GRAB: f32 = 7.0; -/// The selected connector's start and end on its page (points), and its layout. +/// The selected floating connector's start and end on its page (points), and its layout; or a +/// floating line's, whose ends move the same way (they just don't glue); both in the body text, +/// where `shape.connect` moves them. Such a line shows +/// and takes handles at its ends only, as Word's do: the frame's handles would sit on a level +/// line, so pressing it there would resize it into a slant rather than move it. fn connector_ends(app: &WordApp, layout: &DocLayout) -> Option<(ObjectHit, (f32, f32), (f32, f32))> { let (pos, InlineObject::Shape { kind, float, .. }) = selected(app)? else { return None }; - if !kind.is_connector() { + // Where `shape.connect` can't move its ends (In Line with Text, a header or footer), a line or + // connector keeps its frame's handles instead. + if !kind.is_open() || pos.story != StoryRef::Body || float.wrap == Wrap::Inline { return None; } let (flip_h, flip_v) = (float.flip_h, float.flip_v); let o = layout.object(&pos, app.session.page_hint)?; - let (a, b) = wordcraft_doc::connector::ends(o.rect.x, o.rect.y, o.rect.w, o.rect.h, flip_h, flip_v); + let (a, b) = wordcraft_engine::cmd::connectors::page_ends(o.rect, flip_h, flip_v, o.spin.deg); Some((o, a, b)) } @@ -656,7 +662,9 @@ fn object_link(app: &WordApp, object: &ObjectHit) -> Option { /// being edited (body, or the header/footer). fn grab_at(app: &WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Pos2) -> Option<(ObjectHit, Grab)> { let story = active_story(app, layout); - let handle = active(app, layout).filter(|(o, _)| o.story == story && !fixed(app, o)).and_then(|(o, _)| { + // A connector or line is resized by its ends (`connector_end_at`), not by a frame. + let framed = connector_ends(app, layout).is_none(); + let handle = active(app, layout).filter(|(o, _)| framed && o.story == story && !fixed(app, o)).and_then(|(o, _)| { let f = screen(pages, scale, o.page, o.rect)?; if !size_only(app, &o) && frame::rotate_handle_at(f, o.spin.deg, at) { return Some((o, Grab::Rotate)); @@ -811,8 +819,10 @@ pub fn paint(app: &WordApp, painter: &Painter, t: &Tokens, layout: &DocLayout, p paint_end_drag(app, d, painter, t, layout, pages, scale); return; } - if let Some((o, a, b)) = connector_ends(app, layout) { - // A connector: a handle at each end (filled when glued). + // A connector or line: a handle at each end (filled when glued). While it is dragged by its + // body, the drag preview below shows instead (the page leaves it out meanwhile). + let body_drag = app.canvas.obj_drag.as_ref().is_some_and(|d| d.drag.moved); + if !body_drag && let Some((o, a, b)) = connector_ends(app, layout) { let glued = match selected(app) { Some((_, InlineObject::Shape { extra, .. })) => (extra.start.is_some(), extra.end.is_some()), _ => (false, false), @@ -893,14 +903,16 @@ fn paint_drop_caret(d: &ObjectDrag, painter: &Painter, layout: &DocLayout, pages } /// A connector's end being dragged: a line from its other end to the pointer, and the connection -/// sites of the shapes near the pointer (the one it would glue to, filled). +/// sites of the shapes near the pointer (the one it would glue to, filled). A line's end doesn't +/// glue, so it shows no sites. fn paint_end_drag(app: &WordApp, d: &ObjectDrag, painter: &Painter, t: &Tokens, layout: &DocLayout, pages: &[Rect], scale: f32) { let Some((which, at)) = d.end.filter(|_| d.drag.moved) else { return }; let Some((_, a, b)) = connector_ends(app, layout) else { return }; let fixed = if which { a } else { b }; let snap = wordcraft_engine::cmd::connectors::SNAP; + let glues = matches!(selected(app), Some((_, InlineObject::Shape { kind, .. })) if kind.is_connector()); let mut best: Option<((f32, f32), f32)> = None; - if let Some(pg) = layout.pages.get(d.object.page) { + if glues && let Some(pg) = layout.pages.get(d.object.page) { for it in &pg.items { let wordcraft_layout::Placed::Object { rect, spin, story: StoryRef::Body, path, off, .. } = it else { continue }; let pos = Pos { story: StoryRef::Body, path: path.clone(), off: *off }; diff --git a/crates/ui-egui/src/objects/tests.rs b/crates/ui-egui/src/objects/tests.rs index d9c53be039..57efcdd94a 100644 --- a/crates/ui-egui/src/objects/tests.rs +++ b/crates/ui-egui/src/objects/tests.rs @@ -423,6 +423,109 @@ fn floating_rect(w: f32, h: f32) -> InlineObject { } } +/// A floating line `w` wide and `h` tall (0: level, as Word files often store a rule). +fn floating_line(w: f32, h: f32, flip_v: bool) -> InlineObject { + InlineObject::Shape { + kind: ShapeKind::Line, + w, + h, + fill: None, + stroke: Some(wordcraft_doc::Rgb(0, 0, 0)), + stroke_width: 0.75, + float: wordcraft_doc::para::Float { wrap: Wrap::InFrontOfText, x: 60.0, y: 120.0, flip_v, ..Default::default() }, + story: None, + freeform: None, + effects: Default::default(), + extra: Default::default(), + } +} + +/// A selected level line, pressed in its middle and dragged, moves and stays level: its +/// middle is its body, not a resize handle (a level line's top and bottom edge handles sit on +/// it there, and grabbing one gave it a height, so it came out slanted). +#[test] +fn a_level_line_dragged_by_its_middle_moves_and_stays_level() { + use crate::table_resize::tests::{H, button, steps}; + for flip_v in [false, true] { + let (mut app, hit) = app_with(floating_line(300.0, 0.0, flip_v)); + app.run("view.commentsPane", json!({"value": false})).unwrap(); + app.run("select.range", json!({"anchor": hit.pos(), "focus": Pos { off: hit.off + OBJ.len_utf8(), ..hit.pos() }})).unwrap(); + let mut h: H = rotation_window(app); + let r = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).unwrap().rect; + let at = |h: &mut H, x: f32, y: f32| crate::canvas::page_to_screen(h.state_mut(), 0, x, y).unwrap(); + let start = at(&mut h, r.x + r.w / 2.0, r.y); + // Along the page and a little down, as a hand drags. + let end = start + egui::vec2(60.0, 3.0); + h.event(egui::Event::PointerMoved(start)); + button(&h, start, true); + h.step(); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(start + (end - start) * (k as f32 / 4.0))); + h.step(); + } + assert_eq!(h.state().canvas.obj_drag.as_ref().map(|d| d.drag.grab), Some(Grab::Move), "flip_v {flip_v}: the middle moves it"); + // While it moves, it shows where the pointer has it (the page leaves it out + // meanwhile), not only as its end handles back where it was: something is drawn along + // the line's new place, between its ends. + h.step(); + let img = h.render().unwrap(); + let ppp = h.ctx.pixels_per_point(); + let (x0, x1) = (((end.x - 100.0) * ppp) as u32, ((end.x + 100.0) * ppp) as u32); + let (y0, y1) = (((end.y - 3.0) * ppp) as u32, ((end.y + 3.0) * ppp) as u32); + let pointer = Rect::from_min_size(end - egui::vec2(2.0, 2.0), egui::vec2(20.0, 26.0)); + let drawn = (y0..y1) + .flat_map(|y| (x0..x1).map(move |x| (x, y))) + .filter(|&(x, y)| !pointer.contains(egui::pos2(x as f32 / ppp, y as f32 / ppp))) + .filter(|&(x, y)| img.get_pixel(x, y).0[..3].iter().any(|c| *c < 200)) + .count(); + assert!(drawn > 50, "flip_v {flip_v}: the dragged line shows at its new place ({drawn} pixels)"); + button(&h, end, false); + steps(&mut h, 3); + let n = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).unwrap().rect; + assert!(n.h.abs() < 0.01 && (n.w - r.w).abs() < 0.01, "flip_v {flip_v}: still a level line as long: {r:?} -> {n:?}"); + assert!(n.x > r.x + 10.0, "flip_v {flip_v}: moved along: {r:?} -> {n:?}"); + // Its end is a handle: dragged down, that end goes there and the other stays. + let right = at(&mut h, n.right(), n.y); + let down = right + egui::vec2(0.0, 40.0); + h.event(egui::Event::PointerMoved(right)); + button(&h, right, true); + h.step(); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(right + (down - right) * (k as f32 / 4.0))); + h.step(); + } + button(&h, down, false); + steps(&mut h, 3); + let e = h.state_mut().session.layout().object(&Pos::body(0, 0), 0).unwrap().rect; + // Screen points per page point. + let scale = (at(&mut h, n.x + 100.0, n.y).x - at(&mut h, n.x, n.y).x) / 100.0; + assert!((e.x - n.x).abs() < 0.5 && (e.y - n.y).abs() < 0.5, "flip_v {flip_v}: the left end stays: {n:?} -> {e:?}"); + assert!( + (e.right() - n.right()).abs() < 0.5 && (e.bottom() - (n.y + 40.0 / scale)).abs() < 0.5, + "flip_v {flip_v}: the right end follows: {e:?}" + ); + } +} + +/// End handles go only to the lines and connectors `shape.connect` moves: floating ones in the +/// body text. One In Line with Text keeps its frame's handles, so it can still be resized on the +/// page. +#[test] +fn only_floating_lines_and_connectors_take_end_handles() { + for kind in [ShapeKind::Line, ShapeKind::StraightConnector] { + for (wrap, ends) in [(Wrap::InFrontOfText, true), (Wrap::Inline, false)] { + let mut obj = floating_line(200.0, 40.0, false); + if let InlineObject::Shape { kind: k, float, .. } = &mut obj { + (*k, float.wrap) = (kind, wrap); + } + let (mut app, hit) = app_with(obj); + app.run("select.range", json!({"anchor": hit.pos(), "focus": Pos { off: hit.off + OBJ.len_utf8(), ..hit.pos() }})).unwrap(); + let layout = app.session.layout(); + assert_eq!(connector_ends(&app, &layout).is_some(), ends, "{kind:?} {wrap:?}"); + } + } +} + /// A text box doesn't snap to the objects inside it (they move with it). #[test] fn a_text_box_does_not_snap_to_its_own_contents() { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c4b899b397..e9abcefef2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -43,7 +43,7 @@ Document title opens Rename Document; the account badge opens Options › Genera | Rulers: indents, tabs, margins, table columns | indents draggable (one undo, #62); tab stops: corner selector (Left/Center/Right/Decimal/Bar), click to set, drag to move, drag off to clear, per-kind markers, Alt skips the snap, one undo step per gesture, double-click opens the Tabs dialog (#320); table column and row markers drag their borders (one undo) and in a cell the indents are measured from it (#700); the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, never closer than 30 px, the small ticks never closer than 4 px, the text keeps its size), give way to an indent, tab or column marker on them, and the margins get ticks only; both rulers span the caret's page at its own scale in every layout (one column, One Page, Multiple Pages) and follow the caret to another page (#1878) | ✅ | 92% | 1 | | On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text. Inside a Drawing Canvas a click picks the member under it (shape, picture or text box) on its own, its frame and handles shown inside the canvas frame; it is dragged, resized, turned and nudged inside the canvas, and Shape Format, Delete, Cut and Copy act on it alone; a click in a text box member's text puts the caret there (#2637, `objects::tests::clicking_and_dragging_inside_a_canvas_works_on_its_members`). Not yet: Shift+click on several members, dragging a member out of its canvas, drag-selecting a text box member's text, members of a turned canvas | ✅ | 75% | — | | Rulers: indents, tabs, margins, table columns | indents draggable (one undo, #62); tab stops: corner selector (Left/Center/Right/Decimal/Bar), click to set, drag to move, drag off to clear, per-kind markers, Alt skips the snap, one undo step per gesture, double-click opens the Tabs dialog (#320); table column and row markers drag their borders (one undo) and in a cell the indents are measured from it (#700); the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, never closer than 30 px, the small ticks never closer than 4 px, the text keeps its size), give way to an indent, tab or column marker on them, and the margins get ticks only; both rulers span the caret's page at its own scale in every layout (one column, One Page, Multiple Pages) and follow the caret to another page (#1878); in a section of several text columns the spaces between them are shaded like the margins (Print Layout, in the main text outside tables, with the selection in one section), an edge dragged changes the spacing (equal columns stay equal, as in Word for Mac), one undo step per drag (#5197) | ✅ | 92% | 1 | -| On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text | ✅ | 75% | — | +| On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text; a floating line has a handle at each end, as in Word (dragging one moves only that end; dragging the line anywhere else moves all of it), and a level line stays level when moved | ✅ | 75% | — | | On-canvas objects: select, drag, Ctrl+drag to copy, Ctrl+Shift+drag to copy along an axis, resize handles, nudge | ✅ tested (#228, #1014); Ctrl/Command+Shift on a selected floating picture, shape or text box copies along the dominant horizontal or vertical axis, with guides only along the free axis; the original and clipboard stay, the duplicate is selected, and the drop is one undo step. Inline copies still follow the text insertion cursor (#4764). Synthetic Linux pointer/render tests only; native desktop and Word untested; an In Line with Text object drags within the text as in Word: a dashed insertion cursor follows the pointer through the text and the drop (or Ctrl+drop copy) lands there, still inline (#2233, #2234) | ✅ | 75% | — | | Rotation handle, crop handles on canvas, alignment guides, smart guides | rotation handle (Shift: 15° steps), pictures and shapes without text stories preview their content turning while the pointer is held; release commits one `arrange.rotation` command and Escape cancels (#2277); text boxes retain a frame-only rotation preview, with text staying upright; turned frames resize along their axes (#332), and the arrow over each handle turns with the frame to the nearest of the four resize arrows (#3932); crop handles: Picture Format › Crop puts the picture in crop mode, black crop handles trim a side (a corner, two) keeping the scale and the visible part in place, the cropped-away part shows dimmed, Esc/Enter/a click outside/Crop again keep the crop, one undo step per drag (unturned pictures; no Crop to Shape, Aspect Ratio or Fill/Fit); alignment guides, our own design: a moved picture, shape or text box snaps its left, centre or right (top, middle or bottom) to the page's edges and centre, the margins and the other floating objects on the page within 6 screen points, x and y independently, turned objects by their rotated bounds, with a thin line across the page for each guide while dragging; Alt moves freely; File › Options › Advanced › Editing (`ui.alignmentGuides`) turns them off. Smart guides missing | Word for Mac 16.113.4 shows no guide lines and snaps inconsistently (to the page's left edge, not its top, right or bottom; Word check K); Word for Windows' guides not observed | 75% | 1–2 | | On-canvas objects: select, drag, Ctrl+drag to copy, Ctrl+Shift+drag to copy along an axis, resize handles, nudge | ✅ tested (#228, #1014); Ctrl/Command+Shift on a selected floating picture, shape or text box copies along the dominant horizontal or vertical axis, with guides only along the free axis; the original and clipboard stay, the duplicate is selected, and the drop is one undo step. Inline copies still follow the text insertion cursor (#4764). Synthetic Linux pointer/render tests only; native desktop and Word untested; an In Line with Text object drags within the text as in Word: a bold insertion cursor (solid, twice the caret's width) follows the pointer through the text and the drop (or Ctrl+drop copy) lands there, still inline (#2233, #2234, #4195) | ✅ | 75% | — | @@ -186,6 +186,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-10-22 | trivial | One native window per open document on the desktop (the web app keeps one window): New and Open open the document in a window of its own, focused and cascaded from the last; Open replaces an untouched blank document in its window and brings an already-open file's window forward; each window keeps its own ribbon tab, File page, dialogs, panes and composition; View › Window › Switch Windows lists the windows and brings the chosen one forward; File › Close and the window's close button close the window (asking about unsaved changes) and the window focused before comes forward, while the last window stays open with no document; quitting asks Save / Don't Save / Cancel about each document in its own window | | 2026-10-22 | trivial | Several open documents in one window (one window per document comes next): View › Window › Switch Windows lists the open documents, the shown one marked and unsaved ones dotted, and shows the one chosen, with its own scroll position, zoom, comment drafts and AutoSave file; File › New, Open, Envelopes, Labels, Finish & Merge and personal templates open beside the open documents without asking about unsaved changes; File › Close shows the next open document; the window's close button asks Save / Don't Save / Cancel about each document with unsaved changes, showing it, and Cancel keeps the app open. Untitled documents are numbered (Document2) in the interface language | | 2026-10-25 | trivial | Read Mode: the Page color is kept from one entry to the next; ink, object drag previews and table drag arrows follow it instead of Switch Modes | +| 2026-10-26 | trivial | Lines on the page: a selected floating line shows and takes handles at its ends only (dragging one moves that end; lines don't glue), pressing elsewhere on it moves it, and moving keeps a level line 0 high | | 2026-10-25 | trivial | Custom Document Properties dialog: File › Info › Properties › Advanced Properties… opens it; the document's custom properties listed with Add, Modify and Delete over a name/value form (text properties only; Word's number/date/yes-no types not offered), OK one undoable `file.properties` step, Cancel discards; modal dialogs 62 → 63 (#2982) | | 2026-10-25 | trivial | Text Highlight Color shows the remembered colour on the ribbon and mini-toolbar buttons; No Color leaves the pen without a misleading yellow bar (#4087) | | 2026-10-24 | trivial | Read Mode: a Page color menu (None, Sepia, Inverse) beside Line spacing; the columns are drawn on white, sepia or a dark page, in place of the document's page color (`view.readPageColor`) | From e784a2aaedc849b5e0a37d196215aca4dceaedbc Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:12:46 +0100 Subject: [PATCH 80/99] Tests: review.language's no-proofing case uses zxx, not fr-FR (#6944) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6ea3c4f71a..45052d0956 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -10406,8 +10406,9 @@ fn review_language_validates_tags_and_marks_text_unchecked() { assert_eq!(run(&mut s, "format.state", json!({}))["lang"], "pl"); run(&mut s, "review.language", json!({})); assert_eq!(run(&mut s, "format.state", json!({}))["lang"], "en-US"); - // A language without proofing tools: no marks. - run(&mut s, "review.language", json!({"lang": "fr-FR"})); + // A language without proofing tools: no marks. `zxx` (no linguistic content) never has + // them; a real language such as fr-FR does wherever its system Hunspell dictionary is installed. + run(&mut s, "review.language", json!({"lang": "zxx"})); assert_eq!(run(&mut s, "review.issues", json!({})), json!([])); } From 26b3ae2cc2f9c6ae2436e9394865e161f5a1683e Mon Sep 17 00:00:00 2001 From: Diego Guerini <106814760+D13GOOOO@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:26:33 +0100 Subject: [PATCH 81/99] inspect_document marks the page fields of headers and footers (#4467) (#4474) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/file.rs | 90 ++++++++++++++++++++++++- crates/engine/src/tests.rs | 119 ++++++++++++++++++++++++++++++++++ crates/mcp/src/tools.rs | 2 +- docs/mcp.md | 2 +- 4 files changed, 209 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 1301213659..3ec6ce025c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -651,6 +651,77 @@ fn info(s: &mut Session, _: &Value) -> CmdResult { })) } +/// Most fields [`story_fields`] lists for one story, and how deep it goes into nested tables. +const MAX_STORY_FIELDS: usize = 200; +const MAX_STORY_DEPTH: usize = 8; + +/// The fields of a story's paragraphs, tables included: the code, the result stored with it, and +/// whether the page shows a value of its own (#4467). A header or footer's text carries the +/// stored result of a page field (`1` for a PAGE, the page count when it was inserted for a +/// NUMPAGES); each page shows its own, as the layout draws it. A STYLEREF counts too: the layout +/// looks its text up from the page it lands on. False when a limit cut the list short. +fn story_fields(blocks: &wordcraft_doc::Blocks, depth: usize, out: &mut Vec) -> bool { + if depth > MAX_STORY_DEPTH { + return false; + } + for b in blocks { + match &**b { + Block::Para(p) => { + for o in &p.objects { + if let wordcraft_doc::para::InlineObject::Field { instr, result, .. } = o { + if out.len() >= MAX_STORY_FIELDS { + return false; + } + out.push(field_json(instr, result)); + } + } + } + Block::Table(t) => { + for cell in t.rows.iter().flat_map(|r| &r.cells) { + if !story_fields(&cell.blocks, depth + 1, out) { + return false; + } + } + } + } + } + true +} + +/// The range fields of `story` (a `FieldStart` … `FieldEnd` pair: what the DOCX reader makes of a +/// field whose result has tracked changes of its own or spans paragraphs, and of every TOC), +/// listed as [`story_fields`] lists inline ones, after them; the result is the text between the +/// markers as it is, at most [`MAX_RANGE_RESULT`] characters of it (`resultTruncated` when it is +/// cut: a bibliography or a long TOC). False when a limit cut the list short. +fn range_fields(doc: &Document, story: StoryRef, out: &mut Vec) -> bool { + for r in doc.field_ranges(story) { + if out.len() >= MAX_STORY_FIELDS { + return false; + } + let from = wordcraft_doc::Pos { off: r.start.off.saturating_add(wordcraft_doc::para::OBJ.len_utf8()), ..r.start.clone() }; + let text = doc.copy_range(&from, &r.end).plain_text(); + let mut chars = text.chars().filter(|c| *c != wordcraft_doc::para::OBJ); + let result: String = chars.by_ref().take(MAX_RANGE_RESULT).collect(); + let mut field = field_json(&r.instr, &result); + if chars.next().is_some() { + field["resultTruncated"] = json!(true); + } + out.push(field); + } + true +} + +/// Longest result `document.inspect` gives a range field, in characters. +const MAX_RANGE_RESULT: usize = 2000; + +/// A field as `document.inspect` lists it: its code, its stored result, and whether each page +/// shows a value of its own. +fn field_json(instr: &str, result: &str) -> Value { + let name = wordcraft_layout::fields::field_name(instr); + let per_page = matches!(name.as_str(), "PAGE" | "NUMPAGES" | "SECTIONPAGES" | "SECTION" | "PAGEREF" | "STYLEREF"); + json!({"code": instr.trim(), "result": result, "perPage": per_page}) +} + /// Structure for agents: blocks with text and formatting summary, selection, stats. fn inspect(s: &mut Session, v: &Value) -> CmdResult { let with_text = p::bool(v, "text").unwrap_or(true); @@ -702,8 +773,23 @@ fn inspect(s: &mut Session, v: &Value) -> CmdResult { } } let l = s.layout(); - let parts: Vec = - s.doc.parts.iter().map(|(id, p)| json!({"id": id, "kind": p.kind, "text": s.doc.plain_text(StoryRef::Part(*id))})).collect(); + let parts: Vec = s + .doc + .parts + .iter() + .map(|(id, p)| { + let mut o = json!({"id": id, "kind": p.kind, "text": s.doc.plain_text(StoryRef::Part(*id))}); + let mut fields = Vec::new(); + let complete = story_fields(&p.blocks, 0, &mut fields) && range_fields(&s.doc, StoryRef::Part(*id), &mut fields); + if !fields.is_empty() { + o["fields"] = json!(fields); + } + if !complete { + o["fieldsTruncated"] = json!(true); + } + o + }) + .collect(); Ok(json!({ "blocks": blocks, "parts": parts, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 45052d0956..6becd6ef12 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13182,6 +13182,125 @@ fn scale_font_sizes_reaches_char_table_and_cs_sizes_and_unset_default() { assert_eq!(grid.regions.get(&TablePart::Band2Horz).unwrap().chr.size, Some(10.0)); } +/// #4467: `document.inspect` lists a footer's fields and marks the ones each page shows its own +/// value of, so a caller knows "1 of 1" is a stored result and not what page 2 shows. +#[test] +fn inspect_marks_page_fields_in_headers_and_footers() { + let mut s = s(); + let id = run(&mut s, "insert.pageNumber", json!({"format": "x of y"}))["story"].as_u64().unwrap(); + let doc = run(&mut s, "document.inspect", json!({})); + let part = doc["parts"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone(); + assert_eq!(part["text"], "Page 1 of 1"); + assert_eq!(part["fields"], json!([{"code": "PAGE", "result": "1", "perPage": true}, {"code": "NUMPAGES", "result": "1", "perPage": true}])); +} + +/// #4467 review: a STYLEREF in a footer's table cell is listed as per page too (the layout looks +/// it up on each page), and a part with more fields than `document.inspect` lists says so. +#[test] +fn inspect_lists_cell_fields_and_marks_a_cut_list() { + use wordcraft_doc::{Block, CharProps, InlineObject, Paragraph, Table, para_block}; + let field = + |instr: &str| InlineObject::Field { instr: instr.into(), result: "x".into(), locked: false, dirty: false, code: false, form: String::new() }; + let mut s = s(); + let id = run(&mut s, "insert.pageNumber", json!({}))["story"].as_u64().unwrap(); + let key = u32::try_from(id).unwrap(); + let mut cell = Paragraph::new(); + cell.insert_object(0, field("STYLEREF \"Heading 1\""), &CharProps::default()).unwrap(); + let mut table = Table::new(1, 1, 200.0); + table.rows[0].cells[0].blocks = vec![para_block(cell)]; + s.doc.parts.get_mut(&key).unwrap().blocks.push(std::sync::Arc::new(Block::Table(table))); + let part = |s: &mut Session| { + let doc = run(s, "document.inspect", json!({})); + doc["parts"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone() + }; + let p = part(&mut s); + assert_eq!(p["fields"][1], json!({"code": "STYLEREF \"Heading 1\"", "result": "x", "perPage": true})); + assert!(p.get("fieldsTruncated").is_none(), "{p}"); + + let mut many = Paragraph::new(); + for _ in 0..250 { + many.insert_object(0, field("AUTHOR"), &CharProps::default()).unwrap(); + } + s.doc.parts.get_mut(&key).unwrap().blocks.push(para_block(many)); + let p = part(&mut s); + assert_eq!(p["fields"].as_array().unwrap().len(), 200); + assert_eq!(p["fieldsTruncated"], true); +} + +/// #4467 review: a field kept as a range (`FieldStart` … `FieldEnd`, as the DOCX reader keeps a +/// PAGE whose result has tracked changes, or a TOC spanning paragraphs) is listed too, its result +/// the text between the markers. +#[test] +fn inspect_lists_range_fields() { + use wordcraft_doc::{CharProps, InlineObject, Paragraph, para_block}; + let start = |instr: &str| InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false }; + let mut s = s(); + let id = run(&mut s, "insert.pageNumber", json!({}))["story"].as_u64().unwrap(); + let key = u32::try_from(id).unwrap(); + let c = CharProps::default(); + let mut page = Paragraph::new(); + page.insert_object(0, start("PAGE"), &c).unwrap(); + page.insert_text(page.len(), "7 ", &c).unwrap(); + page.insert_object(page.len(), InlineObject::FieldEnd, &c).unwrap(); + let mut first = Paragraph::new(); + first.insert_object(0, start("TOC \\o \"1-3\""), &c).unwrap(); + first.insert_text(first.len(), "One", &c).unwrap(); + let mut second = Paragraph::with_text("Two", c.clone()); + second.insert_object(second.len(), InlineObject::FieldEnd, &c).unwrap(); + // A result longer than `document.inspect` gives: cut, and marked. + let mut long = Paragraph::new(); + long.insert_object(0, start("BIBLIOGRAPHY"), &c).unwrap(); + long.insert_text(long.len(), &"x".repeat(2500), &c).unwrap(); + long.insert_object(long.len(), InlineObject::FieldEnd, &c).unwrap(); + let blocks = &mut s.doc.parts.get_mut(&key).unwrap().blocks; + blocks.extend([para_block(page), para_block(first), para_block(second), para_block(long)]); + let doc = run(&mut s, "document.inspect", json!({})); + let part = doc["parts"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone(); + let fields = part["fields"].as_array().unwrap(); + assert!(fields.contains(&json!({"code": "PAGE", "result": "7 ", "perPage": true})), "spaces kept: {fields:?}"); + assert!(fields.contains(&json!({"code": "TOC \\o \"1-3\"", "result": "One\nTwo", "perPage": false})), "{fields:?}"); + let bib = fields.iter().find(|f| f["code"] == "BIBLIOGRAPHY").unwrap(); + assert_eq!((bib["result"].as_str().map(str::len), &bib["resultTruncated"]), (Some(2000), &json!(true))); + assert!(fields.iter().filter(|f| f["code"] != "BIBLIOGRAPHY").all(|f| f.get("resultTruncated").is_none())); + assert!(part.get("fieldsTruncated").is_none(), "{part}"); +} + +/// #4467 review: a field name in lower case is a page field all the same, and a field in a table +/// nested deeper than `document.inspect` walks (8 tables) is left out with `fieldsTruncated`. +#[test] +fn inspect_reads_field_names_in_any_case_and_bounds_nested_tables() { + use wordcraft_doc::{Block, CharProps, InlineObject, Paragraph, Table, para_block}; + let field = + |instr: &str| InlineObject::Field { instr: instr.into(), result: "1".into(), locked: false, dirty: false, code: false, form: String::new() }; + // A field `depth` tables deep. + let nested = |depth: usize| { + let mut p = Paragraph::new(); + p.insert_object(0, field("page"), &CharProps::default()).unwrap(); + let mut block = para_block(p); + for _ in 0..depth { + let mut t = Table::new(1, 1, 200.0); + t.rows[0].cells[0].blocks = vec![block]; + block = std::sync::Arc::new(Block::Table(t)); + } + block + }; + for (depth, listed) in [(0, true), (8, true), (9, false)] { + let mut s = s(); + let id = run(&mut s, "insert.pageNumber", json!({}))["story"].as_u64().unwrap(); + let key = u32::try_from(id).unwrap(); + s.doc.parts.get_mut(&key).unwrap().blocks = vec![nested(depth)]; + let doc = run(&mut s, "document.inspect", json!({})); + let part = doc["parts"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone(); + if listed { + assert_eq!(part["fields"], json!([{"code": "page", "result": "1", "perPage": true}]), "{depth}"); + assert!(part.get("fieldsTruncated").is_none(), "{depth}: {part}"); + } else { + assert!(part.get("fields").is_none(), "{depth}: {part}"); + assert_eq!(part["fieldsTruncated"], true, "{depth}"); + } + } +} + /// #3676: a 1-based page parameter becomes a 0-based index without wrapping. /// On 32-bit and wasm the old cast truncated 2^32 to 0 and `0 - 1` panicked. #[test] diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index a3c008aec3..0dd2c734ab 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -145,7 +145,7 @@ pub fn tool_definitions() -> Value { tool( "inspect_document", "Inspect document", - "Structure: blocks with text, styles, formatting runs, lists, tables, sections, parts, selection, pages.", + "Structure: blocks with text, styles, formatting runs, lists, tables, sections, parts (headers, footers, notes: their text and fields; a field with perPage true, such as PAGE, NUMPAGES or STYLEREF, shows its own value on each page, so its stored result is not what every page shows: render_page shows it; fieldsTruncated means a part has more than the 200 fields listed; a range field's result, such as a TOC's, is cut at 2000 characters, with resultTruncated), selection, pages.", with_doc(obj(json!({}), &[])), true ), diff --git a/docs/mcp.md b/docs/mcp.md index 7a20d0d97b..15b04ab989 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -175,7 +175,7 @@ test source in File › Options › Language and on the bar's Install. | `list_documents` | the open documents: `id`, `title`, `path`, `dirty`, `active` | | `type_text` | type at the caret (`paragraphs: true` splits lines into paragraphs: one undo step; each break is the Enter it stands for, so AutoFormat and AutoCorrect run and a one-line control refuses; at most 10,000 lines — the cap is `text.insert`'s own, so a control-channel or CLI call is held to it too) | | `select_text` | select the n-th occurrence of some text | -| `get_text` / `inspect_document` | read the document back (verify without screenshots) | +| `get_text` / `inspect_document` | read the document back (verify without screenshots); a header or footer's `fields` mark those with `perPage` (PAGE, NUMPAGES, STYLEREF…), whose stored result isn't what every page shows (`render_page` shows that); `fieldsTruncated` means a part has more than the 200 listed; a field kept as a range (a TOC, a bibliography) gives at most 2000 characters of its result, with `resultTruncated` when it has more | | `render_page` | a page as PNG | | `parity` | feature coverage | | `screenshot`, `click`, `key`, `ui_inspect` | app only (`--connect`) | From 8b212e6665d803440c35431bcc07c54f094fb945 Mon Sep 17 00:00:00 2001 From: Michael Mu <69072633+MichaelMuClaude@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:42:25 +0800 Subject: [PATCH 82/99] KeyTips: a compact button's badge no longer covers its icon (#4497) (#4503) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/keytips.rs | 26 ++++++++++++++++++++++++-- crates/ui-egui/src/keytips/tests.rs | 19 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/keytips.rs b/crates/ui-egui/src/keytips.rs index a6fc6c41fa..239acd8168 100644 --- a/crates/ui-egui/src/keytips.rs +++ b/crates/ui-egui/src/keytips.rs @@ -544,6 +544,21 @@ pub fn controls_public(tab: &str) -> Vec { .collect() } +/// Compact ribbon buttons (the 24×22 icon buttons) are at most this tall. +const COMPACT_H: f32 = 26.0; + +/// Where a badge `width` wide goes for a control at `rect`. A big control has room for the badge +/// in its top-left corner. A compact button is nearly all icon (17×17 in 24×22), so there the +/// badge is smaller and hangs out over the button's corner, in the padding and the gap to the +/// neighbours, instead of sitting on the glyph (#4497). +pub fn badge_rect(rect: Rect, width: f32) -> Rect { + if rect.height() <= COMPACT_H { + Rect::from_min_size(rect.min + Vec2::new(-4.0, -4.0), Vec2::new((width + 3.0).max(12.0), 12.0)) + } else { + Rect::from_min_size(rect.min + Vec2::new(2.0, 1.0), Vec2::new((width + 4.0).max(15.0), 15.0)) + } +} + /// A keytip badge: letters or toolbar numbers, high contrast in both themes. pub fn badge(ui: &Ui, rect: Rect, letter: &str) { let count = letter.chars().count(); @@ -551,9 +566,16 @@ pub fn badge(ui: &Ui, rect: Rect, letter: &str) { return; } let t = Tokens::get(ui.ctx()); - let font = semibold(if count > 3 { 8.5 } else { 10.0 }); + let compact = rect.height() <= COMPACT_H; + let font = semibold(if count > 3 || (compact && count > 1) { + 8.5 + } else if compact { + 9.0 + } else { + 10.0 + }); let width = ui.ctx().fonts_mut(|f| f.layout_no_wrap(letter.to_string(), font.clone(), t.on_accent).size().x); - let r = Rect::from_min_size(rect.min + Vec2::new(2.0, 1.0), Vec2::new((width + 4.0).max(15.0), 15.0)); + let r = badge_rect(rect, width); let p = ui.painter(); p.rect_filled(r, CornerRadius::same(3), t.accent); p.rect_stroke(r, CornerRadius::same(3), Stroke::new(1.0, t.menu), egui::StrokeKind::Inside); diff --git a/crates/ui-egui/src/keytips/tests.rs b/crates/ui-egui/src/keytips/tests.rs index 63926f7b7e..f0719e5257 100644 --- a/crates/ui-egui/src/keytips/tests.rs +++ b/crates/ui-egui/src/keytips/tests.rs @@ -12,6 +12,25 @@ fn input_frame(ctx: &egui::Context, app: &mut WordApp, events: Vec) ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| logic(app, ui.ctx())).drop_without_applying_deltas(); } +/// #4497: a compact button is nearly all icon (`widgets::small`: 17×17 in 24×22), and its +/// badge sat on 63% of the glyph. It now hangs out over the corner and covers a sliver, for a +/// one-letter and a two-letter badge alike; a big control keeps its corner badge. +#[test] +fn a_compact_buttons_badge_leaves_its_icon_visible() { + let button = Rect::from_min_size(egui::pos2(100.0, 60.0), Vec2::new(24.0, 22.0)); + let icon = Rect::from_center_size(egui::pos2(button.min.x + 12.0, button.center().y), Vec2::splat(17.0)); + for (width, most) in [(7.0, 0.10), (14.0, 0.20)] { + let r = badge_rect(button, width); + let covered = r.intersect(icon); + let share = covered.width().max(0.0) * covered.height().max(0.0) / (icon.width() * icon.height()); + assert!(share <= most, "a badge {width} wide covers {share:.2} of the icon (at most {most})"); + assert!(r.min.x >= button.min.x - 4.0 && r.min.y >= button.min.y - 4.0, "it hangs out of the corner by no more than 4 px"); + assert!(r.width() >= 12.0 && r.height() >= 12.0, "and stays big enough to read"); + } + let big = Rect::from_min_size(egui::pos2(100.0, 60.0), Vec2::new(44.0, 66.0)); + assert_eq!(badge_rect(big, 7.0), Rect::from_min_size(egui::pos2(102.0, 61.0), Vec2::new(15.0, 15.0))); +} + #[test] fn native_alt_taps_toggle_once_in_either_event_order() { let alt = egui::Modifiers { alt: true, ..Default::default() }; From 7b3c2efb1fd939fcbbe5b048f63355394824630e Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:29:14 +0100 Subject: [PATCH 83/99] CI: skip every performance test under coverage instrumentation (#6873) SonarCloud's coverage shards run tests built with -Cinstrument-coverage on shared runners. Tests that assert a wall-clock limit or a time ratio swing there: the megabyte-word test took 5.7-23 s against a 15 s limit, and three linear-time tests read 24-31x against 24x. Each one that flakes turns main red after merging. Ignore under cfg(coverage) every test whose purpose is performance (linear time, bounded, capped, fast). The gate CI still runs them all uninstrumented. Behaviour tests that only carry a generous time guard (fuzz, never-panics, clipboard, regex, render, recent fonts) and the SSIP speech timeout tests keep running, so their checks stay covered. Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8 Co-authored-by: Claude Opus 5.5 --- crates/doc/src/tests.rs | 4 ++++ crates/docx/tests/it/comment_save_cost.rs | 1 + crates/docx/tests/it/content_control_save_cost.rs | 2 ++ crates/docx/tests/it/malformed.rs | 2 ++ crates/engine/src/cmd/citations/tests.rs | 1 + crates/engine/src/cmd/connectors.rs | 1 + crates/engine/src/cmd/review/tests.rs | 1 + crates/engine/src/speech/tests.rs | 1 + crates/engine/src/tests.rs | 2 ++ crates/fonts/src/fontdb/tests.rs | 1 + crates/formats/src/tests.rs | 4 ++++ crates/layout/src/tests.rs | 4 ++++ crates/layout/src/tests/numeral.rs | 1 + crates/pdf/src/tests.rs | 3 +++ crates/zotero/src/tests/limits.rs | 2 ++ 15 files changed, 30 insertions(+) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 088bd3bd2c..43cdedcb44 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -144,6 +144,7 @@ fn parts_and_media() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn many_distinct_media_add_in_linear_time() { // An import with tens of thousands of small distinct images (same length, differing only at // the end) used to compare each against every earlier one. @@ -645,6 +646,7 @@ fn para_of_objects(objs: Vec) -> Paragraph { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn object_walks_are_linear_in_the_paragraph() { // #3614: loops of object_offsets + object_at recounted the objects before each one, so a // paragraph of 40,000 markers took seconds per walk. @@ -691,6 +693,7 @@ fn object_walks_are_linear_in_the_paragraph() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn deleting_across_many_lone_control_markers_is_not_quadratic() { // A millisecond now; the old delete took 18 s at 1,500 markers and 114 s at 3,000. let n = 3_000; @@ -725,6 +728,7 @@ fn control_markers_kept_are_sorted() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn lone_table_open_markers_linear_time() { let mut d = Document::new(); let mut t = Table::new(1, 1, 100.0); diff --git a/crates/docx/tests/it/comment_save_cost.rs b/crates/docx/tests/it/comment_save_cost.rs index 2716578b29..e6858e5785 100644 --- a/crates/docx/tests/it/comment_save_cost.rs +++ b/crates/docx/tests/it/comment_save_cost.rs @@ -27,6 +27,7 @@ fn cpu_cost(mut f: impl FnMut()) -> f64 { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn many_comments_save_without_quadratic_id_searches() { for imported in [true, false] { let small = comments(4_000, imported); diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index c61268e96c..0ed92b64d6 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -74,6 +74,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( /// looked for each paragraph's markers in the whole set of markers, once per paragraph, so a /// document with 32,000 controls took four seconds to save where it takes a tenth of one now. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn a_document_with_many_inline_content_controls_saves_in_linear_time() { let scale = 4; let small = inline_controls(8_000); @@ -94,6 +95,7 @@ fn a_document_with_many_inline_content_controls_saves_in_linear_time() { /// The same for the controls written around whole paragraphs: the writer compared every control /// with every other one to find the ones that clash, so the save was quadratic in their number. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn a_document_with_many_block_content_controls_saves_in_linear_time() { let scale = 4; let small = block_controls(8_000); diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index e5e06407ae..304b9fcf38 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -152,6 +152,7 @@ fn many_fields_and_huge_attribute_values() { /// A paragraph with 2,000,000 attributes deflates to ~15 KB. Opening it is refused with a /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn millions_of_attributes_on_one_paragraph_are_capped() { let attrs: String = (0..2_000_000).map(|i| format!(" a{i}=\"\"")).collect(); let x = format!("kept"); @@ -222,6 +223,7 @@ fn malformed_or_hostile_bibliography_never_panics() { /// A file with a huge number of bibliography sources (duplicates and distinct ones) reads in /// linear time and keeps at most 10,000 of them. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn hostile_bibliography_source_count_is_capped() { let doc = format!("body"); let mut sources = String::from(r#""#); diff --git a/crates/engine/src/cmd/citations/tests.rs b/crates/engine/src/cmd/citations/tests.rs index cdf12e23ed..b1fcdfede0 100644 --- a/crates/engine/src/cmd/citations/tests.rs +++ b/crates/engine/src/cmd/citations/tests.rs @@ -871,6 +871,7 @@ fn citation_source_lookups_keep_first_duplicates_case_and_style_order() { #[cfg(not(target_arch = "wasm32"))] #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn citation_refresh_source_lookup_work_scales_with_document_size() { fn doc(n: usize) -> Session { let mut p = Paragraph::new(); diff --git a/crates/engine/src/cmd/connectors.rs b/crates/engine/src/cmd/connectors.rs index b530ee858d..16114da442 100644 --- a/crates/engine/src/cmd/connectors.rs +++ b/crates/engine/src/cmd/connectors.rs @@ -332,6 +332,7 @@ mod tests { /// Drawing commands must not search every page again for each glued connector. #[test] + #[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() { use wordcraft_doc::{Document, Paragraph, para_block}; let mut doc = Document::new(); diff --git a/crates/engine/src/cmd/review/tests.rs b/crates/engine/src/cmd/review/tests.rs index 64dd983970..feb8f0ec4d 100644 --- a/crates/engine/src/cmd/review/tests.rs +++ b/crates/engine/src/cmd/review/tests.rs @@ -799,6 +799,7 @@ fn deleting_a_comment_in_a_parent_cycle_ends() { /// A very long reply chain (as a hostile file could hold) is deleted in one pass over the /// comments, not one pass per reply: 50,000 replies would otherwise freeze the app. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn deleting_a_long_reply_chain_stays_fast() { let mut s = Session::new(Document::new()); s.view.proofing = false; diff --git a/crates/engine/src/speech/tests.rs b/crates/engine/src/speech/tests.rs index 9433326a78..39144a6efb 100644 --- a/crates/engine/src/speech/tests.rs +++ b/crates/engine/src/speech/tests.rs @@ -102,6 +102,7 @@ fn tidy_matches_replacing_until_nothing_changes() { /// Nested empty brackets are removed in one pass: 40,000 pairs took seconds when each pass /// removed one level (#3680). #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn tidy_is_linear_on_nested_brackets() { let n = 40_000; let started = std::time::Instant::now(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6becd6ef12..1181f55c09 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1052,6 +1052,7 @@ fn rep_mode(text: &str, q: &str, with: &str, extra: serde_json::Value) -> String } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn hostile_find_patterns_are_bounded() { let mut s = s(); run(&mut s, "document.setText", json!({"text": &"a".repeat(5000)})); @@ -12161,6 +12162,7 @@ fn inspect_document_removes_the_note_of_a_hidden_reference() { /// #1344: many hidden pieces (index entries are hidden text) are removed quickly, and the /// found list is capped. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn inspect_document_removes_thousands_of_hidden_pieces() { use wordcraft_doc::props::CharProps; use wordcraft_doc::{Paragraph, para_block}; diff --git a/crates/fonts/src/fontdb/tests.rs b/crates/fonts/src/fontdb/tests.rs index d3f2fd34ab..b589921e85 100644 --- a/crates/fonts/src/fontdb/tests.rs +++ b/crates/fonts/src/fontdb/tests.rs @@ -450,6 +450,7 @@ fn long_names_are_cut_before_faces_copy_them() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn named_instances_and_collection_members_are_capped() { // #3716: a file's faces are capped before they are built, however the file multiplies them. let font = variable_font(300); diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs index 1214e7742c..e7c4d9b697 100644 --- a/crates/formats/src/tests.rs +++ b/crates/formats/src/tests.rs @@ -488,6 +488,7 @@ fn code_blocks_and_rules() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn deep_nesting_is_bounded() { let html = "
".repeat(5000) + "x"; let d = import("html", html.as_bytes()).unwrap().unwrap(); @@ -566,6 +567,7 @@ fn latex_export_carries_no_commands_from_the_document() { /// past them for the last text made a megabyte of labels take tens of seconds), and labels /// separated by text are all kept. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] 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)] { @@ -743,6 +745,7 @@ fn decorative_picture_exports_with_empty_alt_text() { /// Hostile Markdown and HTML that rescanned the rest of the text from every `[`, `![`, `<` or `&` /// took quadratic time: a few hundred KB froze the importer for tens of seconds. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn hostile_importer_input_takes_linear_time() { use std::time::{Duration, Instant}; let cases: [(&str, String); 5] = [ @@ -764,6 +767,7 @@ fn hostile_importer_input_takes_linear_time() { /// bracket scan over them looking for a closing run through the rest of the text: superlinear /// time on hostile Markdown. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn unmatched_backtick_runs_take_linear_time() { use std::time::{Duration, Instant}; // Runs of 1, 2, … 2000 backticks (2 MB), none of them closed. diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index c1c51083e2..d80b0c082a 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -923,6 +923,7 @@ fn a_long_unbreakable_word_lays_out_in_linear_time() { /// A word a megabyte long lays out in a fraction of a second: it used to take half a minute. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn a_megabyte_long_word_lays_out_quickly() { let d = long_word_beside_a_float(1_000_000); let t = std::time::Instant::now(); @@ -1143,6 +1144,7 @@ fn a_word_with_alternating_advances_lays_out_in_linear_time() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn hidden_separators_with_automatic_hyphenation_lay_out_in_linear_time() { crate::test_fonts(); // "hyphenation " n times with every space hidden: one joined word of 11n letters reaches the @@ -1175,6 +1177,7 @@ fn page_break_paragraphs(n: usize) -> Document { /// the section list by walking the whole body, so a document of n paragraphs paid n body-length /// scans: a two-megabyte file took half a minute before the first page was drawn. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn a_document_of_many_paragraphs_lays_out_in_linear_time() { let (t1, tk, ratio) = layout_time_ratio(page_break_paragraphs, 2_500, &LayoutOptions::default()); eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}"); @@ -1182,6 +1185,7 @@ fn a_document_of_many_paragraphs_lays_out_in_linear_time() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn many_hidden_float_anchors_lay_out_in_linear_time() { crate::test_fonts(); // n square-wrapped shapes, each anchored in its own hidden run (bold alternating, so runs do not diff --git a/crates/layout/src/tests/numeral.rs b/crates/layout/src/tests/numeral.rs index a1052dae84..9bf244e879 100644 --- a/crates/layout/src/tests/numeral.rs +++ b/crates/layout/src/tests/numeral.rs @@ -117,6 +117,7 @@ fn resolve_uses_the_given_system_locale() { } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn context_mode_on_a_very_long_digit_run_stays_linear() { crate::test_fonts(); // Every digit used to scan back over all the digits and spaces before it (O(n²)). diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 19f183d62f..aab3988cc5 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -390,6 +390,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( } #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn long_fragmented_hidden_headings_export_in_linear_time() { // Headings of n chars in one-char runs: all hidden with bold alternating, and hidden and visible // alternating. Layout and the bookmark/tag titles once scanned every left-out range for every @@ -1917,6 +1918,7 @@ fn comments_print_in_balloons_beside_scaled_pages() { /// references) exports in time proportional to its length: each link looked its bookmark up by /// walking the whole document, so NIH's 67-page protocol template took 10.6 s (0.9 s now). #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn internal_links_export_in_linear_time() { let doc = |n: usize| { let mut d = Document::new(); @@ -3121,6 +3123,7 @@ fn only_safe_link_targets_become_annotations() { /// without one), found in one pass: a long run of glyphs sharing a cluster used to rescan the rest /// of the run for every glyph. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn cluster_ends_match_the_next_larger_cluster_in_linear_time() { let brute = |cl: &[usize], len: usize| -> Vec { (0..cl.len()).map(|i| cl.iter().skip(i + 1).copied().find(|n| *n > cl[i]).unwrap_or(len)).collect::>() diff --git a/crates/zotero/src/tests/limits.rs b/crates/zotero/src/tests/limits.rs index ce6b12c673..b18c4fe18f 100644 --- a/crates/zotero/src/tests/limits.rs +++ b/crates/zotero/src/tests/limits.rs @@ -56,6 +56,7 @@ fn listing_stops_at_the_field_budget() { // Finding 16: rich text with alternating formatting is built in one pass, not run by run with // every earlier run merged again. #[test] +#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")] fn rich_text_with_many_runs_is_linear() { let html: String = "ab".repeat(50_000); let t = Instant::now(); @@ -82,6 +83,7 @@ fn call(b: &mut Bridge, s: &mut Session, method: &str, args: Value) -> Result Date: Tue, 17 Nov 2026 20:47:27 +0100 Subject: [PATCH 84/99] #778: the ZIP entry-count guard delegates to craft-zip (#6948) * #778: zip_guard delegates to craft-zip's entry-count guard wordcraft_doc::zip_guard::check and zip64_entry_count_sample now call craft-zip, which also treats a central-directory size of u32::MAX as a ZIP64 marker. Co-Authored-By: Claude Opus 5.5 * #778: Cargo.lock: wordcraft-doc depends on craft-zip Co-Authored-By: Claude Opus 5.5 * #778: zip_guard: craft-zip test-support as a dev-dependency Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 1 + crates/doc/Cargo.toml | 4 +- crates/doc/src/zip_guard.rs | 264 ++++++++++++++++++++---------------- 3 files changed, 149 insertions(+), 120 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 527d0426dd..3505fb3a9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7385,6 +7385,7 @@ name = "wordcraft-doc" version = "0.18.1" dependencies = [ "base64 0.23.1", + "craft-zip", "log", "proptest", "serde", diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index e6c7f41c0c..7d640d5a5e 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -13,10 +13,11 @@ workspace = true # `zip_guard::zip64_entry_count_sample`) and the step count of # `work::count`; turned on only as a dev-dependency, so never built into # the app. -test-support = [] +test-support = ["craft-zip/test-support"] [dependencies] wordcraft-geom = { workspace = true } +craft-zip = { workspace = true } base64 = { workspace = true } log = { workspace = true } serde = { workspace = true } @@ -25,4 +26,5 @@ thiserror = { workspace = true } unicode-segmentation = { workspace = true } [dev-dependencies] +craft-zip = { workspace = true, features = ["test-support"] } proptest = { workspace = true } diff --git a/crates/doc/src/zip_guard.rs b/crates/doc/src/zip_guard.rs index 0610cac1e3..b6364c5bac 100644 --- a/crates/doc/src/zip_guard.rs +++ b/crates/doc/src/zip_guard.rs @@ -1,131 +1,21 @@ -//! A bytes-only check of a ZIP package's declared entry count before the `zip` crate opens it -//! (#3660). Every reader of `.docx`, `.odt` and spreadsheet packages calls [`check`] first. -//! -//! `zip::ZipArchive::new` reserves room for, and parses, as many central directory headers as the -//! end record declares before its caller can look at `len()`. A ZIP64 end record can declare -//! millions of entries for a file of a few hundred megabytes (only 46 bytes each have to fit), and -//! each parsed entry costs several times that in memory. Here the end records are found the way -//! `zip` finds them (APPNOTE.TXT §4.3.14 to §4.3.16), and a package declaring more than the -//! reader's limit is refused before `zip` parses anything. Anything else that is wrong is left for -//! `zip` to report. - -const EOCD: &[u8; 4] = b"PK\x05\x06"; -const EOCD64_LOCATOR: &[u8; 4] = b"PK\x06\x07"; -const EOCD64: &[u8; 4] = b"PK\x06\x06"; -const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; - -/// End records looked at, at most. A package has one; a few more can turn up inside stored data. -const MAX_END_RECORDS: usize = 16; +//! A bytes-only check of a ZIP package's declared entry count, run before anything opens the ZIP +//! (#3660). The logic lives in `craft-zip`; this wraps its error as a `String`. /// Refuse `bytes` when the end record `zip` would use declares more than `max_entries` entries. -/// -/// `zip` searches the file backwards for an end of central directory record. A ZIP64 one points -/// through its locator at the ZIP64 end record, which `zip` looks for from the locator's offset -/// on: every such record there is checked, and as `zip` may fall back to an earlier end record -/// when one doesn't parse, the search goes on. A plain one is used when it declares no entries, or -/// a central directory header lies between its directory offset and itself: it is the last one -/// looked at. pub fn check(bytes: &[u8], max_entries: u64) -> Result<(), String> { - let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); - let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let u64_at = |at: usize| bytes.get(at..at.checked_add(8)?).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes); - let refuse = |n: u64| -> Result<(), String> { - if n > max_entries { Err(format!("the package declares {n} entries, more than {max_entries}")) } else { Ok(()) } - }; - let mut end = bytes.len(); - let mut seen = 0; - while let Some(at) = bytes.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) { - end = at; - seen += 1; - if seen > MAX_END_RECORDS { - return Err(format!("more than {MAX_END_RECORDS} end of central directory records")); - } - // `zip` skips a record whose comment runs past the end of the file. - let Some(comment) = u16_at(at + 20) else { continue }; - if at + 22 + usize::from(comment) > bytes.len() { - continue; - } - let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(at + 8), u16_at(at + 10), u32_at(at + 16)) else { continue }; - let zip64 = total == u16::MAX || cd_offset == u32::MAX; - if zip64 - && let Some(locator) = at.checked_sub(20) - && bytes.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) - { - let (Some(eocd64), Some(disks)) = (u64_at(locator + 8), u32_at(locator + 16)) else { continue }; - let Some(from) = usize::try_from(eocd64).ok().filter(|&f| f < locator) else { continue }; - if disks > 1 { - continue; - } - let records = bytes.get(from..locator).unwrap_or_default().windows(4).enumerate().filter(|(_, w)| *w == EOCD64); - for (i, _) in records { - let p = from + i; - refuse(u64_at(p + 24).unwrap_or(0).max(u64_at(p + 32).unwrap_or(0)))?; - } - continue; - } - if total == 0 { - return Ok(()); - } - let cd = cd_offset as usize; - if cd < at && bytes.get(cd..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER)) { - return refuse(u64::from(on_disk.max(total))); - } - } - Ok(()) + craft_zip::check_entry_count(bytes, max_entries).map_err(|e| e.to_string()) } -/// A package of one empty stored file, `a`, whose central directory lists it `entries` times (at -/// most as many as fit in 64 MiB) under a ZIP64 end record that declares them all: `zip` 3.0.0 -/// parses and keeps every one of them before its caller can count them. Regression input for the -/// readers' tests: built only for tests, this crate's and (through the `test-support` feature, -/// which they turn on as a dev-dependency) the readers', never into the app. +/// A ZIP64 package declaring `entries` entries: regression input for the readers' tests. #[cfg(any(test, feature = "test-support"))] -pub fn zip64_entry_count_sample(entries: u64) -> Vec { - // Local file header (APPNOTE.TXT §4.3.7): version 10, stored, no data, name "a". - let mut f = b"PK\x03\x04".to_vec(); - f.extend_from_slice(&[10, 0, 0, 0, 0, 0, 0, 0, 0x21, 0]); // version, flags, method, time, date - f.extend_from_slice(&[0; 12]); // crc, sizes - f.extend_from_slice(&[1, 0, 0, 0]); // name and extra lengths - f.push(b'a'); - let cd_at = f.len() as u64; - // Its central header (§4.3.12), 47 bytes. - let mut header = CENTRAL_HEADER.to_vec(); - header.extend_from_slice(&[10, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0x21, 0]); // versions, flags, method, time, date - header.extend_from_slice(&[0; 12]); // crc, sizes - header.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // name, extra, comment, disk, attributes - header.extend_from_slice(&[0; 4]); // local header offset - header.push(b'a'); - let count = entries.min((64 << 20) / header.len() as u64); - for _ in 0..count { - f.extend_from_slice(&header); - } - let cd_len = f.len() as u64 - cd_at; - let eocd64_at = f.len() as u64; - // ZIP64 end of central directory record (§4.3.14), 56 bytes. - f.extend_from_slice(EOCD64); - f.extend_from_slice(&44u64.to_le_bytes()); // size of the rest of the record - f.extend_from_slice(&[45, 0, 45, 0]); // versions - f.extend_from_slice(&[0; 8]); // this disk, disk with the central directory - f.extend_from_slice(&entries.to_le_bytes()); // entries on this disk - f.extend_from_slice(&entries.to_le_bytes()); // entries - f.extend_from_slice(&cd_len.to_le_bytes()); - f.extend_from_slice(&cd_at.to_le_bytes()); - // Its locator (§4.3.15), 20 bytes. - f.extend_from_slice(EOCD64_LOCATOR); - f.extend_from_slice(&0u32.to_le_bytes()); - f.extend_from_slice(&eocd64_at.to_le_bytes()); - f.extend_from_slice(&1u32.to_le_bytes()); - // End of central directory record (§4.3.16), 22 bytes, each count and offset "see ZIP64". - f.extend_from_slice(EOCD); - f.extend_from_slice(&[0; 4]); - f.extend_from_slice(&[0xFF; 12]); - f.extend_from_slice(&[0; 2]); - f -} +pub use craft_zip::zip64_entry_count_sample; #[cfg(test)] mod tests { - use super::{CENTRAL_HEADER, EOCD, check, zip64_entry_count_sample}; + use super::{check, zip64_entry_count_sample}; + + const EOCD: &[u8; 4] = b"PK\x05\x06"; + const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; /// A plain package's tail: one central header at 0, then an end record declaring `entries`. fn plain(entries: u16, comment: &[u8]) -> Vec { @@ -188,4 +78,140 @@ mod tests { let f: Vec = (0..20).flat_map(|_| EOCD.iter().copied().chain(record)).collect(); assert!(check(&f, 20_000).is_err_and(|e| e.contains("end of central directory records"))); } + + /// The pre-cutover implementation, kept as a differential oracle. + mod old { + const EOCD: &[u8; 4] = b"PK\x05\x06"; + const EOCD64_LOCATOR: &[u8; 4] = b"PK\x06\x07"; + const EOCD64: &[u8; 4] = b"PK\x06\x06"; + const CENTRAL_HEADER: &[u8; 4] = b"PK\x01\x02"; + /// End records looked at, at most. A package has one; a few more can turn up inside stored data. + const MAX_END_RECORDS: usize = 16; + + /// Refuse `bytes` when the end record `zip` would use declares more than `max_entries` entries. + /// + /// `zip` searches the file backwards for an end of central directory record. A ZIP64 one points + /// through its locator at the ZIP64 end record, which `zip` looks for from the locator's offset + /// on: every such record there is checked, and as `zip` may fall back to an earlier end record + /// when one doesn't parse, the search goes on. A plain one is used when it declares no entries, or + /// a central directory header lies between its directory offset and itself: it is the last one + /// looked at. + pub fn check(bytes: &[u8], max_entries: u64) -> Result<(), String> { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u64_at = |at: usize| bytes.get(at..at.checked_add(8)?).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes); + let refuse = |n: u64| -> Result<(), String> { + if n > max_entries { Err(format!("the package declares {n} entries, more than {max_entries}")) } else { Ok(()) } + }; + let mut end = bytes.len(); + let mut seen = 0; + while let Some(at) = bytes.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) { + end = at; + seen += 1; + if seen > MAX_END_RECORDS { + return Err(format!("more than {MAX_END_RECORDS} end of central directory records")); + } + // `zip` skips a record whose comment runs past the end of the file. + let Some(comment) = u16_at(at + 20) else { continue }; + if at + 22 + usize::from(comment) > bytes.len() { + continue; + } + let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(at + 8), u16_at(at + 10), u32_at(at + 16)) else { continue }; + let zip64 = total == u16::MAX || cd_offset == u32::MAX; + if zip64 + && let Some(locator) = at.checked_sub(20) + && bytes.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) + { + let (Some(eocd64), Some(disks)) = (u64_at(locator + 8), u32_at(locator + 16)) else { continue }; + let Some(from) = usize::try_from(eocd64).ok().filter(|&f| f < locator) else { continue }; + if disks > 1 { + continue; + } + let records = bytes.get(from..locator).unwrap_or_default().windows(4).enumerate().filter(|(_, w)| *w == EOCD64); + for (i, _) in records { + let p = from + i; + refuse(u64_at(p + 24).unwrap_or(0).max(u64_at(p + 32).unwrap_or(0)))?; + } + continue; + } + if total == 0 { + return Ok(()); + } + let cd = cd_offset as usize; + if cd < at && bytes.get(cd..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER)) { + return refuse(u64::from(on_disk.max(total))); + } + } + Ok(()) + } + } + + fn sentinel_sample() -> Vec { + // ZIP64 sample whose plain end record claims one entry and a real directory offset but + // sets the directory size to u32::MAX, the ZIP64 marker `zip` honours. + let mut f = zip64_entry_count_sample(30_000); + let n = f.len(); + f[n - 14..n - 12].copy_from_slice(&1u16.to_le_bytes()); + f[n - 12..n - 10].copy_from_slice(&1u16.to_le_bytes()); + f[n - 10..n - 6].copy_from_slice(&u32::MAX.to_le_bytes()); + f[n - 6..n - 2].copy_from_slice(&31u32.to_le_bytes()); + f + } + + fn corpus() -> Vec> { + let mut seed = 0x2545_F491_4F6C_DD1Du64; + let mut rnd = |n: usize| -> Vec { + (0..n) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 24) as u8 + }) + .collect() + }; + let mut truncated = zip64_entry_count_sample(10); + truncated.truncate(truncated.len() - 5); + vec![ + vec![], + plain(3, b""), + plain(30_000, b"c"), + zip64_entry_count_sample(1), + zip64_entry_count_sample(10), + zip64_entry_count_sample(30_000), + zip64_entry_count_sample(5_000_000), + truncated, + rnd(1), + rnd(100), + rnd(5000), + ] + } + + #[test] + fn agrees_with_the_old_implementation_except_for_the_sentinel() { + for (i, input) in corpus().iter().enumerate() { + for max in [0u64, 9, 10, 20_000] { + assert_eq!(check(input, max).is_ok(), old::check(input, max).is_ok(), "input {i}, max {max}"); + } + } + } + + #[test] + fn a_directory_size_sentinel_alone_cannot_bypass_the_count_limit() { + let f = sentinel_sample(); + assert!(old::check(&f, 20_000).is_ok(), "the old check missed it"); + assert!(check(&f, 20_000).is_err_and(|e| e.contains("30000 entries"))); + } + + #[test] + fn no_truncation_of_a_zip64_package_panics() { + for f in [zip64_entry_count_sample(10), sentinel_sample()] { + for end in 0..=f.len().min(4096) { + let _ = check(&f[..end], 5); + } + for start in f.len().saturating_sub(300)..f.len() { + let _ = check(&f[start..], 5); + } + } + } } From 1d71d904d2b0351ce1848998cda3869e66993b85 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:47:31 +0100 Subject: [PATCH 85/99] #778: a clipboard DIB's size is read by craft-image-codecs' BMP probe (#6949) `dib_header_dims` read a DIB header's width and height by hand. It now wraps the header's first 12 bytes as a BMP and asks `craft_image_codecs::bmp_probe::dimensions`. Header sizes other than 12 and 40 or more are still refused here, since the probe reads them as info headers. The old reader stays as a test oracle. Co-authored-by: Claude Opus 5.5 --- crates/geom/src/picture.rs | 79 +++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 10 deletions(-) diff --git a/crates/geom/src/picture.rs b/crates/geom/src/picture.rs index 42a097b874..67de79e076 100644 --- a/crates/geom/src/picture.rs +++ b/crates/geom/src/picture.rs @@ -320,19 +320,16 @@ pub fn probe_dib(dib: Vec) -> Result, Refusal> { Ok(Probe { bytes: Cow::Owned(bmp), format: ImageFormat::Bmp, width, height, peak, alpha }) } +/// A DIB's width and height, read by the shared BMP probe. Header sizes other than 12 (core) and +/// 40 or more (info) are refused here: the probe would read them as info headers. fn dib_header_dims(dib: &[u8]) -> Option<(u32, u32)> { let bi_size = u32::from_le_bytes(dib.get(0..4)?.try_into().ok()?); - if bi_size == 12 { - let w = u16::from_le_bytes(dib.get(4..6)?.try_into().ok()?); - let h = u16::from_le_bytes(dib.get(6..8)?.try_into().ok()?); - Some((u32::from(w), u32::from(h))) - } else if bi_size >= 40 { - let w = i32::from_le_bytes(dib.get(4..8)?.try_into().ok()?); - let h = i32::from_le_bytes(dib.get(8..12)?.try_into().ok()?); - Some((u32::try_from(w).ok()?, h.unsigned_abs())) - } else { - None + if bi_size != 12 && bi_size < 40 { + return None; } + // Only the first 12 header bytes are read, so only they are wrapped: this runs for DIBs too + // big to decode, which must not be copied whole. + craft_image_codecs::bmp_probe::dimensions(&dib_to_bmp(dib.get(..12).unwrap_or(dib))) } /// A `width` × `height` picture of `native` bytes a pixel, with its peak (see [`peak_bytes`]). @@ -577,6 +574,68 @@ fn dib_layout(mut dib: Vec) -> Vec { mod tests { use super::*; + // Hand-written reader the shared probe replaced; kept as the oracle. + fn dib_header_dims_old(dib: &[u8]) -> Option<(u32, u32)> { + let bi_size = u32::from_le_bytes(dib.get(0..4)?.try_into().ok()?); + if bi_size == 12 { + let w = u16::from_le_bytes(dib.get(4..6)?.try_into().ok()?); + let h = u16::from_le_bytes(dib.get(6..8)?.try_into().ok()?); + Some((u32::from(w), u32::from(h))) + } else if bi_size >= 40 { + let w = i32::from_le_bytes(dib.get(4..8)?.try_into().ok()?); + let h = i32::from_le_bytes(dib.get(8..12)?.try_into().ok()?); + Some((u32::try_from(w).ok()?, h.unsigned_abs())) + } else { + None + } + } + + fn hdr(size: u32, w: i32, h: i32, len: usize) -> Vec { + let mut v = [0u8; 124].to_vec(); + v.resize(124.max(len), 0); + v[0..4].copy_from_slice(&size.to_le_bytes()); + v[4..8].copy_from_slice(&w.to_le_bytes()); + v[8..12].copy_from_slice(&h.to_le_bytes()); + v.truncate(len); + v + } + + #[test] + fn dib_dims_match_the_hand_written_reader() { + let sizes = [0u32, 11, 12, 13, 16, 39, 40, 41, 52, 108, 124, u32::MAX]; + let dims = [(0, 0), (1, 1), (3, -2), (0, 5), (7, i32::MIN), (i32::MIN, 1), (-1, 1), (65536, 70000), (i32::MAX, i32::MAX)]; + for &s in &sizes { + for &(w, h) in &dims { + for len in 0..=130 { + let d = hdr(s, w, h, len); + assert_eq!(dib_header_dims(&d), dib_header_dims_old(&d), "size {s} w {w} h {h} len {len}"); + } + } + } + assert_eq!(dib_header_dims(&hdr(40, 3, -2, 40)), Some((3, 2))); + let mut core = hdr(12, 3, 0, 12); + core[6..8].copy_from_slice(&2u16.to_le_bytes()); + assert_eq!(dib_header_dims(&core), Some((3, 2))); + } + + #[test] + fn dib_dims_never_panic_on_junk() { + let mut x = 0x2545_f491_4f6c_dd1du64; + let mut buf = [0u8; 64]; + for _ in 0..2000 { + for b in buf.iter_mut() { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + *b = x as u8; + } + for n in 0..=buf.len() { + assert_eq!(dib_header_dims(&buf[..n]), dib_header_dims_old(&buf[..n])); + let _ = probe_dib(buf[..n].to_vec()); + } + } + } + fn encode(img: impl Into, format: ImageFormat) -> Vec { let dyn_img = img.into(); let codec_img = dynamic_to_codec(&dyn_img).unwrap(); From 8331f2e68d5cdad32c73915b00337074099be781 Mon Sep 17 00:00:00 2001 From: Aleksander Helgaker Date: Tue, 17 Nov 2026 21:05:13 +0100 Subject: [PATCH 86/99] Fonts: tell where a missing font can be downloaded (Get the Missing Fonts) (#6826) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fonts: tell where a missing font can be downloaded (Get the Missing Fonts) A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download. Once per document; never for a new document or one a script opened. "Don't show this again" turns it off (File > Options > General turns it back on); the status bar's missing-fonts menu opens it by hand (ui.dialog fontDownload). font.missing reports the same page as "download", so agents get it without the box. WordCraft links to the page only: nothing is downloaded or bundled. The desktop and web apps switch the box on at start-up (tell_about_font_downloads); tests and ui_shot don't, so what they show doesn't depend on the fonts installed where they run. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GBVQLv63guWCuWUM3SctPP * Get the Missing Fonts: the box with nothing to download is one row tall Its Close button's far-side layout took the rest of the window's height. The button row is now a row of its own, shared by both forms of the box. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GBVQLv63guWCuWUM3SctPP * Floating windows: a flat title bar and room around the content Dialogs, the Read Aloud player and the built-in file browser had a grey band behind a centred title and 6 pt margins. The title bar is now the window's own colour with no band or line under it, and the title and the content have 18 pt of room. The close box follows the new title bar height. egui fills the front window's title bar with the colour of an open menu button, so show_window makes that colour the window's while the title bar is drawn and puts it back before the content is. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GBVQLv63guWCuWUM3SctPP * Get the Missing Fonts: a headline, a card to each download, numbered steps The box was a plain table and a paragraph of steps. It now opens with the warning mark and how many fonts are missing; lists each download once (Aptos and Aptos Display come in one) with the fonts drawn instead, the publisher and a Download button that opens the publisher's page; and gives the two steps that add the download, with Add Font… beside its step. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GBVQLv63guWCuWUM3SctPP * Fonts: the download pages are a JSON list (font_downloads.json) The list of fonts their publisher gives away, and each publisher's page, was a table in the code. It is now crates/fonts/src/font_downloads.json, built into the app: adding a font is a new entry there. Entries without a family, a publisher or an https page are left out, and a list that isn't JSON has no downloads rather than failing. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GBVQLv63guWCuWUM3SctPP * Get the Missing Fonts: licence notice, and fonts offered with limits The box says that fonts come with licence terms and that following the publisher's terms is up to the user. A font whose publisher limits who may use it is marked "restricted" in font_downloads.json, says so on its card and in font.missing ("restricted"), and has a card of its own. The list gains Selawik (Microsoft's open-source font) and, marked restricted, Segoe UI Variable, Segoe Fluent Icons and Segoe MDL2 Assets from Microsoft's Windows design downloads page. Plain Segoe UI is not offered for download and is not matched. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GBVQLv63guWCuWUM3SctPP * Get the Missing Fonts: the downloads scroll in a short window With many downloads in a short window the box ran past the bottom of the screen, leaving the steps, Add Font…, Don't show this again and Close out of reach. The cards now scroll in the room the window has left, between 96 and 320 pt, and the rest of the box stays in view. Co-Authored-By: Claude Fable 5.2 * Get the Missing Fonts: all above the Close row scrolls in a short window Only the download cards scrolled, within fixed limits, so in a window shorter than about 480 pt the opt-out and Close could still fall off screen. Everything above the row with Don't show this again and Close now scrolls in the room the window has left, and that row stays on screen. Co-Authored-By: Claude Fable 5.2 * Floating windows: the flat title bar and wider margins leave this change Reverts 2d39c54e and its revision-history row. The restyle changes every dialog, the Read Aloud player and the file browser, and is to be reviewed on its own. Co-Authored-By: Claude Fable 5.2 * Get the Missing Fonts: the headline counts the fonts that can be downloaded The box lists only the missing fonts with a download, so "1 font in this document isn't installed" was wrong for a document missing others too. It now says "1 missing font can be downloaded", and the line under it no longer mixes one and many. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude --- Cargo.lock | 1 + ROADMAP.md | 4 +- apps/wordcraft-web/src/web.rs | 1 + apps/wordcraft/src/main.rs | 1 + crates/engine/src/cmd/font.rs | 17 +- crates/engine/src/tests/fonts.rs | 21 ++ crates/fonts/Cargo.toml | 1 + crates/fonts/src/download.rs | 149 +++++++++++ crates/fonts/src/font_downloads.json | 50 ++++ crates/fonts/src/lib.rs | 1 + crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/chrome.rs | 4 + crates/ui-egui/src/control/handler.rs | 11 + crates/ui-egui/src/dialogs.rs | 8 + crates/ui-egui/src/dialogs/chrome.rs | 1 + crates/ui-egui/src/dialogs/dispatch.rs | 1 + crates/ui-egui/src/font_download.rs | 308 ++++++++++++++++++++++ crates/ui-egui/src/font_download/tests.rs | 253 ++++++++++++++++++ crates/ui-egui/src/i18n/audit.rs | 2 + crates/ui-egui/src/lib.rs | 10 + crates/ui-egui/src/options.rs | 1 + crates/ui-egui/src/window_ui.rs | 3 + docs/gaps.md | 3 +- docs/ui-parity.md | 3 +- 25 files changed, 852 insertions(+), 5 deletions(-) create mode 100644 crates/fonts/src/download.rs create mode 100644 crates/fonts/src/font_downloads.json create mode 100644 crates/ui-egui/src/font_download.rs create mode 100644 crates/ui-egui/src/font_download/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 3505fb3a9f..bf5e960aea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7469,6 +7469,7 @@ dependencies = [ "harfrust 0.13.3", "kurbo", "log", + "serde_json", "skrifa 0.47.0", "unicode-bidi", "unicode-script", diff --git a/ROADMAP.md b/ROADMAP.md index ff34d391e8..352e8751b0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,7 +8,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. @@ -151,6 +151,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing. - 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged. fix/6146-touchpad-scroll-speed - 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed. @@ -400,6 +401,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-11-15 | trivial | Progress log: Get the Missing Fonts (download pages for missing fonts their publisher gives away) | | 2026-11-05 | trivial | Progress log: ODT documents keep their language (gap 19) | | 2026-11-04 | The CLI opens a non-Unicode input filename even after options such as `--page 2` or `--format flatopc`; text option values still require Unicode; `run --file` and `run --script` retain native paths. | | 2026-11-06 | Accept All and Reject All no longer restyle the paragraph after an empty one carrying a section break (#5667): a Compare that added a section, then Reject All, left `Body` in the removed paragraph's Normal style and indents. The empty paragraph now goes whole and its section joins the following one, as deleting the break does. | diff --git a/apps/wordcraft-web/src/web.rs b/apps/wordcraft-web/src/web.rs index fb808decf8..b6f765d05b 100644 --- a/apps/wordcraft-web/src/web.rs +++ b/apps/wordcraft-web/src/web.rs @@ -81,6 +81,7 @@ pub fn start() { // Pasted pictures wait apart from dropped files: the app inserts one only when the page is the edit target (#1349). app.services.pasted = Some(pasted); app.autosave = false; + app.tell_about_font_downloads(); // Preferences from an earlier visit (#2132), as the desktop app reads `ui.json`. let stored = stored_prefs(); crate::prefs::restore(&mut app, stored.as_deref()); diff --git a/apps/wordcraft/src/main.rs b/apps/wordcraft/src/main.rs index 7f81caa91e..65cdca1dc2 100644 --- a/apps/wordcraft/src/main.rs +++ b/apps/wordcraft/src/main.rs @@ -728,6 +728,7 @@ fn main() -> eframe::Result { app.replace_startup_document(doc); } app.watch_desktop_theme(&cc.egui_ctx); + app.tell_about_font_downloads(); if prefs_enabled() && let Some(dir) = wordcraft_control_key::settings_dir() { diff --git a/crates/engine/src/cmd/font.rs b/crates/engine/src/cmd/font.rs index 587467391d..6fe95689a2 100644 --- a/crates/engine/src/cmd/font.rs +++ b/crates/engine/src/cmd/font.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { CommandSpec::new("font.remove", "Remove Added Font", "Home › Font", remove).params(r#"{"family": string}"#).pure(), CommandSpec::new("font.loadSystem", "Load System Installed Fonts…", "Home › Font", load_system).pure(), CommandSpec::new("font.missing", "Missing Fonts", "Status Bar", missing) - .params(r#"{} → {"missing": [{"font": string, "shownAs": [string] (the families drawn instead), "metricCompatible": bool (its substitute measures like the font)}]} — the text the current view shows"#) + .params(r#"{} → {"missing": [{"font": string, "shownAs": [string] (the families drawn instead), "metricCompatible": bool (its substitute measures like the font), "download"?: {"name": string, "publisher": string, "url": string, "restricted": bool (the publisher limits who may use it: check its licence terms)} (its publisher's download page, when it offers the font at no charge)}]} — the text the current view shows"#) .pure(), ] } @@ -136,6 +136,9 @@ pub struct MissingFont { /// Fallback faces for characters the substitute lacks don't count: the font itself might /// lack them too (an emoji in Calibri text). pub metric_compatible: bool, + /// Its publisher's download page, when the publisher offers the font at no charge + /// ([`wordcraft_fonts::download`]): installing it shows the document as it was written. + pub download: Option<&'static wordcraft_fonts::download::FontDownload>, } /// The family text set in `font` is drawn in when `font` isn't installed (None when it is), as @@ -174,6 +177,7 @@ pub fn missing_fonts(doc: &Document, layout: &DocLayout) -> Vec { // Judged by the name layout looked up, spaces and all: "Arial " isn't Arial to it, so // its text is in a substitute even where Arial is installed. metric_compatible: shown_as(doc, &recorded).is_some_and(|s| !warns(font, &s)), + download: wordcraft_fonts::download::download_for(font), }); if !m.shown_as.contains(&family) { m.shown_as.push(family); @@ -216,7 +220,16 @@ fn missing(s: &mut Session, _: &Value) -> CmdResult { (_, n) if n > NAMED => format!("Not installed: {named} and {} more", n - NAMED), _ => format!("Not installed: {named}"), }; - let fonts: Vec = found.iter().map(|f| json!({"font": f.font, "shownAs": f.shown_as, "metricCompatible": f.metric_compatible})).collect(); + let fonts: Vec = found + .iter() + .map(|f| { + let mut font = json!({"font": f.font, "shownAs": f.shown_as, "metricCompatible": f.metric_compatible}); + if let Some(d) = f.download { + font["download"] = json!({"name": d.name, "publisher": d.publisher, "url": d.url, "restricted": d.restricted}); + } + font + }) + .collect(); Ok(json!({"missing": fonts})) } diff --git a/crates/engine/src/tests/fonts.rs b/crates/engine/src/tests/fonts.rs index 304382c511..5560e0be99 100644 --- a/crates/engine/src/tests/fonts.rs +++ b/crates/engine/src/tests/fonts.rs @@ -371,6 +371,27 @@ fn missing_fonts_from_command_search_say_so_in_the_status_line() { assert!(s.status.ends_with(" and 35 more") && s.status.len() < 300, "{}", s.status); } +/// A missing font its publisher gives away says where to get it; others don't. +#[test] +fn a_missing_font_its_publisher_gives_away_names_the_download_page() { + if wordcraft_fonts::FontDb::global().families().iter().any(|f| f.eq_ignore_ascii_case("Aptos")) { + return; // Installed here: not missing. + } + let mut s = Session::new(doc_of(vec![para_in("Text", "Aptos"), para_in("Text", "Wordcraft Nowhere Face")])); + let layout = s.layout(); + let m = crate::cmd::font::missing_fonts(&s.doc, &layout); + let aptos = m.iter().find(|f| f.font == "Aptos").unwrap(); + assert_eq!(aptos.download.map(|d| d.publisher.as_str()), Some("Microsoft")); + assert!(m.iter().find(|f| f.font == "Wordcraft Nowhere Face").unwrap().download.is_none()); + let out = s.run("font.missing", &json!({})).unwrap(); + let listed = out["missing"].as_array().unwrap(); + let aptos = listed.iter().find(|f| f["font"] == "Aptos").unwrap(); + assert!(aptos["download"]["url"].as_str().unwrap().starts_with("https://www.microsoft.com/"), "{aptos}"); + assert_eq!(aptos["download"]["publisher"], "Microsoft"); + assert_eq!(aptos["download"]["restricted"], false); + assert!(listed.iter().find(|f| f["font"] == "Wordcraft Nowhere Face").unwrap().get("download").is_none()); +} + #[test] fn a_huge_font_name_is_kept_short() { let name = format!("Wordcraft {}", "é".repeat(100_000)); diff --git a/crates/fonts/Cargo.toml b/crates/fonts/Cargo.toml index eef1b75427..ad9f456906 100644 --- a/crates/fonts/Cargo.toml +++ b/crates/fonts/Cargo.toml @@ -21,3 +21,4 @@ brotli-decompressor = { workspace = true } unicode-bidi = { workspace = true } unicode-script = { workspace = true } log = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/fonts/src/download.rs b/crates/fonts/src/download.rs new file mode 100644 index 0000000000..182b60d4ff --- /dev/null +++ b/crates/fonts/src/download.rs @@ -0,0 +1,149 @@ +//! Fonts a document may ask for that their publisher gives away, and where: when one isn't +//! installed, the app can say where to get it instead of only naming the substitute. +//! +//! Only a publisher's own page is listed, for fonts it offers for download at no charge. The app +//! links to the page; it never downloads, bundles or redistributes the fonts, and following the +//! publisher's licence terms is the user's part. A font whose publisher limits who may use it +//! is marked [`FontDownload::restricted`], so the app can say so beside the link. Most Office +//! fonts (Calibri, Cambria, Consolas, Segoe UI…) come only with Windows or Office, so they are +//! not here. +//! +//! The list is `font_downloads.json` beside this file, built into the app: adding a font is a +//! new entry there. + +/// The list: `{"downloads": [{"family", "publisher", "url", "restricted"?, "note"?}]}`. +const LIST: &str = include_str!("font_downloads.json"); + +/// Most entries read from the list. +const MAX_DOWNLOADS: usize = 1024; + +/// Where a font family can be downloaded at no charge. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FontDownload { + /// The name of the download: the family or collection the page offers. It covers the + /// family itself and every name that continues it after a space ("Aptos" covers "Aptos + /// Display", "Aptos Narrow", "Aptos Mono"…). + pub name: String, + /// Who publishes the font and hosts the page. + pub publisher: String, + /// The publisher's download page. + pub url: String, + /// The publisher limits who may use the font or what for (its design resources for one + /// platform, say): worth saying beside the link. + pub restricted: bool, +} + +/// The entries of `list` that name a family, a publisher and an `https` page; others are left +/// out, and a list that isn't JSON has none. +fn parse(list: &str) -> Vec { + let Ok(json) = serde_json::from_str::(list) else { + log::warn!("font downloads: the list isn't JSON"); + return Vec::new(); + }; + let entries = json.get("downloads").and_then(|d| d.as_array()).map(Vec::as_slice).unwrap_or_default(); + entries + .iter() + .take(MAX_DOWNLOADS) + .filter_map(|e| { + let field = |k: &str| e.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|v| !v.is_empty()); + let (name, publisher, url) = (field("family")?, field("publisher")?, field("url")?); + let restricted = e.get("restricted").and_then(|v| v.as_bool()).unwrap_or(false); + url.starts_with("https://").then(|| FontDownload { name: name.into(), publisher: publisher.into(), url: url.into(), restricted }) + }) + .collect() +} + +/// The built-in list, read once. +fn downloads() -> &'static [FontDownload] { + static DOWNLOADS: std::sync::OnceLock> = std::sync::OnceLock::new(); + DOWNLOADS.get_or_init(|| parse(LIST)) +} + +/// Where `family` can be downloaded free of charge from its publisher, if it can. The name is +/// matched whatever its case, with a charset suffix ("Aptos CE") or alternates ("Aptos;Arial") +/// as a document may write it. +pub fn download_for(family: &str) -> Option<&'static FontDownload> { + family.split(';').map(str::trim).filter(|f| !f.is_empty()).find_map(|f| { + let f = crate::word::charset_base_family(f).trim(); + downloads().iter().find(|d| { + // Compared as bytes: `get` on a `str` would refuse a split inside a character. + let (name, f) = (d.name.as_bytes(), f.as_bytes()); + f.get(..name.len()).is_some_and(|head| head.eq_ignore_ascii_case(name)) && matches!(f.get(name.len()), None | Some(b' ')) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn microsoft_fonts_offered_free_of_charge_have_a_download_page() { + let aptos = download_for("Aptos").unwrap(); + assert_eq!(aptos.publisher, "Microsoft"); + assert!(aptos.url.starts_with("https://www.microsoft.com/")); + for family in ["aptos", "Aptos Display", "APTOS NARROW", "Aptos Mono", "Aptos Serif", " Aptos ", "Aptos;Arial", "Aptos CE"] { + assert_eq!(download_for(family), Some(aptos), "{family}"); + } + assert_eq!(download_for("Cascadia Code").map(|d| d.name.as_str()), Some("Cascadia Code")); + assert_eq!(download_for("Cascadia Mono PL").map(|d| d.name.as_str()), Some("Cascadia Mono")); + assert_eq!(download_for("Selawik Semibold").map(|d| (d.name.as_str(), d.restricted)), Some(("Selawik", false))); + assert!(!aptos.restricted); + } + + /// Fonts offered with limits on their use are listed, and say so. Plain Segoe UI isn't + /// offered for download, and the Segoe UI Variable entry doesn't stand in for it. + #[test] + fn fonts_with_limited_licences_are_marked() { + for family in ["Segoe UI Variable", "Segoe UI Variable Text", "segoe fluent icons", "Segoe MDL2 Assets"] { + let d = download_for(family).unwrap_or_else(|| panic!("{family}")); + assert!(d.restricted, "{family}"); + assert!(d.url.starts_with("https://learn.microsoft.com/"), "{}", d.url); + } + for family in ["Segoe UI", "Segoe UI Semibold", "Segoe UI Symbol", "Segoe Print"] { + assert_eq!(download_for(family), None, "{family}"); + } + } + + #[test] + fn other_fonts_have_none() { + // Fonts that come only with Windows or Office, look-alike names, and junk. + for family in ["Calibri", "Cambria", "Consolas", "Arial", "Aptosa", "Apt", "", ";", "Aptosé", "é", "Cascadia"] { + assert_eq!(download_for(family), None, "{family}"); + } + } + + #[test] + fn every_page_is_https_on_the_publishers_site() { + // Every entry of the file is read: none is left out for a missing field. + let entries = serde_json::from_str::(LIST).unwrap()["downloads"].as_array().unwrap().len(); + assert_eq!(downloads().len(), entries); + assert!(entries >= 3); + for d in downloads() { + let hosts = ["https://www.microsoft.com/", "https://learn.microsoft.com/", "https://github.com/microsoft/"]; + assert!(hosts.iter().any(|h| d.url.starts_with(h)), "{}", d.url); + } + } + + #[test] + fn a_broken_list_has_no_downloads() { + assert!(parse("not json").is_empty()); + assert!(parse("{}").is_empty()); + assert!(parse(r#"{"downloads": 7}"#).is_empty()); + // Entries without a family, a publisher or an https page are left out. + let list = r#"{"downloads": [ + {"family": "A", "publisher": "P", "url": "http://plain.example"}, + {"family": "", "publisher": "P", "url": "https://x.example"}, + {"publisher": "P", "url": "https://x.example"}, + {"family": 3, "publisher": "P", "url": "https://x.example"}, + "junk", + {"family": " Kept ", "publisher": "P", "url": "https://x.example"} + ]}"#; + let read = parse(list); + assert_eq!(read.len(), 1); + assert_eq!(read[0].name, "Kept"); + assert!(!read[0].restricted, "not restricted unless it says so"); + let marked = parse(r#"{"downloads": [{"family": "A", "publisher": "P", "url": "https://x.example", "restricted": true}]}"#); + assert!(marked[0].restricted); + } +} diff --git a/crates/fonts/src/font_downloads.json b/crates/fonts/src/font_downloads.json new file mode 100644 index 0000000000..a5d4cb16e8 --- /dev/null +++ b/crates/fonts/src/font_downloads.json @@ -0,0 +1,50 @@ +{ + "about": "Fonts a document may ask for that their publisher offers for download at no charge, and the publisher's own download page. WordCraft links to the page; it never downloads, bundles or redistributes the fonts, and the user is responsible for the publisher's licence terms. 'family' also covers every name that continues it after a space: 'Aptos' covers 'Aptos Display'. 'restricted': true marks a font whose publisher limits who may use it or what for; the app then says so beside the download.", + "downloads": [ + { + "family": "Aptos", + "publisher": "Microsoft", + "url": "https://www.microsoft.com/download/details.aspx?id=106087", + "note": "Microsoft Download Center, 'Microsoft Aptos Fonts': the whole Aptos family." + }, + { + "family": "Cascadia Code", + "publisher": "Microsoft", + "url": "https://github.com/microsoft/cascadia-code/releases", + "note": "Microsoft's own repository; SIL Open Font License." + }, + { + "family": "Cascadia Mono", + "publisher": "Microsoft", + "url": "https://github.com/microsoft/cascadia-code/releases", + "note": "Comes in the Cascadia Code release." + }, + { + "family": "Selawik", + "publisher": "Microsoft", + "url": "https://github.com/microsoft/fonts", + "note": "Microsoft's open-source stand-in for Segoe UI; SIL Open Font License." + }, + { + "family": "Segoe UI Variable", + "publisher": "Microsoft", + "url": "https://learn.microsoft.com/windows/apps/design/downloads", + "restricted": true, + "note": "Microsoft's Windows design downloads page. Offered with the design resources for Windows apps; plain 'Segoe UI' is not offered for download and is not matched by this entry." + }, + { + "family": "Segoe Fluent Icons", + "publisher": "Microsoft", + "url": "https://learn.microsoft.com/windows/apps/design/downloads", + "restricted": true, + "note": "Microsoft's Windows design downloads page." + }, + { + "family": "Segoe MDL2 Assets", + "publisher": "Microsoft", + "url": "https://learn.microsoft.com/windows/apps/design/downloads", + "restricted": true, + "note": "Microsoft's Windows design downloads page." + } + ] +} diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 7305f5af5b..588696ada5 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -8,6 +8,7 @@ #![forbid(unsafe_code)] pub mod color; +pub mod download; mod fontdb; pub mod math; mod script; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 297c0080a9..ddfa5f97b1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -110,6 +110,8 @@ impl WordApp { integrated_titlebar: false, mac_titlebar: chrome::MacTitleBar::default(), updates_rt: updates_ui::Runtime::default(), + font_notice_seen: Vec::new(), + font_notices: false, packs_rt: Default::default(), control_rx: None, shots: crate::control::Shots::default(), diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 41d5f88111..6ff9ad94a3 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -129,6 +129,7 @@ impl WordApp { let window = self.windows.shown(); let moved = |app: &WordApp| app.windows.shown() != window; content_controls::popup(self, ctx); + crate::font_download::tick(self); dialogs::show(self, ctx); if moved(self) { return; diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 837235ef60..1b74b3552d 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -853,6 +853,10 @@ pub fn status_bar(app: &mut WordApp, ui: &mut Ui) { ui.label(crate::i18n::tn((count - SHOWN) as u64, "…and {n} more", "…and {n} more")); } ui.separator(); + if missing.iter().any(|f| f.download.is_some()) && ui.button(tl!("Get the Missing Fonts…")).clicked() { + let _ = app.run("ui.dialog", json!({"name": "fontDownload"})); + ui.close(); + } if ui.button(tl!("Add Font…")).clicked() { let _ = app.run("font.add", json!({})); ui.close(); diff --git a/crates/ui-egui/src/control/handler.rs b/crates/ui-egui/src/control/handler.rs index c2416efda3..cf319659cc 100644 --- a/crates/ui-egui/src/control/handler.rs +++ b/crates/ui-egui/src/control/handler.rs @@ -226,6 +226,17 @@ fn handle_in(app: &mut WordApp, doc: u64, method: &str, p: &Value) -> Outcome { /// drag, key, wheel and text input, screenshots and renders, resize, focus and quit, and unknown /// ids as commands. It refuses closing unsaved work and document operations without a document. pub fn handle(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let before = app.session.document_id(); + let outcome = handle_request(app, ctx, req); + // A document a script opened doesn't bring up the missing-fonts box. + let after = app.session.document_id(); + if after != before { + crate::font_download::skip(app, after); + } + outcome +} + +fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; if DOC_METHODS.contains(&req.method.as_str()) { match addressed(app, p) { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 178f6f5c7a..3a9f6056ad 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -321,6 +321,12 @@ pub enum Dialog { #[serde(skip)] note: String, }, + /// The document's missing fonts that can be downloaded, and how ([`crate::font_download`]). + FontDownload { + fonts: Vec, + /// "Don't show this again". + dont_show: bool, + }, /// Tabs: 0 About, 1 Contributors, 2 Models. About { tab: u8, @@ -550,6 +556,7 @@ impl Dialog { Dialog::Icons { .. } => "icons", Dialog::PasteSpecial { .. } => "pasteSpecial", Dialog::About { .. } => "about", + Dialog::FontDownload { .. } => "fontDownload", Dialog::SaveChanges { .. } => "saveChanges", Dialog::DiscardRecovery { .. } => "discardRecovery", Dialog::RecipientList { .. } => "recipientList", @@ -803,6 +810,7 @@ impl Dialog { "pasteSpecial" => Dialog::paste_special(app, &json!({})), "renameDocument" => Dialog::RenameDocument { name: app.title_stem(), message: String::new(), focus: true }, "about" => Dialog::About { tab: 0 }, + "fontDownload" => crate::font_download::open(app), "contributors" => Dialog::About { tab: 1 }, "models" => Dialog::About { tab: 2 }, "languageData" => Dialog::About { tab: 3 }, diff --git a/crates/ui-egui/src/dialogs/chrome.rs b/crates/ui-egui/src/dialogs/chrome.rs index 90b09f33ec..b7e610cab0 100644 --- a/crates/ui-egui/src/dialogs/chrome.rs +++ b/crates/ui-egui/src/dialogs/chrome.rs @@ -188,6 +188,7 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) { Dialog::Icons { .. } => "Icons", Dialog::PasteSpecial { .. } => "Paste Special", Dialog::About { .. } => "About WordCraft", + Dialog::FontDownload { .. } => "Get the Missing Fonts", Dialog::SaveChanges { .. } => "WordCraft", Dialog::DiscardRecovery { .. } => "Discard recovery copy", Dialog::RecipientList { .. } => "Recipient List", diff --git a/crates/ui-egui/src/dialogs/dispatch.rs b/crates/ui-egui/src/dialogs/dispatch.rs index 18693522de..5ad4a0f5aa 100644 --- a/crates/ui-egui/src/dialogs/dispatch.rs +++ b/crates/ui-egui/src/dialogs/dispatch.rs @@ -40,6 +40,7 @@ pub(super) fn body(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { Dialog::Icons { query, category, selected } => icons_body(app, ui, query, category, selected), Dialog::PasteSpecial { .. } => paste_special_dialog(app, ui, d), Dialog::About { .. } => about_dialog(ui, d), + Dialog::FontDownload { fonts, dont_show } => crate::font_download::body(app, ui, fonts, dont_show), Dialog::DiscardRecovery { .. } => discard_recovery_dialog(app, ui, d), Dialog::SaveChanges { .. } => save_changes_dialog(app, ui, d), Dialog::RecipientList { fields, rows, message, filter } => recipient_list(app, ui, fields, rows, message, filter), diff --git a/crates/ui-egui/src/font_download.rs b/crates/ui-egui/src/font_download.rs new file mode 100644 index 0000000000..b07130412e --- /dev/null +++ b/crates/ui-egui/src/font_download.rs @@ -0,0 +1,308 @@ +//! "Get the missing fonts": a document opened from a file that asks for fonts their publisher +//! gives away (Microsoft's Aptos, the default in recent Word documents) is told about once, in a +//! box that names each font, the font drawn in its place, the publisher's download page and how +//! to install the download. "Don't show this again" turns the box off (File › Options › General +//! turns it back on); the status bar's missing-fonts menu opens it by hand. +//! +//! The list is `font.missing`'s ([`wordcraft_engine::cmd::font::missing_fonts`]), so agents read +//! the same fonts and pages without the box. WordCraft only links to the page: it never +//! downloads or bundles the fonts. + +use serde::Serialize; + +use crate::WordApp; +use crate::dialogs::Dialog; +use crate::theme::{Tokens, semibold}; + +/// Most documents the box has been considered for that are remembered: beyond that the oldest +/// are forgotten (a document shown again after hundreds of others may be told about twice). +const REMEMBERED: usize = 256; + +/// Most fonts the box lists: a hostile file can name thousands. +const LISTED: usize = 12; + +/// The height the box takes around what scrolls: the title bar, the row with Close and the +/// window's margins. +const ROOM_AROUND_SCROLL: f32 = 190.0; +/// The least height what scrolls gets, however short the window. +const SCROLL_MIN: f32 = 80.0; + +/// One missing font the box lists. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Row { + /// The font the document asks for. + pub font: String, + /// The families its text is drawn in instead. + pub shown_as: Vec, + /// The download the font comes in (a family: "Aptos" holds Aptos Display too). + pub download: String, + /// Who publishes the font and hosts the page. + pub publisher: String, + /// The publisher's download page. + pub url: String, + /// The publisher limits who may use the font: the box says so beside the download. + pub restricted: bool, +} + +/// The shown document's missing fonts that can be downloaded. +pub(crate) fn rows(app: &mut WordApp) -> Vec { + let layout = app.session.layout(); + let missing = app.cached_missing_fonts(&layout).0; + missing + .iter() + .filter_map(|f| { + let d = f.download?; + Some(Row { + font: f.font.clone(), + shown_as: f.shown_as.clone(), + download: d.name.clone(), + publisher: d.publisher.clone(), + url: d.url.clone(), + restricted: d.restricted, + }) + }) + .take(LISTED) + .collect() +} + +/// The box for the shown document (`ui.dialog {"name": "fontDownload"}`), listing nothing when +/// none of its missing fonts can be downloaded. +pub(crate) fn open(app: &mut WordApp) -> Dialog { + Dialog::FontDownload { fonts: rows(app), dont_show: !app.ui.font_download_notice } +} + +/// The document `id` has been considered for the box, and is not considered again. +fn remember(app: &mut WordApp, id: u64) { + if app.font_notice_seen.len() >= REMEMBERED { + app.font_notice_seen.remove(0); + } + app.font_notice_seen.push(id); +} + +/// A document a script opened is not told about: programmatic calls never open dialogs. +pub(crate) fn skip(app: &mut WordApp, id: u64) { + if !app.font_notice_seen.contains(&id) { + remember(app, id); + } +} + +impl WordApp { + /// Bring the box up by itself when a document opened from a file is missing fonts that can be + /// downloaded. The desktop and web apps call this once at start-up; unit tests and `ui_shot` + /// don't, so what they show doesn't depend on the fonts installed where they run. + pub fn tell_about_font_downloads(&mut self) { + self.font_notices = true; + } +} + +/// Show the box once for a document opened from a file, when it is missing fonts that can be +/// downloaded and the box hasn't been turned off. Called every frame; it waits for an open +/// dialog or the File tab to close rather than replace them. +pub(crate) fn tick(app: &mut WordApp) { + let id = app.session.document_id(); + if !app.font_notices || app.font_notice_seen.contains(&id) || app.dialog.is_some() || app.ui.backstage { + return; + } + remember(app, id); + // A new document has no file: its fonts are WordCraft's choice, not a document's from elsewhere. + if !app.ui.font_download_notice || app.session.path.is_none() { + return; + } + let fonts = rows(app); + if !fonts.is_empty() { + app.dialog = Some(Dialog::FontDownload { fonts, dont_show: false }); + } +} + +/// How to install a downloaded font on this system, after the files are unpacked. +fn system_install_steps() -> &'static str { + if cfg!(target_arch = "wasm32") { + "" + } else if cfg!(target_os = "windows") { + tl!("Or install it for every app: select the font files, right-click and choose Install, then restart WordCraft.") + } else if cfg!(target_os = "macos") { + tl!("Or install it for every app: double-click each font file and choose Install in Font Book, then restart WordCraft.") + } else { + tl!("Or install it for every app: copy the font files to the .local/share/fonts folder in your home folder, then restart WordCraft.") + } +} + +/// The Close button (Escape too) at the far side, in a row of its own: the far-side layout +/// then takes one row's height and not the rest of the window's. +fn close_row(ui: &mut egui::Ui) -> bool { + let mut close = ui.input(|i| i.key_pressed(egui::Key::Escape)); + ui.horizontal(|ui| { + ui.with_layout(crate::rtl::far_side(ui, egui::Align::Center), |ui| { + close |= ui.add(crate::widgets::primary_button(ui, tl!("Close"))).clicked(); + }); + }); + close +} + +/// The fonts one download brings: listed once, however many of its fonts are missing. +struct Group<'a> { + /// Its missing fonts. + fonts: Vec<&'a str>, + /// The families they are drawn in instead, each once. + shown_as: Vec<&'a str>, + publisher: &'a str, + url: &'a str, + /// The publisher limits who may use them. + restricted: bool, +} + +/// `fonts` by download page, in the order first met. +fn groups(fonts: &[Row]) -> Vec> { + let mut out: Vec = Vec::new(); + for f in fonts { + let at = match out.iter().position(|g| g.url == f.url && g.publisher == f.publisher && g.restricted == f.restricted) { + Some(at) => at, + None => { + out.push(Group { fonts: Vec::new(), shown_as: Vec::new(), publisher: &f.publisher, url: &f.url, restricted: f.restricted }); + out.len() - 1 + } + }; + if let Some(g) = out.get_mut(at) { + g.fonts.push(&f.font); + for s in &f.shown_as { + if !g.shown_as.contains(&s.as_str()) { + g.shown_as.push(s); + } + } + } + } + out +} + +/// A step's number in a filled circle. +fn step_badge(ui: &mut egui::Ui, n: usize, t: &Tokens) { + let (r, _) = ui.allocate_exact_size(egui::vec2(20.0, 20.0), egui::Sense::hover()); + ui.painter().circle_filled(r.center(), 10.0, t.accent); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, n.to_string(), semibold(12.0), t.on_accent); +} + +/// The box's content: a headline, a card to a download with its button, the two steps that +/// add the downloaded font (Add Font… beside the step that uses it), then the opt-out and Close. +/// Returns true to close. +pub(crate) fn body(app: &mut WordApp, ui: &mut egui::Ui, fonts: &[Row], dont_show: &mut bool) -> bool { + ui.set_width(520.0); + if fonts.is_empty() { + ui.label(tl!("None of the fonts this document is missing can be downloaded free of charge from their publisher.")); + ui.add_space(8.0); + return close_row(ui); + } + let t = Tokens::get(ui.ctx()); + let mut open_url = None; + let mut add = false; + // Everything above the row with Close scrolls when the window is too short for it, so + // that row is on screen and the rest in reach however many downloads there are. + let room = (ui.ctx().content_rect().height() - ROOM_AROUND_SCROLL).max(SCROLL_MIN); + egui::ScrollArea::vertical().id_salt("font_downloads").max_height(room).show(ui, |ui| { + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(egui::vec2(34.0, 34.0), egui::Sense::hover()); + crate::icons::paint(ui.painter(), r, "fontMissing", t.icon, t.accent); + ui.add_space(4.0); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 3.0; + // `fonts` holds only the missing fonts that can be downloaded: the document may + // be missing others, so the headline counts downloads, not missing fonts. + let headline = crate::i18n::tn(fonts.len() as u64, "{n} missing font can be downloaded", "{n} missing fonts can be downloaded"); + ui.label(egui::RichText::new(headline).font(semibold(15.0))); + let note = + tl!("Text in a missing font is shown in another font, so it may not look as it was written. The downloads are free of charge."); + ui.label(egui::RichText::new(note).color(t.text_dim)); + }); + }); + ui.add_space(12.0); + for g in groups(fonts) { + egui::Frame::NONE + .fill(t.panel) + .stroke(egui::Stroke::new(1.0, t.border)) + .corner_radius(8) + .inner_margin(egui::Margin::symmetric(14, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + // A label to a name: each is the document's own word, not interface text. + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + for (i, font) in g.fonts.iter().enumerate() { + if i > 0 { + ui.label(egui::RichText::new(", ").font(semibold(14.0))); + } + ui.label(egui::RichText::new(*font).font(semibold(14.0))); + } + }); + let shown = crate::i18n::fmt( + tl!("Shown as {fonts} · {publisher}"), + &[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)], + ); + ui.label(egui::RichText::new(shown).color(t.text_dim)); + if g.restricted { + let limits = tl!("Its licence limits who may use it: read the terms first."); + ui.label(egui::RichText::new(limits).small().color(t.text_dim)); + } + }); + ui.with_layout(crate::rtl::far_side(ui, egui::Align::Center), |ui| { + let tip = crate::i18n::fmt(tl!("Download from {publisher}"), &[("publisher", g.publisher)]); + if ui.add(crate::widgets::primary_button(ui, tl!("Download"))).on_hover_text(format!("{tip}\n{}", g.url)).clicked() { + open_url = Some(g.url.to_string()); + } + }); + }); + }); + ui.add_space(6.0); + } + if open_url.is_some() { + // The publisher's page, in the browser: WordCraft downloads nothing itself. + app.canvas.open_url = open_url; + } + // Whose part the licence is: WordCraft only points at the publisher's page. + let terms = tl!("Fonts come with licence terms. Read the publisher's terms on the download page: following them is up to you."); + ui.label(egui::RichText::new(terms).small().color(t.text_dim)); + ui.add_space(12.0); + ui.label(egui::RichText::new(tl!("Then add it to WordCraft")).font(semibold(14.0))); + ui.add_space(4.0); + ui.horizontal(|ui| { + step_badge(ui, 1, &t); + ui.label(tl!("Download the font. If it comes as a .zip file, unpack it.")); + }); + ui.add_space(2.0); + ui.horizontal(|ui| { + step_badge(ui, 2, &t); + ui.label(tl!("Pick the font files:")); + add = ui.button(tl!("Add Font…")).clicked(); + }); + let system = system_install_steps(); + if !system.is_empty() { + ui.add_space(6.0); + ui.label(egui::RichText::new(system).small().color(t.text_dim)); + } + }); + ui.add_space(12.0); + ui.separator(); + ui.add_space(8.0); + // The downloads are the accent buttons; Close (Escape too) is plain beside them. + let mut close = ui.input(|i| i.key_pressed(egui::Key::Escape)); + ui.horizontal(|ui| { + if ui.checkbox(dont_show, tl!("Don't show this again")).changed() { + // Kept at once, however the box is closed. + app.ui.font_download_notice = !*dont_show; + } + ui.with_layout(crate::rtl::far_side(ui, egui::Align::Center), |ui| { + close |= ui.button(tl!("Close")).clicked(); + }); + }); + if add { + // The file picker replaces the box; the added font lays the document out again. + let _ = app.run("font.add", serde_json::json!({})); + return true; + } + close +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/font_download/tests.rs b/crates/ui-egui/src/font_download/tests.rs new file mode 100644 index 0000000000..adbcb63628 --- /dev/null +++ b/crates/ui-egui/src/font_download/tests.rs @@ -0,0 +1,253 @@ +use egui_kittest::kittest::Queryable; +use serde_json::json; +use wordcraft_engine::Session; + +use super::*; + +/// Aptos is installed on this machine: nothing is missing, so there is nothing to tell. +fn aptos_installed() -> bool { + wordcraft_fonts::FontDb::global().families().iter().any(|f| f.eq_ignore_ascii_case("Aptos")) +} + +/// A document with text in Aptos (which Microsoft gives away) and in a font nobody has, +/// opened from a file when `opened`. +fn app(opened: bool) -> WordApp { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + a.session.run("format.font", &json!({"name": "Aptos"})).unwrap(); + a.session.run("text.insert", &json!({"text": "Lanterns"})).unwrap(); + a.session.run("text.newParagraph", &json!({})).unwrap(); + a.session.run("format.font", &json!({"name": "Wordcraft Nowhere Face"})).unwrap(); + a.session.run("text.insert", &json!({"text": "Harbour"})).unwrap(); + if opened { + a.session.path = Some("letter.docx".into()); + } + a.tell_about_font_downloads(); + a +} + +fn harness(app: WordApp) -> egui_kittest::Harness<'static, WordApp> { + harness_sized(app, egui::vec2(1440.0, 900.0)) +} + +fn harness_sized(app: WordApp, size: egui::Vec2) -> egui_kittest::Harness<'static, WordApp> { + let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn shown(h: &egui_kittest::Harness<'static, WordApp>) -> Option<&'static str> { + h.state().dialog.as_ref().map(Dialog::name) +} + +#[test] +fn an_opened_document_missing_a_downloadable_font_is_told_about_once() { + if aptos_installed() { + return; + } + let mut h = harness(app(true)); + let Some(Dialog::FontDownload { fonts, dont_show }) = h.state().dialog.clone() else { panic!("no box: {:?}", shown(&h)) }; + // Only the font that can be downloaded, with what it is drawn in and Microsoft's page. + assert_eq!(fonts.len(), 1, "{fonts:?}"); + assert_eq!((fonts[0].font.as_str(), fonts[0].publisher.as_str()), ("Aptos", "Microsoft")); + assert!(fonts[0].url.starts_with("https://www.microsoft.com/"), "{}", fonts[0].url); + assert!(!fonts[0].shown_as.is_empty() && !fonts[0].shown_as.iter().any(|f| f == "Aptos"), "{:?}", fonts[0].shown_as); + assert!(!dont_show); + // The box says so: the font, its substitute and publisher, the download, how to add it, + // and the opt-out. + // The headline counts what can be downloaded, not every font the document is missing. + assert!(h.query_by_label("1 missing font can be downloaded").is_some()); + assert!(h.query_by_label_contains("isn't installed").is_none(), "other fonts may be missing too"); + assert!(h.query_by_label("Aptos").is_some()); + assert!(h.query_by_label(format!("Shown as {} · Microsoft", fonts[0].shown_as.join(", ")).as_str()).is_some()); + assert!(h.query_by_label_contains("following them is up to you").is_some(), "whose part the licence is"); + assert!(h.query_by_label_contains("limits who may use it").is_none(), "Aptos has no such limit"); + assert!(h.query_by_label("Pick the font files:").is_some()); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Add Font…").is_some()); + assert!(h.query_by_label("Don't show this again").is_some()); + // Download opens the publisher's page in the browser; nothing is downloaded here. + h.get_by_role_and_label(egui::accesskit::Role::Button, "Download").click(); + let mut opened = false; + for _ in 0..4 { + h.step(); + opened |= h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url == fonts[0].url)); + } + assert!(opened, "the page is opened"); + assert_eq!(shown(&h), Some("fontDownload"), "and the box stays for the next step"); + // Closed, it stays closed for this document. + // The box's own Close button, below the title bar's. + let close = + h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Close").max_by(|a, b| a.rect().center().y.total_cmp(&b.rect().center().y)); + close.expect("a Close button").click(); + h.run_steps(4); + assert_eq!(shown(&h), None); + assert!(h.state().ui.font_download_notice, "closing alone keeps the box on"); +} + +#[test] +fn the_box_comes_up_only_where_the_host_asked_for_it() { + let mut a = app(true); + a.font_notices = false; + let h = harness(a); + assert_eq!(shown(&h), None, "headless: tests and ui_shot"); +} + +#[test] +fn a_new_document_is_not_told_about() { + let h = harness(app(false)); + assert_eq!(shown(&h), None, "its fonts are WordCraft's choice"); +} + +#[test] +fn dont_show_this_again_turns_the_box_off() { + if aptos_installed() { + return; + } + let mut h = harness(app(true)); + assert_eq!(shown(&h), Some("fontDownload")); + h.get_by_label("Don't show this again").click(); + h.run_steps(2); + assert!(!h.state().ui.font_download_notice, "kept at once"); + // Saved between runs, and read back. + let saved = serde_json::to_value(h.state().prefs()).unwrap(); + assert_eq!(saved["fontDownloadNotice"], json!(false), "{saved}"); + // The next opened document isn't told about. + let mut a = app(true); + a.ui.font_download_notice = false; + let h = harness(a); + assert_eq!(shown(&h), None); +} + +#[test] +fn the_box_waits_for_an_open_dialog_and_can_be_opened_by_hand() { + if aptos_installed() { + return; + } + let mut a = app(true); + a.dialog = Dialog::open("wordCount", &mut a); + let mut h = harness(a); + assert_eq!(shown(&h), Some("wordCount"), "the open dialog stays"); + h.state_mut().dialog = None; + h.run_steps(3); + assert_eq!(shown(&h), Some("fontDownload"), "then the box"); + h.state_mut().dialog = None; + h.run_steps(3); + assert_eq!(shown(&h), None); + // The status bar's menu (`ui.dialog`) opens it again, even with the box turned off. + h.state_mut().ui.font_download_notice = false; + h.state_mut().run("ui.dialog", json!({"name": "fontDownload"})).unwrap(); + let Some(Dialog::FontDownload { fonts, dont_show }) = h.state().dialog.clone() else { panic!("no box") }; + assert_eq!(fonts.len(), 1); + assert!(dont_show, "the box shows the setting"); +} + +#[test] +fn a_document_a_script_opened_is_not_told_about() { + let mut a = app(true); + let id = a.session.document_id(); + skip(&mut a, id); + skip(&mut a, id); + assert_eq!(a.font_notice_seen, vec![id]); + let h = harness(a); + assert_eq!(shown(&h), None); +} + +#[test] +fn a_document_with_nothing_to_download_says_so_when_asked() { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default()); + a.session.run("select.all", &json!({})).unwrap(); + a.session.run("format.font", &json!({"name": "Wordcraft Nowhere Face"})).unwrap(); + a.session.path = Some("letter.docx".into()); + a.tell_about_font_downloads(); + let mut h = harness(a); + assert_eq!(shown(&h), None, "a font nobody gives away brings up no box"); + h.state_mut().run("ui.dialog", json!({"name": "fontDownload"})).unwrap(); + h.run_steps(3); + assert!(h.query_by_label_contains("None of the fonts").is_some()); +} + +/// Fonts that come in one download share a card and a Download button. +#[test] +fn fonts_of_one_download_are_listed_together() { + let row = |font: &str, shown: &str, url: &str| Row { + font: font.into(), + shown_as: vec![shown.into()], + download: font.into(), + publisher: "Microsoft".into(), + url: url.into(), + restricted: false, + }; + let fonts = + [row("Aptos", "Carlito", "https://a"), row("Cascadia Code", "Liberation Mono", "https://c"), row("Aptos Display", "Carlito", "https://a")]; + let g = groups(&fonts); + assert_eq!(g.len(), 2); + assert_eq!( + (g[0].fonts.as_slice(), g[0].shown_as.as_slice(), g[0].url), + (["Aptos", "Aptos Display"].as_slice(), ["Carlito"].as_slice(), "https://a") + ); + assert_eq!((g[1].fonts.as_slice(), g[1].url), (["Cascadia Code"].as_slice(), "https://c")); +} + +/// As many downloads as the box lists, in a short window and a very short one: what is above +/// the row with Close scrolls, so the opt-out and Close stay on screen and the box in the window. +#[test] +fn many_downloads_in_a_short_window_leave_the_opt_out_and_close_on_screen() { + for height in [600.0, 400.0] { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default()); + let fonts: Vec = (0..LISTED) + .map(|i| Row { + font: format!("Harbour Face {i}"), + shown_as: vec!["Carlito".into()], + download: format!("Harbour Face {i}"), + publisher: "Lantern Works".into(), + url: format!("https://example.org/{i}"), + restricted: false, + }) + .collect(); + a.dialog = Some(Dialog::FontDownload { fonts, dont_show: false }); + let h = harness_sized(a, egui::vec2(1000.0, height)); + // The steps are still there, to scroll to. + assert!(h.query_by_label("Add Font…").is_some()); + for label in ["Don't show this again", "Close"] { + // Close is also the window's close box: every match is on screen. + let rects: Vec = h.query_all_by_label(label).map(|n| n.rect()).collect(); + assert!(!rects.is_empty(), "no {label}"); + for r in rects { + assert!(r.min.y >= 0.0 && r.max.y <= height, "{label} is at {r:?}, outside the {height} pt window"); + } + } + } +} + +/// A font whose publisher limits its use says so on its card, and has a card of its own. +#[test] +fn a_font_with_a_limited_licence_says_so() { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default()); + a.session.run("select.all", &json!({})).unwrap(); + a.session.run("format.font", &json!({"name": "Segoe UI Variable"})).unwrap(); + let layout = a.session.layout(); + if !wordcraft_engine::cmd::font::missing_fonts(&a.session.doc, &layout).iter().any(|f| f.font == "Segoe UI Variable") { + return; // Installed here: not missing. + } + a.dialog = Dialog::open("fontDownload", &mut a); + let Some(Dialog::FontDownload { fonts, .. }) = a.dialog.clone() else { panic!("no box") }; + assert!(fonts.iter().any(|f| f.font == "Segoe UI Variable" && f.restricted), "{fonts:?}"); + let h = harness(a); + assert!(h.query_by_label_contains("limits who may use it").is_some()); +} + +#[test] +fn only_so_many_documents_are_remembered() { + let mut a = app(false); + for id in 0..(REMEMBERED as u64 + 50) { + skip(&mut a, id); + } + assert_eq!(a.font_notice_seen.len(), REMEMBERED); + assert_eq!(a.font_notice_seen.last(), Some(&(REMEMBERED as u64 + 49))); +} diff --git a/crates/ui-egui/src/i18n/audit.rs b/crates/ui-egui/src/i18n/audit.rs index 8bac196a70..633ce24149 100644 --- a/crates/ui-egui/src/i18n/audit.rs +++ b/crates/ui-egui/src/i18n/audit.rs @@ -306,6 +306,7 @@ fn untranslated_interface_text() { "tableProperties", "pasteSpecial", "about", + "fontDownload", "contributors", "models", "languageData", @@ -752,6 +753,7 @@ fn the_arabic_interface_is_mirrored_and_never_panics() { "enclose", "pasteSpecial", "about", + "fontDownload", "contributors", "models", "insertMergeField", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 09dc4d7c13..df78b738b1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -43,6 +43,7 @@ pub mod equation_tab; #[cfg(not(target_arch = "wasm32"))] pub mod file_browser; pub mod file_dialogs; +pub mod font_download; pub mod format_shape; pub mod frame; pub mod guides; @@ -435,6 +436,9 @@ pub struct UiState { /// spaces, or characters without spaces. Right-click the count in the status bar, or File › /// Options › Display. Junk saved values read as words. pub status_count: StatusCount, + /// File › Options › General: tell about a document's missing fonts that can be downloaded + /// ([`font_download`]); the box's "Don't show this again" turns it off. + pub font_download_notice: bool, /// How far a mouse-wheel notch scrolls (#6146). #[serde(default, alias = "scrollSpeed")] pub scroll_speed: ScrollSpeed, @@ -540,6 +544,7 @@ impl Default for UiState { dictionary: Vec::new(), display_server: DisplayServer::Auto, status_count: StatusCount::default(), + font_download_notice: true, scroll_speed: ScrollSpeed::default(), touchpad_scroll_speed: ScrollSpeed::default(), } @@ -690,6 +695,11 @@ pub struct WordApp { /// Focus (#1678): the ribbon is dropped down from the Focus bar, over the page. pub(crate) focus_ribbon: bool, pub(crate) updates_rt: updates_ui::Runtime, + /// The documents (by id) the missing-fonts download box has been considered for + /// ([`font_download::tick`]), in every window. + pub(crate) font_notice_seen: Vec, + /// Whether that box comes up by itself ([`WordApp::tell_about_font_downloads`]). + pub(crate) font_notices: bool, /// Language pack installs, the missing-pack bar ([`language_packs`]). pub(crate) packs_rt: language_packs::Runtime, control_rx: Option>, diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 335aaae857..91b6e4d56e 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -250,6 +250,7 @@ fn general(app: &mut WordApp, ui: &mut Ui) { let _ = app.run("view.darkMode", json!({"value": dark_page})); } ui.checkbox(&mut app.ui.show_discord, tl!("Show the community button in the title bar")); + ui.checkbox(&mut app.ui.font_download_notice, tl!("Tell me when a document's missing fonts can be downloaded")); default_app_button(app, ui); ui.add_space(8.0); section(ui, "Start-up"); diff --git a/crates/ui-egui/src/window_ui.rs b/crates/ui-egui/src/window_ui.rs index dbb05cb5dd..61947a4b51 100644 --- a/crates/ui-egui/src/window_ui.rs +++ b/crates/ui-egui/src/window_ui.rs @@ -175,6 +175,8 @@ impl WordApp { mac_titlebar: _, control_rx: _, updates_rt: _, + font_notice_seen: _, + font_notices: _, packs_rt: _, // The control channel's screenshots and input go to the active window, whichever it is. shots: _, @@ -315,6 +317,7 @@ impl WordApp { print_backgrounds: _, update_fields_before_print: _, dictionary: _, + font_download_notice: _, // Where each task pane sits, and their order. styles_pane_dock: _, styles_pane_float: _, diff --git a/docs/gaps.md b/docs/gaps.md index dd855eb30a..caa3ee583e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ > **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** trivial (gap 4: Word 2003's indent rules beside floating objects, #5939); previously trivial (#5: a list item deleted whole under Track Changes shows its number as deleted text, #4828); previously trivial (clipboard: a copied picture now reaches the system clipboard as PNG, with HTML where the host writes it; a copy of only shapes still stays in WordCraft, #6205); previously trivial (#4501 refactor regressions restored, #4683; no ranked gap changed); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** trivial (#4: a missing font its publisher gives away names the download page (`font.missing`, Get the Missing Fonts)); previously trivial (gap 4: Word 2003's indent rules beside floating objects, #5939); previously trivial (#5: a list item deleted whole under Track Changes shows its number as deleted text, #4828); previously trivial (clipboard: a copied picture now reaches the system clipboard as PNG, with HTML where the host writes it; a copy of only shapes still stays in WordCraft, #6205); previously trivial (#4501 refactor regressions restored, #4683; no ranked gap changed); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -252,6 +252,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-11-03 | trivial | #8 (CP4.3): one language list: Set Proofing Language, Review › Language and the status bar offer the Language pack languages (Bulgarian was in none); every published pack named in English; Valencian is `ca-ES-valencia`; gap 8 names built-in proofing | | 2026-11-03 | trivial | #8 (CP4.3): the missing-pack bar offers a language before the list of packs is fetched (a fresh install, or a list cached for an older pin) and gets it on Install; with downloading on, a missing or stale list is fetched once in the background; the caret's typing language counts; the spelling context menu's heading is in the interface language | | 2026-11-03 | trivial | #8 (CP4.3): File › Options › Language lists Your languages and Add a language… (searchable, sorted by name) replaces the Language packs table; the Dictionaries folder and the Dictionary files list moved from Proofing | +| 2026-11-15 | trivial | #4: a missing font its publisher gives away (Microsoft's Aptos family, Cascadia Code and Mono) names the publisher's download page: `font.missing` reports it as `download`, and the app tells about it when such a document is opened (Get the Missing Fonts), so text set in Aptos can be shown in Aptos rather than a substitute that wraps differently | | 2026-10-28 | trivial | #4: fonts the document uses that aren't installed are flagged in the font box and status bar (metric-compatible substitutes and symbol fonts aren't); a missing font is drawn in an installed metric twin before other substitutes (Arial for Helvetica on Windows), so pages break as in the document's own font wherever such a twin is installed | | 2026-11-03 | trivial | #4: a hyphen before a slash and a letter is a line break opportunity, a hyphen before a slash and a digit stays whole (#3408) | | 2026-11-03 | trivial | #8: language-packs-2 published and pinned, 75 packs; Danish, German, Dutch, Swedish, Norwegian, Hungarian, Estonian, Croatian, Persian and Esperanto available as Language packs | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9abcefef2..bd843015f2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (the Insert › Shapes Arrow tile is drawn as the block arrow it inserts, not a thin line arrow, #6768); previously trivial (while editing a header or footer, a click on its Behind Text picture selects it wherever no header or footer line's band (plus 40pt) covers it, down over the body or in a clear area inside the band, and a right-click selects it too so Reset Picture and Wrap Text act on it); previously trivial (File › Print opened again no longer shows the last job's "submitted" or failure message when that window already said it; decided per window, the shared message and `ui.printSettings` untouched); previously trivial (Save As and Export offer Browse in WordCraft… on Linux/BSD, as Open does, #3535); previously trivial (Language dialog: whole-document OK sends Do not check only when the box was clicked, so per-run proofing state is not flattened; glossary skipped while Track Formatting is on and reported as `glossarySkipped`, #3518); previously trivial (Language dialog: Apply to the whole document sets the proofing language or no-proof for every story in one undo step, #3518); previously trivial (Ctrl/Cmd+Shift+V pastes the formatting picked up with Ctrl/Cmd+Shift+C or the Format Painter, or text only when none was, as in Word, #1537); previously trivial (Auto interface size capped to the screen, Ctrl+Shift+0 returns to Auto, #4030); previously trivial (clipboard: a copied picture reaches the system clipboard as PNG, with HTML where the host writes it, while a copy of only shapes stays in WordCraft, #6205); previously trivial (Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (a press the canvas handles, such as Ctrl+click on a link, no longer also shows the link tooltip that frame, #4683); previously trivial (the window moves by its title bar behind a modal dialog, as in Word for Mac, #5124); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux and the BSDs no longer looks semi-bold); previously trivial (the document's scroll bars show wherever the pointer is, not only at the window's edge, #5746); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (dragging an In Line with Text object shows a bold insertion cursor, as in Word, instead of a faint dashed one, #4195); previously trivial (the shapes, pictures and text boxes inside a Drawing Canvas are picked, moved and resized on their own, #2637); previously trivial (Shape Format › Size shows the interface unit and takes any typed unit, #4196); previously trivial (over a turned picture, shape or text box the resize arrows turn with it, #3932); previously trivial (the status bar's count is words by default and can be characters with or without spaces, chosen from its right-click menu or File › Options › Display and kept between runs, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (dialogs are modal except Find and Replace, Symbol, Mark Index Entry, Cross-reference and Insert Merge Field, and a press beside one shakes it, #3859); previously trivial (showing the Format Shape pane leaves a gradient angle above 359.9° as it is, #3955); previously trivial (Return on File › Print prints, as Word's default Print button does); previously trivial (N-up and booklet printing, #641; readiness unchanged); previously trivial (missing fonts flagged in the font box and status bar, read from what layout drew; metric-compatible substitutes and symbol fonts not flagged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (a long comment's card and balloon stop at ten lines, #3382); previously minor (Arabic mirrored interface: ribbon, panes, File page, dialogs, menus; document canvas independent, #1195); previously trivial (Alt, F badges the Backstage pages; Alt, F, P and V open Print, #4960); previously trivial (View › Macros opens a Macros dialog with Run, Delete and Record, #4327); previously trivial (aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (Table Properties: row, column and cell settings apply to the selected rows, columns and cells; mixed row check boxes, #4857); previously trivial (Insert › Shapes shows the basic shapes as a grid of drawn icon tiles, #4349); previously trivial (File › Options › Proofing › AutoCorrect Options opens with no document open, #4585); previously trivial (the Shading buttons show the last picked colour, #4412); previously trivial (a blank User Name in File › Options stays blank after a restart, #4368); previously trivial (window size falls back to the screen rectangle when the reported inner size is invalid; equation symbol tooltips no longer repeat a missing glyph's name); previously trivial (window titles and suggested file names omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (an opened document missing fonts their publisher gives away (Microsoft's Aptos and Cascadia) brings up Get the Missing Fonts: each font, the font drawn instead, the download page and how to install it, with Don't show this again); previously trivial (the Insert › Shapes Arrow tile is drawn as the block arrow it inserts, not a thin line arrow, #6768); previously trivial (while editing a header or footer, a click on its Behind Text picture selects it wherever no header or footer line's band (plus 40pt) covers it, down over the body or in a clear area inside the band, and a right-click selects it too so Reset Picture and Wrap Text act on it); previously trivial (File › Print opened again no longer shows the last job's "submitted" or failure message when that window already said it; decided per window, the shared message and `ui.printSettings` untouched); previously trivial (Save As and Export offer Browse in WordCraft… on Linux/BSD, as Open does, #3535); previously trivial (Language dialog: whole-document OK sends Do not check only when the box was clicked, so per-run proofing state is not flattened; glossary skipped while Track Formatting is on and reported as `glossarySkipped`, #3518); previously trivial (Language dialog: Apply to the whole document sets the proofing language or no-proof for every story in one undo step, #3518); previously trivial (Ctrl/Cmd+Shift+V pastes the formatting picked up with Ctrl/Cmd+Shift+C or the Format Painter, or text only when none was, as in Word, #1537); previously trivial (Auto interface size capped to the screen, Ctrl+Shift+0 returns to Auto, #4030); previously trivial (clipboard: a copied picture reaches the system clipboard as PNG, with HTML where the host writes it, while a copy of only shapes stays in WordCraft, #6205); previously trivial (Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (a press the canvas handles, such as Ctrl+click on a link, no longer also shows the link tooltip that frame, #4683); previously trivial (the window moves by its title bar behind a modal dialog, as in Word for Mac, #5124); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux and the BSDs no longer looks semi-bold); previously trivial (the document's scroll bars show wherever the pointer is, not only at the window's edge, #5746); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (dragging an In Line with Text object shows a bold insertion cursor, as in Word, instead of a faint dashed one, #4195); previously trivial (the shapes, pictures and text boxes inside a Drawing Canvas are picked, moved and resized on their own, #2637); previously trivial (Shape Format › Size shows the interface unit and takes any typed unit, #4196); previously trivial (over a turned picture, shape or text box the resize arrows turn with it, #3932); previously trivial (the status bar's count is words by default and can be characters with or without spaces, chosen from its right-click menu or File › Options › Display and kept between runs, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (dialogs are modal except Find and Replace, Symbol, Mark Index Entry, Cross-reference and Insert Merge Field, and a press beside one shakes it, #3859); previously trivial (showing the Format Shape pane leaves a gradient angle above 359.9° as it is, #3955); previously trivial (Return on File › Print prints, as Word's default Print button does); previously trivial (N-up and booklet printing, #641; readiness unchanged); previously trivial (missing fonts flagged in the font box and status bar, read from what layout drew; metric-compatible substitutes and symbol fonts not flagged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (a long comment's card and balloon stop at ten lines, #3382); previously minor (Arabic mirrored interface: ribbon, panes, File page, dialogs, menus; document canvas independent, #1195); previously trivial (Alt, F badges the Backstage pages; Alt, F, P and V open Print, #4960); previously trivial (View › Macros opens a Macros dialog with Run, Delete and Record, #4327); previously trivial (aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (Table Properties: row, column and cell settings apply to the selected rows, columns and cells; mixed row check boxes, #4857); previously trivial (Insert › Shapes shows the basic shapes as a grid of drawn icon tiles, #4349); previously trivial (File › Options › Proofing › AutoCorrect Options opens with no document open, #4585); previously trivial (the Shading buttons show the last picked colour, #4412); previously trivial (a blank User Name in File › Options stays blank after a restart, #4368); previously trivial (window size falls back to the screen rectangle when the reported inner size is invalid; equation symbol tooltips no longer repeat a missing glyph's name); previously trivial (window titles and suggested file names omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. @@ -129,6 +129,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | Date | Change | Summary | |---|---|---| | 2026-11-16 | trivial | Insert › Shapes: the Arrow tile is drawn as the block arrow it inserts, from the outline the document draws it with, instead of a thin line with a head (#6768) | +| 2026-11-15 | trivial | Get the Missing Fonts: a document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, Cascadia Code and Mono) brings up a box with a headline, a card to each download (its missing fonts, the fonts drawn instead, the publisher, a Download button that opens the publisher's page) and the two steps that add the download (Add Font… beside its step; the system's own way below); once per document, never for a new document or one a script opened. Don't show this again turns it off (File › Options › General turns it back on); the status bar's missing-fonts menu opens it by hand (`ui.dialog {"name":"fontDownload"}`). `font.missing` reports the same page as `download` | | 2026-11-15 | trivial | Header/footer pictures: while editing the header or footer, a click on its Behind Text picture selects it wherever no header or footer text covers it: drawn down over the body (anchored in the header, positioned outside the band) or in a clear area inside the band. What counts as header or footer text is each line's own band (the width available to it, so a centred or right-aligned line covers the empty space beside its ink, while an indent or a float beside the line narrows it) plus a 40pt margin either side; a drag there moves it, and a right-click selects it so Reset Picture and Wrap Text act on it. Over header or footer text the click still goes to the text, and from the body a click there is still body text (`canvas::tests::header_picture_clear_of_header_text_is_selected_while_editing_the_header`, `canvas::tests::footer_picture_clear_of_footer_text_is_selected_while_editing_the_footer`, `canvas::tests::right_clicking_a_repeated_header_picture_selects_it_on_its_own_page`, `tests::header_text_covers_the_whole_band_of_centred_and_right_lines`) | | 2026-11-15 | trivial | File › Print opened again no longer shows how the last job went ("Print job submitted…", a failure): that was said once in the status bar. A failure that comes in while the page is open stays, and printer status (finding printers, none found) shows each time. Decided per window: a result a window never said (it arrived under File's other pages, or in another window) still shows there, and the shared message that `ui.printSettings` reports is never cleared | | 2026-11-14 | trivial | Save As and Export (also the formats on the Print page) offer Browse in WordCraft… on Linux/BSD, as Open does; exporting there lists Export's formats as the types, whose extension replaces a known document extension on the name; an export refusal or failure shows on the Export page, as Save As's does (#3535) | From 30584c81adcf821e4688946a6885573818b23705 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:45:46 +0100 Subject: [PATCH 87/99] #778: pin craft-libs main with the shared cutover prerequisites (#6954) * #778: take craft-libs integration/wordcraft-778 at beeea924 Every craft-libs git dependency (workspace, ui-egui, wordcraft, wordcraft-web, krilla patch) moves from 453b0da782 to beeea92451 (craft-libs main 0649a07aa plus open PRs #2061-#2064). Cargo.lock: only craft-libs sources move, plus windows-sys edge changes inside craft-libs crates; no crates.io versions change. Co-Authored-By: Claude Opus 5.5 * #778: docx stacking-order test follows the shared reader's one-more z craft-libs 5f453efa9 (craft-docx: a relativeHeight of 0 stays the lowest stacking order) reads Float::z as one more than the file's relativeHeight and writes stored orders one less, so a file's 0 is no longer "none". The test expected the old values; relative order and the round trip are unchanged. Co-Authored-By: Claude Opus 5.5 * #778: take craft-libs integration/wordcraft-778 at 24a15211 Co-Authored-By: Claude Opus 5.5 * deps: pin craft-libs to the merged shared cutover prerequisites * #778: pin craft-libs main at 93dac78c (with #2061-#2064) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Dylan M. Taylor --- Cargo.lock | 84 ++++++++++++++++---------------- Cargo.toml | 54 ++++++++++---------- apps/wordcraft-web/Cargo.toml | 4 +- apps/wordcraft/Cargo.toml | 2 +- crates/docx/tests/it/fixtures.rs | 6 ++- crates/ui-egui/Cargo.toml | 6 +-- 6 files changed, 79 insertions(+), 77 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bf5e960aea..6c088c3b9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1060,7 +1060,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "rustix 1.1.5", ] @@ -1068,17 +1068,17 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "rayon", ] @@ -1086,7 +1086,7 @@ dependencies = [ [[package]] name = "craft-doc-binary" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "chrono", "craft-cfb", @@ -1102,7 +1102,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "base64 0.23.1", "chrono", @@ -1122,7 +1122,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-xml", "kurbo", @@ -1133,7 +1133,7 @@ dependencies = [ [[package]] name = "craft-flow" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-wordmodel", "image", @@ -1143,7 +1143,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "cap-primitives", "craft-atomic", @@ -1179,12 +1179,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-html" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-codepage", "craft-flow", @@ -1197,7 +1197,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1220,7 +1220,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-dds", "craft-jpeg", @@ -1247,7 +1247,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "thiserror 2.0.21", ] @@ -1255,7 +1255,7 @@ dependencies = [ [[package]] name = "craft-latex" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-flow", "craft-math", @@ -1266,7 +1266,7 @@ dependencies = [ [[package]] name = "craft-markdown" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-flow", "craft-html", @@ -1276,7 +1276,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-xml", "serde", @@ -1285,7 +1285,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1297,7 +1297,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "encoding_rs", "image", @@ -1308,7 +1308,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "chardetng", "chrono", @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "aes", "base64 0.23.1", @@ -1345,7 +1345,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-odf", "craft-sheet", @@ -1356,7 +1356,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "aes", "base64 0.23.1", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-xml", "craft-zip", @@ -1384,7 +1384,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "krilla", "thiserror 2.0.21", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-winprint-gdi", "log", @@ -1407,7 +1407,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1418,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-codepage", "craft-flow", @@ -1431,12 +1431,12 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "serde", "thiserror 2.0.21", @@ -1445,7 +1445,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1465,7 +1465,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "chrono", "dunce", @@ -1492,7 +1492,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "js-sys", "serde_json", @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "wasm-bindgen", "web-sys", @@ -1512,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "egui", "objc2 0.6.5", @@ -1531,7 +1531,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "base64 0.23.1", "craft-math", @@ -1545,7 +1545,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-cfb", "craft-sheet", @@ -1558,7 +1558,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "craft-drawingml", "craft-opc", @@ -1570,7 +1570,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1580,7 +1580,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3416,7 +3416,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" dependencies = [ "base64 0.22.1", "bumpalo", diff --git a/Cargo.toml b/Cargo.toml index 880500f2fd..de95a41c7d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,19 +24,19 @@ wordcraft-pdf = { path = "crates/pdf" } # Proofing is craft-libs' craft-proof (it was crates/proof); its Language data is craft-i18n's # language-data/, embedded from CRAFT_I18N_DIR (craft-i18n.rev). The package keeps the # `wordcraft-proof` name here so `wordcraft_proof::` paths are unchanged. -# craft-proof is storytold/craft-libs main at 453b0da782. That commit has #590 (ca-ES-valencia +# craft-proof is storytold/craft-libs main at 93dac78c. That tree has #590 (ca-ES-valencia # reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based # compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font # store's `language-pack` kind is #486 (CP4.1). -wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } wordcraft-engine = { path = "crates/engine" } wordcraft-mcp = { path = "crates/mcp" } wordcraft-zotero = { path = "crates/zotero" } wordcraft-control-key = { path = "crates/control-key" } wordcraft-ui-egui = { path = "crates/ui-egui" } -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -67,28 +67,28 @@ wuff = "0.2.9" brotli-decompressor = "5" vello_cpu = "0.2" image = { version = "0.25", default-features = false } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", default-features = false, features = ["write"] } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", default-features = false, features = ["write"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["doc"] } -craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["text"] } -craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-html = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["flow"] } -craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-math = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["detect"] } -craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", features = ["egui"] } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["doc"] } +craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["text"] } +craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-html = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["flow"] } +craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["detect"] } +craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } # zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates. miniz_oxide = "0.9" cfb = "0.15" @@ -153,7 +153,7 @@ debug = 0 # Required by craft-pdf: the backend rejects writers that failed during unwinding. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/wordcraft-web/Cargo.toml b/apps/wordcraft-web/Cargo.toml index 382d35f566..721ee5cd36 100644 --- a/apps/wordcraft-web/Cargo.toml +++ b/apps/wordcraft-web/Cargo.toml @@ -18,8 +18,8 @@ wordcraft-engine = { workspace = true } wordcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.wordcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/wordcraft/Cargo.toml b/apps/wordcraft/Cargo.toml index 8bd6f5b39c..ccf00cfcc8 100644 --- a/apps/wordcraft/Cargo.toml +++ b/apps/wordcraft/Cargo.toml @@ -86,7 +86,7 @@ clipboard-win = { version = "5.4", features = ["std"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # At the same craft-libs commit as the workspace's crates: `printer_queues`, the printer list that # asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622). -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" } rfd = { workspace = true } # Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94); # rfd itself already depends on it. diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 7f6cddb6e7..ec1852b797 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1280,10 +1280,12 @@ fn anchor_stacking_order_is_read_and_kept() { paras(d)[0].objects.iter().filter_map(|o| if let InlineObject::Shape { float, .. } = o { Some(float.z) } else { None }).collect() }; let d = read_body(&body); - assert_eq!(zs(&d), [251660288, 251657214, 0]); + // The shared reader keeps one more than the file's `relativeHeight` (so a file's 0 is the + // lowest order, not "none") and the writer writes one less. + assert_eq!(zs(&d), [251660289, 251657215, 0]); let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap(); let z = zs(&again); - assert_eq!(&z[..2], &[251660288, 251657214]); + assert_eq!(&z[..2], &[251660289, 251657215]); assert!(z[2] > 0, "an object without one gets an order on saving: {z:?}"); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 20386d13c1..866e3d978f 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -9,14 +9,14 @@ description = "WordCraft egui front end (Word-style ribbon UI); swappable: nothi workspace = true [dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" } # Interface translations: lookup, fallback, plurals and system-locale matching over the craft-i18n # catalogs that `build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, pinned in # `craft-i18n.rev`). Same craft-libs rev as craft-ui; it brings lazy per-locale parsing # (storytold/craft-libs#247), ICU4X plural rules and bidi isolates around inserted values. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" } # One native window per open document: the window list, the Window menu and the egui viewports. -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", features = ["egui"] } wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } From 1531007d5e8c5b0ca3913953ae0a13924b15d141 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:47:52 +0100 Subject: [PATCH 88/99] #778: plain-text detection uses craft-mime detect (#6950) The local is_text/decode/legacy copies in formats::txt are replaced by a re-export of craft_mime::detect. The old code stays as a test oracle, with differential and random-buffer tests showing identical output. chardetng stays only as a dev-dependency of that oracle. Co-authored-by: Claude Opus 5.5 --- Cargo.toml | 5 +- crates/formats/Cargo.toml | 2 +- crates/formats/src/txt.rs | 93 +------- crates/formats/src/txt/legacy_oracle_tests.rs | 210 ++++++++++++++++++ 4 files changed, 219 insertions(+), 91 deletions(-) create mode 100644 crates/formats/src/txt/legacy_oracle_tests.rs diff --git a/Cargo.toml b/Cargo.toml index de95a41c7d..61aaa177d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -93,9 +93,10 @@ craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93 miniz_oxide = "0.9" cfb = "0.15" # Legacy text encodings (GBK/GB18030, Big5, Shift_JIS, EUC-KR, single-byte code pages) for plain -# text and CSV recipient lists (#778): encoding_rs ((Apache-2.0 OR MIT) AND BSD-3-Clause) and its -# detector chardetng (Apache-2.0 OR MIT), both pure Rust (Firefox's). +# text and CSV recipient lists (#778): encoding_rs ((Apache-2.0 OR MIT) AND BSD-3-Clause), pure +# Rust (Firefox's). Detection is craft-mime's `detect` feature. encoding_rs = "0.8" +# chardetng (Apache-2.0 OR MIT): only the formats test oracle for the old detector uses it directly. chardetng = "1" # Password-protected (agile-encrypted) Word documents: pure-Rust RustCrypto primitives. aes = "0.9" diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index d2bc45fe7d..d242971c81 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -33,7 +33,6 @@ craft-zip = { workspace = true } wordcraft-geom = { workspace = true, features = ["image"] } craft-metafile = { workspace = true } encoding_rs = { workspace = true } -chardetng = { workspace = true } log = { workspace = true } chrono = { workspace = true } # Password-protected ODT (ODF 1.3 Part 2 §3.4): AES-256-CBC, SHA-1/SHA-256, PBKDF2 (HMAC-SHA-1). @@ -41,3 +40,4 @@ chrono = { workspace = true } wordcraft-doc = { workspace = true, features = ["test-support"] } craft-image-codecs = { workspace = true } proptest = { workspace = true } +chardetng = { workspace = true } diff --git a/crates/formats/src/txt.rs b/crates/formats/src/txt.rs index 9968af80b3..1d1b913cd5 100644 --- a/crates/formats/src/txt.rs +++ b/crates/formats/src/txt.rs @@ -10,95 +10,12 @@ pub use wordcraft_doc::encoding::cp1252; use crate::model::{FBlock, ListCounter, from_doc}; -fn utf16(b: &[u8], le: bool) -> String { - let units: Vec = b.as_chunks::<2>().0.iter().map(|c| if le { u16::from_le_bytes(*c) } else { u16::from_be_bytes(*c) }).collect(); - String::from_utf16_lossy(&units) -} +#[cfg(test)] +mod legacy_oracle_tests; -/// UTF-16 without a BOM, told by its zero bytes: `Some(true)` little-endian, `Some(false)` -/// big-endian. -fn unmarked_utf16(b: &[u8]) -> Option { - if b.len() < 4 || !b.len().is_multiple_of(2) { - return None; - } - let sample = b.get(..b.len().min(512))?; - let even_zero = sample.iter().step_by(2).filter(|x| **x == 0).count(); - let odd_zero = sample.iter().skip(1).step_by(2).filter(|x| **x == 0).count(); - let half = sample.len() / 2; - if odd_zero * 10 >= half * 4 && even_zero * 10 < half { - return Some(true); - } - if even_zero * 10 >= half * 4 && odd_zero * 10 < half { - return Some(false); - } - None -} - -/// Does `b` look like plain text, so a file with an extension WordCraft doesn't know (a -/// playlist, a log, a config file…) can open as text the way Word's text import opens it? -/// -/// Text has a BOM, or reads as UTF-16 by its zero bytes, or has no NUL byte and next to no -/// other control characters in its first 64 KB. PDFs are refused by their signature (they -/// start as text). An empty file is text. -pub fn is_text(b: &[u8]) -> bool { - if b.starts_with(&[0xEF, 0xBB, 0xBF]) || b.starts_with(&[0xFF, 0xFE]) || b.starts_with(&[0xFE, 0xFF]) { - return true; - } - if b.starts_with(b"%PDF-") { - return false; - } - let sample = b.get(..b.len().min(64 << 10)).unwrap_or(b); - // Tab, line feed, form feed, carriage return, DOS end-of-file (^Z) and escape appear in text; - // other controls in more than 1 of 100 characters mean binary. - let odd = |c: u32| c == 0 || (c < 0x20 && !matches!(c, 0x09 | 0x0A | 0x0C | 0x0D | 0x1A | 0x1B)) || c == 0x7F; - if let Some(le) = unmarked_utf16(sample) { - let units = sample.as_chunks::<2>().0; - let n = units.iter().filter(|c| odd(u32::from(if le { u16::from_le_bytes(**c) } else { u16::from_be_bytes(**c) }))).count(); - return n.saturating_mul(100) <= units.len(); - } - if sample.contains(&0) { - return false; - } - sample.iter().filter(|c| odd(u32::from(**c))).count().saturating_mul(100) <= sample.len() -} - -/// Decode text bytes: BOMs first, then UTF-16 without BOM (by its zero bytes), UTF-8, and the -/// legacy encoding the bytes look like ([`legacy`]) as the last resort. -pub fn decode(b: &[u8]) -> String { - if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { - return String::from_utf8_lossy(rest).into_owned(); - } - if let Some(rest) = b.strip_prefix(&[0xFF, 0xFE]) { - return utf16(rest, true); - } - if let Some(rest) = b.strip_prefix(&[0xFE, 0xFF]) { - return utf16(rest, false); - } - if let Some(le) = unmarked_utf16(b) { - return utf16(b, le); - } - match std::str::from_utf8(b) { - Ok(s) => s.to_string(), - Err(_) => legacy(b), - } -} - -/// Most bytes looked at to guess a legacy encoding. -const SNIFF: usize = 1 << 20; - -/// Bytes that aren't UTF-8 in the legacy encoding they look like (chardetng, the detector -/// Firefox uses for unlabelled pages): GBK/GB18030 for Simplified Chinese, Big5, Shift_JIS or -/// EUC-JP, EUC-KR, or a single-byte Windows / ISO code page; Windows-1252 as before when the -/// guess is a single-byte Western one. -pub fn legacy(b: &[u8]) -> String { - let mut det = chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Deny); - det.feed(b.get(..SNIFF).unwrap_or(b), b.len() <= SNIFF); - let enc = det.guess(None, chardetng::Utf8Detection::Deny); - if enc == encoding_rs::WINDOWS_1252 { - return b.iter().map(|c| cp1252(*c)).collect(); - } - enc.decode_without_bom_handling(b).0.into_owned() -} +// Detection is shared with the other Craft apps. WordCraft's `cp1252` and encoding_rs agree on +// every byte (pinned by `legacy_oracle_tests`), so a Windows-1252 guess needs no local mapping. +pub use craft_mime::detect::{decode, is_text, legacy}; /// Decode bytes in a named encoding (a WHATWG label such as `gbk`, `gb18030`, `big5`, /// `shift_jis`, `euc-kr`, `utf-16le`, `windows-1251`); `None` when the label isn't known. diff --git a/crates/formats/src/txt/legacy_oracle_tests.rs b/crates/formats/src/txt/legacy_oracle_tests.rs new file mode 100644 index 0000000000..ebc2c6fd11 --- /dev/null +++ b/crates/formats/src/txt/legacy_oracle_tests.rs @@ -0,0 +1,210 @@ +//! The pre-cutover local implementations, kept as an oracle: the shared `craft_mime::detect` +//! functions plus the cp1252 wrapper must agree with them byte for byte. + +use super::cp1252; + +fn utf16(b: &[u8], le: bool) -> String { + let units: Vec = b.as_chunks::<2>().0.iter().map(|c| if le { u16::from_le_bytes(*c) } else { u16::from_be_bytes(*c) }).collect(); + String::from_utf16_lossy(&units) +} + +/// UTF-16 without a BOM, told by its zero bytes: `Some(true)` little-endian, `Some(false)` +/// big-endian. +fn unmarked_utf16(b: &[u8]) -> Option { + if b.len() < 4 || !b.len().is_multiple_of(2) { + return None; + } + let sample = b.get(..b.len().min(512))?; + let even_zero = sample.iter().step_by(2).filter(|x| **x == 0).count(); + let odd_zero = sample.iter().skip(1).step_by(2).filter(|x| **x == 0).count(); + let half = sample.len() / 2; + if odd_zero * 10 >= half * 4 && even_zero * 10 < half { + return Some(true); + } + if even_zero * 10 >= half * 4 && odd_zero * 10 < half { + return Some(false); + } + None +} + +/// Does `b` look like plain text, so a file with an extension WordCraft doesn't know (a +/// playlist, a log, a config file…) can open as text the way Word's text import opens it? +/// +/// Text has a BOM, or reads as UTF-16 by its zero bytes, or has no NUL byte and next to no +/// other control characters in its first 64 KB. PDFs are refused by their signature (they +/// start as text). An empty file is text. +fn is_text(b: &[u8]) -> bool { + if b.starts_with(&[0xEF, 0xBB, 0xBF]) || b.starts_with(&[0xFF, 0xFE]) || b.starts_with(&[0xFE, 0xFF]) { + return true; + } + if b.starts_with(b"%PDF-") { + return false; + } + let sample = b.get(..b.len().min(64 << 10)).unwrap_or(b); + // Tab, line feed, form feed, carriage return, DOS end-of-file (^Z) and escape appear in text; + // other controls in more than 1 of 100 characters mean binary. + let odd = |c: u32| c == 0 || (c < 0x20 && !matches!(c, 0x09 | 0x0A | 0x0C | 0x0D | 0x1A | 0x1B)) || c == 0x7F; + if let Some(le) = unmarked_utf16(sample) { + let units = sample.as_chunks::<2>().0; + let n = units.iter().filter(|c| odd(u32::from(if le { u16::from_le_bytes(**c) } else { u16::from_be_bytes(**c) }))).count(); + return n.saturating_mul(100) <= units.len(); + } + if sample.contains(&0) { + return false; + } + sample.iter().filter(|c| odd(u32::from(**c))).count().saturating_mul(100) <= sample.len() +} + +/// Decode text bytes: BOMs first, then UTF-16 without BOM (by its zero bytes), UTF-8, and the +/// legacy encoding the bytes look like ([`legacy`]) as the last resort. +fn decode(b: &[u8]) -> String { + if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { + return String::from_utf8_lossy(rest).into_owned(); + } + if let Some(rest) = b.strip_prefix(&[0xFF, 0xFE]) { + return utf16(rest, true); + } + if let Some(rest) = b.strip_prefix(&[0xFE, 0xFF]) { + return utf16(rest, false); + } + if let Some(le) = unmarked_utf16(b) { + return utf16(b, le); + } + match std::str::from_utf8(b) { + Ok(s) => s.to_string(), + Err(_) => legacy(b), + } +} + +/// Most bytes looked at to guess a legacy encoding. +const SNIFF: usize = 1 << 20; + +/// Bytes that aren't UTF-8 in the legacy encoding they look like (chardetng, the detector +/// Firefox uses for unlabelled pages): GBK/GB18030 for Simplified Chinese, Big5, Shift_JIS or +/// EUC-JP, EUC-KR, or a single-byte Windows / ISO code page; Windows-1252 as before when the +/// guess is a single-byte Western one. +fn legacy(b: &[u8]) -> String { + let mut det = chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Deny); + det.feed(b.get(..SNIFF).unwrap_or(b), b.len() <= SNIFF); + let enc = det.guess(None, chardetng::Utf8Detection::Deny); + if enc == encoding_rs::WINDOWS_1252 { + return b.iter().map(|c| cp1252(*c)).collect(); + } + enc.decode_without_bom_handling(b).0.into_owned() +} + +fn samples() -> Vec> { + let mut v: Vec> = vec![vec![]]; + for b in 0..=255u8 { + v.push(vec![b]); + } + for b in 0x80..=0x9Fu8 { + v.push([b"caf".as_slice(), &[b], b" ok text here"].concat()); + v.push(vec![b, b'a', b'b']); + } + // Western text with each byte Windows-1252 leaves undefined: the case the cp1252 wrapper is for. + for b in [0x81u8, 0x8D, 0x8F, 0x90, 0x9D] { + v.push([b"caf\xE9 au lait ".as_slice(), &[b], b" ok"].concat()); + v.push([b"Le caf\xE9 de la gare ".as_slice(), &[b]].concat()); + v.push([b"r\xE9sum\xE9 ".as_slice(), &[b]].concat()); + } + v.push("héllo wörld € naïve".as_bytes().to_vec()); + v.push([&[0xEF, 0xBB, 0xBF][..], "héllo".as_bytes()].concat()); + v.push([&[0xEF, 0xBB, 0xBF][..], &[0xE9, 0x80]].concat()); + for (bom, le) in [(&[0xFF, 0xFE][..], true), (&[0xFE, 0xFF][..], false)] { + let t = "héllo wörld 日本語 😀"; + v.push([bom, &t.encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }).collect::>()[..]].concat()); + v.push([bom, b"h\0i\0!"].concat()); + let raw: Vec = "hello world, plain ascii".encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }).collect(); + v.push(raw); + let raw: Vec = + "héllo wörld, mostly ascii \u{20AC}".encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }).collect(); + v.push(raw); + } + v.push(vec![0xC3, 0x28, 0xA0, 0xA1, 0xE2, 0x82]); + v.push(b"#EXTM3U\r\n#EXTINF:1,x\r\n".to_vec()); + v.push(b"%PDF-1.7\n%\xE2\xE3".to_vec()); + v.push(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec()); + v.push(vec![1, 0, 2, 0, 3]); + for (enc, text) in [ + (encoding_rs::GBK, "这是一个用简体中文写的文本文件,用来测试编码检测。"), + (encoding_rs::BIG5, "這是一個用繁體中文寫的文字檔案,用來測試編碼偵測。"), + (encoding_rs::SHIFT_JIS, "これは日本語で書かれたテキストファイルです。エンコーディングの検出をテストします。"), + (encoding_rs::EUC_KR, "이것은 한국어로 작성된 텍스트 파일입니다. 인코딩 감지를 테스트합니다."), + (encoding_rs::WINDOWS_1251, "Это текстовый файл на русском языке для проверки определения кодировки."), + ] { + let (b, _, _) = enc.encode(text); + v.push(b.into_owned()); + } + // Past the 1 MiB sniff limit, and a 2 MiB input. + let mut big = vec![b'a'; 1 << 20]; + big.extend_from_slice(&[0xE9; 3]); + v.push(big); + let mut big = "héllo wörld ".repeat((2 << 20) / 13).into_bytes(); + big.push(0xE9); + v.push(big); + v.push(vec![0x80; 2 << 20]); + v +} + +fn assert_same(b: &[u8]) { + let head: Vec = b.iter().take(24).copied().collect(); + assert_eq!(is_text(b), super::is_text(b), "is_text {head:02x?}"); + assert_eq!(legacy(b), super::legacy(b), "legacy {head:02x?}"); + assert_eq!(decode(b), super::decode(b), "decode {head:02x?}"); +} + +#[test] +fn shared_detect_matches_the_old_local_copies() { + for b in samples() { + assert_same(&b); + } +} + +#[test] +fn cp1252_agrees_with_encoding_rs_on_every_byte() { + // Why a Windows-1252 guess needs no local mapping: both give U+0081, U+008D, U+008F, U+0090 + // and U+009D for the bytes the code page leaves undefined. + for b in 0..=255u8 { + let one = [b]; + let (s, _) = encoding_rs::WINDOWS_1252.decode_without_bom_handling(&one); + assert_eq!(s.chars().collect::>(), vec![cp1252(b)], "byte {b:#x}"); + } +} + +#[test] +fn random_buffers_never_panic_and_match() { + let mut s: u64 = 0x2545_F491_4F6C_DD1D; + let mut next = || { + s = s.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (s >> 33) as u32 + }; + for i in 0..3000 { + let len = (next() % 700) as usize; + let mode = i % 4; + let b: Vec = (0..len) + .map(|_| { + let r = next(); + match mode { + 0 => r as u8, + 1 => 0x80 | (r as u8 & 0x1F), // 0x80..=0x9F + 2 => { + if r % 3 == 0 { + 0 + } else { + (r >> 8) as u8 % 0x80 + } + } + _ => { + if r % 5 == 0 { + 0x80 + (r >> 8) as u8 % 0x80 + } else { + b'a' + (r >> 8) as u8 % 26 + } + } + } + }) + .collect(); + assert_same(&b); + } +} From d2bfcd4d160a1024a553994f43fa3a915023ee85 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:18:55 +0100 Subject: [PATCH 89/99] #778: speech: use craft-ssip for the SSIP wire helpers (#6951) Message encoding, reply framing and final-code parsing now come from the shared crate; socket discovery, timings, conversation and events stay here. Co-authored-by: Claude Opus 5.5 Co-authored-by: Dylan M. Taylor --- Cargo.lock | 6 ++ Cargo.toml | 1 + crates/engine/Cargo.toml | 4 + crates/engine/src/speech/ssip.rs | 149 +++++++++++++++---------------- 4 files changed, 83 insertions(+), 77 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6c088c3b9b..cf443adfc7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1433,6 +1433,11 @@ name = "craft-sheet" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" +[[package]] +name = "craft-ssip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" + [[package]] name = "craft-tiff" version = "0.1.0" @@ -7436,6 +7441,7 @@ dependencies = [ "craft-font-store", "craft-mime", "craft-proof", + "craft-ssip", "craft-zip", "encoding_rs", "getrandom 0.3.4", diff --git a/Cargo.toml b/Cargo.toml index 61aaa177d9..28d4647791 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ wordcraft-pdf = { path = "crates/pdf" } wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } wordcraft-engine = { path = "crates/engine" } wordcraft-mcp = { path = "crates/mcp" } wordcraft-zotero = { path = "crates/zotero" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a3049aa21a..a4f11931e9 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -48,6 +48,10 @@ craft-font-catalog = { workspace = true } # The local time zone's offset for Insert ▸ Date & Time and date fields (#1707); the web asks the browser's Date. chrono = { workspace = true, features = ["clock"] } +[target.'cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))'.dependencies] +# Speech Dispatcher's wire framing for Read Aloud (speech/ssip.rs). +craft-ssip = { workspace = true } + [target.'cfg(unix)'.dependencies] # O_NONBLOCK, so a path swapped for a named pipe can't block `open` (#3666). libc = { workspace = true } diff --git a/crates/engine/src/speech/ssip.rs b/crates/engine/src/speech/ssip.rs index 979b144453..d814e74dce 100644 --- a/crates/engine/src/speech/ssip.rs +++ b/crates/engine/src/speech/ssip.rs @@ -13,6 +13,7 @@ //! client halts reading on it ([`Outcome::Halted`]), and so does one that never began //! ([`Outcome::NotStarted`]). +use craft_ssip::{Lines, final_code, message_data}; use std::io::{ErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::os::unix::net::UnixStream; @@ -23,8 +24,8 @@ use std::time::{Duration, Instant}; const POLL: Duration = Duration::from_millis(30); /// Longest wait for a reply to a command (the server answers at once; this only bounds a stuck one). const REPLY_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(1) } else { Duration::from_secs(5) }; -/// Longest reply line kept (a server sends short lines; this bounds a broken one). -const MAX_LINE: usize = 4096; +/// Most bytes of one sentence sent as message data: [`super::MAX_UTTERANCE`] chars of up to 4 bytes each. +const MAX_MESSAGE_BYTES: usize = 4 * super::MAX_UTTERANCE; /// Speech Dispatcher's TCP port when `SPEECHD_ADDRESS` names none. const DEFAULT_PORT: u16 = 6560; /// How long a freshly started server gets to open its socket (it loads its speech modules first). @@ -286,63 +287,6 @@ fn start_server(command: &mut std::process::Command, until: Instant, changed: &d stopped } -/// The sentence as SSIP message data: one line (a line break is a space when read aloud anyway), -/// a leading `.` doubled so it can't end the message, and the terminating `.` line. -pub(super) fn message_data(text: &str) -> String { - let line: String = text.chars().map(|c| if c == '\r' || c == '\n' { ' ' } else { c }).collect(); - let dot = if line.starts_with('.') { "." } else { "" }; - format!("{dot}{line}\r\n.\r\n") -} - -/// Reads reply lines. Bytes wait in `pending` until their line is complete, so a character split -/// across reads stays whole, and a line longer than [`MAX_LINE`] is an error, never a growing buffer. -struct Lines { - reader: R, - pending: Vec, -} - -impl Lines { - fn new(reader: R) -> Self { - Lines { reader, pending: Vec::new() } - } - - /// The next complete line without its line ending, or `Ok(None)` when none is complete after - /// one read (a timeout, or part of a line): the caller looks at its deadline and whether reading - /// moved on between calls, however slowly the bytes trickle in. - fn next(&mut self) -> std::io::Result> { - if let Some(line) = self.complete_line() { - return Ok(Some(line)); - } - if self.pending.len() > MAX_LINE { - return Err(ErrorKind::InvalidData.into()); - } - let mut buf = [0u8; 512]; - match self.reader.read(&mut buf) { - Ok(0) => Err(ErrorKind::UnexpectedEof.into()), - Ok(n) => { - self.pending.extend_from_slice(buf.get(..n).unwrap_or_default()); - Ok(self.complete_line()) - } - Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted) => Ok(None), - Err(e) => Err(e), - } - } - - /// The first complete line in `pending`, taken out of it. - fn complete_line(&mut self) -> Option { - let end = self.pending.iter().position(|&b| b == b'\n')?; - let line: Vec = self.pending.drain(..=end).collect(); - Some(String::from_utf8_lossy(&line).trim_end_matches(['\r', '\n']).to_string()) - } -} - -/// The three-digit code of a final reply line (`225 OK MESSAGE QUEUED`); `None` for a -/// continuation line (`225-12`). -fn final_code(line: &str) -> Option { - let code = line.get(..3)?.parse().ok()?; - (line.as_bytes().get(3) == Some(&b' ') || line.len() == 3).then_some(code) -} - /// A `2xx` reply, or an error naming the code. fn ok(code: u16) -> std::io::Result<()> { if (200..300).contains(&code) { Ok(()) } else { Err(std::io::Error::other(format!("Speech Dispatcher refused a command ({code})"))) } @@ -378,7 +322,7 @@ impl Conversation<'_, W, R> { fn reply(&mut self) -> std::io::Result { let start = Instant::now(); loop { - if let Some(line) = self.lines.next()? { + if let Some(line) = self.lines.next_line()? { match final_code(&line) { Some(BEGIN) => self.begun = true, Some(code @ (END | CANCEL | PAUSE)) => self.event = Some(code), @@ -425,7 +369,7 @@ impl Conversation<'_, W, R> { Some(t) if t.elapsed() > limit => return Err(std::io::Error::new(ErrorKind::TimedOut, "the sentence didn't end")), _ => {} } - if let Some(line) = self.lines.next()? { + if let Some(line) = self.lines.next_line()? { match final_code(&line) { Some(BEGIN) => { began.get_or_insert_with(Instant::now); @@ -444,7 +388,7 @@ impl Conversation<'_, W, R> { if (self.changed)() { return Err(moved_on()); } - self.lines.next()?; + self.lines.next_line()?; } Ok(()) } @@ -474,7 +418,7 @@ impl Conversation<'_, W, R> { self.event = None; self.begun = false; ok(self.command("SPEAK")?)?; - self.w.write_all(message_data(req.text).as_bytes())?; + self.w.write_all(message_data(req.text, MAX_MESSAGE_BYTES)?.as_bytes())?; ok(self.reply()?)?; match self.fate(limit)? { Fate::End => return Ok(Outcome::Done), @@ -520,6 +464,7 @@ pub(super) fn converse(stream: &Stream, req: &Request<'_>, changed: &dyn Fn() -> #[cfg(test)] mod tests { use super::*; + use craft_ssip::MAX_LINE; use std::io::{BufRead, BufReader}; #[test] @@ -549,11 +494,11 @@ mod tests { #[test] fn document_text_is_always_message_data() { // `spd-say -e` would run this line as an SSIP command; here it's spoken text. - assert_eq!(message_data("!-!SET SELF RATE 50"), "!-!SET SELF RATE 50\r\n.\r\n"); + assert_eq!(message_data("!-!SET SELF RATE 50", 64).unwrap(), "!-!SET SELF RATE 50\r\n.\r\n"); // A line of a single `.` would end the message early, and a line break would start a // new line that could be one. - assert_eq!(message_data(".\r\nQUIT"), ".. QUIT\r\n.\r\n"); - assert_eq!(message_data("a\n.\nb"), "a . b\r\n.\r\n"); + assert_eq!(message_data(".\r\nQUIT", 64).unwrap(), ".. QUIT\r\n.\r\n"); + assert_eq!(message_data("a\n.\nb", 64).unwrap(), "a . b\r\n.\r\n"); assert_eq!(final_code("225 OK MESSAGE QUEUED"), Some(225)); assert_eq!(final_code("225-17"), None); assert_eq!(final_code("x"), None); @@ -582,11 +527,11 @@ mod tests { fn a_character_split_by_a_read_timeout_stays_whole() { // `é` is C3 A9; the read times out (the empty read) between its two bytes. let mut lines = Lines::new(Reads(vec![b"249-Caf\xC3".to_vec(), Vec::new(), b"\xA9\tfr\tnone\r\n702 END\r\n".to_vec()].into())); - assert_eq!(lines.next().unwrap(), None, "half a line"); - assert_eq!(lines.next().unwrap(), None, "the timeout"); - assert_eq!(lines.next().unwrap().as_deref(), Some("249-Café\tfr\tnone")); - assert_eq!(lines.next().unwrap().as_deref(), Some("702 END")); - assert_eq!(lines.next().unwrap(), None); + assert_eq!(lines.next_line().unwrap(), None, "half a line"); + assert_eq!(lines.next_line().unwrap(), None, "the timeout"); + assert_eq!(lines.next_line().unwrap().as_deref(), Some("249-Café\tfr\tnone")); + assert_eq!(lines.next_line().unwrap().as_deref(), Some("702 END")); + assert_eq!(lines.next_line().unwrap(), None); } #[test] @@ -597,14 +542,13 @@ mod tests { let err = loop { calls += 1; assert!(calls < 100, "never gave up"); - match lines.next() { + match lines.next_line() { Ok(None) => {} Ok(Some(l)) => panic!("{l}"), Err(e) => break e, } }; assert_eq!(err.kind(), ErrorKind::InvalidData); - assert!(lines.pending.len() <= MAX_LINE + 512); } #[test] @@ -612,10 +556,61 @@ mod tests { // One byte per read and never a line end: every call returns, so the caller can look at // its deadline and at whether reading moved on. let mut lines = Lines::new(Reads(vec![b"2".to_vec(), b"0".to_vec(), b"0".to_vec(), b" OK\r\n".to_vec()].into())); - assert_eq!(lines.next().unwrap(), None); - assert_eq!(lines.next().unwrap(), None); - assert_eq!(lines.next().unwrap(), None); - assert_eq!(lines.next().unwrap().as_deref(), Some("200 OK")); + assert_eq!(lines.next_line().unwrap(), None); + assert_eq!(lines.next_line().unwrap(), None); + assert_eq!(lines.next_line().unwrap(), None); + assert_eq!(lines.next_line().unwrap().as_deref(), Some("200 OK")); + } + + /// The sentence encoder this module had before it moved to `craft-ssip`, kept as the oracle. + fn old_message_data(text: &str) -> String { + let line: String = text.chars().map(|c| if c == '\r' || c == '\n' { ' ' } else { c }).collect(); + let dot = if line.starts_with('.') { "." } else { "" }; + format!("{dot}{line}\r\n.\r\n") + } + + #[test] + fn shared_message_data_matches_the_old_encoder() { + let near_cap = "é".repeat(super::super::MAX_UTTERANCE); + let at_cap = "𝄞".repeat(super::super::MAX_UTTERANCE); + assert_eq!(at_cap.len(), MAX_MESSAGE_BYTES, "the cap fits the worst case"); + for text in ["", ".", "..x", "a\r\nb", "\n.", "!-!SET SELF RATE 50", "\r\n.\r\n", near_cap.as_str(), at_cap.as_str()] { + assert_eq!(message_data(text, MAX_MESSAGE_BYTES).unwrap(), old_message_data(text), "{text:?}"); + } + } + + /// A server that answers the first command with `reply` instead of a code. + fn bad_server(mut s: UnixStream, reply: Vec) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + let mut line = String::new(); + let _ = BufReader::new(s.try_clone().unwrap()).read_line(&mut line); + let _ = s.write_all(&reply); + // Hold the socket open so the client sees the reply, not a hang-up. + std::thread::sleep(Duration::from_millis(1500)); + }) + } + + #[test] + fn a_reply_code_with_a_sign_is_not_a_code() { + // `+22` parsed as a number before; now it's no reply at all, so the wait ends in a timeout. + let (client, srv) = UnixStream::pair().unwrap(); + let h = bad_server(srv, b"+22 OK\r\n".to_vec()); + let req = Request { text: "Hello.", rate: 0, lang: None }; + let err = converse(&Stream::Unix(client), &req, &|| false).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + h.join().unwrap(); + } + + #[test] + fn an_overlong_reply_line_is_an_error() { + let (client, srv) = UnixStream::pair().unwrap(); + let mut junk = vec![b'x'; MAX_LINE + 100]; + junk.extend_from_slice(b"\r\n"); + let h = bad_server(srv, junk); + let req = Request { text: "Hello.", rate: 0, lang: None }; + let err = converse(&Stream::Unix(client), &req, &|| false).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidData); + h.join().unwrap(); } /// How the stand-in server ends a message. From c39b0e575564f8447512493670c2210ecae64dc6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 16:19:05 -0500 Subject: [PATCH 90/99] doc: cut legacy encoding tables over to craft-codepage (#6785) * doc: reuse shared legacy codepage tables with parity tests * Regenerate codepage dependency ordering in Cargo lockfile * #778: Cargo.lock: wordcraft-doc depends on craft-codepage after merging main Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Martin Ball Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 1 + crates/doc/Cargo.toml | 1 + crates/doc/src/encoding.rs | 381 +++------------------ crates/doc/src/encoding_legacy_tests.rs | 428 ++++++++++++++++++++++++ 5 files changed, 475 insertions(+), 337 deletions(-) create mode 100644 crates/doc/src/encoding_legacy_tests.rs diff --git a/Cargo.lock b/Cargo.lock index cf443adfc7..5b6389efca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7390,6 +7390,7 @@ name = "wordcraft-doc" version = "0.18.1" dependencies = [ "base64 0.23.1", + "craft-codepage", "craft-zip", "log", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 28d4647791..45d2ca8a2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ wordcraft-mcp = { path = "crates/mcp" } wordcraft-zotero = { path = "crates/zotero" } wordcraft-control-key = { path = "crates/control-key" } wordcraft-ui-egui = { path = "crates/ui-egui" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } # foundation diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 7d640d5a5e..11aeb4df7a 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -16,6 +16,7 @@ workspace = true test-support = ["craft-zip/test-support"] [dependencies] +craft-codepage = { workspace = true } wordcraft-geom = { workspace = true } craft-zip = { workspace = true } base64 = { workspace = true } diff --git a/crates/doc/src/encoding.rs b/crates/doc/src/encoding.rs index d6c7edda8a..658b5d51c5 100644 --- a/crates/doc/src/encoding.rs +++ b/crates/doc/src/encoding.rs @@ -1,345 +1,52 @@ -//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows -//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central -//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), Mac OS Roman -//! (10000, RTF `\mac`), and the East Asian multibyte code pages (932 Shift-JIS, 936 GBK, 949 UHC, -//! 950 Big5), whose bytes decode as runs rather than one at a time. +//! Legacy character decoding delegates to craft-codepage; document fallback policy stays here. +pub use craft_codepage::{ + MAC_ROMAN_CODE_PAGE, MULTIBYTE_CODE_PAGES, OEM_CODE_PAGES, SINGLE_BYTE_CODE_PAGES, cp1252, is_multibyte_code_page, multibyte_encoding_name, + oem_byte, windows_byte, +}; -/// Windows-1252 code points for 0x80..=0x9F. -const CP1252: [u16; 32] = [ - 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, -]; - -/// One Windows-1252 byte as a char. -pub fn cp1252(b: u8) -> char { - if (0x80..0xA0).contains(&b) { - CP1252.get((b - 0x80) as usize).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') - } else { - b as char - } +/// Word's supported single-byte document code pages (symbol-font policy is separate). +pub fn is_byte_code_page(cp: u16) -> bool { + SINGLE_BYTE_CODE_PAGES.contains(&cp) || OEM_CODE_PAGES.contains(&cp) || cp == MAC_ROMAN_CODE_PAGE } - -/// Windows-874 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP874: [u16; 128] = [ - 0x20AC, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0E01, 0x0E02, 0x0E03, - 0x0E04, 0x0E05, 0x0E06, 0x0E07, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, - 0x0E16, 0x0E17, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27, - 0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, - 0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, - 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD, - 0xFFFD, 0xFFFD, -]; - -/// Windows-1250 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1250: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, 0x00A0, 0x02C7, 0x02D8, 0x0141, - 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, - 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, - 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, - 0x011B, 0x00ED, 0x00EE, 0x010F, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, - 0x0163, 0x02D9, -]; - -/// Windows-1251 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1251: [u16; 128] = [ - 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408, - 0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, - 0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, - 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, - 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, - 0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, - 0x044E, 0x044F, -]; - -/// Windows-1253 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1253: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0385, 0x0386, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, - 0x00B6, 0x00B7, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, - 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, - 0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, - 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, - 0x03CE, 0xFFFD, -]; - -/// Windows-1254 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1254: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, - 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, - 0x00DA, 0x00DB, 0x00DC, 0x0130, 0x015E, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, - 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131, - 0x015F, 0x00FF, -]; - -/// Windows-1255 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1255: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x00A1, 0x00A2, 0x00A3, - 0x20AA, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7, - 0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0xFFFD, - 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, - 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E, - 0x200F, 0xFFFD, -]; - -/// Windows-1256 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1256: [u16; 128] = [ - 0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688, 0x06AF, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA, 0x00A0, 0x060C, 0x00A2, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, - 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7, 0x0637, 0x0638, - 0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, - 0x0649, 0x064A, 0x00EE, 0x00EF, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, - 0x200F, 0x06D2, -]; - -/// Windows-1257 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1257: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0x00A8, 0x02C7, 0x00B8, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0x00AF, 0x02DB, 0xFFFD, 0x00A0, 0xFFFD, 0x00A2, 0x00A3, - 0x00A4, 0xFFFD, 0x00A6, 0x00A7, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112, - 0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7, 0x0172, 0x0141, - 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113, 0x010D, 0x00E9, 0x017A, 0x0117, - 0x0123, 0x0137, 0x012B, 0x013C, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C, - 0x017E, 0x02D9, -]; - -/// Windows-1258 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). -const CP1258: [u16; 128] = [ - 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, - 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, - 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, - 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7, - 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7, 0x00D8, 0x00D9, - 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, - 0x0301, 0x00ED, 0x00EE, 0x00EF, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, - 0x20AB, 0x00FF, -]; - -/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at -/// 0xDB (Mac OS 8.5 and later). -const MAC_ROMAN: [u16; 128] = [ - 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB, - 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3, - 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, - 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, - 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, - 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, - 0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, - 0x02DB, 0x02C7, -]; -/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437 -/// mapping file). -const CP437: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, - 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, - 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, - 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode -/// Consortium's CP850 mapping file). -const CP850: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, - 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, - 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518, - 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9, - 0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852 -/// mapping file). -const CP852: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139, - 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, - 0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518, - 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170, - 0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, - 0x25A0, 0x00A0, -]; - -/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866 -/// mapping file). -const CP866: [u16; 128] = [ - 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, - 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, - 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, - 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, - 0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, - 0x25A0, 0x00A0, -]; - -/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737 -/// mapping file). -const CP737: [u16; 128] = [ - 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3, - 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, - 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, - 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388, - 0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857 -/// mapping file). -const CP857: [u16; 128] = [ - 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6, - 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA, - 0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, - 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, - 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518, - 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9, - 0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, - 0x25A0, 0x00A0, -]; - -/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as -/// Windows' Alt+numpad entry produces them rather than the control characters. -const OEM_GLYPHS: [u16; 31] = [ - 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195, - 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, -]; - -/// The OEM code pages [`oem_byte`] decodes. -pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866]; - -/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a -/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL. -pub fn oem_byte(code_page: u16, b: u8) -> char { - let table: &[u16; 128] = match code_page { - 737 => &CP737, - 850 => &CP850, - 852 => &CP852, - 857 => &CP857, - 866 => &CP866, - _ => &CP437, - }; - let u = match b { - 0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(), - 0x7F => Some(0x2302), - 0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(), - _ => Some(u16::from(b)), - }; - u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}') +/// Decode document text without applying OEM control glyphs or symbol-font remapping. +pub fn code_page_byte(cp: u16, b: u8) -> char { + if b >= 0x80 && OEM_CODE_PAGES.contains(&cp) { oem_byte(cp, b) } else { windows_byte(cp, b) } } - -/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included). -pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258]; - -/// Mac OS Roman, RTF's `\mac` character set. -pub const MAC_ROMAN_CODE_PAGE: u16 = 10000; - -/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or -/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252. -pub fn windows_byte(code_page: u16, b: u8) -> char { - let table: &[u16; 128] = match code_page { - 874 => &CP874, - 1250 => &CP1250, - 1251 => &CP1251, - 1253 => &CP1253, - 1254 => &CP1254, - 1255 => &CP1255, - 1256 => &CP1256, - 1257 => &CP1257, - 1258 => &CP1258, - MAC_ROMAN_CODE_PAGE => &MAC_ROMAN, - _ => return cp1252(b), - }; - if b < 0x80 { - return b as char; - } - table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') +/// Whether Word's document import accepts this encoding. +pub fn is_text_code_page(cp: u16) -> bool { + is_byte_code_page(cp) || is_multibyte_code_page(cp) } - -/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an -/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three. -pub fn is_byte_code_page(code_page: u16) -> bool { - SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE -} - -/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80 -/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply). -pub fn code_page_byte(code_page: u16, b: u8) -> char { - if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) } -} - -/// The East Asian multibyte code pages a document format names with `\ansicpg` or a font's `\cpg`: -/// 932 Shift-JIS (Japanese), 936 GBK (Simplified Chinese), 949 UHC (Korean) and 950 Big5 -/// (Traditional Chinese). -pub const MULTIBYTE_CODE_PAGES: [u16; 4] = [932, 936, 949, 950]; - -/// Whether `code_page` is one of the East Asian multibyte code pages ([`MULTIBYTE_CODE_PAGES`]): -/// its bytes decode as a run, a lead byte together with its trail byte. -pub fn is_multibyte_code_page(code_page: u16) -> bool { - multibyte_encoding_name(code_page).is_some() -} - -/// The WHATWG encoding name of an East Asian multibyte code page (see [`MULTIBYTE_CODE_PAGES`]), -/// for `encoding_rs::Encoding::for_label`; `None` for the single-byte code pages, whose bytes -/// decode one at a time, and anything else. -pub fn multibyte_encoding_name(code_page: u16) -> Option<&'static str> { - Some(match code_page { - 932 => "shift_jis", - 936 => "gbk", - 949 => "euc-kr", - 950 => "big5", - _ => return None, - }) -} - -/// Whether a document format can name `code_page` for its text: a single-byte Windows, DOS or Mac -/// one ([`is_byte_code_page`]) or an East Asian multibyte one ([`is_multibyte_code_page`]). -pub fn is_text_code_page(code_page: u16) -> bool { - is_byte_code_page(code_page) || is_multibyte_code_page(code_page) -} - -/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern -/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949, -/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950… `None` for the ANSI and default -/// charsets (the document's code page applies) and symbol fonts. +/// Preserve Word's existing symbol-font selection policy, not the shared symbol extension. pub fn charset_code_page(charset: i32) -> Option { - Some(match charset { - 77 => MAC_ROMAN_CODE_PAGE, - 128 => 932, - 129 => 949, - 134 => 936, - 136 => 950, - 161 => 1253, - 162 => 1254, - 163 => 1258, - 177 => 1255, - 178 => 1256, - 186 => 1257, - 204 => 1251, - 222 => 874, - 238 => 1250, - 254 | 255 => 437, - _ => return None, - }) + if charset == 2 { None } else { craft_codepage::charset_code_page(charset) } +} +#[cfg(test)] +#[allow(dead_code)] +#[path = "encoding_legacy_tests.rs"] +mod legacy; +#[cfg(test)] +mod parity { + use super::*; + #[test] + fn every_supported_byte_and_fallback_matches_original() { + let pages = [0, 42, 437, 737, 850, 852, 857, 866, 874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 10000, 9999, u16::MAX]; + for cp in pages { + for b in 0..=u8::MAX { + assert_eq!(windows_byte(cp, b), legacy::windows_byte(cp, b), "windows {cp}/{b}"); + assert_eq!(oem_byte(cp, b), legacy::oem_byte(cp, b), "oem {cp}/{b}"); + assert_eq!(code_page_byte(cp, b), legacy::code_page_byte(cp, b), "text {cp}/{b}"); + assert_eq!(cp1252(b), legacy::cp1252(b)); + } + } + for cp in 0..=u16::MAX { + assert_eq!(is_byte_code_page(cp), legacy::is_byte_code_page(cp)); + assert_eq!(is_text_code_page(cp), legacy::is_text_code_page(cp)); + assert_eq!(multibyte_encoding_name(cp), legacy::multibyte_encoding_name(cp)); + } + for charset in -1..=256 { + assert_eq!(charset_code_page(charset), legacy::charset_code_page(charset)); + } + } } #[cfg(test)] diff --git a/crates/doc/src/encoding_legacy_tests.rs b/crates/doc/src/encoding_legacy_tests.rs new file mode 100644 index 0000000000..30bef4d745 --- /dev/null +++ b/crates/doc/src/encoding_legacy_tests.rs @@ -0,0 +1,428 @@ +// Frozen pre-cutover implementation, test-only parity oracle. Original authors retained in file history. +//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows +//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central +//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), Mac OS Roman +//! (10000, RTF `\mac`), and the East Asian multibyte code pages (932 Shift-JIS, 936 GBK, 949 UHC, +//! 950 Big5), whose bytes decode as runs rather than one at a time. + +/// Windows-1252 code points for 0x80..=0x9F. +const CP1252: [u16; 32] = [ + 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, +]; + +/// One Windows-1252 byte as a char. +pub fn cp1252(b: u8) -> char { + if (0x80..0xA0).contains(&b) { + CP1252.get((b - 0x80) as usize).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') + } else { + b as char + } +} + +/// Windows-874 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP874: [u16; 128] = [ + 0x20AC, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0E01, 0x0E02, 0x0E03, + 0x0E04, 0x0E05, 0x0E06, 0x0E07, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, + 0x0E16, 0x0E17, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27, + 0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, + 0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, + 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD, + 0xFFFD, 0xFFFD, +]; + +/// Windows-1250 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1250: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, 0x00A0, 0x02C7, 0x02D8, 0x0141, + 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, + 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, + 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, + 0x011B, 0x00ED, 0x00EE, 0x010F, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, + 0x0163, 0x02D9, +]; + +/// Windows-1251 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1251: [u16; 128] = [ + 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408, + 0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, + 0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, + 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, + 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, + 0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, + 0x044E, 0x044F, +]; + +/// Windows-1253 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1253: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0385, 0x0386, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, + 0x00B6, 0x00B7, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, + 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, + 0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, + 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, + 0x03CE, 0xFFFD, +]; + +/// Windows-1254 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1254: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, + 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, + 0x00DA, 0x00DB, 0x00DC, 0x0130, 0x015E, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, + 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131, + 0x015F, 0x00FF, +]; + +/// Windows-1255 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1255: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x00A1, 0x00A2, 0x00A3, + 0x20AA, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7, + 0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0xFFFD, + 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, + 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E, + 0x200F, 0xFFFD, +]; + +/// Windows-1256 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1256: [u16; 128] = [ + 0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688, 0x06AF, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA, 0x00A0, 0x060C, 0x00A2, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, + 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7, 0x0637, 0x0638, + 0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, + 0x0649, 0x064A, 0x00EE, 0x00EF, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, + 0x200F, 0x06D2, +]; + +/// Windows-1257 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1257: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0x00A8, 0x02C7, 0x00B8, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0x00AF, 0x02DB, 0xFFFD, 0x00A0, 0xFFFD, 0x00A2, 0x00A3, + 0x00A4, 0xFFFD, 0x00A6, 0x00A7, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112, + 0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7, 0x0172, 0x0141, + 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113, 0x010D, 0x00E9, 0x017A, 0x0117, + 0x0123, 0x0137, 0x012B, 0x013C, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C, + 0x017E, 0x02D9, +]; + +/// Windows-1258 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned). +const CP1258: [u16; 128] = [ + 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, + 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, + 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7, + 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7, 0x00D8, 0x00D9, + 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, + 0x0301, 0x00ED, 0x00EE, 0x00EF, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, + 0x20AB, 0x00FF, +]; + +/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at +/// 0xDB (Mac OS 8.5 and later). +const MAC_ROMAN: [u16; 128] = [ + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB, + 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3, + 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, + 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, + 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, + 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, + 0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, + 0x02DB, 0x02C7, +]; +/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437 +/// mapping file). +const CP437: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, + 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, + 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, + 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode +/// Consortium's CP850 mapping file). +const CP850: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, + 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, + 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518, + 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9, + 0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852 +/// mapping file). +const CP852: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139, + 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, + 0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518, + 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170, + 0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, + 0x25A0, 0x00A0, +]; + +/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866 +/// mapping file). +const CP866: [u16; 128] = [ + 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, + 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, + 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, + 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, + 0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, + 0x25A0, 0x00A0, +]; + +/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737 +/// mapping file). +const CP737: [u16; 128] = [ + 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3, + 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, + 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, + 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388, + 0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857 +/// mapping file). +const CP857: [u16; 128] = [ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6, + 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA, + 0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, + 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518, + 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9, + 0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, + 0x25A0, 0x00A0, +]; + +/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as +/// Windows' Alt+numpad entry produces them rather than the control characters. +const OEM_GLYPHS: [u16; 31] = [ + 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195, + 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, +]; + +/// The OEM code pages [`oem_byte`] decodes. +pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866]; + +/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a +/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL. +pub fn oem_byte(code_page: u16, b: u8) -> char { + let table: &[u16; 128] = match code_page { + 737 => &CP737, + 850 => &CP850, + 852 => &CP852, + 857 => &CP857, + 866 => &CP866, + _ => &CP437, + }; + let u = match b { + 0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(), + 0x7F => Some(0x2302), + 0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(), + _ => Some(u16::from(b)), + }; + u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}') +} + +/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included). +pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258]; + +/// Mac OS Roman, RTF's `\mac` character set. +pub const MAC_ROMAN_CODE_PAGE: u16 = 10000; + +/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or +/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252. +pub fn windows_byte(code_page: u16, b: u8) -> char { + let table: &[u16; 128] = match code_page { + 874 => &CP874, + 1250 => &CP1250, + 1251 => &CP1251, + 1253 => &CP1253, + 1254 => &CP1254, + 1255 => &CP1255, + 1256 => &CP1256, + 1257 => &CP1257, + 1258 => &CP1258, + MAC_ROMAN_CODE_PAGE => &MAC_ROMAN, + _ => return cp1252(b), + }; + if b < 0x80 { + return b as char; + } + table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}') +} + +/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an +/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three. +pub fn is_byte_code_page(code_page: u16) -> bool { + SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE +} + +/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80 +/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply). +pub fn code_page_byte(code_page: u16, b: u8) -> char { + if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) } +} + +/// The East Asian multibyte code pages a document format names with `\ansicpg` or a font's `\cpg`: +/// 932 Shift-JIS (Japanese), 936 GBK (Simplified Chinese), 949 UHC (Korean) and 950 Big5 +/// (Traditional Chinese). +pub const MULTIBYTE_CODE_PAGES: [u16; 4] = [932, 936, 949, 950]; + +/// Whether `code_page` is one of the East Asian multibyte code pages ([`MULTIBYTE_CODE_PAGES`]): +/// its bytes decode as a run, a lead byte together with its trail byte. +pub fn is_multibyte_code_page(code_page: u16) -> bool { + multibyte_encoding_name(code_page).is_some() +} + +/// The WHATWG encoding name of an East Asian multibyte code page (see [`MULTIBYTE_CODE_PAGES`]), +/// for `encoding_rs::Encoding::for_label`; `None` for the single-byte code pages, whose bytes +/// decode one at a time, and anything else. +pub fn multibyte_encoding_name(code_page: u16) -> Option<&'static str> { + Some(match code_page { + 932 => "shift_jis", + 936 => "gbk", + 949 => "euc-kr", + 950 => "big5", + _ => return None, + }) +} + +/// Whether a document format can name `code_page` for its text: a single-byte Windows, DOS or Mac +/// one ([`is_byte_code_page`]) or an East Asian multibyte one ([`is_multibyte_code_page`]). +pub fn is_text_code_page(code_page: u16) -> bool { + is_byte_code_page(code_page) || is_multibyte_code_page(code_page) +} + +/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern +/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949, +/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950… `None` for the ANSI and default +/// charsets (the document's code page applies) and symbol fonts. +pub fn charset_code_page(charset: i32) -> Option { + Some(match charset { + 77 => MAC_ROMAN_CODE_PAGE, + 128 => 932, + 129 => 949, + 134 => 936, + 136 => 950, + 161 => 1253, + 162 => 1254, + 163 => 1258, + 177 => 1255, + 178 => 1256, + 186 => 1257, + 204 => 1251, + 222 => 874, + 238 => 1250, + 254 | 255 => 437, + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_byte_code_pages() { + let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| windows_byte(cp, b)).collect::(); + assert_eq!(decode(1251, &[0xD1, 0xF7, 0xE5, 0xF2, 0x20, 0xB9]), "Счет №"); + assert_eq!(decode(1251, &[0xA8, 0xB8]), "Ёё"); + assert_eq!(decode(1250, &[0xA3, 0xF3, 0x9F]), "Łóź"); + assert_eq!(decode(1253, &[0xC1, 0xE2]), "Αβ"); + assert_eq!(decode(1252, &[0x80, 0xE9]), "€é"); + assert_eq!(decode(9999, &[0xE9]), "é"); + // Mac OS Roman (#1653): accents, the euro sign at 0xDB, typographic quotes. + assert_eq!(decode(10000, &[0x80, 0x8E, 0xDB, 0xF1, 0xF2, 0xF3, 0xD2, 0xD3, 0x41]), "Äé€ÒÚÛ“”A"); + assert_eq!(charset_code_page(77), Some(10000)); + assert_eq!(charset_code_page(254), Some(437)); + assert_eq!(charset_code_page(255), Some(437)); + assert_eq!(charset_code_page(204), Some(1251)); + assert_eq!(charset_code_page(0), None); + for cp in SINGLE_BYTE_CODE_PAGES { + for b in 0..=255u8 { + let _ = windows_byte(cp, b); + } + } + } + + #[test] + fn windows_1255_holam_haser_for_vav() { + assert_eq!(windows_byte(1255, 0xCA), '\u{05BA}'); + } + + /// #1653: one decoder for document text in any code page RTF names: Windows, DOS or Mac. + #[test] + fn document_text_in_windows_dos_and_mac_code_pages() { + let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| code_page_byte(cp, b)).collect::(); + assert_eq!(decode(437, &[0x82, 0xA0, 0x41, 0x01]), "éáA\u{1}", "DOS text; ASCII stays ASCII"); + assert_eq!(decode(850, &[0x9D, 0xE9]), "ØÚ"); + assert_eq!(decode(10000, &[0x8E]), "é"); + assert_eq!(decode(1251, &[0xC4]), "Д"); + for cp in [437, 850, 866, 1250, 1252, 10000] { + assert!(is_byte_code_page(cp), "{cp}"); + } + assert!(!is_byte_code_page(932) && !is_byte_code_page(0) && !SINGLE_BYTE_CODE_PAGES.contains(&10000)); + } + + /// #1653: the East Asian charsets and code pages RTF names are multibyte: their bytes decode + /// as runs (a lead byte and its trail byte together), not one at a time. + #[test] + fn east_asian_code_pages_are_multibyte() { + assert_eq!(charset_code_page(128), Some(932), "Japanese"); + assert_eq!(charset_code_page(129), Some(949), "Korean"); + assert_eq!(charset_code_page(134), Some(936), "Simplified Chinese"); + assert_eq!(charset_code_page(136), Some(950), "Traditional Chinese"); + assert_eq!(charset_code_page(255), Some(437), "OEM is single-byte"); + assert_eq!(MULTIBYTE_CODE_PAGES, [932, 936, 949, 950]); + for cp in MULTIBYTE_CODE_PAGES { + assert!(is_multibyte_code_page(cp) && is_text_code_page(cp), "{cp}"); + assert!(!is_byte_code_page(cp) && !SINGLE_BYTE_CODE_PAGES.contains(&cp), "{cp}"); + assert!(multibyte_encoding_name(cp).is_some(), "{cp}"); + } + assert!(is_text_code_page(1251) && is_text_code_page(437) && is_text_code_page(10000)); + assert!(!is_text_code_page(0) && !is_text_code_page(9999)); + } + + #[test] + fn oem_code_pages() { + let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| oem_byte(cp, b)).collect::(); + assert_eq!(decode(437, &[0x82, 0xE9, 0x01, 0x7F]), "éΘ☺⌂"); + assert_eq!(decode(850, &[0x9B, 0xE9]), "øÚ"); + assert_eq!(decode(852, &[0xA5, 0x88, 0xBE, 0xA9]), "ąłżę"); + assert_eq!(decode(866, &[0x8F, 0xE0, 0xA8, 0xA2, 0xA5, 0xE2, 0xF0, 0xFC]), "ПриветЁ№"); + assert_eq!(decode(737, &[0x80, 0x99, 0xE0]), "Αβω"); + assert_eq!(decode(857, &[0x8D, 0x98, 0xA6, 0x9F]), "ıİĞş"); + assert_eq!(oem_byte(857, 0xD5), '\u{FFFD}', "unassigned in 857"); + assert_eq!(decode(9999, &[0xE9]), "Θ", "unknown pages read as 437"); + for cp in OEM_CODE_PAGES { + for b in 0..=255u8 { + let _ = oem_byte(cp, b); + } + } + } +} From dfd51a3cdc073b6dad10e7685cc7101aa9299ccb Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:19:16 +0100 Subject: [PATCH 91/99] #778: land the picture-probe and MCP cutovers (#6955, #6956) on main (#6960) * #778: take craft-libs integration/wordcraft-778 at beeea924 Every craft-libs git dependency (workspace, ui-egui, wordcraft, wordcraft-web, krilla patch) moves from 453b0da782 to beeea92451 (craft-libs main 0649a07aa plus open PRs #2061-#2064). Cargo.lock: only craft-libs sources move, plus windows-sys edge changes inside craft-libs crates; no crates.io versions change. Co-Authored-By: Claude Opus 5.5 * #778: docx stacking-order test follows the shared reader's one-more z craft-libs 5f453efa9 (craft-docx: a relativeHeight of 0 stays the lowest stacking order) reads Float::z as one more than the file's relativeHeight and writes stored orders one less, so a file's 0 is no longer "none". The test expected the old values; relative order and the round trip are unchanged. Co-Authored-By: Claude Opus 5.5 * #778: take craft-libs integration/wordcraft-778 at 24a15211 Co-Authored-By: Claude Opus 5.5 * deps: pin craft-libs to the merged shared cutover prerequisites * #778: pin craft-libs main at 93dac78c (with #2061-#2064) Co-Authored-By: Claude Opus 5.5 * #778: picture probes use craft-image-codecs (DIB wrapping, JPEG budget, PNG/WebP) (#6955) * #778: picture: wrap clipboard DIBs with craft-image-codecs' bmp_probe probe_dib's local dib_to_bmp and dib_layout are replaced by craft_image_codecs::bmp_probe::{dib_to_bmp, dib_layout}. The shared copies are the same code; the only change is that they reserve their output fallibly. A failed reservation in dib_to_bmp (the BMP's bytes can't be allocated) is Refusal::TooLarge with the size the DIB header declares, the refusal a picture too large to hold already gets; dib_layout leaves the DIB unchanged then. The local dib_to_bmp name stays as a thin wrapper returning Result<_, Refusal>. The old code is kept in the tests as an oracle: wrapping and layout are byte-equal on thousands of crafted DIBs (core, info, V4, V5 headers, bit fields, alpha with BI_RGB, every truncation), and probe_dib agrees. Co-Authored-By: Claude Opus 5.5 * #778: picture: budget JPEG coefficients with craft-image-codecs probe's JPEG held-coefficient estimate (jpeg_coefficients, frame_coefficients, worst_coefficients) is replaced by craft_image_codecs::jpeg_worst_case_coefficients, which returns the larger of that same estimate and the shared held_coefficients. So the charge can only grow, never shrink. It grows for: a SOF0/SOF1 8-bit first frame whose first scan has fewer components than the frame (the decoder holds the coefficients until the other scans); and a first-frame SOF2 with sampling factors above 4 (the old rule clamped them to 4). A real baseline JPEG with all components in its first scan is charged nothing, as before. With the 512 MiB budget, a 4:4:4 non-interleaved baseline JPEG is now refused from about 59.6 Mpx instead of 67 Mpx; 4:2:0 and 4:2:2 stay under the RGBA8 conversion and are unchanged. The old code is kept in the tests as an oracle: the new charge is never less (crafted headers, every prefix, random damage), equal where the shared rule adds nothing, and one test pins a case where it grows. Co-Authored-By: Claude Opus 5.5 * #778: picture: read PNG and WebP probes with craft-image-codecs The local png_chunks header read is replaced by craft_image_codecs::png_probe::pixel_model, and the VP8X alpha check in probe by webp_probe::has_alpha (an error reads as no alpha, as non-RIFF input did). PNG: for every valid colour type and bit depth, with and without tRNS and an iCCP chunk, the size, bytes a pixel and alpha are what the old read gave (PixelModel::bytes_per_pixel is channels * 2 for 16 bits, else channels, with a palette as RGB and tRNS adding a channel to grey, RGB and palette). pixel_model is stricter, so these are now refused (probe: Refusal::Broken, dimensions: None) where the old read measured them: an invalid colour type and bit depth pair, a zero or past-i32::MAX side, and more than 65,536 chunks before the image data. None is a valid PNG. WebP: a bare lossless (VP8L) picture whose header sets alpha_is_used now reports alpha; the old rule only knew the VP8X flag. The old PNG read and WebP rule are kept in the tests as oracles. Co-Authored-By: Claude Opus 5.5 * #778: picture tests follow craft-image-codecs' DIB fixes The shared dib_to_bmp no longer adds 12 appended mask bytes to the pixel offset of 52/56-byte BI_BITFIELDS headers, and dib_layout treats the bytes after the header as a mask copy only when the payload is longer than the pixel rows need. The differential test excludes exactly those inputs by named predicate, asserts the new output for them, and stays byte-equal elsewhere. Co-Authored-By: Claude Opus 5.5 * #778: dib_header_dims uses the shared fallible dib_to_bmp Calls the shared probe directly so a failed allocation cannot recurse through the refusal wrapper. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 * #778: WordCraft's MCP stdio server runs on craft-mcp-server (#6956) The JSON-RPC framing, bounded line reading, initialize, ping, tools/* and resources/* now come from craft_mcp_server::Server; WordCraft keeps its tools, resources, instructions and backends. The old server.rs stays as a test-only oracle for a differential test. click/key schemas list every argument the app accepts, since the shared check refuses unlisted ones. Co-authored-by: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Dylan M. Taylor --- Cargo.lock | 9 + Cargo.toml | 1 + crates/geom/src/picture.rs | 834 +++++++++++++++++++++------ crates/mcp/Cargo.toml | 1 + crates/mcp/src/server.rs | 193 ++----- crates/mcp/src/tests.rs | 10 +- crates/mcp/src/tests/differential.rs | 452 +++++++++++++++ crates/mcp/src/tests/oracle.rs | 174 ++++++ crates/mcp/src/tools.rs | 10 +- docs/mcp.md | 13 +- 10 files changed, 1374 insertions(+), 323 deletions(-) create mode 100644 crates/mcp/src/tests/differential.rs create mode 100644 crates/mcp/src/tests/oracle.rs diff --git a/Cargo.lock b/Cargo.lock index 5b6389efca..a720a0bc46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1282,6 +1282,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=93dac78c93a7f1fd66e2022edeb089233b1dc45a#93dac78c93a7f1fd66e2022edeb089233b1dc45a" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -7547,6 +7555,7 @@ dependencies = [ name = "wordcraft-mcp" version = "0.18.1" dependencies = [ + "craft-mcp-server", "log", "serde_json", "wordcraft-control-key", diff --git a/Cargo.toml b/Cargo.toml index 45d2ca8a2f..e9a7630354 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,6 +76,7 @@ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93 craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", features = ["egui"] } craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["doc"] } craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" } diff --git a/crates/geom/src/picture.rs b/crates/geom/src/picture.rs index 67de79e076..52a43dddeb 100644 --- a/crates/geom/src/picture.rs +++ b/crates/geom/src/picture.rs @@ -9,7 +9,8 @@ use std::borrow::Cow; use craft_image_codecs::{ ChannelLayout, CodecError, DecodeOptions, EncodeOptions, Format as CodecFormat, Image as CodecImage, Limits as CodecLimits, RasterColorType, - SampleType, decode_as_with, detect, encode as codec_encode, inspect_raster, probe_size, + SampleType, bmp_probe, decode_as_with, detect, encode as codec_encode, inspect_raster, jpeg_worst_case_coefficients, png_probe, probe_size, + webp_probe, }; use image::{DynamicImage, ImageBuffer, ImageFormat}; @@ -147,7 +148,7 @@ pub fn encode_jpeg(rgb: &[u8], width: u32, height: u32, quality: u8) -> Result Option<(u32, u32)> { let format = detect(bytes)?; match format { - CodecFormat::Png => png_chunks(bytes).map(|(w, h, _, _)| (w, h)), + CodecFormat::Png => png_probe::pixel_model(bytes).ok().map(|m| (m.width, m.height)), CodecFormat::Jpeg | CodecFormat::Tiff | CodecFormat::Gif | CodecFormat::Bmp => { inspect_raster(bytes).ok().flatten().map(|i| (i.width, i.height)) } @@ -197,7 +198,7 @@ pub fn probe(bytes: &[u8]) -> Result, Refusal> { let format = from_codec_format(codec_fmt).ok_or(Refusal::NotAPicture)?; let held = match format { ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP | ImageFormat::Bmp => 0, - ImageFormat::Jpeg => jpeg_coefficients(bytes), + ImageFormat::Jpeg => jpeg_worst_case_coefficients(bytes), ImageFormat::Tiff => { if !tiff_compression(bytes).is_some_and(|c| TIFF_COMPRESSIONS.contains(&c)) { return Err(Refusal::Unsupported("TIFF pictures with JPEG or an unknown compression can't be read")); @@ -207,14 +208,17 @@ pub fn probe(bytes: &[u8]) -> Result, Refusal> { _ => return Err(Refusal::NotAPicture), }; if format == ImageFormat::Png { - let (width, height, native, alpha) = png_chunks(bytes).ok_or_else(|| Refusal::Broken("its PNG header can't be read".into()))?; + // Measured from `IHDR` and the chunk headers: an ICC profile (`iCCP`) isn't inflated, though the + // decoder's own header read inflates one up to its 512 MiB limit. + let m = png_probe::pixel_model(bytes).map_err(|_| Refusal::Broken("its PNG header can't be read".into()))?; + let (width, height, native, alpha) = (m.width, m.height, u64::from(m.bytes_per_pixel()), m.has_alpha()); let (width, height, peak) = sized(width, height, native, 0)?; return Ok(Probe { bytes: Cow::Borrowed(bytes), format, width, height, peak, alpha }); } if format == ImageFormat::WebP { let (width, height) = probe_size(bytes).map_err(broken)?; let (width, height, peak) = sized(width, height, 4, 0)?; - let alpha = bytes.get(12..16) == Some(b"VP8X") && bytes.get(20).is_some_and(|b| b & 0x10 != 0); + let alpha = webp_probe::has_alpha(bytes).unwrap_or(false); return Ok(Probe { bytes: Cow::Borrowed(bytes), format, width, height, peak, alpha }); } let info = inspect_raster(bytes).map_err(broken)?.ok_or_else(|| Refusal::Broken("its header can't be read".into()))?; @@ -225,84 +229,26 @@ pub fn probe(bytes: &[u8]) -> Result, Refusal> { Ok(Probe { bytes: Cow::Borrowed(bytes), format, width, height, peak, alpha }) } -/// A PNG's width, height, the bytes a pixel its decoder gives (samples under 8 bits widened to 8, -/// a palette to RGB, `tRNS` to an alpha channel) and whether it has transparency, from `IHDR` and -/// the chunk headers before the image data. The decoder's own header read inflates an ICC profile -/// (`iCCP`) up to its 512 MiB default limit, for a picture that may only be measured. -fn png_chunks(bytes: &[u8]) -> Option<(u32, u32, u64, bool)> { - let be = |at: usize| bytes.get(at..at.checked_add(4)?).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_be_bytes); - // The 8-byte signature, then IHDR: length, type, width, height, bit depth, colour type. - if bytes.get(12..16) != Some(b"IHDR".as_slice()) { - return None; - } - let (width, height) = (be(16)?, be(20)?); - let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?); - let mut trns = false; - let mut at = 8usize; - loop { - let len = usize::try_from(be(at)?).ok()?; - match bytes.get(at.checked_add(4)?..at.checked_add(8)?)? { - b"IDAT" => break, - b"IEND" => return None, - b"tRNS" => trns = true, - _ => {} - } - at = at.checked_add(12)?.checked_add(len)?; - } - let (channels, alpha) = match color { - 0 => (1 + u64::from(trns), trns), - 2 | 3 => (3 + u64::from(trns), trns), - 4 => (2, true), - 6 => (4, true), - _ => return None, - }; - Some((width, height, channels * if depth == 16 { 2 } else { 1 }, alpha)) -} - -/// Prepend a 14-byte `BITMAPFILEHEADER` to a normalized DIB so `craft-image-codecs` can inspect and decode it as BMP. -fn dib_to_bmp(dib: &[u8]) -> Vec { - let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); - let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - let bi_size = u32_at(0).unwrap_or(40); - let offset = if bi_size == 12 { - let bpp = u16_at(10).unwrap_or(24); - let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 }; - 14 + bi_size + palette - } else { - let bpp = u16_at(14).unwrap_or(24); - let compression = u32_at(16).unwrap_or(0); - let clr_used = u32_at(32).unwrap_or(0); - let palette_entries = if clr_used != 0 { - clr_used - } else if bpp <= 8 { - 1u32 << bpp - } else { - 0 - }; - let masks = if compression == 3 && bi_size >= 40 { 12 } else { 0 }; - 14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4)) - }; - let file_size = u32::try_from(14 + dib.len()).unwrap_or(u32::MAX); - let mut bmp = Vec::with_capacity(14 + dib.len()); - bmp.extend_from_slice(b"BM"); - bmp.extend_from_slice(&file_size.to_le_bytes()); - bmp.extend_from_slice(&[0u8; 4]); - bmp.extend_from_slice(&offset.to_le_bytes()); - bmp.extend_from_slice(dib); - bmp +/// [`bmp_probe::dib_to_bmp`], its failure (the BMP's bytes can't be allocated) as the refusal a +/// picture too large to hold gets, with the size its header declares (0 × 0 when it can't be read). +fn dib_to_bmp(dib: &[u8]) -> Result, Refusal> { + bmp_probe::dib_to_bmp(dib).map_err(|_| { + let (width, height) = dib_header_dims(dib).unwrap_or((0, 0)); + Refusal::TooLarge { width, height } + }) } /// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds /// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see -/// [`dib_layout`]). +/// [`bmp_probe::dib_layout`]). /// /// # Errors /// /// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic /// overflow. pub fn probe_dib(dib: Vec) -> Result, Refusal> { - let dib = dib_layout(dib); - let bmp = dib_to_bmp(&dib); + let dib = bmp_probe::dib_layout(dib); + let bmp = dib_to_bmp(&dib)?; let (width, height, native, alpha) = match inspect_raster(&bmp) { Ok(Some(info)) => { let native = u64::from(info.channels.max(1)) * u64::from(info.bits_per_sample.max(8) / 8); @@ -329,7 +275,7 @@ fn dib_header_dims(dib: &[u8]) -> Option<(u32, u32)> { } // Only the first 12 header bytes are read, so only they are wrapped: this runs for DIBs too // big to decode, which must not be copied whole. - craft_image_codecs::bmp_probe::dimensions(&dib_to_bmp(dib.get(..12).unwrap_or(dib))) + craft_image_codecs::bmp_probe::dimensions(&bmp_probe::dib_to_bmp(dib.get(..12).unwrap_or(dib)).ok()?) } /// A `width` × `height` picture of `native` bytes a pixel, with its peak (see [`peak_bytes`]). @@ -474,64 +420,6 @@ fn peak_bytes(width: u32, height: u32, native: u64, held: u64) -> Option { Some(decoding.max(converting).max(premultiplying)) } -/// Bytes of DCT coefficients a progressive JPEG's decoder keeps for the whole picture while it -/// reads the scans: zune-jpeg holds an `i16` per coefficient of every component, in whole MCUs. -/// 0 for a baseline JPEG, decoded an MCU row at a time. Each frame header before the first scan -/// counts and the largest wins; headers this can't follow are charged as the costliest frame. -fn jpeg_coefficients(bytes: &[u8]) -> u64 { - let mut at = 2; - let mut most = 0u64; - loop { - if bytes.get(at) != Some(&0xFF) { - return worst_coefficients(bytes).max(most); - } - while bytes.get(at) == Some(&0xFF) { - at += 1; - } - let Some(&code) = bytes.get(at) else { return worst_coefficients(bytes).max(most) }; - at += 1; - match code { - // Markers without a length: start of image, TEM, restarts. - 0xD8 | 0x01 | 0xD0..=0xD7 => continue, - // End of image, start of scan: every frame header is behind. - 0xD9 | 0xDA => return most, - _ => {} - } - let len = match (bytes.get(at), bytes.get(at + 1)) { - (Some(&hi), Some(&lo)) => usize::from(u16::from_be_bytes([hi, lo])), - _ => 0, - }; - let Some(segment) = bytes.get(at + 2..at + len).filter(|_| len >= 2) else { return worst_coefficients(bytes).max(most) }; - // SOF2, SOF6, SOF10 and SOF14 are the progressive frames. - if matches!(code, 0xC2 | 0xC6 | 0xCA | 0xCE) { - let Some(held) = frame_coefficients(segment) else { return worst_coefficients(bytes).max(most) }; - most = most.max(held); - } - at += len; - } -} - -/// [`jpeg_coefficients`] of one progressive frame header (after its length): the components' -/// blocks per MCU (horizontal × vertical sampling) times the MCUs that cover the picture. -fn frame_coefficients(sof: &[u8]) -> Option { - let height = u64::from(u16::from_be_bytes([*sof.get(1)?, *sof.get(2)?])); - let width = u64::from(u16::from_be_bytes([*sof.get(3)?, *sof.get(4)?])); - let n = usize::from(*sof.get(5)?); - let sampling: Vec<(u64, u64)> = - sof.get(6..6 + 3 * n)?.as_chunks::<3>().0.iter().map(|&[_, s, _]| (u64::from(s >> 4).clamp(1, 4), u64::from(s & 15).clamp(1, 4))).collect(); - let (h_max, v_max) = sampling.iter().fold((1, 1), |(h, v), &(a, b)| (h.max(a), v.max(b))); - let mcus = width.div_ceil(8 * h_max).checked_mul(height.div_ceil(8 * v_max))?; - sampling.iter().try_fold(0u64, |sum, &(h, v)| sum.checked_add(mcus.checked_mul(2 * 64 * h * v)?)) -} - -/// The coefficients of the costliest progressive frame of the size the image crate reads from -/// `bytes`: four components, each sampled 4 × 4, in MCUs of 32 pixels a side. -fn worst_coefficients(bytes: &[u8]) -> u64 { - let Some((w, h)) = dimensions(bytes) else { return 0 }; - let mcus = u64::from(w).div_ceil(32) * u64::from(h).div_ceil(32); - mcus.saturating_mul(2 * 64 * 16 * 4) -} - /// The compression of a classic TIFF's first image (the one the image crate decodes): 1 when the /// tag is missing. None when the header can't be read, or when the tag appears more than once: /// the decoder keeps the last copy, so a harmless first one must not hide a JPEG one after it. @@ -539,37 +427,6 @@ fn tiff_compression(bytes: &[u8]) -> Option { craft_tiff::probe::first_image_compression(bytes) } -/// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask -/// is set but whose compression says `BI_RGB` is marked `BI_BITFIELDS` (with the usual colour -/// masks when it gives none), so its alpha is kept as Windows programs mean it; arboard makes the -/// same change. Bit fields then need the colour masks after the header too, where Windows puts a -/// copy and the decoder skips them; a DIB without that copy (arboard writes one) gets it. -fn dib_layout(mut dib: Vec) -> Vec { - let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib }; - let put = |d: &mut Vec, at: usize, v: u32| { - if let Some(b) = d.get_mut(at..at + 4) { - b.copy_from_slice(&v.to_le_bytes()); - } - }; - if dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000) { - put(&mut dib, 16, 3); - if (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)) { - put(&mut dib, 40, 0x00FF_0000); - put(&mut dib, 44, 0x0000_FF00); - put(&mut dib, 48, 0x0000_00FF); - } - } - if u32_at(&dib, 16) == Some(3) - && size <= dib.len() - && let Some(masks) = dib.get(40..52).map(<[u8]>::to_vec) - && dib.get(size..size + 12) != Some(masks.as_slice()) - { - dib.splice(size..size, masks); - } - dib -} - #[cfg(test)] mod tests { use super::*; @@ -768,33 +625,120 @@ mod tests { assert_eq!(probe(&baseline).unwrap().peak_bytes(), 64 * 64 * 8); } + /// A JPEG's headers up to the first scan: frames `(marker, precision, w, h, components)`, then + /// a scan of `scan` components (none: no scan, the end of the image). + fn jpeg_headers(frames: &[(u8, u8, u16, u16, &[u8])], scan: Option) -> Vec { + let mut b = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0]; + for &(marker, prec, w, h, comps) in frames { + b.extend_from_slice(&[0xFF, marker]); + #[expect(clippy::cast_possible_truncation, reason = "Fixtures hold at most four components.")] + let (n, len) = ((comps.len() / 3) as u8, (8 + comps.len()) as u16); + b.extend(len.to_be_bytes()); + b.push(prec); + b.extend(h.to_be_bytes()); + b.extend(w.to_be_bytes()); + b.push(n); + b.extend_from_slice(comps); + } + if let Some(n) = scan { + b.extend_from_slice(&[0xFF, 0xDA, 0, 6 + 2 * n, n]); + (1..=n).for_each(|c| b.extend_from_slice(&[c, 0])); + b.extend_from_slice(&[0, 63, 0]); + } + b.extend_from_slice(&[0xFF, 0xD9]); + b + } + + const C444: &[u8] = &[1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0]; + const C420: &[u8] = &[1, 0x22, 0, 2, 0x11, 0, 3, 0x11, 0]; + const GREY: &[u8] = &[1, 0x11, 0]; + + /// The JPEG budget before the cutover to the shared rule, as the oracle: the shared charge is + /// never less, and is equal wherever it adds nothing. #[test] - fn coefficients_follow_sampling_and_mcu_padding() { - // P, height, width, components (id, sampling, table). - let sof = |w: u16, h: u16, comps: &[u8]| { - let mut s = vec![8]; - s.extend(h.to_be_bytes()); - s.extend(w.to_be_bytes()); - #[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")] - s.push((comps.len() / 3) as u8); - s.extend(comps); - s - }; - // Four components, no subsampling: 2 bytes a coefficient, 8 a pixel. - assert_eq!(frame_coefficients(&sof(64, 64, &[1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0, 4, 0x11, 0])), Some(64 * 64 * 8)); - // 4:2:0: MCUs of 16 × 16 holding 4 + 1 + 1 blocks; a 1-pixel-wide picture still takes one. - assert_eq!(frame_coefficients(&sof(1, 16, &[1, 0x22, 0, 2, 0x11, 0, 3, 0x11, 0])), Some(128 * 6)); - let mut short = sof(1, 16, &[1, 0x22, 0, 2, 0x11, 0]); - short[5] = 3; - assert_eq!(frame_coefficients(&short), None, "three components declared, two there"); - // A marker walk over SOI, an APP0 segment, SOF2, then the scan. - let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2]; - let f = sof(64, 64, &[1, 0x11, 0]); - #[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")] - jpeg.extend(((f.len() + 2) as u16).to_be_bytes()); - jpeg.extend(&f); - jpeg.extend([0xFF, 0xDA]); - assert_eq!(jpeg_coefficients(&jpeg), 64 * 64 * 2); + fn jpeg_charge_is_never_less_than_the_local_one_it_replaced() { + let wide = &[1, 0xFF, 0, 2, 0xFF, 0, 3, 0xFF, 0]; + let cmyk = &[1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0, 4, 0x11, 0]; + let zero = &[1, 0x00, 0, 2, 0x00, 0, 3, 0x00, 0]; + // (case, whether the shared rule is expected to charge more). + let cases: Vec<(Vec, bool)> = vec![ + (jpeg_headers(&[(0xC0, 8, 640, 480, C420)], Some(3)), false), + (jpeg_headers(&[(0xC0, 8, 640, 480, GREY)], Some(1)), false), + (jpeg_headers(&[(0xC0, 8, 640, 480, C444)], Some(1)), true), + (jpeg_headers(&[(0xC1, 8, 640, 480, C420)], Some(2)), true), + (jpeg_headers(&[(0xC0, 8, 640, 480, C444)], None), false), + (jpeg_headers(&[(0xC2, 8, 640, 480, C420)], Some(1)), false), + (jpeg_headers(&[(0xC2, 8, 640, 480, C444)], Some(3)), false), + (jpeg_headers(&[(0xC2, 12, 640, 480, C444)], Some(1)), false), + (jpeg_headers(&[(0xC2, 8, 640, 480, cmyk)], Some(1)), false), + (jpeg_headers(&[(0xC2, 8, 640, 480, wide)], None), true), + (jpeg_headers(&[(0xC2, 8, 640, 480, zero)], None), false), + (jpeg_headers(&[(0xC6, 8, 640, 480, C444)], None), false), + (jpeg_headers(&[(0xCA, 8, 640, 480, C444)], None), false), + (jpeg_headers(&[(0xCE, 8, 640, 480, C444)], None), false), + (jpeg_headers(&[(0xC0, 8, 64, 64, GREY), (0xC2, 8, 6000, 4000, C444), (0xC2, 8, 100, 100, C444)], Some(1)), false), + (jpeg_headers(&[(0xC2, 8, 65535, 65535, cmyk)], None), false), + (jpeg_headers(&[], None), false), + (vec![0xFF, 0xD8], false), + (vec![], false), + (b"not a jpeg at all".to_vec(), false), + ]; + let mut grew = 0; + for (b, expect_more) in &cases { + let (old, new) = (oracle_jpeg_coefficients(b), jpeg_worst_case_coefficients(b)); + assert!(new >= old, "{b:02x?}: {new} < {old}"); + assert_eq!(new > old, *expect_more, "{b:02x?}: {old} -> {new}"); + grew += usize::from(new > old); + } + assert_eq!(grew, 3); + // Every prefix of a frame with a cut header, and pseudo-random damage: never less. + let full = jpeg_headers(&[(0xC2, 8, 3000, 2000, C420), (0xC0, 8, 100, 100, C444)], Some(1)); + for n in 0..=full.len() { + assert!(jpeg_worst_case_coefficients(&full[..n]) >= oracle_jpeg_coefficients(&full[..n]), "prefix {n}"); + } + let mut seed = 0x9e37_79b9u32; + for _ in 0..3000 { + let mut f = full.clone(); + for _ in 0..3 { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let (i, v) = ((seed >> 8) as usize % f.len(), (seed >> 24) as u8); + f[i] = v; + } + assert!(jpeg_worst_case_coefficients(&f) >= oracle_jpeg_coefficients(&f), "{f:02x?}"); + } + } + + #[test] + fn a_baseline_jpeg_with_a_short_first_scan_is_charged_its_coefficients() { + // 3-component 4:4:4 SOF0 of 8000 x 8000 (64 Mpx) whose first scan has one component: the + // decoder holds 2 bytes a coefficient of all three until the other scans, 6 bytes a pixel. + let b = jpeg_headers(&[(0xC0, 8, 8000, 8000, C444)], Some(1)); + let (old, new) = (oracle_jpeg_coefficients(&b), jpeg_worst_case_coefficients(&b)); + assert_eq!((old, new), (0, 8000 * 8000 * 6)); + // 3 + 6 bytes a pixel beside the output passes the 512 MiB budget; it fit as 7 (the RGBA8 conversion). + let (before, after) = (peak_bytes(8000, 8000, 3, old), peak_bytes(8000, 8000, 3, new)); + assert_eq!((before, after), (Some(8000 * 8000 * 8), Some(8000 * 8000 * 9))); + assert!(before.is_some_and(|p| p <= crate::MAX_DECODED_BYTES) && after.is_some_and(|p| p > crate::MAX_DECODED_BYTES)); + // The same through `probe`, on a real JPEG whose headers are made so. + let mut jpeg = encode(image::RgbImage::from_pixel(16, 16, image::Rgb([200, 30, 30])), ImageFormat::Jpeg); + let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap(); + jpeg[sof + 5..sof + 7].copy_from_slice(&8000u16.to_be_bytes()); + jpeg[sof + 7..sof + 9].copy_from_slice(&8000u16.to_be_bytes()); + (0..3).for_each(|c| jpeg[sof + 11 + 3 * c] = 0x11); + let sos = jpeg.windows(2).position(|m| m == [0xFF, 0xDA]).unwrap(); + jpeg.splice(sos..sos + 14, [0xFF, 0xDA, 0, 8, 1, 1, 0, 0, 63, 0]); + let p = probe(&jpeg).unwrap(); + assert_eq!((p.width, p.height, p.peak_bytes()), (8000, 8000, 8000 * 8000 * 9)); + assert!(!p.fits(crate::MAX_DECODED_BYTES)); + } + + #[test] + fn jpeg_coefficients_follow_a_marker_walk() { + // SOI, an APP0 segment, SOF2, then the scan. + let jpeg = jpeg_headers(&[(0xC2, 8, 64, 64, GREY)], Some(1)); + assert_eq!(jpeg_worst_case_coefficients(&jpeg), 64 * 64 * 2); + // 4:2:0: MCUs of 16 x 16 holding 4 + 1 + 1 blocks; a 1-pixel-wide picture still takes one. + assert_eq!(jpeg_worst_case_coefficients(&jpeg_headers(&[(0xC2, 8, 1, 16, C420)], None)), 128 * 6); } /// A little-endian TIFF header whose first IFD holds just a compression tag. @@ -898,4 +842,516 @@ mod tests { assert!(probe_dib(d).and_then(|p| p.decode(1 << 20)).is_err()); } } + + // The local JPEG budget before it moved to `craft_image_codecs::jpeg_worst_case_coefficients` (#778), kept as the oracle. + /// Bytes of DCT coefficients a progressive JPEG's decoder keeps for the whole picture while it + /// reads the scans: zune-jpeg holds an `i16` per coefficient of every component, in whole MCUs. + /// 0 for a baseline JPEG, decoded an MCU row at a time. Each frame header before the first scan + /// counts and the largest wins; headers this can't follow are charged as the costliest frame. + fn oracle_jpeg_coefficients(bytes: &[u8]) -> u64 { + let mut at = 2; + let mut most = 0u64; + loop { + if bytes.get(at) != Some(&0xFF) { + return oracle_worst_coefficients(bytes).max(most); + } + while bytes.get(at) == Some(&0xFF) { + at += 1; + } + let Some(&code) = bytes.get(at) else { return oracle_worst_coefficients(bytes).max(most) }; + at += 1; + match code { + // Markers without a length: start of image, TEM, restarts. + 0xD8 | 0x01 | 0xD0..=0xD7 => continue, + // End of image, start of scan: every frame header is behind. + 0xD9 | 0xDA => return most, + _ => {} + } + let len = match (bytes.get(at), bytes.get(at + 1)) { + (Some(&hi), Some(&lo)) => usize::from(u16::from_be_bytes([hi, lo])), + _ => 0, + }; + let Some(segment) = bytes.get(at + 2..at + len).filter(|_| len >= 2) else { return oracle_worst_coefficients(bytes).max(most) }; + // SOF2, SOF6, SOF10 and SOF14 are the progressive frames. + if matches!(code, 0xC2 | 0xC6 | 0xCA | 0xCE) { + let Some(held) = oracle_frame_coefficients(segment) else { return oracle_worst_coefficients(bytes).max(most) }; + most = most.max(held); + } + at += len; + } + } + + /// `oracle_jpeg_coefficients` of one progressive frame header (after its length): the components' + /// blocks per MCU (horizontal × vertical sampling) times the MCUs that cover the picture. + fn oracle_frame_coefficients(sof: &[u8]) -> Option { + let height = u64::from(u16::from_be_bytes([*sof.get(1)?, *sof.get(2)?])); + let width = u64::from(u16::from_be_bytes([*sof.get(3)?, *sof.get(4)?])); + let n = usize::from(*sof.get(5)?); + let sampling: Vec<(u64, u64)> = sof + .get(6..6 + 3 * n)? + .as_chunks::<3>() + .0 + .iter() + .map(|&[_, s, _]| (u64::from(s >> 4).clamp(1, 4), u64::from(s & 15).clamp(1, 4))) + .collect(); + let (h_max, v_max) = sampling.iter().fold((1, 1), |(h, v), &(a, b)| (h.max(a), v.max(b))); + let mcus = width.div_ceil(8 * h_max).checked_mul(height.div_ceil(8 * v_max))?; + sampling.iter().try_fold(0u64, |sum, &(h, v)| sum.checked_add(mcus.checked_mul(2 * 64 * h * v)?)) + } + + /// The coefficients of the costliest progressive frame of the size the image crate reads from + /// `bytes`: four components, each sampled 4 × 4, in MCUs of 32 pixels a side. + fn oracle_worst_coefficients(bytes: &[u8]) -> u64 { + let Some((w, h)) = dimensions(bytes) else { return 0 }; + let mcus = u64::from(w).div_ceil(32) * u64::from(h).div_ceil(32); + mcus.saturating_mul(2 * 64 * 16 * 4) + } + + // The local DIB wrapping before it moved to `craft_image_codecs::bmp_probe` (#778), kept as the oracle. + /// Prepend a 14-byte `BITMAPFILEHEADER` to a normalized DIB so `craft-image-codecs` can inspect and decode it as BMP. + fn oracle_dib_to_bmp(dib: &[u8]) -> Vec { + let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let bi_size = u32_at(0).unwrap_or(40); + let offset = if bi_size == 12 { + let bpp = u16_at(10).unwrap_or(24); + let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 }; + 14 + bi_size + palette + } else { + let bpp = u16_at(14).unwrap_or(24); + let compression = u32_at(16).unwrap_or(0); + let clr_used = u32_at(32).unwrap_or(0); + let palette_entries = if clr_used != 0 { + clr_used + } else if bpp <= 8 { + 1u32 << bpp + } else { + 0 + }; + let masks = if compression == 3 && bi_size >= 40 { 12 } else { 0 }; + 14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4)) + }; + let file_size = u32::try_from(14 + dib.len()).unwrap_or(u32::MAX); + let mut bmp = Vec::with_capacity(14 + dib.len()); + bmp.extend_from_slice(b"BM"); + bmp.extend_from_slice(&file_size.to_le_bytes()); + bmp.extend_from_slice(&[0u8; 4]); + bmp.extend_from_slice(&offset.to_le_bytes()); + bmp.extend_from_slice(dib); + bmp + } + + /// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask + /// is set but whose compression says `BI_RGB` is marked `BI_BITFIELDS` (with the usual colour + /// masks when it gives none), so its alpha is kept as Windows programs mean it; arboard makes the + /// same change. Bit fields then need the colour masks after the header too, where Windows puts a + /// copy and the decoder skips them; a DIB without that copy (arboard writes one) gets it. + fn oracle_dib_layout(mut dib: Vec) -> Vec { + let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib }; + let put = |d: &mut Vec, at: usize, v: u32| { + if let Some(b) = d.get_mut(at..at + 4) { + b.copy_from_slice(&v.to_le_bytes()); + } + }; + if dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000) { + put(&mut dib, 16, 3); + if (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)) { + put(&mut dib, 40, 0x00FF_0000); + put(&mut dib, 44, 0x0000_FF00); + put(&mut dib, 48, 0x0000_00FF); + } + } + if u32_at(&dib, 16) == Some(3) + && size <= dib.len() + && let Some(masks) = dib.get(40..52).map(<[u8]>::to_vec) + && dib.get(size..size + 12) != Some(masks.as_slice()) + { + dib.splice(size..size, masks); + } + dib + } + + /// The size and peak `probe_dib` reported before the cutover, as `(width, height, peak, alpha, bytes)`. + fn oracle_probe_dib(dib: Vec) -> Result<(u32, u32, u64, bool, Vec), Refusal> { + let dib = oracle_dib_layout(dib); + let bmp = oracle_dib_to_bmp(&dib); + let (width, height, native, alpha) = match inspect_raster(&bmp) { + Ok(Some(info)) => { + let native = u64::from(info.channels.max(1)) * u64::from(info.bits_per_sample.max(8) / 8); + (info.width, info.height, native, matches!(info.color_type, RasterColorType::GrayAlpha | RasterColorType::Rgba)) + } + Ok(None) => return Err(Refusal::Broken("its DIB header can't be read".into())), + Err(CodecError::LimitExceeded(_)) => { + let (w, h) = dib_header_dims(&dib).ok_or_else(|| Refusal::Broken("its DIB header can't be read".into()))?; + (w, h, 4, false) + } + Err(e) => return Err(broken(e)), + }; + let (width, height, peak) = sized(width, height, native, 0)?; + Ok((width, height, peak, alpha, bmp)) + } + + /// A DIB with a header of `size` bytes (12, 40, 52, 56, 64, 108 or 124), `bpp`, `compression` + /// and `clr_used`, followed by `tail` bytes. + fn dib_with(size: u32, bpp: u16, compression: u32, clr_used: u32, alpha_mask: u32, tail: &[u8]) -> Vec { + let mut d = vec![0u8; usize::try_from(size).unwrap()]; + d[0..4].copy_from_slice(&size.to_le_bytes()); + if size == 12 { + d[4..6].copy_from_slice(&3u16.to_le_bytes()); + d[6..8].copy_from_slice(&2u16.to_le_bytes()); + d[8..10].copy_from_slice(&1u16.to_le_bytes()); + d[10..12].copy_from_slice(&bpp.to_le_bytes()); + } else { + d[4..8].copy_from_slice(&3i32.to_le_bytes()); + d[8..12].copy_from_slice(&2i32.to_le_bytes()); + d[12..14].copy_from_slice(&1u16.to_le_bytes()); + d[14..16].copy_from_slice(&bpp.to_le_bytes()); + d[16..20].copy_from_slice(&compression.to_le_bytes()); + d[32..36].copy_from_slice(&clr_used.to_le_bytes()); + if size >= 56 { + d[52..56].copy_from_slice(&alpha_mask.to_le_bytes()); + } + if size >= 52 { + for (at, m) in [(40, 0x00FF_0000u32), (44, 0x0000_FF00), (48, 0x0000_00FF)] { + d[at..at + 4].copy_from_slice(&m.to_le_bytes()); + } + } + } + d.extend_from_slice(tail); + d + } + + fn crafted_dibs() -> Vec> { + let px = [[0u8, 0, 255, 128]; 6].concat(); + let masks = [0x00u8, 0, 0xFF, 0, 0, 0xFF, 0, 0, 0xFF, 0, 0, 0]; + let mut v = Vec::new(); + for size in [12u32, 40, 52, 56, 64, 108, 124] { + for bpp in [1u16, 4, 8, 16, 24, 32] { + for compression in [0u32, 1, 2, 3, 6] { + for clr_used in [0u32, 2, 300, u32::MAX] { + for alpha_mask in [0u32, 0xFF00_0000] { + for tail in [&[][..], &px[..], &masks[..], &[&masks[..], &px[..]].concat()[..]] { + v.push(dib_with(size, bpp, compression, clr_used, alpha_mask, tail)); + } + } + } + } + } + } + // Clipboard layouts: the V5 helper's three, and a lying header size. + let q = [[0, 0, 255, 128], [255, 0, 0, 255]]; + for (bitfields, copy) in [(false, false), (true, false), (true, true)] { + v.push(dib(2, 1, 0xFF00_0000, bitfields, copy, &q)); + v.push(dib(2, 1, 0, bitfields, copy, &q)); + } + v.push(dib(60_000, 60_000, 0xFF00_0000, false, false, &[])); + let mut lying = dib(2, 1, 0xFF00_0000, true, false, &q); + lying[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + v.push(lying); + v + } + + // craft-image-codecs fixed two DIB behaviours after the cutover (craft-libs #2062); the oracle + // keeps the old ones, so these predicates name the inputs where the two must differ. + + fn le32(d: &[u8], at: usize) -> Option { + d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) + } + + /// A 52- or 56-byte `BI_BITFIELDS` header: its masks are inside the header, so the pixel offset + /// no longer counts 12 appended mask bytes. Returns the new, independently computed offset. + fn v2v3_bitfields_offset(d: &[u8]) -> Option { + let size = le32(d, 0).unwrap_or(40); + if !matches!(size, 52 | 56) || le32(d, 16).unwrap_or(0) != 3 { + return None; + } + let bpp = d.get(14..16).and_then(|b| b.try_into().ok()).map_or(24, u16::from_le_bytes); + let clr_used = le32(d, 32).unwrap_or(0); + let entries = if clr_used != 0 { + clr_used + } else if bpp <= 8 { + 1u32 << bpp + } else { + 0 + }; + Some(14u32.saturating_add(size).saturating_add(entries.saturating_mul(4))) + } + + /// A V4/V5 bit-fields DIB whose 12 bytes after the header equal the masks but whose payload is + /// no longer than the pixel rows need: those bytes are pixels, not a copy, so a copy is inserted. + /// Returns the masks the shared code inserts at `size`. + fn exact_payload_equal_to_masks(d: &[u8]) -> Option<(usize, [u8; 12])> { + let size = usize::try_from(le32(d, 0).filter(|&s| s >= 108)?).ok()?; + if size > d.len() { + return None; + } + let promote = d.get(14..16) == Some(&[32, 0][..]) && le32(d, 16) == Some(0) && le32(d, 52) == Some(0xFF00_0000); + let mut masks: [u8; 12] = d.get(40..52)?.try_into().ok()?; + if promote && masks == [0; 12] { + masks = [0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00]; + } + if !(promote || le32(d, 16) == Some(3)) || d.get(size..size + 12) != Some(masks.as_slice()) { + return None; + } + let w = u64::try_from(i32::from_le_bytes(d.get(4..8)?.try_into().ok()?)).ok()?; + let h = u64::from(i32::from_le_bytes(d.get(8..12)?.try_into().ok()?).unsigned_abs()); + let bpp = u64::from(u16::from_le_bytes(d.get(14..16)?.try_into().ok()?)); + let need = usize::try_from(w.checked_mul(bpp)?.div_ceil(32).checked_mul(4)?.checked_mul(h)?).ok()?; + (d.len() - size <= need).then_some((size, masks)) + } + + #[test] + fn dib_wrapping_is_byte_equal_to_the_local_one_it_replaced() { + let (mut n, mut v2v3, mut exact) = (0, 0, 0); + for d in crafted_dibs() { + // Every truncation point of the header region, then the whole. + let cuts = (0..=d.len().min(140)).chain([d.len()]); + for cut in cuts { + let d = &d[..cut]; + n += 1; + let (new, old) = (dib_to_bmp(d).unwrap(), oracle_dib_to_bmp(d)); + if let Some(offset) = v2v3_bitfields_offset(d) { + // New behaviour: only the offset differs, and it no longer counts the 12 mask bytes. + v2v3 += 1; + let mut expected = old; + expected[10..14].copy_from_slice(&offset.to_le_bytes()); + assert_eq!(new, expected, "wrap, 52/56-byte bit fields, cut {cut}"); + } else { + assert_eq!(new, old, "wrap, cut {cut}"); + } + let (new, old) = (bmp_probe::dib_layout(d.to_vec()), oracle_dib_layout(d.to_vec())); + if let Some((size, masks)) = exact_payload_equal_to_masks(d) { + // New behaviour: the bytes after the header are pixels, so a mask copy is inserted. + exact += 1; + let mut expected = old; + expected.splice(size..size, masks); + assert_eq!(new, expected, "layout, exact payload equal to the masks, cut {cut}"); + } else { + assert_eq!(new, old, "layout, cut {cut}"); + } + } + } + assert!(n > 100_000, "{n}"); + // The exclusions are small and present: a predicate that matched nothing would hide a regression. + eprintln!("DIB corpus: {n} cases, {v2v3} excluded as 52/56-byte bit fields, {exact} as exact payload equal to the masks"); + assert!(v2v3 > 0 && exact > 0 && v2v3 + exact < n / 10, "{v2v3} {exact}"); + } + + #[test] + fn probe_dib_is_unchanged_by_the_shared_wrapping() { + for d in crafted_dibs() { + for cut in [0, 4, 11, 12, 14, 40, 52, 100, 124, 130, d.len()] { + let d = d[..cut.min(d.len())].to_vec(); + // The two DIB fixes change the bytes handed to the decoder; the wrapping test above pins + // them, so skip those inputs here. + if v2v3_bitfields_offset(&d).is_some() || exact_payload_equal_to_masks(&d).is_some() { + continue; + } + let new = probe_dib(d.clone()); + match (new, oracle_probe_dib(d.clone())) { + (Ok(p), Ok((w, h, peak, alpha, bmp))) => { + assert_eq!((p.width, p.height, p.peak, p.alpha), (w, h, peak, alpha), "{d:02x?}"); + assert_eq!(&*p.bytes, bmp.as_slice()); + } + (Err(a), Err(b)) => assert_eq!(a, b, "{d:02x?}"), + (a, b) => panic!("{d:02x?}: {:?} vs {:?}", a.map(|p| p.width), b.map(|o| o.0)), + } + } + } + } + + // The local PNG header read before it moved to `craft_image_codecs::png_probe` (#778), kept as the oracle. + /// A PNG's width, height, the bytes a pixel its decoder gives (samples under 8 bits widened to 8, + /// a palette to RGB, `tRNS` to an alpha channel) and whether it has transparency, from `IHDR` and + /// the chunk headers before the image data. The decoder's own header read inflates an ICC profile + /// (`iCCP`) up to its 512 MiB default limit, for a picture that may only be measured. + fn oracle_png_chunks(bytes: &[u8]) -> Option<(u32, u32, u64, bool)> { + let be = |at: usize| bytes.get(at..at.checked_add(4)?).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_be_bytes); + // The 8-byte signature, then IHDR: length, type, width, height, bit depth, colour type. + if bytes.get(12..16) != Some(b"IHDR".as_slice()) { + return None; + } + let (width, height) = (be(16)?, be(20)?); + let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?); + let mut trns = false; + let mut at = 8usize; + loop { + let len = usize::try_from(be(at)?).ok()?; + match bytes.get(at.checked_add(4)?..at.checked_add(8)?)? { + b"IDAT" => break, + b"IEND" => return None, + b"tRNS" => trns = true, + _ => {} + } + at = at.checked_add(12)?.checked_add(len)?; + } + let (channels, alpha) = match color { + 0 => (1 + u64::from(trns), trns), + 2 | 3 => (3 + u64::from(trns), trns), + 4 => (2, true), + 6 => (4, true), + _ => return None, + }; + Some((width, height, channels * if depth == 16 { 2 } else { 1 }, alpha)) + } + + /// WordCraft's WebP alpha rule before the cutover: the `VP8X` flag, nothing else. + fn oracle_webp_alpha(bytes: &[u8]) -> bool { + bytes.get(12..16) == Some(b"VP8X") && bytes.get(20).is_some_and(|b| b & 0x10 != 0) + } + + fn new_png(b: &[u8]) -> Option<(u32, u32, u64, bool)> { + png_probe::pixel_model(b).ok().map(|m| (m.width, m.height, u64::from(m.bytes_per_pixel()), m.has_alpha())) + } + + /// A PNG with the given IHDR fields and chunks before a (junk) `IDAT`. + fn png_with(width: u32, height: u32, depth: u8, color: u8, before_idat: &[(&[u8; 4], Vec)]) -> Vec { + let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { + out.extend((data.len() as u32).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(data); + out.extend_from_slice(&[0; 4]); + }; + let mut b = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = [width.to_be_bytes(), height.to_be_bytes()].concat(); + ihdr.extend_from_slice(&[depth, color, 0, 0, 0]); + chunk(&mut b, b"IHDR", &ihdr); + for (k, d) in before_idat { + chunk(&mut b, k, d); + } + chunk(&mut b, b"IDAT", &[1, 2, 3]); + chunk(&mut b, b"IEND", &[]); + b + } + + #[test] + fn png_pixel_model_matches_the_local_header_read_for_every_valid_header() { + let valid: [(u8, &[u8]); 5] = [(0, &[1, 2, 4, 8, 16]), (2, &[8, 16]), (3, &[1, 2, 4, 8]), (4, &[8, 16]), (6, &[8, 16])]; + let mut n = 0; + for (color, depths) in valid { + for &depth in depths { + for (trns, icc) in [(false, false), (true, false), (true, true), (false, true)] { + let mut extra: Vec<(&[u8; 4], Vec)> = vec![]; + if icc { + extra.push((b"iCCP", vec![0xAB; 300])); + } + if trns { + extra.push((b"tRNS", vec![0, 0])); + } + let b = png_with(5, 7, depth, color, &extra); + assert!(new_png(&b).is_some(), "colour {color} depth {depth}"); + assert_eq!(new_png(&b), oracle_png_chunks(&b), "colour {color} depth {depth} trns {trns}"); + // And `probe` reports what the old read gave it: the size and the peak. + let (w, h, native, alpha) = oracle_png_chunks(&b).unwrap(); + let p = probe(&b).unwrap(); + assert_eq!((p.width, p.height, p.has_alpha(), Some(p.peak_bytes())), (w, h, alpha, peak_bytes(w, h, native, 0))); + assert_eq!(dimensions(&b), Some((5, 7))); + n += 1; + } + } + } + assert_eq!(n, 4 * 15); + // Real encoder output, every layout the image types give. + for img in [ + DynamicImage::ImageLuma8(image::GrayImage::new(3, 2)), + DynamicImage::ImageLumaA8(image::GrayAlphaImage::new(3, 2)), + DynamicImage::ImageRgb8(image::RgbImage::new(3, 2)), + DynamicImage::ImageRgba8(image::RgbaImage::new(3, 2)), + DynamicImage::ImageRgb16(image::ImageBuffer::new(3, 2)), + DynamicImage::ImageRgba16(image::ImageBuffer::new(3, 2)), + ] { + let b = encode(img, ImageFormat::Png); + assert_eq!(new_png(&b), oracle_png_chunks(&b)); + } + } + + /// What the old read accepted and `pixel_model` refuses is a header the decoder can't use + /// either; `probe` then says the PNG header can't be read (`Broken`) and `dimensions` is None. + #[test] + fn png_pixel_model_is_stricter_only_on_headers_that_are_not_valid_pngs() { + let ok = png_with(5, 7, 8, 2, &[]); + let mut cases: Vec<(&str, Vec)> = vec![ + ("depth 3 for RGB", png_with(5, 7, 3, 2, &[])), + ("depth 16 for palette", png_with(5, 7, 16, 3, &[])), + ("depth 4 for RGBA", png_with(5, 7, 4, 6, &[])), + ("zero width", png_with(0, 7, 8, 2, &[])), + ("zero height", png_with(5, 0, 8, 2, &[])), + ("width past i32::MAX", png_with(1 << 31, 1, 8, 2, &[])), + ("height past i32::MAX", png_with(1, u32::MAX, 8, 2, &[])), + ]; + let many: Vec<(&[u8; 4], Vec)> = (0..70_000).map(|_| (b"tEXt", Vec::new())).collect(); + cases.push(("70,000 chunks before the image data", png_with(5, 7, 8, 2, &many))); + for (what, b) in &cases { + assert!(oracle_png_chunks(b).is_some(), "{what}: the old read accepted it"); + assert_eq!(new_png(b), None, "{what}"); + assert_eq!(dimensions(b), None, "{what}"); + assert!(matches!(probe(b), Err(Refusal::Broken(_))), "{what}"); + assert!(!header_has_alpha(b), "{what}"); + } + // Everything else the old read refused (no IHDR, unknown colour, a wrong IHDR length that + // throws its chunk walk off, no image data) is still refused. + let mut short_ihdr = ok.clone(); + short_ihdr[8..12].copy_from_slice(&12u32.to_be_bytes()); + for b in [png_with(5, 7, 8, 5, &[]), b"\x89PNG\r\n\x1a\n".to_vec(), ok[..33].to_vec(), short_ihdr] { + assert_eq!(new_png(&b), None); + assert_eq!(oracle_png_chunks(&b), None); + } + // Truncations and damage: where the new read answers, it answers as the old one did. + let full = png_with(5, 7, 8, 6, &[(b"tRNS", vec![0]), (b"gAMA", vec![0; 4])]); + for n in 0..=full.len() { + if new_png(&full[..n]).is_some() { + assert_eq!(new_png(&full[..n]), oracle_png_chunks(&full[..n]), "prefix {n}"); + } + } + let mut seed = 0x9e37_79b9u32; + for _ in 0..3000 { + let mut f = full.clone(); + for _ in 0..3 { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let (i, v) = ((seed >> 8) as usize % f.len(), (seed >> 24) as u8); + f[i] = v; + } + if new_png(&f).is_some() { + assert_eq!(new_png(&f), oracle_png_chunks(&f), "{f:02x?}"); + } + } + } + + /// A RIFF WebP with one chunk. + fn riff_webp(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut b = b"RIFF".to_vec(); + b.extend((4 + 8 + payload.len() as u32).to_le_bytes()); + b.extend_from_slice(b"WEBP"); + b.extend_from_slice(kind); + b.extend((payload.len() as u32).to_le_bytes()); + b.extend_from_slice(payload); + b + } + + #[test] + fn webp_alpha_follows_vp8x_and_now_vp8l() { + // VP8X: the flag, as before. + for flags in [0u8, 0x10, 0x20, 0x30] { + let mut payload = vec![flags, 0, 0, 0]; + payload.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // 1 x 1 canvas + let b = riff_webp(b"VP8X", &payload); + assert_eq!(webp_probe::has_alpha(&b).unwrap(), oracle_webp_alpha(&b), "flags {flags:#x}"); + assert_eq!(oracle_webp_alpha(&b), flags & 0x10 != 0); + } + // A bare lossless picture (VP8L) says so in its header: 1 x 1, `alpha_is_used` (bit 28). + let with = riff_webp(b"VP8L", &[0x2f, 0, 0, 0, 0x10, 0, 0, 0]); + let without = riff_webp(b"VP8L", &[0x2f, 0, 0, 0, 0x00, 0, 0, 0]); + assert!(!oracle_webp_alpha(&with), "the old rule never saw it"); + assert!(webp_probe::has_alpha(&with).unwrap()); + assert!(!webp_probe::has_alpha(&without).unwrap()); + // A real encoder's lossless RGBA WebP. + let enc = encode(image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 8, 7, 100])), ImageFormat::WebP); + assert_eq!(probe(&enc).unwrap().has_alpha(), webp_probe::has_alpha(&enc).unwrap()); + // Lossy VP8 never has alpha; and input that isn't a RIFF WebP reads as none, as before. + assert!(!webp_probe::has_alpha(&riff_webp(b"VP8 ", &[0; 10])).unwrap()); + for junk in [&b"not a webp at all"[..], b"", b"RIFF", b"RIFF\0\0\0\0WEBPVP8L"] { + assert!(!webp_probe::has_alpha(junk).unwrap_or(false)); + } + } } diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index a767a20221..b3d3a39c8d 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -13,5 +13,6 @@ wordcraft-doc = { workspace = true } wordcraft-engine = { workspace = true } wordcraft-render = { workspace = true } wordcraft-control-key = { workspace = true } +craft-mcp-server = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index bd9616222d..204aa2800f 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -1,22 +1,16 @@ -//! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources methods. +//! WordCraft's MCP server: the shared `craft_mcp_server` core (JSON-RPC framing, the lifecycle, +//! `tools/*` and `resources/*`) around WordCraft's own tools, resources and instructions. use std::io::{BufRead, Read, Write}; +use craft_mcp_server::{Contents, Info, Options, Tools}; use serde_json::{Value, json}; use crate::backend::Backend; use crate::tools::{call_tool, tool_definitions}; /// The MCP revision we implement. -pub const PROTOCOL_VERSION: &str = "2025-06-18"; -const SUPPORTED_VERSIONS: &[&str] = &[PROTOCOL_VERSION, "2025-03-26", "2024-11-05"]; - -const PARSE_ERROR: i64 = -32700; -const INVALID_REQUEST: i64 = -32600; -const METHOD_NOT_FOUND: i64 = -32601; -const INVALID_PARAMS: i64 = -32602; -const INTERNAL_ERROR: i64 = -32603; -const RESOURCE_NOT_FOUND: i64 = -32002; +pub use craft_mcp_server::PROTOCOL_VERSION; const INSTRUCTIONS: &str = "WordCraft is a word processor (a Microsoft Word clone). Every action is a command: find ids and \ parameters with list_commands and run them with execute (or several with batch). Positions are \ @@ -74,149 +68,90 @@ pub(crate) fn read_bounded_line(reader: &mut impl BufRead, max: usize) -> std::i String::from_utf8(buf).map(BoundedLine::Line).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } +/// WordCraft's tools, resources and instructions over one backend, for the shared server. +struct WordcraftTools { + backend: Box, +} + +impl Tools for WordcraftTools { + fn instructions(&self) -> String { + format!( + "{INSTRUCTIONS} Backend: {}. Community: https://discord.gg/artcraft · https://getartcraft.com/apps/wordcraft · https://github.com/storytold/wordcraft", + self.backend.describe() + ) + } + + fn list(&mut self) -> Vec { + match tool_definitions() { + Value::Array(tools) => tools, + _ => Vec::new(), + } + } + + fn call(&mut self, name: &str, args: &Value) -> Value { + call_tool(self.backend.as_mut(), name, args).to_value() + } + + fn resources(&self) -> Vec { + vec![ + json!({"uri": DOC_URI, "name": "document", "title": "Active document", "description": "Blocks, text, formatting, sections, parts and selection of the document (document.inspect)", "mimeType": "application/json"}), + json!({"uri": COMMANDS_URI, "name": "commands", "title": "Commands", "description": "Every command: id, label, ribbon location, shortcut, params, enabled (engine.commands)", "mimeType": "application/json"}), + ] + } + + fn read_resource(&mut self, uri: &str) -> Option> { + let method = match uri { + DOC_URI => "document.inspect", + COMMANDS_URI => "engine.commands", + _ => return None, + }; + Some( + self.backend + .call(method, json!({})) + .map(|v| Contents::Text { mime_type: "application/json".into(), text: serde_json::to_string_pretty(&v).unwrap_or_default() }), + ) + } +} + /// An MCP server bound to one backend. pub struct Server { - backend: Box, - initialized: bool, -} - -fn response(id: Value, result: Value) -> Value { - json!({"jsonrpc": "2.0", "id": id, "result": result}) -} - -fn error(id: Value, code: i64, message: impl Into) -> Value { - json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) + inner: craft_mcp_server::Server, } impl Server { pub fn new(backend: Box) -> Self { - Self { backend, initialized: false } + let info = Info { name: "wordcraft", title: "WordCraft", version: env!("CARGO_PKG_VERSION"), max_line: MAX_REQUEST_LINE }; + let options = Options { + website_url: Some("https://getartcraft.com/apps/wordcraft".into()), + // Clients read every tool failure from the result, as before the shared core. + tool_errors_as_results: true, + strict_request_ids: true, + }; + Self { inner: craft_mcp_server::Server::new(info, WordcraftTools { backend }).with_options(options) } } pub fn backend(&mut self) -> &mut dyn Backend { - self.backend.as_mut() + self.inner.tools().backend.as_mut() } /// Whether the client has sent `notifications/initialized`. pub fn is_initialized(&self) -> bool { - self.initialized + self.inner.is_initialized() } /// Serve newline-delimited JSON-RPC until `input` closes. Logs go to stderr only (stdout is /// the protocol stream). - pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { - loop { - let reply = match read_bounded_line(&mut input, MAX_REQUEST_LINE) { - Ok(BoundedLine::Eof) => break, - Ok(BoundedLine::Line(line)) => self.handle_line(&line), - Ok(BoundedLine::TooLong) => Some(error(Value::Null, INVALID_REQUEST, "request line too long").to_string()), - Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { - Some(error(Value::Null, PARSE_ERROR, "request line is not UTF-8").to_string()) - } - Err(e) => return Err(e), - }; - if let Some(reply) = reply { - output.write_all(reply.as_bytes())?; - output.write_all(b"\n")?; - output.flush()?; - } - } - Ok(()) + pub fn serve(&mut self, input: impl BufRead, output: impl Write) -> std::io::Result<()> { + self.inner.serve(input, output) } /// Handle one line; returns the reply line (None for notifications and blank lines). pub fn handle_line(&mut self, line: &str) -> Option { - let line = line.trim(); - if line.is_empty() { - return None; - } - let reply = match serde_json::from_str::(line) { - Ok(Value::Array(batch)) => { - // Batches were removed in 2025-06-18; still answer older clients sensibly. - if batch.is_empty() { - Some(error(Value::Null, INVALID_REQUEST, "empty batch")) - } else { - let replies: Vec = batch.into_iter().filter_map(|m| self.handle(m)).collect(); - (!replies.is_empty()).then_some(Value::Array(replies)) - } - } - Ok(msg) => self.handle(msg), - Err(e) => Some(error(Value::Null, PARSE_ERROR, format!("parse error: {e}"))), - }; - reply.map(|r| r.to_string()) + self.inner.handle_line(line) } /// Handle one JSON-RPC message; `None` for notifications and responses. pub fn handle(&mut self, msg: Value) -> Option { - let Value::Object(o) = &msg else { return Some(error(Value::Null, INVALID_REQUEST, "message must be an object")) }; - let id = o.get("id").cloned(); - let Some(method) = o.get("method").and_then(Value::as_str) else { - // A response to a server→client request (we send none): ignore. Anything else is invalid. - if o.contains_key("result") || o.contains_key("error") { - return None; - } - return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); - }; - let params = o.get("params").cloned().unwrap_or(Value::Null); - let Some(id) = id else { - self.notification(method); - return None; - }; - if !(id.is_string() || id.is_number()) { - return Some(error(Value::Null, INVALID_REQUEST, "`id` must be a string or number")); - } - Some(match self.request(method, ¶ms) { - Ok(r) => response(id, r), - Err((code, m)) => error(id, code, m), - }) - } - - fn notification(&mut self, method: &str) { - match method { - "notifications/initialized" => self.initialized = true, - "notifications/cancelled" | "notifications/progress" | "notifications/roots/list_changed" => {} - other => log::debug!("ignoring notification {other}"), - } - } - - fn request(&mut self, method: &str, params: &Value) -> Result { - match method { - "initialize" => { - let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION); - let version = if SUPPORTED_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSION }; - Ok(json!({ - "protocolVersion": version, - "capabilities": {"tools": {}, "resources": {}}, - "serverInfo": {"name": "wordcraft", "title": "WordCraft", "version": env!("CARGO_PKG_VERSION"), "websiteUrl": "https://getartcraft.com/apps/wordcraft"}, - "instructions": format!( - "{INSTRUCTIONS} Backend: {}. Community: https://discord.gg/artcraft · https://getartcraft.com/apps/wordcraft · https://github.com/storytold/wordcraft", - self.backend.describe() - ), - })) - } - "ping" => Ok(json!({})), - "tools/list" => Ok(json!({"tools": tool_definitions()})), - "tools/call" => { - let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?; - let args = params.get("arguments").cloned().unwrap_or(Value::Null); - Ok(call_tool(self.backend.as_mut(), name, &args).to_value()) - } - "resources/list" => Ok(json!({"resources": [ - {"uri": DOC_URI, "name": "document", "title": "Active document", "description": "Blocks, text, formatting, sections, parts and selection of the document (document.inspect)", "mimeType": "application/json"}, - {"uri": COMMANDS_URI, "name": "commands", "title": "Commands", "description": "Every command: id, label, ribbon location, shortcut, params, enabled (engine.commands)", "mimeType": "application/json"}, - ]})), - "resources/templates/list" => Ok(json!({"resourceTemplates": []})), - "resources/read" => { - let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing `uri`".to_string()))?; - let v = match uri { - DOC_URI => self.backend.call("document.inspect", json!({})), - COMMANDS_URI => self.backend.call("engine.commands", json!({})), - _ => return Err((RESOURCE_NOT_FOUND, format!("resource not found: {uri}"))), - } - .map_err(|e| (INTERNAL_ERROR, e))?; - Ok(json!({"contents": [{"uri": uri, "mimeType": "application/json", "text": serde_json::to_string_pretty(&v).unwrap_or_default()}]})) - } - other => Err((METHOD_NOT_FOUND, format!("method not found: {other}"))), - } + self.inner.handle(msg) } } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index f554d4bb84..fd2951a7bb 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -4,6 +4,9 @@ use serde_json::{Value, json}; use crate::{Headless, Server}; +mod differential; +mod oracle; + fn call(s: &mut Server, id: u64, method: &str, params: Value) -> Value { let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string(); let r = s.handle_line(&line).expect("reply"); @@ -169,7 +172,9 @@ fn render_and_screenshot_through_the_app_use_no_temp_file() { let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let mut s = Server::new(Box::new(FakeApp { calls: calls.clone() })); for (tool, method) in [("render_page", "ui.render"), ("screenshot", "ui.screenshot")] { - let r = call(&mut s, 10, "tools/call", json!({"name": tool, "arguments": {"page": 1}})); + // `screenshot` takes no arguments (the shared check refuses ones its schema does not list). + let args = if tool == "render_page" { json!({"page": 1}) } else { json!({}) }; + let r = call(&mut s, 10, "tools/call", json!({"name": tool, "arguments": args})); let content = &r["result"]["content"]; assert_eq!(r["result"]["isError"], false, "{tool}: {r}"); assert_eq!(content[0]["type"], "image", "{tool}"); @@ -310,7 +315,8 @@ fn over_long_request_line_is_rejected_and_serving_continues() { let text = String::from_utf8(out).unwrap(); let lines: Vec<&str> = text.lines().collect(); assert_eq!(lines.len(), 2, "{text}"); - assert!(lines[0].contains("too long"), "{}", lines[0]); + // The shared core words it "request too large" (was "request line too long"); same -32600. + assert!(lines[0].contains("too large") && lines[0].contains("-32600"), "{}", lines[0]); assert!(lines[1].contains(r#""id":5"#), "{}", lines[1]); } diff --git a/crates/mcp/src/tests/differential.rs b/crates/mcp/src/tests/differential.rs new file mode 100644 index 0000000000..eb6fdb422c --- /dev/null +++ b/crates/mcp/src/tests/differential.rs @@ -0,0 +1,452 @@ +//! The shared server against the hand-written one it replaced (`oracle`): the same scripted +//! JSON-RPC session goes through both and the replies must be equal, after normalising only the +//! differences listed in `normalise`. Differences that cannot be normalised away are pinned by +//! their own tests below. Document ids (a process-wide counter) are zeroed before comparing. + +use serde_json::{Value, json}; + +use super::oracle; +use crate::{Headless, Server}; + +/// One input line of the session; `free_text` marks a tool call whose failure text is the +/// validator's own words (both sides must still say `isError: true`). +struct Step { + line: Vec, + free_text: bool, +} + +fn req(id: Value, method: &str, params: Value) -> Vec { + json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string().into_bytes() +} + +fn step(line: Vec) -> Step { + Step { line, free_text: false } +} + +fn call(id: u64, name: &str, args: Value) -> Step { + step(req(json!(id), "tools/call", json!({"name": name, "arguments": args}))) +} + +fn call_free(id: u64, name: &str, args: Value) -> Step { + Step { free_text: true, ..call(id, name, args) } +} + +fn script() -> Vec { + let mut s = Vec::new(); + // initialize with each supported version, an unknown one, an odd one, and none. + for (i, v) in [json!("2025-06-18"), json!("2025-03-26"), json!("2024-11-05"), json!("1999-01-01"), json!(7), Value::Null].into_iter().enumerate() + { + s.push(step(req(json!(i + 1), "initialize", json!({"protocolVersion": v, "capabilities": {}})))); + } + s.push(step(req(json!(20), "initialize", json!({})))); + s.push(step(req(json!(21), "initialize", Value::Null))); + s.push(step(br#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.to_vec())); + s.push(step(req(json!(30), "ping", json!({})))); + s.push(step(req(json!(31), "tools/list", json!({})))); + s.push(step(req(json!(32), "resources/templates/list", json!({})))); + // tools: a realistic session, an image, an error result, a doc-addressed call. + for (i, (name, args)) in [ + ("new_document", json!({})), + ("new_document", json!({"template": "sample"})), + ("type_text", json!({"text": "Hello there"})), + ("type_text", json!({"text": "a\nb", "paragraphs": true, "doc": null})), + ("select_text", json!({"text": "Hello", "occurrence": 1})), + ("execute", json!({"command": "format.bold"})), + ("execute", json!({"command": "no.such.command"})), + ("execute", json!({"command": "text.insert", "params": {"text": "x"}, "doc": 99})), + ("batch", json!({"commands": [{"command": "caret.docEnd"}, {"command": "text.insert", "params": {"text": "!"}}]})), + ("batch", json!({"commands": [{"command": "no.such"}, {"command": "caret.docEnd"}], "keepGoing": true})), + ("insert_table", json!({"values": [["a", 1], ["b", 2]], "header": true})), + ("list_commands", json!({"query": "bold"})), + ("list_documents", json!({})), + ("get_text", json!({})), + ("inspect_document", json!({})), + ("render_page", json!({"page": 1, "scale": 0.2})), + ("render_page", json!({"page": 99})), + ("screenshot", json!({})), + ("click", json!({"x": 1, "y": 2})), + ("key", json!({"key": "B", "cmd": true})), + ("parity", json!({})), + ("save_document", json!({"path": "/nonexistent-dir-wc/x.docx"})), + ] + .into_iter() + .enumerate() + { + s.push(call(100 + i as u64, name, args)); + } + // bad arguments: both sides fail with isError; the words are the validator's own. + s.push(call_free(200, "execute", json!({}))); + s.push(call_free(201, "execute", json!({"command": 5}))); + s.push(call_free(203, "insert_table", json!({"values": "x"}))); + s.push(call_free(204, "insert_table", json!({"values": null}))); + s.push(call_free(205, "get_text", json!({"doc": "1"}))); + s.push(call_free(206, "render_page", json!({"doc": 1.5}))); + s.push(call_free(207, "open_document", json!({}))); + s.push(call_free(208, "execute", json!("not an object"))); + // A missing or null `arguments` is `{}` to the shared server (it was null). + for (id, params) in [(209, json!({"name": "execute"})), (210, json!({"name": "execute", "arguments": null}))] { + s.push(Step { free_text: true, ..step(req(json!(id), "tools/call", params)) }); + } + s.push(step(req(json!(211), "tools/call", json!({"name": "nope", "arguments": {}})))); + s.push(step(req(json!(212), "tools/call", json!({})))); + s.push(step(req(json!(213), "tools/call", json!({"name": 5})))); + s.push(step(req(json!(214), "tools/call", Value::Null))); + // odd ids. + for id in [json!("abc"), json!(0), json!(-3), json!(1.5), json!(u64::MAX), json!(null), json!(true), json!([1]), json!({"a": 1})] { + s.push(step(req(id, "ping", json!({})))); + } + s.push(step(br#"{"jsonrpc":"2.0","method":"ping"}"#.to_vec())); + // resources. + s.push(step(req(json!(300), "resources/list", json!({})))); + s.push(step(req(json!(301), "resources/read", json!({"uri": "wordcraft://document"})))); + s.push(step(req(json!(302), "resources/read", json!({"uri": "wordcraft://commands"})))); + s.push(step(req(json!(303), "resources/read", json!({"uri": "wordcraft://nothing"})))); + // unknown methods, malformed messages, notifications. + s.push(step(req(json!(310), "nope", json!({})))); + s.push(step(req(json!(311), "tools/nope", Value::Null))); + for raw in [ + &br#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}"#[..], + br#"{"jsonrpc":"2.0","method":"notifications/progress"}"#, + br#"{"jsonrpc":"2.0","method":"notifications/whatever"}"#, + br#"{"jsonrpc":"2.0","id":1,"result":{}}"#, + br#"{"jsonrpc":"2.0","id":1,"error":{"code":1,"message":"x"}}"#, + br#"{"jsonrpc":"2.0","id":7}"#, + br#"{"jsonrpc":"2.0","id":7,"method":5}"#, + br#"{"id":8,"method":"ping"}"#, + br#"[]"#, + br#"42"#, + br#""text""#, + br#"null"#, + br#"{not json"#, + br#" "#, + b"", + ] { + s.push(step(raw.to_vec())); + } + // batches: mixed requests and notifications, only notifications, bad members. + s.push(step( + json!([ + {"jsonrpc": "2.0", "id": 400, "method": "ping"}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 401, "method": "tools/list"}, + 5, + {"jsonrpc": "2.0", "id": 402, "method": "nope"} + ]) + .to_string() + .into_bytes(), + )); + s.push(step(br#"[{"jsonrpc":"2.0","method":"notifications/initialized"}]"#.to_vec())); + // CRLF line ending, leading and trailing whitespace. + s.push(step(b" {\"jsonrpc\":\"2.0\",\"id\":500,\"method\":\"ping\"}\r".to_vec())); + s +} + +/// The documented differences, removed from a reply before comparing. Anything else must match. +fn normalise(mut v: Value, free_text: bool) -> Value { + if let Value::Array(items) = v { + return Value::Array(items.into_iter().map(|i| normalise(i, free_text)).collect()); + } + // 1. `capabilities` gains `listChanged: false` on tools and resources. + if let Some(c) = v.pointer_mut("/result/capabilities").and_then(Value::as_object_mut) { + for cap in c.values_mut() { + if let Some(o) = cap.as_object_mut() { + o.remove("listChanged"); + } + } + } + // 2. Error texts are reworded (too long/large, non-UTF-8, unknown method, unknown resource); + // the codes are compared. + if let Some(e) = v.get_mut("error").and_then(Value::as_object_mut) { + let code = e.get("code").and_then(Value::as_i64).unwrap_or(0); + if [-32601, -32002].contains(&code) || e.get("message").and_then(Value::as_str).is_some_and(|m| m.contains("too ") || m.contains("UTF-8")) { + e.insert("message".into(), json!("")); + } + } + // 3. Document ids come from a process-wide counter, so two sessions in one process differ. + if let Some(text) = v.pointer_mut("/result/content/0/text") + && let Some(Ok(mut j)) = text.as_str().map(serde_json::from_str::) + { + zero_ids(&mut j); + *text = json!(j.to_string()); + } + // 4. A tool call refused before the tool runs: the validator's own words. + if free_text && v.pointer("/result/isError") == Some(&json!(true)) { + v["result"]["content"] = json!(""); + } + v +} + +fn zero_ids(v: &mut Value) { + match v { + Value::Object(o) => { + for (k, x) in o.iter_mut() { + if k == "id" && x.is_number() { + *x = json!(0); + } else { + zero_ids(x); + } + } + } + Value::Array(a) => a.iter_mut().for_each(zero_ids), + _ => {} + } +} + +fn run_oracle(input: &[u8]) -> Vec { + let mut server = oracle::Server::new(Box::new(Headless::default())); + let mut out = Vec::new(); + server.serve(std::io::Cursor::new(input.to_vec()), &mut out).unwrap(); + lines(out) +} + +fn run_shared(input: &[u8]) -> Vec { + let mut server = Server::new(Box::new(Headless::default())); + let mut out = Vec::new(); + server.serve(std::io::Cursor::new(input.to_vec()), &mut out).unwrap(); + lines(out) +} + +fn lines(out: Vec) -> Vec { + String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap_or_else(|e| panic!("{e}: {l}"))).collect() +} + +/// Both servers answer a line at a time, so each step is compared on its own reply (or lack of one). +fn compare(steps: &[Step]) { + let mut old = oracle::Server::new(Box::new(Headless::default())); + let mut new = Server::new(Box::new(Headless::default())); + for (i, s) in steps.iter().enumerate() { + let text = String::from_utf8_lossy(&s.line).into_owned(); + let (a, b) = (old.handle_line(&text), new.handle_line(&text)); + let parse = |r: Option| r.map(|r| normalise(serde_json::from_str::(&r).unwrap(), s.free_text)); + assert_eq!(parse(b), parse(a), "step {i}: {text}"); + } + assert_eq!(old.is_initialized(), new.is_initialized()); +} + +#[test] +fn shared_server_answers_the_scripted_session_like_the_old_one() { + compare(&script()); +} + +/// The same session as a byte stream through `serve`, with an oversize line and a line that is +/// not UTF-8 in the middle: same replies, same order. +#[test] +fn serve_matches_the_old_server_with_an_oversize_and_a_non_utf8_line() { + let mut input = Vec::new(); + for (i, s) in script().iter().enumerate() { + if i == 20 { + input.extend(vec![b'a'; (1 << 20) + 1]); + input.push(b'\n'); + input.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\",\"x\":\"\xff\xfe\"}\n"); + // Exactly at the limit is accepted (and is a parse error); one over is refused. + input.extend(vec![b' '; 1 << 20]); + input.push(b'\n'); + input.extend(vec![b'{'; 1 << 20]); + input.push(b'\n'); + } + input.extend_from_slice(&s.line); + input.push(b'\n'); + } + // An unterminated last line still counts. + input.extend_from_slice(br#"{"jsonrpc":"2.0","id":9,"method":"ping"}"#); + let (old, new) = (run_oracle(&input), run_shared(&input)); + let norm = |v: Vec| v.into_iter().map(|r| normalise(r, false)).collect::>(); + // The script's free-text failures are only compared in `compare`; drop their texts here. + let strip = |v: Vec| -> Vec { + v.into_iter() + .map(|mut r| { + if r.pointer("/result/isError") == Some(&json!(true)) + && r["result"]["content"][0]["text"].as_str().is_some_and(|t| !t.starts_with('{') && !t.starts_with('[')) + { + r["result"]["content"] = json!(""); + } + r + }) + .collect() + }; + let (old, new) = (strip(norm(old)), strip(norm(new))); + assert_eq!(new.len(), old.len()); + for (i, (n, o)) in new.iter().zip(&old).enumerate() { + assert_eq!(n, o, "reply {i}"); + } +} + +/// Difference 1 (accepted): the oversize and non-UTF-8 replies keep their codes, the words change. +#[test] +fn refused_lines_keep_their_codes_and_say_why() { + let mut input = vec![b'a'; (1 << 20) + 1]; + input.extend_from_slice(b"\n\xff\n"); + let old = run_oracle(&input); + let new = run_shared(&input); + assert_eq!(old[0]["error"]["code"], -32600); + assert_eq!(new[0]["error"]["code"], -32600); + assert_eq!(old[0]["error"]["message"], "request line too long"); + assert_eq!(new[0]["error"]["message"], "request too large"); + assert_eq!(old[1]["error"]["code"], -32700); + assert_eq!(new[1]["error"]["code"], -32700); + assert!(new[1]["error"]["message"].as_str().unwrap().contains("UTF-8")); + assert_eq!(new[0]["id"], Value::Null); +} + +/// Difference 2 (accepted): a request with no `uri` is "unknown resource" -32002, not -32602 +/// (the shared core hands the tools an empty uri); an unknown uri keeps -32002. +#[test] +fn resources_read_without_a_uri_is_not_found() { + let mut old = oracle::Server::new(Box::new(Headless::default())); + let mut new = Server::new(Box::new(Headless::default())); + let line = req(json!(1), "resources/read", json!({})); + let line = String::from_utf8(line).unwrap(); + let o: Value = serde_json::from_str(&old.handle_line(&line).unwrap()).unwrap(); + let n: Value = serde_json::from_str(&new.handle_line(&line).unwrap()).unwrap(); + assert_eq!(o["error"]["code"], -32602); + assert_eq!(n["error"]["code"], -32002); +} + +/// Difference 3 (accepted): the shared core serves `prompts/list` (empty) where the old server +/// said "method not found"; WordCraft has no prompts, and `prompts/get` stays not found. +#[test] +fn prompts_list_is_empty_and_prompts_get_is_not_found() { + let mut new = Server::new(Box::new(Headless::default())); + let r = new.handle(json!({"jsonrpc": "2.0", "id": 1, "method": "prompts/list"})).unwrap(); + assert_eq!(r["result"], json!({"prompts": []})); + let r = new.handle(json!({"jsonrpc": "2.0", "id": 2, "method": "prompts/get", "params": {"name": "x"}})).unwrap(); + assert_eq!(r["error"]["code"], -32601); + // And capabilities do not advertise prompts or completions. + let r = new.handle(json!({"jsonrpc": "2.0", "id": 3, "method": "initialize", "params": {}})).unwrap(); + assert_eq!(r["result"]["capabilities"], json!({"tools": {"listChanged": false}, "resources": {"listChanged": false}})); +} + +/// Difference 4 (accepted hardening): a batch of more than 1000 messages is refused whole; the old +/// server answered every member. +#[test] +fn batches_are_capped_at_a_thousand() { + let batch = |n: usize| Value::Array((0..n).map(|i| json!({"jsonrpc": "2.0", "id": i, "method": "ping"})).collect()).to_string(); + let mut old = oracle::Server::new(Box::new(Headless::default())); + let mut new = Server::new(Box::new(Headless::default())); + let (a, b) = (old.handle_line(&batch(1000)).unwrap(), new.handle_line(&batch(1000)).unwrap()); + assert_eq!(a, b); + let a: Value = serde_json::from_str(&old.handle_line(&batch(1001)).unwrap()).unwrap(); + let b: Value = serde_json::from_str(&new.handle_line(&batch(1001)).unwrap()).unwrap(); + assert_eq!(a.as_array().map(Vec::len), Some(1001)); + assert_eq!(b["error"]["code"], -32600); +} + +/// Difference 5 (accepted, stricter): arguments the tool's schema does not list, or of another +/// type, are a tool error before the tool runs. The old server passed them on and ignored them. +#[test] +fn unknown_and_mistyped_arguments_are_tool_errors() { + let mut new = Server::new(Box::new(Headless::default())); + for (name, args, needle) in [ + ("type_text", json!({"text": "x", "bogus": 1}), "unknown argument `bogus`"), + ("get_text", json!({"x": 1}), "unknown argument `x`"), + ("type_text", json!({"text": 5}), "must be of type"), + ("select_text", json!({"text": "x", "occurrence": "1"}), "must be of type"), + ] { + let r = new.handle(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}})).unwrap(); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains(needle), "{r}"); + assert!(r.get("error").is_none(), "a tool failure is a result, not a JSON-RPC error: {r}"); + } +} + +/// Difference 6 (accepted, stricter): a required argument that is missing is refused before the +/// tool runs, where `type_text` and `select_text` used to treat a missing `text` as "". The +/// schemas have always listed `text` as required, so the call was never valid. +#[test] +fn a_missing_required_argument_is_refused_where_the_tool_defaulted_it() { + let mut old = oracle::Server::new(Box::new(Headless::default())); + let mut new = Server::new(Box::new(Headless::default())); + for name in ["type_text", "select_text"] { + let line = String::from_utf8(req(json!(1), "tools/call", json!({"name": name, "arguments": {}}))).unwrap(); + let o: Value = serde_json::from_str(&old.handle_line(&line).unwrap()).unwrap(); + let n: Value = serde_json::from_str(&new.handle_line(&line).unwrap()).unwrap(); + // type_text {} used to type nothing and succeed; select_text {} failed to find "". + assert_eq!(o["result"]["isError"], name == "select_text", "{name}: {o}"); + assert_eq!(n["result"]["isError"], true, "{name}: {n}"); + assert!(n["result"]["content"][0]["text"].as_str().unwrap().contains("missing required argument `text`"), "{n}"); + } +} + +/// Every argument the tools read, and every one the documentation shows, passes the check: the +/// schemas list what the tools accept, so no call that worked now fails. +#[test] +fn every_documented_call_passes_the_argument_check() { + use craft_mcp_server::check_arguments; + let defs = crate::tools::tool_definitions(); + let defs = defs.as_array().unwrap(); + for (name, args) in [ + ("list_commands", json!({"query": "x"})), + ("execute", json!({"command": "insert.table", "params": {"rows": 3, "cols": 4}, "doc": 3})), + ("insert_table", json!({"values": [["Month", "Cases"], ["January", 12]], "header": true, "style": "TableGrid", "doc": 1})), + ("batch", json!({"commands": [{"command": "a"}], "keepGoing": true, "doc": 0})), + ("new_document", json!({"template": "letter"})), + ("open_document", json!({"path": "a.docx", "password": "p"})), + ("save_document", json!({"path": "a.pdf", "doc": 2})), + ("type_text", json!({"text": "x", "paragraphs": true, "doc": 2})), + ("select_text", json!({"text": "x", "occurrence": 2, "doc": 2})), + ("get_text", json!({"doc": 2})), + ("inspect_document", json!({"doc": 2})), + ("render_page", json!({"page": 1, "scale": 0.5, "doc": 2})), + ("list_documents", json!({})), + ("parity", json!({})), + ("screenshot", json!({})), + ("click", json!({"x": 1, "y": 2, "count": 2, "button": "right", "shift": true, "alt": true, "cmd": true, "ctrl": true, "command": true})), + ("key", json!({"key": "B", "shift": true, "alt": true, "cmd": true, "ctrl": true, "command": true})), + ("ui_inspect", json!({})), + ] { + assert_eq!(check_arguments(defs, name, &args), Ok(()), "{name}"); + } + // Every tool is covered above. + assert_eq!(defs.len(), 18); +} + +/// Hostile and random input never panics or breaks the stream: every reply is one JSON line. +#[test] +fn random_lines_never_panic() { + let mut x: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + let valid: Vec> = script().into_iter().map(|s| s.line).filter(|l| !l.is_empty()).collect(); + let toks: [&[u8]; 14] = + [b"{", b"}", b"[", b"]", b"\"", b":", b",", b"null", b"\"method\"", b"\"id\"", b"\"params\"", b"\"tools/call\"", b"\"arguments\"", b"\xff"]; + let mut input = Vec::new(); + for _ in 0..1500 { + let mut line = match next() % 3 { + // Random bytes. + 0 => (0..next() % 64).map(|_| (next() & 0xff) as u8).collect(), + // JSON-ish tokens. + 1 => (0..next() % 20).flat_map(|_| toks[(next() % 14) as usize].to_vec()).collect(), + // A valid request, mutated: bytes flipped, cut, or doubled. + _ => { + let mut l = valid[(next() % valid.len() as u64) as usize].clone(); + for _ in 0..next() % 4 { + if l.is_empty() { + break; + } + let at = (next() % l.len() as u64) as usize; + match next() % 3 { + 0 => l[at] = (next() & 0xff) as u8, + 1 => l.truncate(at), + _ => l.insert(at, toks[(next() % 14) as usize][0]), + } + } + l + } + }; + line.retain(|&b| b != b'\n'); + // Keep random lines from naming tools that touch the disk. + if String::from_utf8_lossy(&line).contains("save_document") || String::from_utf8_lossy(&line).contains("open_document") { + continue; + } + input.extend(line); + input.push(b'\n'); + } + let replies = run_shared(&input); + for r in replies { + assert!(r.is_object() || r.is_array(), "{r}"); + } +} diff --git a/crates/mcp/src/tests/oracle.rs b/crates/mcp/src/tests/oracle.rs new file mode 100644 index 0000000000..487865a7ee --- /dev/null +++ b/crates/mcp/src/tests/oracle.rs @@ -0,0 +1,174 @@ +//! The hand-written MCP server core WordCraft had before it moved to `craft_mcp_server`, kept +//! verbatim as the oracle the differential test compares the shared server against. + +use std::io::{BufRead, Write}; + +use serde_json::{Value, json}; + +use crate::backend::Backend; +use crate::server::{BoundedLine, MAX_REQUEST_LINE, read_bounded_line}; +use crate::server::{COMMANDS_URI, DOC_URI}; +use crate::tools::{call_tool, tool_definitions}; + +/// The MCP revision we implement. +pub(crate) const PROTOCOL_VERSION: &str = "2025-06-18"; +const SUPPORTED_VERSIONS: &[&str] = &[PROTOCOL_VERSION, "2025-03-26", "2024-11-05"]; + +const PARSE_ERROR: i64 = -32700; +const INVALID_REQUEST: i64 = -32600; +const METHOD_NOT_FOUND: i64 = -32601; +const INVALID_PARAMS: i64 = -32602; +const INTERNAL_ERROR: i64 = -32603; +const RESOURCE_NOT_FOUND: i64 = -32002; + +const INSTRUCTIONS: &str = "WordCraft is a word processor (a Microsoft Word clone). Every action is a command: find ids and \ +parameters with list_commands and run them with execute (or several with batch). Positions are \ +{story:\"body\", path:[block,(row,cell,block)...], off:byteOffset}. Typical flow: new_document → type_text \ +\"Hello\" → execute text.newParagraph → execute para.style {style:\"Heading 1\"} → select_text {text:\"Hello\"} → \ +execute format.bold → inspect_document to verify → render_page to look at the result → save {path:\"out.docx\"}. \ +Several documents can be open: new_document and open_document open another one and make it active; \ +list_documents gives their ids, and `doc` on execute, batch and the other document tools works on one \ +without switching."; + +/// An MCP server bound to one backend. +pub(crate) struct Server { + backend: Box, + initialized: bool, +} + +fn response(id: Value, result: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "result": result}) +} + +fn error(id: Value, code: i64, message: impl Into) -> Value { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) +} + +impl Server { + pub fn new(backend: Box) -> Self { + Self { backend, initialized: false } + } + + /// Whether the client has sent `notifications/initialized`. + pub fn is_initialized(&self) -> bool { + self.initialized + } + + /// Serve newline-delimited JSON-RPC until `input` closes. Logs go to stderr only (stdout is + /// the protocol stream). + pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + loop { + let reply = match read_bounded_line(&mut input, MAX_REQUEST_LINE) { + Ok(BoundedLine::Eof) => break, + Ok(BoundedLine::Line(line)) => self.handle_line(&line), + Ok(BoundedLine::TooLong) => Some(error(Value::Null, INVALID_REQUEST, "request line too long").to_string()), + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + Some(error(Value::Null, PARSE_ERROR, "request line is not UTF-8").to_string()) + } + Err(e) => return Err(e), + }; + if let Some(reply) = reply { + output.write_all(reply.as_bytes())?; + output.write_all(b"\n")?; + output.flush()?; + } + } + Ok(()) + } + + /// Handle one line; returns the reply line (None for notifications and blank lines). + pub fn handle_line(&mut self, line: &str) -> Option { + let line = line.trim(); + if line.is_empty() { + return None; + } + let reply = match serde_json::from_str::(line) { + Ok(Value::Array(batch)) => { + // Batches were removed in 2025-06-18; still answer older clients sensibly. + if batch.is_empty() { + Some(error(Value::Null, INVALID_REQUEST, "empty batch")) + } else { + let replies: Vec = batch.into_iter().filter_map(|m| self.handle(m)).collect(); + (!replies.is_empty()).then_some(Value::Array(replies)) + } + } + Ok(msg) => self.handle(msg), + Err(e) => Some(error(Value::Null, PARSE_ERROR, format!("parse error: {e}"))), + }; + reply.map(|r| r.to_string()) + } + + /// Handle one JSON-RPC message; `None` for notifications and responses. + pub fn handle(&mut self, msg: Value) -> Option { + let Value::Object(o) = &msg else { return Some(error(Value::Null, INVALID_REQUEST, "message must be an object")) }; + let id = o.get("id").cloned(); + let Some(method) = o.get("method").and_then(Value::as_str) else { + // A response to a server→client request (we send none): ignore. Anything else is invalid. + if o.contains_key("result") || o.contains_key("error") { + return None; + } + return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); + }; + let params = o.get("params").cloned().unwrap_or(Value::Null); + let Some(id) = id else { + self.notification(method); + return None; + }; + if !(id.is_string() || id.is_number()) { + return Some(error(Value::Null, INVALID_REQUEST, "`id` must be a string or number")); + } + Some(match self.request(method, ¶ms) { + Ok(r) => response(id, r), + Err((code, m)) => error(id, code, m), + }) + } + + fn notification(&mut self, method: &str) { + match method { + "notifications/initialized" => self.initialized = true, + "notifications/cancelled" | "notifications/progress" | "notifications/roots/list_changed" => {} + other => log::debug!("ignoring notification {other}"), + } + } + + fn request(&mut self, method: &str, params: &Value) -> Result { + match method { + "initialize" => { + let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION); + let version = if SUPPORTED_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSION }; + Ok(json!({ + "protocolVersion": version, + "capabilities": {"tools": {}, "resources": {}}, + "serverInfo": {"name": "wordcraft", "title": "WordCraft", "version": env!("CARGO_PKG_VERSION"), "websiteUrl": "https://getartcraft.com/apps/wordcraft"}, + "instructions": format!( + "{INSTRUCTIONS} Backend: {}. Community: https://discord.gg/artcraft · https://getartcraft.com/apps/wordcraft · https://github.com/storytold/wordcraft", + self.backend.describe() + ), + })) + } + "ping" => Ok(json!({})), + "tools/list" => Ok(json!({"tools": tool_definitions()})), + "tools/call" => { + let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?; + let args = params.get("arguments").cloned().unwrap_or(Value::Null); + Ok(call_tool(self.backend.as_mut(), name, &args).to_value()) + } + "resources/list" => Ok(json!({"resources": [ + {"uri": DOC_URI, "name": "document", "title": "Active document", "description": "Blocks, text, formatting, sections, parts and selection of the document (document.inspect)", "mimeType": "application/json"}, + {"uri": COMMANDS_URI, "name": "commands", "title": "Commands", "description": "Every command: id, label, ribbon location, shortcut, params, enabled (engine.commands)", "mimeType": "application/json"}, + ]})), + "resources/templates/list" => Ok(json!({"resourceTemplates": []})), + "resources/read" => { + let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing `uri`".to_string()))?; + let v = match uri { + DOC_URI => self.backend.call("document.inspect", json!({})), + COMMANDS_URI => self.backend.call("engine.commands", json!({})), + _ => return Err((RESOURCE_NOT_FOUND, format!("resource not found: {uri}"))), + } + .map_err(|e| (INTERNAL_ERROR, e))?; + Ok(json!({"contents": [{"uri": uri, "mimeType": "application/json", "text": serde_json::to_string_pretty(&v).unwrap_or_default()}]})) + } + other => Err((METHOD_NOT_FOUND, format!("method not found: {other}"))), + } + } +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 0dd2c734ab..02537c8b1a 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -169,14 +169,20 @@ pub fn tool_definitions() -> Value { "click", "Click", "Click at window coordinates (desktop app only).", - obj(json!({"x": n("x"), "y": n("y"), "count": n("1-3 clicks"), "shift": {"type": "boolean"}, "cmd": {"type": "boolean"}}), &["x", "y"]), + obj( + json!({"x": n("x"), "y": n("y"), "count": n("1-3 clicks"), "button": s("left (default) or right"), "shift": {"type": "boolean"}, "alt": {"type": "boolean"}, "cmd": {"type": "boolean"}, "ctrl": {"type": "boolean"}, "command": {"type": "boolean"}}), + &["x", "y"] + ), false ), tool( "key", "Press key", "Press a key with modifiers (desktop app only), e.g. {key:\"B\", cmd:true}.", - obj(json!({"key": s("Key name"), "shift": {"type": "boolean"}, "alt": {"type": "boolean"}, "cmd": {"type": "boolean"}}), &["key"]), + obj( + json!({"key": s("Key name"), "shift": {"type": "boolean"}, "alt": {"type": "boolean"}, "cmd": {"type": "boolean"}, "ctrl": {"type": "boolean"}, "command": {"type": "boolean"}}), + &["key"] + ), false ), tool( diff --git a/docs/mcp.md b/docs/mcp.md index 15b04ab989..5b0b8e1dee 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # MCP server -> **Last updated:** 2026-11-14 · Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. +> **Last updated:** 2026-11-17 · The protocol core is the shared `craft-mcp-server` crate (#778); `click` and `key` list every argument they accept. Earlier: Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. WordCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so Claude and other agents can write and edit documents. @@ -36,6 +36,17 @@ On stdio, an invalid UTF-8 request line returns JSON-RPC parse error `-32700`. I the backend, and the server continues with the next line instead of substituting characters in text or paths. +The protocol core (framing, lifecycle, `tools/*`, `resources/*`) is the shared `craft-mcp-server` +crate; WordCraft supplies the tools, resources and instructions. What that means for a client: + +- A request line over 1 MiB gets `-32600` "request too large" and the server keeps serving. +- A JSON-RPC batch holds at most 1000 messages; a larger one gets `-32600` "batch too large". +- A `tools/call` whose arguments do not match the tool's schema (a missing required argument, an + argument the tool does not list, or one of the wrong type) or that names an unknown tool returns + a tool result with `isError: true` naming the problem, not a JSON-RPC error. +- `resources/read` with no `uri` is `-32002` (unknown resource), like any unknown `uri`. +- `initialize` reports `listChanged: false` for tools and resources; `prompts/list` is empty. + ## Scripts from the command line `wordcraft-cli run --script job.json` (`--script -` reads standard input) runs the commands in a From 22a73d9f2d10de6ee52780ab4a6019b864d9c598 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:31:05 +0100 Subject: [PATCH 92/99] #778: progress log: file formats, codecs and protocols come from craft-libs (#6962) Co-authored-by: Claude Opus 5.5 --- ROADMAP.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 352e8751b0..b5cf968f5b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,7 +8,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** trivial (progress log: file formats, codecs and protocols from craft-libs, #778); previously trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. @@ -151,6 +151,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-11-17: File formats, codecs and protocols now come from the shared libraries (storytold/craft-libs#778): legacy code pages (craft-codepage, #6785), plain-text encoding detection (craft-mime, #6950), the ZIP entry-count guard (craft-zip, #6948), Read Aloud's Speech Dispatcher wire format (craft-ssip, #6951), picture probes for clipboard DIBs, JPEG memory, PNG and WebP (craft-image-codecs, #6949, #6955) and the MCP stdio server (craft-mcp-server, #6956), all with craft-libs pinned at main `93dac78c` (#6954, #6960). Opening documents and pictures behaves as before, except that large non-interleaved JPEGs are refused sooner (a 4:4:4 picture from about 60 Mpx, was 67 Mpx), invalid PNGs are refused more strictly, a lossless WebP's transparency is now seen, and MCP clients get tool errors for unknown or mistyped arguments and a 1,000-message batch cap (docs/mcp.md). The old code stays as test-only references the shared code is checked against. - 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing. - 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged. fix/6146-touchpad-scroll-speed @@ -401,6 +402,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-11-17 | trivial | Progress log: file formats, codecs and protocols come from craft-libs (#778) | | 2026-11-15 | trivial | Progress log: Get the Missing Fonts (download pages for missing fonts their publisher gives away) | | 2026-11-05 | trivial | Progress log: ODT documents keep their language (gap 19) | | 2026-11-04 | The CLI opens a non-Unicode input filename even after options such as `--page 2` or `--format flatopc`; text option values still require Unicode; `run --file` and `run --script` retain native paths. | From c3fe680a0f799cf571193960ada552b9b230e46b Mon Sep 17 00:00:00 2001 From: Bryan Mark Date: Wed, 18 Nov 2026 18:28:07 +0900 Subject: [PATCH 93/99] Fonts: fallback no longer keeps unneeded font families in memory Font fallback records the file stamp with the first coverage read, so a rescan does not keep loading families that are no longer needed, and a replaced file still invalidates the cache. Originally authored by @arcanii in #2345. --- crates/fonts/src/fontdb.rs | 4 +- crates/fonts/src/fontdb/fallback.rs | 102 +++++++------ crates/fonts/src/fontdb/fallback_data.rs | 177 ++++++++++++++++------ crates/fonts/src/fontdb/names.rs | 113 +++++++++----- crates/fonts/src/fontdb/tests/sysfonts.rs | 165 ++++++++++++++++++-- 5 files changed, 415 insertions(+), 146 deletions(-) diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index 6ae53ac460..d338b0b803 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -26,11 +26,11 @@ mod names; use face::{BUNDLED, FontBytes}; pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled}; +#[cfg(test)] +use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold}; #[cfg(not(target_arch = "wasm32"))] use fallback_data::{CoverageIndex, SysFallback}; use fallback_data::{FallbackCache, RunFallbackCache}; -#[cfg(test)] -use fallback_data::{RUN_FALLBACK_CACHE_CHARS, coverage_ranges, ranges_hold}; #[cfg(not(target_arch = "wasm32"))] use names::CatalogEntry; pub(crate) use names::face_names; diff --git a/crates/fonts/src/fontdb/fallback.rs b/crates/fonts/src/fontdb/fallback.rs index 8c18abb3cb..ffe5fa7b4e 100644 --- a/crates/fonts/src/fontdb/fallback.rs +++ b/crates/fonts/src/fontdb/fallback.rs @@ -1,6 +1,6 @@ use super::face::{FALLBACK_FAMILY, FontFace}; #[cfg(not(target_arch = "wasm32"))] -use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, coverage_ranges, ranges_hold, read_fallback_file}; +use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file}; use super::fallback_data::{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"))] @@ -235,7 +235,7 @@ impl FontDb { } /// Load a system font covering `c` (preferred fallback families first, then any cataloged - /// file under 40 MB, found through the coverage index). Returns true if one was loaded. + /// file under 40 MB, both found through the coverage index). Returns true if one was loaded. /// Misses are remembered. #[cfg(not(target_arch = "wasm32"))] fn system_fallback(&self, c: char) -> bool { @@ -257,6 +257,11 @@ impl FontDb { if self.is_loaded(fam) || !cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) { continue; } + // A family none of whose files maps `c` is not loaded for it: it would stay loaded + // and help nothing (an emoji loaded every CJK family a Mac has first, 500 MB). + if !self.family_maps(fam, c) { + continue; + } if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).tried.insert(fam) { continue; } @@ -276,8 +281,47 @@ impl FontDb { false } - /// Load the first cataloged font file (in path order) that maps `c`, reading each file not - /// yet indexed as the search reaches it. Returns whether a loaded face now covers `c`. + /// Does a file of the installed `family` map `c`? Answered by the coverage index, which reads + /// a file's character maps the first time it is asked about it. + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn family_maps(&self, family: &str, c: char) -> bool { + let paths = self.family_paths(family); + let mut index = self.coverage_index(); + paths.iter().any(|p| index.file_holds(p, u32::from(c))) + } + + /// The coverage index, its file list brought up to date with the catalog. + #[cfg(not(target_arch = "wasm32"))] + fn coverage_index(&self) -> std::sync::MutexGuard<'_, CoverageIndex> { + let mut index = self.coverage.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let generation = self.catalog_gen.load(Ordering::Acquire); + if index.generation != Some(generation) { + // A new scan (or the first search): keep what is known of files still installed, + // unless a file was replaced since its character maps were read. + let mut known: HashMap = + std::mem::take(&mut index.files).into_iter().map(|f| (f.path.clone(), f)).collect(); + let mut paths: Vec = + self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().map(|e| e.path.clone()).collect(); + paths.sort(); + paths.dedup(); + let files = paths.into_iter().map(|path| match known.remove(&path) { + Some(mut file) => { + if file.ranges.is_some() && file.stamp != file_stamp(&file.path) { + file.ranges = None; + } + file + } + None => IndexedFile { used: index.loaded.contains(&path), path, ranges: None, stamp: None }, + }); + index.files = files.collect(); + index.generation = Some(generation); + } + index + } + + /// Load the first cataloged font file (in path order) that maps `c`, reading the character + /// maps of each file not yet indexed as the search reaches it. Returns whether a loaded face + /// now covers `c`. #[cfg(not(target_arch = "wasm32"))] fn indexed_fallback(&self, c: char) -> bool { self.load_indexed(&[c], false) @@ -294,49 +338,22 @@ impl FontDb { self.load_indexed(chars, true); } - /// Load the cataloged font files (in path order) that map every char of `chars`, reading each - /// file not yet indexed as the search reaches it, until a loaded face covers them all; with - /// `whole_family`, each such file's family is loaded with it (whatever of it isn't loaded - /// yet). A collection's faces only together may map them: the search then goes on. Returns - /// whether a loaded face now covers them all. + /// Load the cataloged font files (in path order) that map every char of `chars`, reading the + /// character maps of each file not yet indexed as the search reaches it, until a loaded face + /// covers them all; with `whole_family`, each such file's family is loaded with it (whatever + /// of it isn't loaded yet). A collection's faces only together may map them: the search then + /// goes on. Returns whether a loaded face now covers them all. #[cfg(not(target_arch = "wasm32"))] fn load_indexed(&self, chars: &[char], whole_family: bool) -> bool { let covered = |db: &FontDb| db.read_faces().iter().any(|f| chars.iter().all(|c| f.covers(*c))); let cps: Vec = chars.iter().map(|c| u32::from(*c)).collect(); let maps_all = |ranges: &[(u32, u32)]| cps.iter().all(|cp| ranges_hold(ranges, *cp)); - let mut index = self.coverage.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let generation = self.catalog_gen.load(Ordering::Acquire); - if index.generation != Some(generation) { - // A new scan (or the first search): keep what is known of files still installed. - let mut known: HashMap = - std::mem::take(&mut index.files).into_iter().map(|f| (f.path.clone(), f)).collect(); - let mut paths: Vec = - self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().map(|e| e.path.clone()).collect(); - paths.sort(); - paths.dedup(); - let files = paths - .into_iter() - .map(|path| known.remove(&path).unwrap_or_else(|| IndexedFile { used: index.loaded.contains(&path), path, ranges: None })); - index.files = files.collect(); - index.generation = Some(generation); - } + let mut index = self.coverage_index(); let CoverageIndex { files, reads, .. } = &mut *index; for i in 0..files.len() { let Some(file) = files.get_mut(i).filter(|f| !f.used) else { continue }; - let mut data = None; - match &file.ranges { - Some(r) if !maps_all(r) => continue, - Some(_) => {} - None => { - *reads += 1; - data = read_fallback_file(&file.path); - let ranges = data.as_deref().map(coverage_ranges).unwrap_or_default(); - let hit = maps_all(&ranges); - file.ranges = Some(ranges); - if !hit { - continue; - } - } + if !maps_all(file.ranges(reads)) { + continue; } // The file maps them: load it (once; its faces are loaded fonts from now on). file.used = true; @@ -351,17 +368,12 @@ impl FontDb { load.push(f.path.clone()); } let fonts: Vec<(Vec, Option)> = load.iter().filter_map(|p| read_fallback_file(p)).map(|b| (b, None)).collect(); - *reads += fonts.len(); if self.add_fonts(fonts) > 0 && covered(self) { return true; } continue; } - if data.is_none() { - *reads += 1; - data = read_fallback_file(&file.path); - } - if let Some(data) = data + if let Some(data) = read_fallback_file(&file.path) && self.add_font(data) > 0 && covered(self) { diff --git a/crates/fonts/src/fontdb/fallback_data.rs b/crates/fonts/src/fontdb/fallback_data.rs index 91ffb08b64..a831c75e8a 100644 --- a/crates/fonts/src/fontdb/fallback_data.rs +++ b/crates/fonts/src/fontdb/fallback_data.rs @@ -1,7 +1,9 @@ -use super::face::{FALLBACK_FAMILY, FontFace}; -use super::{Arc, HashMap}; #[cfg(not(target_arch = "wasm32"))] -use super::{FileRef, MetadataProvider}; +use super::MetadataProvider; +use super::face::{FALLBACK_FAMILY, FontFace}; +#[cfg(not(target_arch = "wasm32"))] +use super::names::{TableReader, mini_font}; +use super::{Arc, HashMap}; #[cfg(not(target_arch = "wasm32"))] #[derive(Default)] @@ -17,14 +19,16 @@ pub(super) struct SysFallback { #[cfg(not(target_arch = "wasm32"))] pub(super) const SYS_MISSES_MAX: usize = 65_536; -/// Installed font files larger than this are not searched for fallback characters. +/// Installed font files larger than this are not loaded for a fallback character the coverage +/// index finds in them (a preferred fallback family loads whatever its size). #[cfg(not(target_arch = "wasm32"))] -const SYS_FALLBACK_MAX_FILE: u64 = 40 << 20; +pub(super) const SYS_FALLBACK_MAX_FILE: u64 = 40 << 20; /// Which characters each cataloged font file maps (#605). Before it, every distinct character no /// loaded font covered read and parsed every installed font file again: 500 distinct Tangut -/// characters froze the app for most of a minute. Now each file is read once, when a search -/// first gets to it, and later searches answer from its ranges, reading only a file that matches. +/// characters froze the app for most of a minute. Now each file's character maps are read once, +/// when a search first gets to it, and later searches answer from its ranges, loading only a file +/// that matches. The system fallback asks it too before loading a preferred family. #[cfg(not(target_arch = "wasm32"))] #[derive(Default)] pub(super) struct CoverageIndex { @@ -32,23 +36,58 @@ pub(super) struct CoverageIndex { pub(super) generation: Option, /// The cataloged font files, sorted. pub(super) files: Vec, - /// Font files read by fallback searches (each at most once to index it, once more to load it). + /// Font files whose character maps fallback searches read (each once, and again only when + /// a rescan finds it replaced). pub(super) reads: usize, /// Files loaded by family name ([`FontDb::load_cataloged`]), whether or not they are indexed /// yet: a search never loads them a second time. pub(super) loaded: std::collections::HashSet, } +#[cfg(not(target_arch = "wasm32"))] +impl CoverageIndex { + /// Does the cataloged file at `path` map `cp`? Its character maps are read the first time. + pub(super) fn file_holds(&mut self, path: &std::path::Path, cp: u32) -> bool { + let Ok(i) = self.files.binary_search_by(|f| f.path.as_path().cmp(path)) else { return false }; + let Some(file) = self.files.get_mut(i) else { return false }; + ranges_hold(file.ranges(&mut self.reads), cp) + } +} + #[cfg(not(target_arch = "wasm32"))] pub(super) struct IndexedFile { pub(super) path: std::path::PathBuf, /// The code points the file's faces map, as sorted, disjoint inclusive ranges (`None` until - /// the file is read; empty when it can't be read or is too large). + /// its character maps are read; empty when they can't be). pub(super) ranges: Option>, + /// The file's size and modification time when its character maps were read: a rescan + /// drops the ranges of a file replaced since. + pub(super) stamp: Option<(u64, std::time::SystemTime)>, /// Loaded for a character it covers: its faces are searched as loaded fonts from then on. pub(super) used: bool, } +#[cfg(not(target_arch = "wasm32"))] +impl IndexedFile { + /// The code points the file maps. Its character maps are read the first time (counted in + /// `reads`), and its stamp kept with them, so a rescan keeps them unless the file is replaced. + pub(super) fn ranges(&mut self, reads: &mut usize) -> &[(u32, u32)] { + let (path, stamp) = (&self.path, &mut self.stamp); + self.ranges.get_or_insert_with(|| { + *reads += 1; + *stamp = file_stamp(path); + file_coverage(path) + }) + } +} + +/// The size and modification time of the file at `path` (`None` when it can't be read). +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn file_stamp(path: &std::path::Path) -> Option<(u64, std::time::SystemTime)> { + let meta = std::fs::metadata(path).ok()?; + Some((meta.len(), meta.modified().ok()?)) +} + /// Does `ranges` (sorted, disjoint, inclusive) hold `cp`? #[cfg(not(target_arch = "wasm32"))] pub(super) fn ranges_hold(ranges: &[(u32, u32)], cp: u32) -> bool { @@ -56,56 +95,94 @@ pub(super) fn ranges_hold(ranges: &[(u32, u32)], cp: u32) -> bool { ranges.get(i).is_some_and(|r| r.0 <= cp) } -/// The code points mapped by the faces of `data` (a font file or collection), as sorted, -/// disjoint, inclusive ranges. Bounded however damaged the file: at most 256 faces, a budget of -/// mappings read across them, and a cap on the ranges kept. +/// The code points a font file's faces map, gathered face by face into sorted, disjoint, +/// inclusive ranges. Bounded however damaged the file: a budget of mappings read across its +/// faces, and a cap on the ranges kept. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn coverage_ranges(data: &[u8]) -> Box<[(u32, u32)]> { - const MAX_FACES: u32 = 256; - const MAX_MAPPINGS: usize = 4 * 0x11_0000; - const MAX_RANGES: usize = 1 << 17; - fn compact(r: &mut Vec<(u32, u32)>) { - r.sort_unstable(); - let mut out: Vec<(u32, u32)> = Vec::with_capacity(r.len()); - for &(s, e) in r.iter() { +#[derive(Default)] +pub(super) struct Coverage { + ranges: Vec<(u32, u32)>, + mappings: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Coverage { + pub(super) const MAX_MAPPINGS: usize = 4 * 0x11_0000; + pub(super) const MAX_RANGES: usize = 1 << 17; + + /// Add the code points `f` maps. False once a bound is reached: later faces are left out. + pub(super) fn add(&mut self, f: &skrifa::FontRef<'_>) -> bool { + f.charmap().mappings().all(|(cp, _)| self.push(cp)) + } + + /// Add one mapped code point. False once a bound is reached. + pub(super) fn push(&mut self, cp: u32) -> bool { + if self.mappings >= Self::MAX_MAPPINGS { + return false; + } + self.mappings += 1; + match self.ranges.last_mut() { + Some(last) if last.1.checked_add(1) == Some(cp) => last.1 = cp, + Some(last) if last.0 <= cp && cp <= last.1 => {} + _ => { + if self.ranges.len() >= Self::MAX_RANGES { + self.compact(); + // A compaction must free a quarter of the cap, or a crafted file could make + // every later mapping sort all the ranges again. + if self.ranges.len() > Self::MAX_RANGES / 4 * 3 { + return false; + } + } + self.ranges.push((cp, cp)); + } + } + true + } + + fn compact(&mut self) { + self.ranges.sort_unstable(); + let mut out: Vec<(u32, u32)> = Vec::with_capacity(self.ranges.len()); + for &(s, e) in self.ranges.iter() { match out.last_mut() { Some(last) if s <= last.1.saturating_add(1) => last.1 = last.1.max(e), _ => out.push((s, e)), } } - *r = out; + self.ranges = out; } - let count = match FileRef::new(data) { - Ok(FileRef::Font(_)) => 1, - Ok(FileRef::Collection(c)) => c.len().min(MAX_FACES), - Err(_) => 0, - }; - let mut ranges: Vec<(u32, u32)> = Vec::new(); - let mut budget = MAX_MAPPINGS; - 'faces: for i in 0..count { - let Ok(f) = skrifa::FontRef::from_index(data, i) else { continue }; - for (cp, _) in f.charmap().mappings() { - budget = match budget.checked_sub(1) { - Some(b) => b, - None => break 'faces, - }; - match ranges.last_mut() { - Some(last) if last.1.checked_add(1) == Some(cp) => last.1 = cp, - Some(last) if last.0 <= cp && cp <= last.1 => {} - _ => { - if ranges.len() >= MAX_RANGES { - compact(&mut ranges); - if ranges.len() >= MAX_RANGES { - break 'faces; - } - } - ranges.push((cp, cp)); - } - } + + pub(super) fn finish(mut self) -> Box<[(u32, u32)]> { + self.compact(); + self.ranges.into_boxed_slice() + } +} + +/// The code points the faces of the font file at `path` map, as sorted, disjoint, inclusive +/// ranges, read from their character maps (`cmap`) alone: Apple Color Emoji's 180 MB cost a few +/// kilobytes. Empty when the file can't be read. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn file_coverage(path: &std::path::Path) -> Box<[(u32, u32)]> { + /// The longest character map read (a format 12 map of every code point is 13 MB). + const MAX_CMAP: u32 = 16 << 20; + let mut coverage = Coverage::default(); + let Some(mut file) = TableReader::open(path) else { return coverage.finish() }; + // The faces of a collection often share one map: each is read once. + let mut read: Vec<(u32, u32)> = Vec::new(); + for face in 0..file.faces.len() { + let Some(at) = file.locate(face, b"cmap") else { continue }; + if read.contains(&at) { + continue; + } + read.push(at); + let Some(cmap) = file.read(at, MAX_CMAP) else { continue }; + // A font holding just the map, to read it as the font itself would. + let font = mini_font(&[(*b"cmap", cmap)]); + let Ok(f) = skrifa::FontRef::new(&font) else { continue }; + if !coverage.add(&f) { + break; } } - compact(&mut ranges); - ranges.into_boxed_slice() + coverage.finish() } /// An installed font file's bytes, `None` when it can't be read or is larger than diff --git a/crates/fonts/src/fontdb/names.rs b/crates/fonts/src/fontdb/names.rs index efa66719ee..3d097d87b9 100644 --- a/crates/fonts/src/fontdb/names.rs +++ b/crates/fonts/src/fontdb/names.rs @@ -145,43 +145,15 @@ const COLOR_BITMAP_TABLES: [&[u8; 4]; 2] = [b"sbix", b"CBDT"]; #[cfg(not(target_arch = "wasm32"))] pub(super) fn file_face_names(path: &std::path::Path) -> Vec { use crate::ui_fallback::OUTLINE_TABLES; - use std::io::{Read, Seek, SeekFrom}; - /// Caps on what a (possibly damaged) file can make the scan read. - const MAX_FACES: u32 = 256; + /// The longest `name`, `OS/2` or `fvar` table read. const MAX_TABLE: u32 = 1 << 20; - let Ok(mut file) = std::fs::File::open(path) else { return vec![] }; - let mut read_at = |offset: u64, len: usize| -> Option> { - let mut buf = vec![0; len]; - file.seek(SeekFrom::Start(offset)).ok()?; - file.read_exact(&mut buf).ok()?; - Some(buf) - }; - let be32 = |b: &[u8], at: usize| b.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes); - let Some(head) = read_at(0, 12) else { return vec![] }; - // A collection lists where each face's table directory starts. - let starts: Vec = if head.starts_with(b"ttcf") { - let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize; - read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default() - } else { - vec![0] - }; - starts - .into_iter() - .filter_map(|start| { - let dir = read_at(start.into(), 12)?; - let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize; - let records = read_at(u64::from(start) + 12, tables * 16)?; - if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().chain(&COLOR_BITMAP_TABLES).any(|t| r.starts_with(*t))) { + let Some(mut file) = TableReader::open(path) else { return vec![] }; + (0..file.faces.len()) + .filter_map(|face| { + if !OUTLINE_TABLES.iter().chain(&COLOR_BITMAP_TABLES).any(|t| file.locate(face, t).is_some()) { return None; } - let mut table = |tag: &[u8; 4]| -> Option> { - let rec = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?; - let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?); - if len > MAX_TABLE { - return None; - } - read_at(offset.into(), len as usize) - }; + let mut table = |tag: &[u8; 4]| file.locate(face, tag).and_then(|at| file.read(at, MAX_TABLE)); let name = table(b"name")?; // Variable fonts: the named instances; OS/2: the code pages (East Asian fonts). let mut tables: Vec<([u8; 4], Vec)> = table(b"OS/2").map(|t| (*b"OS/2", t)).into_iter().collect(); @@ -195,6 +167,79 @@ pub(super) fn file_face_names(path: &std::path::Path) -> Vec { .collect() } +/// A font file (or collection) read table by table instead of whole: the font folder scan and +/// the fallback coverage index open hundreds of files, many of them megabytes long (CJK +/// collections run to 20 MB and more, Apple Color Emoji to 180 MB). +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct TableReader { + file: std::fs::File, + /// Each face's table records (tag, checksum, offset, length), for the faces whose table + /// directory could be read. + pub(super) faces: Vec>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl TableReader { + /// Most faces read from a (possibly damaged) collection. + const MAX_FACES: u32 = 256; + + /// Open the font file at `path` and read its table directories; `None` when it can't be read. + pub(super) fn open(path: &std::path::Path) -> Option { + let file = std::fs::File::open(path).ok()?; + let mut reader = TableReader { file, faces: Vec::new() }; + let head = reader.read_at(0, 12)?; + // A collection lists where each face's table directory starts. + let starts: Vec = if head.starts_with(b"ttcf") { + let n = be32(&head, 8).unwrap_or(0).min(Self::MAX_FACES) as usize; + reader.read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default() + } else { + vec![0] + }; + for start in starts { + if let Some(records) = reader.directory(start) { + reader.faces.push(records); + } + } + Some(reader) + } + + /// The table records of the face whose table directory starts at `start`. + fn directory(&mut self, start: u32) -> Option> { + let dir = self.read_at(start.into(), 12)?; + let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize; + let records = self.read_at(u64::from(start) + 12, tables * 16)?; + Some(records.as_chunks::<16>().0.to_vec()) + } + + /// Where face `face`'s table `tag` is: (offset, length). + pub(super) fn locate(&self, face: usize, tag: &[u8; 4]) -> Option<(u32, u32)> { + let rec = self.faces.get(face)?.iter().find(|r| r.starts_with(tag))?; + Some((be32(rec, 8)?, be32(rec, 12)?)) + } + + /// The table at `(offset, length)`; `None` when it is longer than `max_len` or can't be read. + pub(super) fn read(&mut self, (offset, len): (u32, u32), max_len: u32) -> Option> { + if len > max_len { + return None; + } + self.read_at(offset.into(), len as usize) + } + + fn read_at(&mut self, offset: u64, len: usize) -> Option> { + use std::io::{Read, Seek, SeekFrom}; + let mut buf = vec![0; len]; + self.file.seek(SeekFrom::Start(offset)).ok()?; + self.file.read_exact(&mut buf).ok()?; + Some(buf) + } +} + +/// The big-endian `u32` at `at` in `b`. +#[cfg(not(target_arch = "wasm32"))] +fn be32(b: &[u8], at: usize) -> Option { + b.get(at..at.checked_add(4)?).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes) +} + /// A font file holding just `tables` (sorted by tag), each padded to four bytes. #[cfg(not(target_arch = "wasm32"))] pub(super) fn mini_font(tables: &[([u8; 4], Vec)]) -> Vec { diff --git a/crates/fonts/src/fontdb/tests/sysfonts.rs b/crates/fonts/src/fontdb/tests/sysfonts.rs index 7502c360ee..35a1909f95 100644 --- a/crates/fonts/src/fontdb/tests/sysfonts.rs +++ b/crates/fonts/src/fontdb/tests/sysfonts.rs @@ -305,13 +305,11 @@ fn fallback_cache_is_dropped_when_a_face_loads_by_its_legacy_family_name() { assert!(!cache.map.contains_key(&(missing, latin.id())), "answers from before the load are dropped"); } -#[test] -fn fallback_reads_each_installed_font_file_once_however_many_characters_miss() { - // #605: every distinct character no font covers read every installed font file again. - let dir = font_dir("coverage"); - // The installed Regular also maps U+30000 (no bundled font does): its last cmap group, the - // single character U+1F916, moved there (still the highest, so the groups stay sorted). - let mut regular = renamed("SourceSans3-Regular.ttf"); +/// A bundled Source Sans 3 Regular renamed `family` (13 characters) that also maps U+30000 (no +/// bundled font does): its last cmap group, the single character U+1F916, moved there (still the +/// highest, so the groups stay sorted). +fn mapping_u30000(family: &str) -> Vec { + let mut regular = renamed_to("SourceSans3-Regular.ttf", family); let (from, to) = ([0x0001_F916_u32.to_be_bytes(); 2].concat(), [0x0003_0000_u32.to_be_bytes(); 2].concat()); let mut patched = 0; while let Some(at) = regular.windows(from.len()).position(|w| w == from) { @@ -319,7 +317,14 @@ fn fallback_reads_each_installed_font_file_once_however_many_characters_miss() { patched += 1; } assert!(patched > 0); - std::fs::write(dir.join("Sysfont-Regular.ttf"), regular).unwrap(); + regular +} + +#[test] +fn fallback_reads_each_installed_font_file_once_however_many_characters_miss() { + // #605: every distinct character no font covers read every installed font file again. + let dir = font_dir("coverage"); + std::fs::write(dir.join("Sysfont-Regular.ttf"), mapping_u30000(FAMILY)).unwrap(); let db = FontDb::with_font_dirs(vec![dir]); let latin = db.face(FALLBACK_FAMILY, "Regular"); let found = db.fallback_for('\u{30000}', latin.id()).expect("the installed font maps it"); @@ -333,7 +338,7 @@ fn fallback_reads_each_installed_font_file_once_however_many_characters_miss() { } let index = db.coverage.lock().unwrap(); assert_eq!(index.files.len(), 2, "Regular and Bold are cataloged"); - assert_eq!(index.reads, 2, "each file read once"); + assert_eq!(index.reads, 2, "each file's character map read once"); } /// A bundled Source Sans 3 `file` renamed `family` whose last cmap group (the single character @@ -421,6 +426,45 @@ fn a_family_partly_loaded_by_a_character_fallback_is_loaded_whole_for_a_run() { assert_eq!(db.read_faces().iter().filter(|f| f.family == "Sysfont Famly").count(), 3); } +#[test] +fn a_preferred_fallback_family_loads_only_when_it_maps_the_character() { + // A character no loaded font covers loaded every installed family in the fallback list up + // to one that covers it, and kept them all: an emoji loaded every CJK family a Mac has, + // about 500 MB. Malgun Gothic comes before Apple Symbols in that list. + let dir = font_dir("preferred"); + std::fs::write(dir.join("Malgun.ttf"), renamed_to("SourceSans3-Regular.ttf", "Malgun Gothic")).unwrap(); + std::fs::write(dir.join("Symbols.ttf"), mapping_u30000("Apple Symbols")).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let latin = db.face(FALLBACK_FAMILY, "Regular"); + let found = db.fallback_for('\u{30000}', latin.id()).expect("Apple Symbols maps it"); + assert_eq!(found.family, "Apple Symbols"); + assert!(!db.is_loaded("Malgun Gothic"), "a family that lacks the character isn't loaded for it"); + assert_eq!(db.coverage.lock().unwrap().reads, 2, "only the two families' character maps were read"); + // The fallback order is unchanged: when both map it, the first in the list is chosen. + std::fs::write(dir.join("Malgun.ttf"), mapping_u30000("Malgun Gothic")).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let found = db.fallback_for('\u{30000}', latin.id()).expect("both map it"); + assert_eq!(found.family, "Malgun Gothic"); + assert!(!db.is_loaded("Apple Symbols")); +} + +#[test] +fn a_preferred_fallback_family_in_a_very_large_file_is_still_found() { + // The coverage index reads character maps, not whole files, so a preferred family is found + // whatever its size (PingFang is 75 MB, Apple Color Emoji 180 MB): here a font padded past + // the limit on files the index loads by itself. + let dir = font_dir("large"); + let mut data = mapping_u30000("Apple Symbols"); + data.resize(data.len() + SYS_FALLBACK_MAX_FILE as usize, 0); + std::fs::write(dir.join("Symbols.ttf"), &data).unwrap(); + drop(data); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let latin = db.face(FALLBACK_FAMILY, "Regular"); + let found = db.fallback_for('\u{30000}', latin.id()).map(|f| f.family.clone()); + std::fs::remove_file(dir.join("Symbols.ttf")).unwrap(); + assert_eq!(found.as_deref(), Some("Apple Symbols")); +} + #[test] fn screen_hinting_runs_a_tricky_fonts_instructions_with_the_monochrome_target() { // FreeType's "tricky" fonts (old CJK fonts listed by name, such as DynaLab's "cpop") assemble @@ -455,20 +499,111 @@ fn screen_hinting_runs_a_tricky_fonts_instructions_with_the_monochrome_target() } #[test] -fn coverage_ranges_hold_exactly_the_mapped_characters() { +fn coverage_holds_exactly_the_mapped_characters() { + let dir = font_dir("coverage-ranges"); let data = renamed("SourceSans3-Regular.ttf"); - let ranges = coverage_ranges(&data); + let ranges = file_coverage(&dir.join("Sysfont-Regular.ttf")); assert!(ranges.windows(2).all(|w| w[0].1 + 1 < w[1].0), "sorted, disjoint and merged"); let font = skrifa::FontRef::new(&data).unwrap(); let mapped: Vec = font.charmap().mappings().map(|(cp, _)| cp).collect(); assert!(ranges.len() < mapped.len() / 4, "ranges, not a set of characters"); assert!(mapped.iter().all(|cp| ranges_hold(&ranges, *cp))); - for cp in [0x0, 0x9, 0x0E01, 0x17000, 0x10_FFFF] { + for cp in [0x0, 0x9, 0x0E01, 0x17000, 0x3_0000, 0x10_FFFF] { assert_eq!(ranges_hold(&ranges, cp), font.charmap().map(cp).is_some(), "U+{cp:04X}"); } - // Damaged data indexes as nothing. - assert!(coverage_ranges(b"ttcf\0\x01\0\0\xff\xff\xff\xff").is_empty()); - assert!(coverage_ranges(&data[..100]).is_empty()); + // A collection: what its faces map together. + std::fs::write(dir.join("both.ttc"), collection(&[data.clone(), mapping_u30000(FAMILY)])).unwrap(); + let both = file_coverage(&dir.join("both.ttc")); + assert!(ranges_hold(&both, 0x3_0000) && mapped.iter().all(|cp| ranges_hold(&both, *cp))); + // Damaged, cut short, not a font or missing: nothing. + std::fs::write(dir.join("short.ttf"), &data[..100]).unwrap(); + for name in ["damaged.ttf", "short.ttf", "readme.txt", "missing.ttf"] { + assert!(file_coverage(&dir.join(name)).is_empty(), "{name}"); + } +} + +#[test] +fn coverage_stops_when_a_compaction_frees_too_little() { + // A crafted file whose faces interleave their code points made every mapping past the cap + // sort all the ranges again, freeing one: a compaction must free a quarter of the cap. + let cap = u32::try_from(Coverage::MAX_RANGES).unwrap(); + let mut c = Coverage::default(); + // One face maps every third code point, one range short of the cap; the next face maps the + // code points after them: the first fills the cap, the second compacts it and frees one. + assert!((0..cap - 1).all(|i| c.push(3 * i))); + assert!(c.push(1)); + assert!(!c.push(4), "a compaction that frees one range ends the file's coverage"); + // A compaction that frees enough goes on. + let mut c = Coverage::default(); + assert!((0..cap / 2).all(|i| c.push(2 * i)) && (0..cap / 2).all(|i| c.push(2 * i + 1))); + assert!(c.push(cap + 1), "the compaction merges every range"); + assert_eq!(&*c.finish(), &[(0, cap - 1), (cap + 1, cap + 1)]); +} + +#[test] +fn a_rescan_reads_a_replaced_font_files_character_maps_again() { + // A font updated in place since its character maps were read: what the update maps counts. + let dir = font_dir("replaced"); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + assert!(!db.family_maps(FAMILY, '\u{30000}')); + // The update is a few bytes longer, so it differs however coarse the file times are. + let mut data = mapping_u30000(FAMILY); + data.extend_from_slice(&[0; 4]); + std::fs::write(dir.join("Sysfont-Regular.ttf"), data).unwrap(); + assert!(!db.family_maps(FAMILY, '\u{30000}'), "the index answers until the folders are scanned again"); + db.load_system_fonts(); + assert!(db.family_maps(FAMILY, '\u{30000}')); + assert_eq!(db.coverage.lock().unwrap().reads, 3, "the unchanged Bold file isn't read again"); +} + +#[test] +fn a_rescan_keeps_the_character_maps_a_fallback_search_read() { + // Files indexed by a fallback search, not only by a family lookup, keep their character maps + // through a rescan: #605's hundreds of files aren't read again after each font folder change. + let dir = font_dir("rescan-fallback"); + std::fs::write(dir.join("Sysfont-Regular.ttf"), mapping_u30000(FAMILY)).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let latin = db.face(FALLBACK_FAMILY, "Regular"); + assert!(db.fallback_for('\u{30000}', latin.id()).is_some(), "the installed font maps it"); + assert_eq!(db.coverage.lock().unwrap().reads, 2, "the Bold file and then the Regular"); + db.load_system_fonts(); + // Nothing maps it: the search reaches the Bold file, which isn't loaded, and asks its ranges. + assert!(db.fallback_for('\u{F0001}', latin.id()).is_none()); + assert_eq!(db.coverage.lock().unwrap().reads, 2, "the rescan kept both files' character maps"); +} + +#[test] +fn coverage_of_installed_fonts_is_what_their_loaded_faces_map() { + // Read from the character maps alone, as the whole file maps. Uses installed fonts when + // there are some, collections among them. + let paths: Vec<&Path> = [ + "/System/Library/Fonts/Helvetica.ttc", + "/System/Library/Fonts/Hiragino Sans GB.ttc", + "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", + "C:\\Windows\\Fonts\\arial.ttf", + "C:\\Windows\\Fonts\\msyh.ttc", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/noto/NotoSans-Regular.ttf", + ] + .iter() + .map(Path::new) + .filter(|p| p.exists()) + .collect(); + if paths.is_empty() { + eprintln!("no known font installed: nothing to check"); + } + for path in paths { + let data = std::fs::read(path).unwrap(); + let faces = match FileRef::new(&data).unwrap() { + FileRef::Font(_) => 1, + FileRef::Collection(c) => c.len(), + }; + let mut whole = Coverage::default(); + for i in 0..faces { + assert!(whole.add(&skrifa::FontRef::from_index(&data, i).unwrap())); + } + assert_eq!(file_coverage(path), whole.finish(), "{}", path.display()); + } } /// A bundled font renamed by a `name` table holding just its family names: (Windows language id, From c3be9f094fa1baee182cc9868371e71275ca31df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Wed, 18 Nov 2026 16:28:30 +0700 Subject: [PATCH 94/99] #2702: a missing font is drawn in its font table's altName, as Word does A missing font is drawn in its font table altName, as Word does. The DOCX reader half lives in craft-libs#1426; this is the fonts, layout and settings half. Originally authored by @Nghiathan13 in #2711. --- crates/doc/src/settings.rs | 11 +++ crates/fonts/src/word.rs | 82 +++++++++++++++--- crates/layout/src/para/builder.rs | 32 ++++--- crates/layout/src/para/chars.rs | 62 ++++++++++---- crates/layout/src/tests.rs | 133 +++++++++++++++++++++++++++++ crates/layout/src/tests/complex.rs | 51 +++++++++++ 6 files changed, 330 insertions(+), 41 deletions(-) diff --git a/crates/doc/src/settings.rs b/crates/doc/src/settings.rs index b97019351c..1fd4e598dd 100644 --- a/crates/doc/src/settings.rs +++ b/crates/doc/src/settings.rs @@ -128,6 +128,15 @@ pub struct Settings { /// draws one that isn't installed in a serif face. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub roman_fonts: Vec, + /// Fonts the font table classes as modern (fixed pitch, `w:family w:val="modern"`): Word draws + /// one that isn't installed, and whose alternate isn't either, in a serif face (#2702). Not + /// the East Asian ones (`w:charset` 80, 81, 86, 88: MS Gothic, SimHei…). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub modern_fonts: Vec, + /// Alternate names the document's font table gives its fonts (`w:font/w:altName`), as (font, + /// alternate): Word draws a font that isn't installed in its alternate when that one is. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub font_alt_names: Vec<(String, String)>, /// `w:doNotUseHTMLParagraphAutoSpacing`: the space between two paragraphs is the first's space /// after plus the second's space before, not the larger of the two. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -325,6 +334,8 @@ impl Default for Settings { protect_hash: Vec::new(), compat_mode: COMPAT_MODE_CURRENT, roman_fonts: Vec::new(), + modern_fonts: Vec::new(), + font_alt_names: Vec::new(), sum_paragraph_spacing: false, do_not_expand_shift_return: false, allow_space_of_same_style_in_table: false, diff --git a/crates/fonts/src/word.rs b/crates/fonts/src/word.rs index 4860faf5a0..f9352a95bf 100644 --- a/crates/fonts/src/word.rs +++ b/crates/fonts/src/word.rs @@ -40,6 +40,23 @@ pub fn has_named_substitutes(family: &str) -> bool { const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "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] = &[ + "cambria", + "cambria math", + "georgia", + "garamond", + "constantia", + "baskerville old face", + "century", + "century schoolbook", + "bookman old style", + "sitka text", + "sitka", + "aptos serif", +]; + /// [`substitutes`], and whether they were chosen for this family by name. fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) { if family.contains(';') { @@ -149,18 +166,7 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) { "courier new" | "courier" | "consolas" | "lucida console" | "cascadia code" | "cascadia mono" => (MONO, true), "symbol" | "wingdings" | "wingdings 2" | "wingdings 3" | "segoe ui symbol" | "webdings" => (SYMBOL, true), // Serif faces with no open clone of their own: the generic serif list, as for any font. - "cambria" - | "cambria math" - | "georgia" - | "garamond" - | "constantia" - | "baskerville old face" - | "century" - | "century schoolbook" - | "bookman old style" - | "sitka text" - | "sitka" - | "aptos serif" => (SERIF, false), + _ if KNOWN_SERIFS.contains(&f.as_str()) => (SERIF, false), _ if f.contains("mono") || f.contains("code") => (MONO, false), _ if f.contains("serif") && !f.contains("sans") => (SERIF, false), _ => (SANS, false), @@ -207,6 +213,22 @@ pub fn charset_base_family(family: &str) -> &str { .map_or(family, str::trim_end) } +/// Whether `family` (or the font its charset name stands for) has substitutes of its own: Times +/// New Roman, Book Antiqua, Courier New, the symbol, Hebrew and Persian fonts, or a serif face we +/// know (Georgia, Garamond…), rather than the generic list a font we don't know gets, also when +/// its name only suggests one ("… Mono", "… Serif"). +pub fn has_own_substitutes(family: &str) -> bool { + let base = charset_base_family(family); + has_named_substitutes(base) || KNOWN_SERIFS.contains(&base.to_ascii_lowercase().as_str()) +} + +/// Whether `family` has substitutes of its own ([`has_own_substitutes`]) and one of them is +/// installed, so [`resolve`] draws it in a face chosen for it rather than the generic fallback. +pub fn has_installed_substitute(family: &str) -> bool { + let base = charset_base_family(family); + has_own_substitutes(base) && substitute(FontDb::global(), base).is_some() +} + /// Fonts made to measure alike (the same advance widths and line height), so text drawn in one /// wraps and paginates as in the others: Carlito for Calibri, Caladea for Cambria, Liberation and /// Croscore fonts for Arial, Times New Roman and Courier New, the Palatino look-alikes for Palatino @@ -848,6 +870,42 @@ mod tests { assert_eq!(substitutes(charset_base_family("Times New Roman Cyr")), substitutes("Times New Roman")); } + /// #2702 review: an alternate counts as drawable only when one of its own substitutes is + /// installed; a font without a list of its own never does. + #[test] + fn installed_substitutes_are_the_fonts_own_and_installed() { + let db = FontDb::global(); + for f in ["Times New Roman", "Wingdings", "Courier New", "Book Antiqua"] { + let any = substitutes(f).iter().any(|s| db.has_family(s)); + assert_eq!(has_installed_substitute(f), any, "{f}"); + } + for f in ["No Such Brand Font", ""] { + assert!(!has_installed_substitute(f), "{f}"); + } + } + + #[test] + fn fonts_known_by_name_have_their_own_substitutes() { + for f in [ + "Times New Roman", + "times", + "Times New Roman Cyr", + "Book Antiqua", + "Palatino Linotype", + "Courier New", + "Arial", + "Georgia", + "Wingdings", + "David", + ] { + assert!(has_own_substitutes(f), "{f}"); + } + // A name that only suggests a list ("… Mono", "… Serif") isn't a font we know. + for f in ["No Such Brand Font", "NewCenturySchlbk", "", "Brand Serif", "Foo Mono", "Source Code Pro"] { + assert!(!has_own_substitutes(f), "{f}"); + } + } + #[test] fn pcl6_symbol_has_symbols_line_metrics() { assert_eq!(symbol_font_metrics("Symbol (PCL6)"), symbol_font_metrics("Symbol")); diff --git a/crates/layout/src/para/builder.rs b/crates/layout/src/para/builder.rs index 99ae60f6f3..927887baba 100644 --- a/crates/layout/src/para/builder.rs +++ b/crates/layout/src/para/builder.rs @@ -214,7 +214,9 @@ impl<'a> Builder<'a> { if let Some(f) = missing.latin.filter(|_| asks_latin) { self.note_substituted(f, drawn); } - if let Some(f) = missing.east_asian.filter(|_| !in_ea_font && sub.chars().any(east_asian)) { + // A missing East Asian font has no face of its own: CJK text drawn in the East Asian + // face is in its font table alternate (#2702) and still asks for it. + if let Some(f) = missing.east_asian.filter(|_| sub.chars().any(east_asian)) { self.note_substituted(f, drawn); } } @@ -248,25 +250,29 @@ impl<'a> Builder<'a> { let rc_cs: Option> = text.chars().any(|c| rc.uses_complex(c)).then(|| Arc::new(rc.complex())); let family = lookup_family(self.env.doc, &rc.font); let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic); + // The requested font is missing when it was substituted, or when another family stands in + // for it: its font table alternate (#2702), which may itself be installed. + let requested_missing = resolved.substituted || !family.eq_ignore_ascii_case(&rc.font); let primary = resolved.face; // Symbol-font characters are laid out as their Unicode equivalents. let sym = SymbolRun::of(&rc.font, &resolved); let show = |c: char| sym.map_or(c, |m| m.show(c)); - // A font isn't installed when it was substituted, or looked up as a missing roman font. + // A font isn't installed when it was substituted, or looked up as a missing roman font or + // its font table alternate (#2702). let resolved_cs = rc_cs.as_ref().map(|r| { let family = lookup_family(self.env.doc, &r.font); let resolved = wordcraft_fonts::word::resolve(family, r.bold, r.italic); - (resolved.face, resolved.substituted || family != r.font) + (resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font)) }); let primary_cs = resolved_cs.map(|(face, _)| face); // Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsia`) when - // it is installed and has them. - let wanted_ea = rc - .font_ea - .as_deref() - .filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)) - .map(|f| (f, wordcraft_fonts::word::resolve(f, rc.bold, rc.italic))); - let primary_ea = wanted_ea.filter(|(_, r)| !r.substituted).map(|(_, r)| r.face); + // it, or the font table alternate it is drawn in (#2702), is installed and has them. + let wanted_ea = rc.font_ea.as_deref().filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| { + let family = lookup_family(self.env.doc, f); + let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic); + (f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f)) + }); + let primary_ea = wanted_ea.filter(|(_, r, _)| !r.substituted).map(|(_, r, _)| r.face); // The levels by byte of `text`, from `lbase` on. let (levels, lbase): (&[u8], usize) = match dir { Dir::Para => (&self.levels, base), @@ -278,7 +284,7 @@ impl<'a> Builder<'a> { // A missing Thai font: one face for the run's Thai and Latin text (#1549). A run with its // own complex-script font keeps that font for the Thai letters. let run_face: Option = if primary_cs.is_none_or(|f| f.id() == primary.id()) { - thai_run_face(&rc.font, resolved.substituted, primary, text, rc.bold, rc.italic) + thai_run_face(&rc.font, requested_missing, primary, text, rc.bold, rc.italic) } else { None }; @@ -314,9 +320,9 @@ impl<'a> Builder<'a> { context: &context, }); let missing = MissingFonts { - latin: (resolved.substituted || family != rc.font).then_some(rc.font.as_str()), + latin: requested_missing.then_some(rc.font.as_str()), complex: rc_cs.as_ref().filter(|_| resolved_cs.is_some_and(|(_, missing)| missing)).map(|r| r.font.as_str()), - east_asian: wanted_ea.filter(|(_, r)| r.substituted).map(|(f, _)| f), + east_asian: wanted_ea.filter(|(_, _, missing)| *missing).map(|(f, _, _)| f), names_east_asian: wanted_ea.is_some(), }; self.note_missing_fonts(text, &segs, (primary, primary_cs, primary_ea), &missing); diff --git a/crates/layout/src/para/chars.rs b/crates/layout/src/para/chars.rs index b68d578287..d8c0bec822 100644 --- a/crates/layout/src/para/chars.rs +++ b/crates/layout/src/para/chars.rs @@ -124,23 +124,52 @@ pub(crate) fn remap_range(map_starts: &[usize], orig_of: &[usize], orig_len: usi /// as roman (measured in Word; Calibri otherwise, which our own substitutes already match). pub(super) const MISSING_ROMAN_FONT: &str = "Cambria"; -/// The family to look `font` up as: [`MISSING_ROMAN_FONT`] for a missing roman font, else `font`. -/// A missing Thai font keeps its name: it is drawn in a Thai face, not in Cambria (#1549). -/// A font with substitutes of its own keeps them: Times New Roman is roman in every font table, -/// and where it isn't installed Liberation Serif has its metrics; Word never meets it missing. -pub(super) fn lookup_family<'f>(doc: &Document, font: &'f str) -> &'f str { +/// The family to look `font` up as. A font that isn't installed is drawn, as Word draws it +/// (measured in Word 2024, #2702): +/// 1. in the alternate the font table names for it (`w:altName`), when that one can be drawn: +/// installed, or a font one of whose own substitutes is installed. That comes before the +/// family class: a roman font with an installed alternate is drawn in the alternate; +/// 2. in [`MISSING_ROMAN_FONT`] when the font table classes it as roman, or as modern with an +/// alternate that can't be drawn either (a modern font with no alternate, and a swiss one with +/// or without, take the generic substitutes, as Calibri does in Word). Not for a Thai font +/// (drawn in a Thai face, #1549), a symbol font, or a font with substitutes of its own (Times +/// New Roman is roman in every font table, and where it isn't installed Liberation Serif has +/// its metrics; Word never meets it missing); +/// 3. else as `font`, which [`wordcraft_fonts::word::resolve`] substitutes. +pub(super) fn lookup_family<'f>(doc: &'f Document, font: &'f str) -> &'f str { + let settings = &doc.settings; + // A fallback list (`Liberation Serif;Times New Roman`) is in a class when one of its + // candidates is. + let listed = |list: &[String]| { + !list.is_empty() && font.split(';').map(str::trim).filter(|f| !f.is_empty()).any(|f| list.iter().any(|r| r.eq_ignore_ascii_case(f))) + }; + let alternate = settings.font_alt_names.iter().find(|(f, _)| f.eq_ignore_ascii_case(font)).map(|(_, alt)| alt.as_str()); + let roman = listed(&settings.roman_fonts); + if alternate.is_none() && !roman { + return font; + } let db = wordcraft_fonts::FontDb::global(); - let roman = !doc.settings.roman_fonts.is_empty() - && font.split(';').map(str::trim).filter(|f| !f.is_empty()).any(|f| doc.settings.roman_fonts.iter().any(|r| r.eq_ignore_ascii_case(f))); - if roman + let installed = |f: &str| db.has_family(f) || db.has_family(wordcraft_fonts::word::charset_base_family(f)); + // A fallback list is there when one of its candidates is. + let missing = if font.contains(';') { wordcraft_fonts::word::resolve(font, false, false).substituted } else { !installed(font) }; + if !missing { + return font; + } + // Calibri has no list of its own because the generic sans list is its (Carlito first). + let drawable = + |f: &&str| !f.is_empty() && (installed(f) || wordcraft_fonts::word::has_installed_substitute(f) || f.eq_ignore_ascii_case("Calibri")); + // ECMA-376 calls the alternate a comma-separated list, but Word reads the whole value as one + // name (MS-OE376 2.1.264), so a value with a comma names a font that isn't there. + if let Some(alt) = alternate.map(str::trim).filter(drawable) { + return alt; + } + let modern_alternate_missing = alternate.is_some() && listed(&settings.modern_fonts); + // Thai, symbol and fonts with substitutes of their own keep their name: those substitutes + // draw them, Cambria wouldn't. + if (roman || modern_alternate_missing) && !wordcraft_fonts::word::is_thai_family(font) && !wordcraft_doc::symbol_fonts::is_symbol_font(font) && !wordcraft_fonts::word::has_named_substitutes(font) - && if font.contains(';') { - wordcraft_fonts::word::resolve(font, false, false).substituted - } else { - !db.has_family(font) && !db.has_family(wordcraft_fonts::word::charset_base_family(font)) - } { MISSING_ROMAN_FONT } else { @@ -150,9 +179,10 @@ pub(super) fn lookup_family<'f>(doc: &Document, font: &'f str) -> &'f str { /// One face for a run in a Thai font that isn't installed (#1549): Word substitutes one font /// (Cordia New) for the whole run, so the Latin letters, digits and ฿ keep the Thai letters' face -/// and size. `None` unless `font` is a Thai family, it was substituted, and its substitute -/// `primary` lacks some of the run's Thai or Latin characters; then the first face covering all of -/// them, if one does. Other families keep Latin text in their own substitute, as Word does. +/// and size. `None` unless `font` is a Thai family, it was substituted (or drawn in its font +/// table alternate, #2702), and its stand-in `primary` lacks some of the run's Thai or Latin +/// characters; then the first face covering all of them, if one does. Other families keep Latin +/// text in their own substitute, as Word does. pub(crate) fn thai_run_face(font: &str, substituted: bool, primary: FaceRef, text: &str, bold: bool, italic: bool) -> Option { if !substituted || !wordcraft_fonts::word::is_thai_family(font) { return None; diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 7566437088..ff3b0a9274 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -1429,6 +1429,93 @@ fn a_missing_roman_font_is_drawn_as_word_draws_it() { assert_ne!(face(false), cambria); } +#[test] +fn a_missing_font_is_drawn_in_its_font_table_alternate() { + crate::test_fonts(); + // Measured in Word 2024 and Word for Windows 16.0.20527 (#2702): a font that isn't installed is + // drawn in the alternate its font table names (`w:altName`), before the roman rule; an + // alternate that can't be drawn either leaves the family class in charge: Cambria for a roman + // or modern font, the generic substitutes (Calibri in Word) for a swiss one. + #[derive(Clone, Copy)] + enum Family { + Swiss, + Roman, + Modern, + } + let face_of = |alt: Option<&str>, family: Family| { + let mut d = Document::from_text("Lanterns"); + if let Some(alt) = alt { + d.settings.font_alt_names = vec![("No Such Brand Font".into(), alt.into())]; + } + match family { + Family::Roman => d.settings.roman_fonts = vec!["No Such Brand Font".into()], + Family::Modern => d.settings.modern_fonts = vec!["No Such Brand Font".into()], + Family::Swiss => {} + } + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some("No Such Brand Font".into()); + let l = lay(&d); + let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!("no text") }; + let first = para.clusters.first().expect("a cluster"); + para.styles[first.style as usize].face + }; + let face = |alt: Option<&str>, roman: bool| face_of(alt, if roman { Family::Roman } else { Family::Swiss }); + let resolve = |f: &str| wordcraft_fonts::word::resolve(f, false, false).face; + let (courier, times, calibri, cambria) = (resolve("Courier New"), resolve("Times New Roman"), resolve("Calibri"), resolve("Cambria")); + let generic = face(None, false); + // Serif and sans faces are bundled, so these differ on any machine. + assert_ne!(times, generic); + assert_ne!(cambria, generic); + // A, B: a missing font with an alternate. + assert_eq!(face(Some("Times New Roman"), false), times); + assert_eq!(face(Some("Courier New"), false), courier); + // go_math (docxide-pdf corpus): Museo Sans 300 → Calibri. + assert_eq!(face(Some("Calibri"), false), calibri); + // D: the alternate beats the roman rule. + assert_eq!(face(Some("Times New Roman"), true), times); + assert_eq!(face(Some("Courier New"), true), courier); + // E: an alternate that is missing too, with no substitutes of its own: the roman rule, or the + // generic substitutes for a font that isn't roman. + assert_eq!(face(Some("No Such Alternate"), true), cambria); + assert_eq!(face(Some("No Such Alternate"), false), generic); + // Word reads a value with a comma as one name, not a list (MS-OE376 2.1.264): no font is + // called that, so the roman rule or the generic substitutes draw it. + assert_eq!(face(Some("No Such Alternate, Times New Roman"), false), generic); + assert_eq!(face(Some("No Such Alternate, Times New Roman"), true), cambria); + // A modern font: its installed alternate draws it, a missing alternate leaves it in Cambria, + // and with no alternate at all it takes the generic substitutes (Calibri in Word). + assert_eq!(face_of(Some("Courier New"), Family::Modern), courier); + assert_eq!(face_of(Some("No Such Alternate"), Family::Modern), cambria); + assert_eq!(face_of(None, Family::Modern), generic); + // An alternate that names another missing font with an alternate of its own: the chain isn't + // followed. + let mut d = Document::from_text("Lanterns"); + d.settings.font_alt_names = vec![("No Such Brand Font".into(), "No Such Alternate".into()), ("No Such Alternate".into(), "Courier New".into())]; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some("No Such Brand Font".into()); + let l = lay(&d); + let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!("no text") }; + let first = para.clusters.first().expect("a cluster"); + assert_eq!(para.styles[first.style as usize].face, generic, "the chain isn't followed"); +} + +#[test] +fn an_installed_font_ignores_its_font_table_alternate() { + // The alternate is only for a font that isn't there: an installed (here bundled) font keeps its + // own face. + let font = wordcraft_fonts::FALLBACK_FAMILY; + let mut d = Document::from_text("Lanterns"); + d.settings.font_alt_names = vec![(font.into(), "Times New Roman".into())]; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some(font.into()); + let l = lay(&d); + let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!("no text") }; + let first = para.clusters.first().expect("a cluster"); + let own = wordcraft_fonts::word::resolve(font, false, false).face; + assert_ne!(own, wordcraft_fonts::word::resolve("Times New Roman", false, false).face); + assert_eq!(para.styles[first.style as usize].face, own); +} + #[test] fn a_missing_roman_font_with_its_own_substitute_keeps_it() { crate::test_fonts(); @@ -10634,6 +10721,52 @@ fn east_asian_text_takes_the_asian_font_and_latin_text_the_latin_font() { } } +#[test] +fn a_missing_east_asian_font_is_drawn_in_its_font_table_alternate() { + crate::test_fonts(); + // #2702 for the run's East Asian font (`w:eastAsia`): one that isn't installed is drawn in the + // alternate its font table names, when that one is installed and has the characters. Take an + // installed CJK font other than the one fallback would pick anyway, so the test tells them apart. + let resolve = |f: &str| wordcraft_fonts::word::resolve(f, false, false); + let fallback = wordcraft_fonts::FontDb::global().fallback_for('你', 0).map(|f| f.family.clone()); + let Some(asian) = wordcraft_fonts::FontDb::global().east_asian_families().into_iter().find(|f| { + let r = resolve(f); + Some(f) != fallback.as_ref() && !r.substituted && r.face.covers('你') && r.face.covers('好') + }) else { + eprintln!("skipped: no second Chinese font installed"); + return; + }; + let missing = "No Such East Asian Font 2702"; + let text = "Hello 你好"; + let faces = |alternate: bool| { + let mut d = Document::from_text(text); + if alternate { + d.settings.font_alt_names = vec![(missing.into(), asian.clone())]; + } + d.format_range(&Pos::body(0, 0), &Pos::body(0, text.len()), &|c| { + c.font = Some(wordcraft_doc::styles::BODY_FONT.into()); + c.font_ea = Some(missing.into()); + }) + .unwrap(); + let l = lay(&d); + let para = + l.pages.iter().flat_map(|p| p.items.iter()).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap(); + let drawn = para + .clusters + .iter() + .filter(|c| text.get(c.start..c.end).and_then(|s| s.chars().next()).is_some_and(|ch| !ch.is_ascii())) + .map(|c| para.styles[c.style as usize].face.id()) + .collect::>(); + (drawn, l.substituted_fonts()) + }; + let asian_face = resolve(&asian).face.id(); + let (with, reported) = faces(true); + assert!(!with.is_empty() && with.iter().all(|f| *f == asian_face), "你好 in the alternate {asian}"); + // Drawn in an installed alternate, the font asked for is still missing (#4770). + assert!(reported.iter().any(|(f, _)| f == missing), "{reported:?}"); + assert!(faces(false).0.iter().all(|f| *f != asian_face), "without the alternate, fallback picks another font"); +} + /// A page total in the footer ("Page X of Y") is filled in after pagination, so it doesn't make /// the body lay out a second time; one in the body still does. #[test] diff --git a/crates/layout/src/tests/complex.rs b/crates/layout/src/tests/complex.rs index 206f48875a..31fc2576cc 100644 --- a/crates/layout/src/tests/complex.rs +++ b/crates/layout/src/tests/complex.rs @@ -167,6 +167,57 @@ fn a_missing_thai_font_draws_the_whole_run_in_one_thai_face() { } } +/// Body paragraph 0 of `text` at 16 pt, its run set in `font` whose font table alternate +/// (`w:altName`) is `alt`, and the face of every cluster: (cluster start, face). +fn cluster_faces_with_alternate(text: &str, font: &str, alt: &str) -> Vec<(usize, wordcraft_fonts::FaceRef)> { + let mut d = Document::from_text(text); + d.settings.font_alt_names = vec![(font.into(), alt.into())]; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some(font.into()); + p.runs[0].props.size = Some(16.0); + let l = lay(&d); + let pl = para_layout(&l, 0); + pl.clusters.iter().map(|c| (c.start, pl.styles[c.style as usize].face)).collect() +} + +#[test] +fn a_missing_thai_font_with_a_latin_alternate_still_draws_the_run_in_one_face() { + if !thai_font_installed() { + eprintln!("skipped: no Thai font installed"); + return; + } + // #2702 draws a missing font in its font table alternate. When the font is Thai and the + // installed alternate has no Thai letters, the run still takes one face for its Thai and + // Latin text (#1549), not the alternate for the Latin and per-letter fallback for the Thai. + let alt = "Source Sans 3"; + let alt_face = wordcraft_fonts::word::resolve(alt, false, false).face; + assert!(!alt_face.covers('\u{0E19}'), "{} has no Thai, so the run must move", alt_face.family); + let db = wordcraft_fonts::FontDb::global(); + // One face for the run needs a Thai font with Latin letters and digits too. + let thai_latin = thai_latin_font_installed(); + if !thai_latin { + eprintln!("skipped the one-face cases: no Thai font with Latin letters installed"); + } + for font in ["TH Sarabun New", "Angsana New"] { + if !thai_latin || db.has_family(font) { + continue; + } + let faces = cluster_faces_with_alternate(THAI_RUN, font, alt); + let first = faces[0].1; + let names: Vec<&str> = faces.iter().map(|(_, f)| f.family.as_str()).collect(); + assert!(faces.iter().all(|(_, f)| f.id() == first.id()), "{font} (alternate {alt}): one face for the run, not {names:?}"); + assert!(first.covers('\u{0E19}') && first.covers('D') && first.covers('1') && first.covers('\u{0E3F}'), "{font} → {}", first.family); + // A Latin-only run in the same font is drawn in the alternate, as #2702 has it. + let latin = cluster_faces_with_alternate("Lanterns 1,250", font, alt); + assert!(latin.iter().all(|(_, f)| f.id() == alt_face.id()), "{font}: Latin text in {alt}"); + } + // A missing Latin font with the same alternate isn't Thai: its Latin text stays in the + // alternate and only the Thai letters fall back. + let faces = cluster_faces_with_alternate("Hello \u{0E2A}\u{0E27}\u{0E31}\u{0E2A}\u{0E14}\u{0E35}", "No Such Latin Font 2702", alt); + assert!(faces.iter().filter(|(at, _)| *at < 5).all(|(_, f)| f.id() == alt_face.id()), "Hello stays in {alt}"); + assert!(faces.iter().any(|(at, f)| *at >= 6 && f.id() != alt_face.id()), "the Thai letters fall back"); +} + #[test] fn a_thai_substitute_without_latin_hands_the_run_to_one_face_covering_it() { crate::test_fonts(); From 32b4ab57241c9ad4e9f7817c8d16b7cef7afa0a5 Mon Sep 17 00:00:00 2001 From: pakiat <49967840+pakiat@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:29:00 +0700 Subject: [PATCH 95/99] Paragraph dialog: Special box sets First line and Hanging indents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Paragraph dialog's Special box sets First line and Hanging indents, keeps By when the kind changes, leaves a mixed selection blank, and limits By to 0–22 inches. Originally authored by @pakiat in #4922. --- ROADMAP.md | 2 + crates/ui-egui/src/dialogs/dispatch.rs | 7 +- crates/ui-egui/src/dialogs/paragraph.rs | 61 ++++++++ crates/ui-egui/src/dialogs/tests.rs | 195 ++++++++++++++++++++++++ docs/ui-parity.md | 1 + 5 files changed, 261 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b5cf968f5b..6bc06fd92b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -425,6 +425,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-11-01 | Rulers: in a section of several text columns the horizontal ruler shades the space between each two columns like the margins (Print Layout, in the main text outside tables, with the selection in one section); dragging an edge of a space changes the spacing (equal columns stay equal, as in Word for Mac), one undo step per drag (#5197) | | 2026-10-29 | Window sizing falls back to the screen rectangle when the reported inner size is invalid, and an Equation symbol tooltip no longer repeats a missing glyph's name or code point | | 2026-10-29 | A NUL in a document title no longer reaches the native window title, which panicked on X11 (#3634): displayed titles and suggested file names drop NUL characters and fall back to the untitled name when empty; the stored title is unchanged | +| 2026-10-30 | Paragraph dialog: Word's Special box (none, First line, Hanging) and By replace the signed First line box, so a hanging indent is set as Hanging by a positive length instead of a negative first-line indent. Picking a kind from (none) starts at 0.5", as Word does, and switching between First line and Hanging keeps By. A By typed in counts once committed, so the 0 of 0.25 doesn't turn Special to (none) mid-typing. | | 2026-10-28 | The Traditional Chinese interface draws hanzi to the Taiwan standard: on the desktop an installed Traditional Chinese font (PingFang TC on macOS, Microsoft JhengHei on Windows, Noto Sans CJK TC on Linux) comes before the embedded Noto Sans CJK SC, which drew 說, 這, 為, 戶 in mainland shapes; without one, and on the web, nothing changes. | | 2026-10-17 | macOS launch arguments (`-psn_*`, `-NS*`, `-Apple*`) are no longer opened as files, and a file that fails to open names the file and the real cause on the status bar and in the log (#1103). The reported "corrupt" error could not be reproduced. | | 2026-10-19 | Linux: File › Options › Advanced › Linux display server picks Automatic (the default: XWayland where there's an X server, for file drag-and-drop), Wayland or X11 (XWayland), so people who don't start WordCraft from a terminal can switch without an environment variable (#2184). It's kept in `ui.json` and applies at the next launch; `WORDCRAFT_WAYLAND` still overrides it, and `WORDCRAFT_WAYLAND=0` now asks for X11. A choice that isn't available falls back to the other instead of failing to start, and the log's `display:` line says which ran and why. Hidden on Windows, macOS and the web; `ui.displayServer` for agents. | @@ -1052,6 +1053,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-10-29 | trivial | HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged. | | 2026-10-29 | trivial | Progress log: window fallback geometry and equation symbol tooltips | | 2026-10-29 | trivial | Progress log: window titles omit NUL characters (#3634) | +| 2026-10-30 | trivial | Progress log: the Paragraph dialog's Special box sets First line and Hanging indents | | 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. | | 2026-10-19 | trivial | Progress log: Linux display server setting (#2184) | | 2026-10-19 | trivial | Progress log: the status bar's count can be words, characters or characters without spaces (#2797) | diff --git a/crates/ui-egui/src/dialogs/dispatch.rs b/crates/ui-egui/src/dialogs/dispatch.rs index 5ad4a0f5aa..d2b3052368 100644 --- a/crates/ui-egui/src/dialogs/dispatch.rs +++ b/crates/ui-egui/src/dialogs/dispatch.rs @@ -5,7 +5,7 @@ use super::font::{apply_font, font_box, font_sample_box, font_sample_props, samp use super::forms::{cell_margins_dialog, custom_properties, table_properties}; use super::mailings::{ADDRESS_PARTS, recipient_list, rule_params}; use super::page_setup::{page_layout_commands, page_paper_group, page_valign_combo, page_valign_value, run_as_one_step}; -use super::paragraph::{ParaNumber, apply_paragraph, para_check, para_number}; +use super::paragraph::{ParaNumber, apply_paragraph, para_check, para_number, para_special}; use super::styles::manage_styles; use super::{Dialog, MeasureExt, Tokens, Ui, Value, WordApp, json, semibold, vec2}; @@ -324,10 +324,7 @@ fn paragraph_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { let right_label = r.cell(|ui| ui.label(tl!(r_label))); r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label)); }); - t.row(|r| { - let first_label = r.cell(|ui| ui.label(tl!("First line:"))); - r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label)); - }); + t.row(|r| para_special(r, first, mixed)); }); para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed); }); diff --git a/crates/ui-egui/src/dialogs/paragraph.rs b/crates/ui-egui/src/dialogs/paragraph.rs index 5579fb0275..0c2887764d 100644 --- a/crates/ui-egui/src/dialogs/paragraph.rs +++ b/crates/ui-egui/src/dialogs/paragraph.rs @@ -90,6 +90,67 @@ pub(super) fn para_number(ui: &mut Ui, value: &mut f32, kind: ParaNumber, key: & } } +/// The Paragraph dialog's Special box and its By value, as in Word: the first-line indent +/// `first` (in the measurement unit) is a First line indent when above 0 and a Hanging one when +/// below. Picking First line or Hanging from (none), or while the selected paragraphs differ, +/// starts it at half an inch as Word does; switching between the two keeps By. +pub(super) fn para_special(r: &mut crate::rtl::Cells, first: &mut f32, mixed: &mut BTreeSet) { + const SPECIAL: [&str; 3] = ["(none)", "First line", "Hanging"]; + let unit = crate::options::unit(); + let kind_of = |first: f32| { + if first > 0.0 { + 1 + } else if first < 0.0 { + 2 + } else { + 0 + } + }; + let blank = mixed.contains("indentFirst"); + let kind = kind_of(*first); + let special_label = r.cell(|ui| ui.label(tl!("Special:"))); + let shown = if blank { "" } else { tl!(SPECIAL[kind]) }; + r.cell(|ui| { + let combo = craft_ui::ComboBox::from_id_salt("para_special").selected_text(shown).show_ui(ui, |ui| { + for (k, l) in SPECIAL.into_iter().enumerate() { + if ui.selectable_label(!blank && k == kind, tl!(l)).clicked() && (blank || k != kind) { + let by = if blank || kind == 0 { 36.0 / unit.pt_per_unit() } else { first.abs() }; + *first = [0.0, by, -by][k]; + mixed.remove("indentFirst"); + } + } + }); + combo.response.labelled_by(special_label.id); + }); + // A kind just picked counts from this frame on. + let (blank, kind) = (mixed.contains("indentFirst"), kind_of(*first)); + let by_label = r.cell(|ui| ui.label(tl!("By:"))); + r.cell(|ui| { + if blank || kind == 0 { + // Nothing to set until Special says which way. + let mut none = 0.0; + ui.add_enabled(false, egui::DragValue::new(&mut none).measure_blank(unit)).labelled_by(by_label.id); + } else { + // Typed values count once committed: the 0 of "0.25" would otherwise turn Special + // to (none) and disable the box mid-typing. + let mut by = first.abs(); + // By stops at 0 when dragged down instead of turning negative for a frame (which the + // `abs` below would flip back), and at Word's 22". + let field = egui::DragValue::new(&mut by) + .speed(3.6 / unit.pt_per_unit()) + .range(0.0..=1584.0 / unit.pt_per_unit()) + .clamp_existing_to_range(false) + .max_decimals(2) + .update_while_editing(false) + .measure(unit); + if ui.add(field).labelled_by(by_label.id).changed() { + mixed.remove("indentFirst"); + } + *first = if kind == 2 { -by.abs() } else { by.abs() }; + } + }); +} + /// A Paragraph dialog check box for the field `key`. While the selected paragraphs differ in /// it, it shows as neither on nor off, and a click turns it on for all of them. pub(super) fn para_check(ui: &mut Ui, on: &mut bool, text: &str, key: &str, mixed: &mut BTreeSet) { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index a1ea146d36..07c74d848c 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -682,6 +682,201 @@ fn paragraph_dialog_keeps_fixed_line_spacing() { assert_eq!(props(&app).line_spacing, Some(LineSpacing::Multiple(1.5))); } +/// The Paragraph dialog's Special box, as in Word: (none), First line or Hanging, By how much. +/// Hanging is a first-line indent below 0; picking a kind from (none) starts at half an inch, +/// switching between First line and Hanging keeps By, and a By typed in counts once committed. +#[test] +fn paragraph_dialog_sets_first_line_and_hanging_indents() { + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = app_with("Some text"); + app.dialog = Dialog::open("paragraph", &mut app); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + let pick = |h: &mut egui_kittest::Harness<'_, WordApp>, kind: &str| { + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Special:").click(); + h.run_steps(4); + h.get_by_label(kind).click(); + h.run_steps(4); + }; + let first = |h: &egui_kittest::Harness<'_, WordApp>| match &h.state().dialog { + Some(Dialog::Paragraph { first, .. }) => *first, + _ => panic!("no paragraph dialog"), + }; + for _ in 0..4 { + h.step(); + } + let ok = |h: &mut egui_kittest::Harness<'_, WordApp>| { + h.get_by_role_and_label(egui::accesskit::Role::Button, "OK").click(); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "OK closes the dialog"); + }; + h.run_steps(4); + pick(&mut h, "Hanging"); + assert_eq!(first(&h), -0.5, "Hanging starts at half an inch"); + // Typing 0.75 over By: the leading 0 doesn't turn Special to (none) on the way. The box, + // not its label: the one "By:" node that isn't a label. + fn by_box<'h>(h: &'h egui_kittest::Harness<'_, WordApp>) -> egui_kittest::Node<'h> { + h.get_all_by_label("By:").find(|n| n.accesskit_node().role() != egui::accesskit::Role::Label).expect("the By box") + } + by_box(&h).click(); + h.run_steps(2); + by_box(&h).type_text("0"); + h.run_steps(2); + assert_eq!(first(&h), -0.5, "a value still being typed doesn't count yet"); + by_box(&h).type_text(".75"); + // Tab moves on and commits it (Enter would also press OK, as in Word). + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(first(&h), -0.75, "the typed By counts once committed"); + pick(&mut h, "First line"); + assert_eq!(first(&h), 0.75, "switching kinds keeps By"); + // By has a range, 0 to Word's 22": a larger value stops there (and dragging down stops at 0). + by_box(&h).click(); + h.run_steps(2); + by_box(&h).type_text("30"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(first(&h), 22.0, "By stops at 22\""); + by_box(&h).click(); + h.run_steps(2); + by_box(&h).type_text("0.75"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(first(&h), 0.75); + pick(&mut h, "Hanging"); + ok(&mut h); + assert_eq!(props(h.state()).indent_first, Some(-54.0), "a hanging indent of 0.75\""); + // Opened again, it shows Hanging by 0.75"; (none) takes the indent away. + let app = h.state_mut(); + let d = Dialog::open("paragraph", app); + app.dialog = d; + h.run_steps(4); + assert_eq!(first(&h), -0.75); + pick(&mut h, "(none)"); + assert_eq!(first(&h), 0.0); + ok(&mut h); + assert_eq!(props(h.state()).indent_first, Some(0.0)); +} + +/// The Special box opens from the paragraph: a first-line indent above 0 shows First line by its +/// size, and By reads and takes lengths in the measurement unit File › Options sets (centimetres, +/// points), as Word's dialog does. +#[test] +fn paragraph_dialog_special_box_opens_from_the_paragraph_in_the_measurement_unit() { + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = app_with("Some text"); + let _ = app.run("para.set", json!({"props": {"indentFirst": 28.35}})); + app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + // The frames before copy the unit for dialog code; the dialog opens in it. + h.run_steps(2); + let open = |h: &mut egui_kittest::Harness<'_, WordApp>| { + let app = h.state_mut(); + let d = Dialog::open("paragraph", app); + app.dialog = d; + h.run_steps(4); + }; + let first = |h: &egui_kittest::Harness<'_, WordApp>| match &h.state().dialog { + Some(Dialog::Paragraph { first, .. }) => *first, + _ => panic!("no paragraph dialog"), + }; + let special = |h: &egui_kittest::Harness<'_, WordApp>| { + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Special:").accesskit_node().value().map(|v| v.to_string()) + }; + let ok = |h: &mut egui_kittest::Harness<'_, WordApp>| { + h.get_by_role_and_label(egui::accesskit::Role::Button, "OK").click(); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "OK closes the dialog"); + }; + open(&mut h); + assert!((first(&h) - 1.0).abs() < 0.01, "1 cm: {}", first(&h)); + assert_eq!(special(&h).as_deref(), Some("First line")); + // 2 typed over By counts 2 cm. + let by = h.get_all_by_label("By:").find(|n| n.accesskit_node().role() != egui::accesskit::Role::Label).expect("the By box"); + by.click(); + h.run_steps(2); + let by = h.get_all_by_label("By:").find(|n| n.accesskit_node().role() != egui::accesskit::Role::Label).expect("the By box"); + by.type_text("2"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + ok(&mut h); + let set = props(h.state()).indent_first.unwrap_or_default(); + assert!((set - 56.69).abs() < 0.05, "2 cm is {set} pt"); + // In points: the same indent shows 56.69, and Hanging keeps it, below 0. + h.state_mut().session.prefs.units = Some(wordcraft_geom::Unit::Points); + h.run_steps(2); + open(&mut h); + assert!((first(&h) - set).abs() < 0.01, "in points: {}", first(&h)); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Special:").click(); + h.run_steps(4); + h.get_by_label("Hanging").click(); + h.run_steps(4); + ok(&mut h); + assert!((props(h.state()).indent_first.unwrap_or_default() + set).abs() < 0.01, "a hanging indent of the same size"); +} +/// Selected paragraphs with different first-line indents: Special and By show blank, an +/// unchanged OK leaves each indent as it was, and picking a kind starts By at half an inch for +/// all of them. +#[test] +fn paragraph_dialog_special_box_over_differing_first_line_indents() { + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = app_with("One\nTwo\nThree"); + let _ = app.run("caret.docStart", json!({})); + let _ = app.run("para.set", json!({"props": {"indentLeft": 36, "indentFirst": 18}})); + let _ = app.run("caret.down", json!({})); + let _ = app.run("para.set", json!({"props": {"indentLeft": 36, "indentFirst": -18}})); + let _ = app.run("select.all", json!({})); + let was: Vec<_> = (0..3).map(|i| para_props(&app, i).indent_first).collect(); + assert_eq!(was, [Some(18.0), Some(-18.0), None]); + app.dialog = Dialog::open("paragraph", &mut app); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + let ok = |h: &mut egui_kittest::Harness<'_, WordApp>| { + h.get_by_role_and_label(egui::accesskit::Role::Button, "OK").click(); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "OK closes the dialog"); + }; + let Some(Dialog::Paragraph { mixed, .. }) = &h.state().dialog else { panic!("no paragraph dialog") }; + assert!(mixed.contains("indentFirst"), "{mixed:?}"); + let special = h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Special:"); + assert_eq!(special.accesskit_node().value().as_deref(), Some(""), "Special shows blank"); + ok(&mut h); + assert_eq!((0..3).map(|i| para_props(h.state(), i).indent_first).collect::>(), was, "an unchanged OK keeps each indent"); + // Hanging from the blank box: half an inch for every selected paragraph. + let app = h.state_mut(); + let d = Dialog::open("paragraph", app); + app.dialog = d; + h.run_steps(4); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Special:").click(); + h.run_steps(4); + h.get_by_label("Hanging").click(); + h.run_steps(4); + let Some(Dialog::Paragraph { first, mixed, .. }) = &h.state().dialog else { panic!("no paragraph dialog") }; + assert_eq!((*first, mixed.contains("indentFirst")), (-0.5, false)); + ok(&mut h); + assert_eq!((0..3).map(|i| para_props(h.state(), i).indent_first).collect::>(), [Some(-36.0); 3]); +} + #[test] fn font_dialog_sets_the_asian_and_latin_fonts_separately() { // #505: the Asian text font box and the Latin text font box each set their own font, and diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bd843015f2..4fb5781607 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -176,6 +176,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-10-29 | trivial | File › Options › User Name left blank stays blank after a restart (it came back as the default name); a name of only spaces still keeps the default (#4368) | | 2026-10-29 | trivial | Window sizing uses the screen rectangle when the inner rectangle is missing, empty or not finite; an Equation symbol tooltip shows a missing glyph's linear name or code point once instead of twice | | 2026-10-29 | trivial | Displayed document titles and suggested file names omit NUL characters (X11 panicked on them) and use the localized untitled name when nothing remains (#3634) | +| 2026-10-30 | trivial | Paragraph dialog: Word's Special box ((none), First line, Hanging) and By replace the signed First line box; picking a kind from (none) starts at 0.5", switching kinds keeps By, and a By typed in counts once committed | | 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. | | 2026-10-26 | trivial | Layout › Arrange › Group stays on while a group is selected, so Ungroup in its menu can be reached; it was greyed out because one object has nothing to group (#4229) | | 2026-10-27 | trivial | Port the existing Proofing pane and navigation/selection regressions to extracted engine/UI modules on main `436d444`; preserve compact context menus; new-SHA validation pending, readiness unchanged | From 5bf3ffb92038b603c8bce427ef4c03eb6553ba38 Mon Sep 17 00:00:00 2001 From: pakiat <49967840+pakiat@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:29:27 +0700 Subject: [PATCH 96/99] Tables: percentage cell widths size their columns whichever rows give them Percentage cell widths size their columns from whichever rows give them, taking the largest when rows disagree, sharing a merged cell's percentage, and keeping a grid that already matches. Originally authored by @pakiat in #5074. --- ROADMAP.md | 2 + crates/layout/src/table.rs | 145 ++++++++++++++++++++++++- crates/layout/src/tests.rs | 213 +++++++++++++++++++++++++++++++++++++ docs/gaps.md | 3 +- docs/layout-parity.md | 3 +- 5 files changed, 362 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6bc06fd92b..e8281f3767 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -304,6 +304,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-11-01: Tab leaders are drawn as Word draws them: the dots are spaced by their advance in whole 600-dpi pixels (2.64 pt for TH SarabunPSK at 16 pt, not 2.59), from the first place on that grid after the text before the tab to the last one that ends before the text after it. - 2026-10-31: List numbers count as Word counts them when a deeper item comes first: a list that opens with 10.1–10.4 goes on with 11, not a second 10, and 1.1, 1.2 are followed by 2. A level above that hasn't counted yet takes its first number at the first deeper item. - 2026-11-01: Paragraph side borders lie outside the text, so a thick border no longer covers the first letter (#5036). +- 2026-10-31: Percentage cell widths size table columns as in Word, whichever rows give them: where rows disagree a column takes the largest, a merged cell's percentage is shared by the columns under it, a header row of percentages over rows without cell widths now sets the columns, in autofit and fixed tables, scaled to the table's width or, without one, the text width (a fixed table's grid width); past 100% the columns take their shares left to right until the width runs out, and the ones after it get their longest words, or 2 pt each with their text clipped in a fixed table. Conflicting percentages, unsized columns, spans and absolute widths keep the grid. - 2026-10-31: DOCX: a paragraph naming a style the file doesn't define is formatted as Normal, as in Word, not with the document defaults alone, so a Pandoc footer naming an undefined `Footer` style is as tall as Word's and no longer pushes the last paragraph to the next page (#5077). Readiness unchanged. - 2026-10-31: Table of contents: with Word's table over entries in columns, where the title sits in a one-column section above a continuous break, Insert Table of Contents with new settings keeps the title above the break and the entries in their columns (the new title went under the break, into the columns), and Remove Table of Contents takes the title, the blank paragraph and its break with the entries, as Word does (observed in Word for Mac); a paragraph of another style above the break stays (#4041). - 2026-10-31: A table of contents writes its page numbers as `PAGEREF` fields to the headings' bookmarks, as Word does, so updating the fields in Word moves the numbers with the headings; they were plain text (#5097). @@ -1028,6 +1029,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-01 | trivial | Progress log: proofing moved to craft-proof (craft-libs) and its data to craft-i18n `language-data/` (CP1) | | 2026-11-01 | trivial | #3915: preserve guarded whole-line ordinary-tab alignment with current main. Existing controls retained; source checks only, primary qualification pending. | | 2026-11-01 | trivial | #2437: Preserve finite paragraph-border flow extents and terminal-break keep preflight with current-main changes. Recursive terminal-successor lookahead remains outside scope. Source checks only; primary qualification pending. | +| 2026-10-31 | trivial | Progress log: percentage cell widths size table columns whichever rows give them | | 2026-10-31 | trivial | Progress log: a paragraph naming an undefined DOCX style is formatted as Normal (#5077) | | 2026-10-31 | minor | #3398: persistent screen-only green, cream and gray paper presets, with document backgrounds and export colors retained. Read Mode None follows the screen preset; Sepia/Inverse retain priority. | | 2026-10-31 | trivial | Progress log: TOC page numbers are PAGEREF fields (#5097) | diff --git a/crates/layout/src/table.rs b/crates/layout/src/table.rs index 9ea319127b..1372e24a94 100644 --- a/crates/layout/src/table.rs +++ b/crates/layout/src/table.rs @@ -378,7 +378,9 @@ struct TableFrame { x: f32, } -// Nested measurement needs the same preferred weights as layout before sharing span minima. +/// The table's column widths before autofit: its grid, or equal shares of `avail` without one, +/// then the cells' absolute and percentage widths. Nested measurement needs the same preferred +/// weights as layout before sharing span minima. fn preferred_grid(t: &Table, avail: f32) -> Vec { let ncols = grid_cols(t).max(1); let mut grid: Vec = if t.grid.len() == ncols { @@ -395,6 +397,7 @@ fn preferred_grid(t: &Table, avail: f32) -> Vec { vec![avail / ncols as f32; ncols] }; apply_cell_widths(t, &mut grid); + apply_pct_widths(t, &mut grid, avail); grid } @@ -723,6 +726,9 @@ struct TableRows<'a> { total: 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; // Grid columns holding a vertical-merge continuation, per row. @@ -858,7 +864,9 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { row: ri, cell: ci, story, - clip: exact && c.h > span_h + 0.01, + // A fixed table's cell too narrow for any text (its lines are laid out 4 pt wide) + // clips them, as Word does, rather than letting them run past its edges. + clip: (exact && c.h > span_h + 0.01) || (t.props.fixed && c.w - c.margins[1] - c.margins[3] < 4.0), }); let top = c.margins[0] + c.borders.top.filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0)); parts.push(CellPart { top, items: first..items.len(), end, align }); @@ -1535,6 +1543,121 @@ fn apply_cell_widths(t: &Table, grid: &mut [f32]) { grid.copy_from_slice(&widths); } +/// Word sizes each column by the percentage its cells ask for, whichever rows ask: cells without a +/// preferred width take no part, so a header row of percentages sizes the automatic rows below it. +/// The percentages are shares of the table's width, scaled up when they come short of 100%; past +/// 100% the columns take their shares left to right until the width runs out +/// (`overfull_shares`). A table without a +/// width of its own takes `avail` when autofit and its grid's width when fixed. Where rows ask +/// different percentages of a column it takes the largest. A merged cell's percentage is shared +/// by the columns under it that ask none of their own, in their grid proportions (Word shares it +/// by their content), and makes no column narrower than it asks. Measured in Word. Columns no cell +/// sizes and absolute widths keep the grid. +fn apply_pct_widths(t: &Table, grid: &mut [f32], avail: f32) { + let mut pcts: Vec> = vec![None; grid.len()]; + let mut merged: Vec<(usize, usize, f32)> = Vec::new(); + for row in &t.rows { + let mut g = row.first_grid(); + for cell in &row.cells { + if cell.props.width.is_some() { + return; + } + if let Some(p) = cell.props.width_pct { + if !p.is_finite() || p <= 0.0 { + return; + } + if cell.span() == 1 { + let Some(slot) = pcts.get_mut(g) else { return }; + *slot = Some(slot.map_or(p, |q| q.max(p))); + } else { + merged.push((g, cell.span(), p)); + } + } + g = g.saturating_add(cell.span()); + } + } + for (g, span, p) in merged { + let Some(cols) = pcts.get_mut(g..g.saturating_add(span)) else { return }; + let Some(weights) = grid.get(g..g.saturating_add(span)) else { return }; + let own: f32 = cols.iter().flatten().sum(); + let free: f32 = cols.iter().zip(weights).filter(|(c, _)| c.is_none()).map(|(_, w)| *w).sum(); + let rest = (p - own).max(0.0); + if free > 0.0 { + for (c, w) in cols.iter_mut().zip(weights) { + if c.is_none() { + *c = Some(rest * w / free); + } + } + } else if own > 0.0 && rest > 0.0 { + // Every column asks its own, short of the merged cell's: they grow to it together. + cols.iter_mut().flatten().for_each(|c| *c *= p / own); + } + } + let Some(pcts) = pcts.into_iter().collect::>>() else { return }; + if pcts.iter().any(|p| *p <= 0.0) { + return; + } + let sum: f32 = pcts.iter().sum(); + let own_width = t.props.width_pct.is_some_and(|p| p > 0.0) || t.props.width.is_some_and(|w| w > 0.0); + // A table with its own width is scaled to it afterwards; any positive total will do. A fixed + // table without one keeps its grid's width. + let total = if own_width || t.props.fixed { grid.iter().sum() } else { avail }; + if !sum.is_finite() || sum <= 0.0 || !total.is_finite() || total <= 0.0 { + return; + } + if sum <= 100.0 { + let shares: Vec = pcts.iter().map(|p| total * (p / sum)).collect(); + // A grid Word wrote from these same percentages is within its rounding of them (whole + // twips, and percentages in fiftieths): it is kept exactly. Rebuilt, a column could come + // out a few hundredths of a point narrower and wrap its text differently (#6575). + let rounding = 0.05 + total * 0.0002; + if grid.iter().zip(&shares).all(|(g, s)| (g - s).abs() <= rounding) { + return; + } + grid.copy_from_slice(&shares); + return; + } + // A grid too narrow for the floor in every column shares its width out instead, so the table + // keeps it. + let floor = if t.props.fixed { FIXED_PCT_MIN_COLUMN.min(total / pcts.len() as f32) } else { 0.0 }; + grid.copy_from_slice(&overfull_shares(&pcts, total, floor)); +} + +/// Over 100%, as Word lays it out: the columns take their shares left to right until the table's +/// width runs out; the column it runs out in takes what is left, and those after it nothing. In an +/// autofit table autofit then widens them to their longest words at the others' expense. In a +/// fixed table they keep `floor` each, their text clipped, and the shares are of what is left +/// once those are set aside. +fn overfull_shares(pcts: &[f32], total: f32, floor: f32) -> Vec { + let mut starved = 0; + loop { + let room = (total - floor * starved as f32).max(0.0); + let mut used = 0.0; + let mut short = 0; + let widths: Vec = pcts + .iter() + .map(|p| { + let w = (room * p / 100.0).min(room - used); + if w < floor || w <= 0.0 { + short += 1; + return floor; + } + used += w; + w + }) + .collect(); + // More columns starved than were set aside for: set aside for them and share again. + if short <= starved || starved >= pcts.len() { + return widths; + } + starved = short; + } +} + +/// The narrowest a fixed table's columns get when the percentages before them fill the table +/// (measured in Word: 2 pt, with or without a table width). +const FIXED_PCT_MIN_COLUMN: f32 = 2.0; + /// Word's autofit for a table whose widths may follow its content (`tblLayout` not fixed). /// - With no preferred width anywhere (the table's and every cell's automatic) the columns come /// from their content alone: each its widest line if they all fit in `avail`, else shared out @@ -1594,6 +1717,24 @@ mod width_tests { assert_eq!(grid, [28.0, 111.0, 40.0, 81.0]); } + /// #5074 review (and #6575): a grid Word wrote from the cells' percentages is kept exactly, + /// while one that is off by more than Word's rounding is rebuilt from them. + #[test] + fn a_grid_matching_its_percentages_is_kept() { + let mut t = Table::new(1, 3, 300.0); + t.props.width = Some(300.0); + for (cell, p) in t.rows[0].cells.iter_mut().zip([33.32, 33.34, 33.34]) { + cell.props.width = None; + cell.props.width_pct = Some(p); + } + let mut grid = [99.95, 100.05, 100.0]; + apply_pct_widths(&t, &mut grid, 468.0); + assert_eq!(grid, [99.95, 100.05, 100.0], "kept"); + let mut stale = [90.0, 110.0, 100.0]; + apply_pct_widths(&t, &mut stale, 468.0); + assert!(stale.iter().zip([99.96, 100.02, 100.02]).all(|(g, w)| (g - w).abs() < 0.01), "rebuilt: {stale:?}"); + } + #[test] fn autofit_exhausts_donors() { crate::test_fonts(); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index ff3b0a9274..6f6b28bd55 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -12444,6 +12444,219 @@ fn cell_widths_override_grid() { } } +#[test] +fn percentage_cell_widths_that_disagree_or_span_columns() { + // Measured in Word (A4, 451.3 pt between the margins; 468 pt here), autofit tables 100% wide: + // rows asking 30/10/10/30 and 10/30/10/30, in either order, give 30/30/10/30 (each column its + // largest); a merged cell asking 50% over the first two columns, beside 10% and 40%, gives + // those two 50% between them; a merged 20% over columns asking 40% and 10% changes nothing; + // and a nested table's percentages are of its own width. + let cell_text = |s: &str| vec![wordcraft_doc::para_block(Paragraph::with_text(s, Default::default()))]; + let table = |rows: &[&[(Option, u32)]]| { + let mut t = Table::new(rows.len(), 4, 460.3); + t.grid = vec![107.3, 37.2, 31.95, 283.85]; + t.props.width_pct = Some(100.0); + for (row, spec) in t.rows.iter_mut().zip(rows) { + row.cells.truncate(spec.len()); + for (cell, (pct, span)) in row.cells.iter_mut().zip(spec.iter()) { + cell.props.width = None; + cell.props.width_pct = *pct; + cell.props.span = *span; + cell.blocks = cell_text("A"); + } + } + t + }; + let starts_at = |t: Table, prefix: &[u32], row: u32| { + let mut d = Document::from_text("After"); + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let x: Vec = (0..4) + .map(|c| { + let path: Vec = prefix.iter().copied().chain([row, c, 0]).collect(); + let [(x, _, _)] = para_at(&l, &path)[..] else { panic!("cell {c} missing") }; + x + }) + .collect(); + x.iter().map(|v| v - x[0]).collect::>() + }; + let near = |got: Vec, want: [f32; 4], what: &str| { + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 0.01), "{what}: columns start at {got:?}, not {want:?}"); + }; + let at = |shares: [f32; 3]| [0.0, shares[0] * 468.0, shares[1] * 468.0, shares[2] * 468.0]; + let p = |v: f32| (Some(v), 1); + let auto = (None, 1); + let open = [auto, auto, auto, auto]; + near( + starts_at(table(&[&[p(30.0), p(10.0), p(10.0), p(30.0)], &[p(10.0), p(30.0), p(10.0), p(30.0)], &open]), &[0], 2), + at([0.3, 0.6, 0.7]), + "rows disagree", + ); + near( + starts_at(table(&[&[p(10.0), p(30.0), p(10.0), p(30.0)], &[p(30.0), p(10.0), p(10.0), p(30.0)], &open]), &[0], 2), + at([0.3, 0.6, 0.7]), + "the other order", + ); + let merged = starts_at(table(&[&[(Some(50.0), 2), p(10.0), p(40.0)], &open]), &[0], 1); + near(vec![merged[0], merged[2], merged[3]].into_iter().chain([0.0]).collect(), [0.0, 0.5 * 468.0, 0.6 * 468.0, 0.0], "merged 50%"); + near( + starts_at(table(&[&[p(40.0), p(10.0), p(10.0), p(40.0)], &[(Some(20.0), 2), auto, auto], &open]), &[0], 2), + at([0.4, 0.5, 0.6]), + "a smaller merged cell", + ); + // The nested table fills the outer table's only cell, less the cell's margins. + let inner = table(&[&[p(40.0), p(10.0), p(10.0), p(40.0)], &open]); + let mut outer = Table::new(1, 1, 468.0); + outer.props.width_pct = Some(100.0); + outer.rows[0].cells[0].props.width_pct = Some(100.0); + outer.rows[0].cells[0].blocks = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(inner)), wordcraft_doc::para_block(Paragraph::new())]; + let nested = starts_at(outer, &[0, 0, 0, 0], 1); + let w = nested[3] / 0.6; + near(nested, [0.0, 0.4 * w, 0.5 * w, 0.6 * w], "nested"); + assert!(w > 400.0 && w <= 468.0, "the nested table is {w} wide"); +} +#[test] +fn percentage_cell_widths_size_the_columns_whichever_rows_ask() { + // Measured in Word (A4, 451.3 pt between the margins; 468 pt here): a 40/10/10/40 header row + // over rows without cell widths lays out 40/10/10/40 of the table, from the grid + // 107.3/37.2/32/283.9 pt a document saved. The same with the row in the middle, in a fixed + // table, with the table 100% wide or without a width; 144 pt for 40% of a 360 pt table; and + // 20/5/5/20 scaled up to fill the table. + let starts = |t: Table| { + let mut d = Document::from_text("After"); + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let x: Vec = (0..4) + .map(|c| { + let [(x, _, _)] = para_at(&l, &[0, 2, c, 0])[..] else { panic!("cell {c} missing") }; + x + }) + .collect(); + x.iter().map(|v| v - x[0]).collect::>() + }; + let table = |pct_row: usize, pcts: [f32; 4]| { + let mut t = Table::new(4, 4, 460.3); + t.grid = vec![107.3, 37.2, 31.95, 283.85]; + for (r, row) in t.rows.iter_mut().enumerate() { + for (cell, p) in row.cells.iter_mut().zip(pcts) { + cell.props.width = None; + cell.props.width_pct = (r == pct_row).then_some(p); + cell.blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("A", Default::default()))]; + } + } + t + }; + let near = |got: Vec, want: [f32; 4]| { + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 0.01), "columns start at {got:?}, not {want:?}"); + }; + let of = |w: f32| [0.0, w * 0.4, w * 0.5, w * 0.6]; + near(starts(table(0, [40.0, 10.0, 10.0, 40.0])), of(468.0)); + near(starts(table(1, [40.0, 10.0, 10.0, 40.0])), of(468.0)); + near(starts(table(0, [20.0, 5.0, 5.0, 20.0])), of(468.0)); + // A fixed table without a width of its own keeps its grid's 460.3 pt; 100% wide, it takes + // the text width. + let mut fixed = table(0, [40.0, 10.0, 10.0, 40.0]); + fixed.props.fixed = true; + near(starts(fixed.clone()), of(460.3)); + fixed.props.width_pct = Some(100.0); + near(starts(fixed), of(468.0)); + let mut full = table(0, [40.0, 10.0, 10.0, 40.0]); + full.props.width_pct = Some(100.0); + near(starts(full), of(468.0)); + let mut narrow = table(0, [20.0, 5.0, 5.0, 20.0]); + narrow.props.width = Some(360.0); + near(starts(narrow), of(360.0)); + // A row that starts one column in gives its percentages to the columns it covers: 10/10/40 + // there agree with the header row's 10/10/40 over the last three columns. + let mut shifted = table(0, [40.0, 10.0, 10.0, 40.0]); + shifted.rows[1].props.grid_before = 1; + shifted.rows[1].cells.remove(0); + for (cell, p) in shifted.rows[1].cells.iter_mut().zip([10.0, 10.0, 40.0]) { + cell.props.width_pct = Some(p); + } + near(starts(shifted), of(468.0)); + // Past 100% Word gives every column but the last its share of the table and the last what + // is left: 44/11/11/44 starts the columns at 44%, 55% and 66%. At 60/20/20/60 nothing is left, + // so the last column takes its longest word and the other three give up the same width. + near(starts(table(0, [44.0, 11.0, 11.0, 44.0])), [0.0, 0.44, 0.55, 0.66].map(|f| f * 468.0)); + let over = starts(table(0, [60.0, 20.0, 20.0, 60.0])); + let lost = [0.6 * 468.0 - over[1], 0.2 * 468.0 - (over[2] - over[1]), 0.2 * 468.0 - (over[3] - over[2])]; + assert!(lost[0] > 1.0 && lost.iter().all(|l| (l - lost[0]).abs() < 0.01), "columns start at {over:?}"); + // A fixed table gives the last column 2 pt and clips its text to the cell instead; the + // others share the rest of its 460.3 pt (Word: 275.5, 91.5, 91 and 2 pt). + let mut fixed_over = table(0, [60.0, 20.0, 20.0, 60.0]); + fixed_over.props.fixed = true; + for row in &mut fixed_over.rows { + row.cells[3].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("Lorem ipsum", Default::default()))]; + } + near(starts(fixed_over.clone()), [0.0, 0.6, 0.8, 1.0].map(|f| f * (460.3 - 2.0))); + let mut d = Document::from_text("After"); + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(fixed_over)).unwrap(); + let l = lay(&d); + let cells: Vec<(usize, f32, bool)> = l.pages[0] + .items + .iter() + .filter_map(|i| if let Placed::Cell { cell, rect, clip, row: 0, .. } = i { Some((*cell, rect.w, *clip)) } else { None }) + .collect(); + assert!(cells.iter().any(|&(c, w, clip)| c == 3 && (w - 2.0).abs() < 0.01 && clip), "the last cell is 2 pt and clipped: {cells:?}"); + assert!(cells.iter().all(|&(c, _, clip)| c == 3 || !clip), "only the last cell is clipped: {cells:?}"); + // When the columns before the last already pass 100% (80/40/40/20), Word gives them their + // shares left to right until the width runs out, and the table keeps its width: in a fixed + // table the third and fourth columns get 2 pt, the shares being of 460.3 - 4 pt; in an + // autofit table they get their longest words, the first two giving up the same width. + let widths = |t: Table| { + let mut d = Document::from_text("After"); + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let mut w: Vec<(usize, f32)> = l.pages[0] + .items + .iter() + .filter_map(|i| if let Placed::Cell { cell, rect, row: 0, .. } = i { Some((*cell, rect.w)) } else { None }) + .collect(); + w.sort_by_key(|c| c.0); + w.into_iter().map(|c| c.1).collect::>() + }; + let mut fixed_far = table(0, [80.0, 40.0, 40.0, 20.0]); + fixed_far.props.fixed = true; + let got = widths(fixed_far); + let room = 460.3 - 4.0; + let want = [0.8 * room, 0.2 * room, 2.0, 2.0]; + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 0.01), "fixed 80/40/40/20: {got:?}, not {want:?}"); + assert!((got.iter().sum::() - 460.3).abs() < 0.01, "fixed 80/40/40/20 is {} wide", got.iter().sum::()); + // A fixed grid narrower than 2 pt a column keeps its width: the columns share it. + let mut fixed_narrow = table(0, [80.0, 40.0, 40.0, 20.0]); + fixed_narrow.props.fixed = true; + fixed_narrow.grid = vec![1.5; 4]; + let got = widths(fixed_narrow); + assert!(got.iter().all(|w| (w - 1.5).abs() < 0.01), "a fixed 6 pt grid of 80/40/40/20: {got:?}"); + let got = widths(table(0, [80.0, 40.0, 40.0, 20.0])); + assert!((got.iter().sum::() - 468.0).abs() < 0.01, "autofit 80/40/40/20 is {} wide: {got:?}", got.iter().sum::()); + let lost = [0.8 * 468.0 - got[0], 0.2 * 468.0 - got[1]]; + assert!(lost[0] > 1.0 && (lost[0] - lost[1]).abs() < 0.01 && got[2] > 1.0 && got[3] > 1.0, "autofit 80/40/40/20: {got:?}"); + // A smaller percentage in another row of a column changes nothing: the column takes its + // largest. A merged cell's 20% goes to the two columns under it, which ask none. + let mut disagreeing = table(0, [40.0, 10.0, 10.0, 40.0]); + disagreeing.rows[1].cells[0].props.width_pct = Some(10.0); + near(starts(disagreeing), of(468.0)); + let mut spanned = table(0, [40.0, 10.0, 10.0, 40.0]); + spanned.rows[0].cells.remove(2); + spanned.rows[0].cells[1].props.span = 2; + spanned.rows[0].cells[1].props.width_pct = Some(20.0); + let got = starts(spanned); + assert!((got[1] - 0.4 * 468.0).abs() < 0.01 && (got[3] - 0.6 * 468.0).abs() < 0.01, "merged 20%: columns start at {got:?}"); + // A column no cell sizes and an absolute width alongside keep the grid. + let grid = [0.0, 107.3, 144.5, 176.45]; + let mut unsized_column = table(0, [40.0, 10.0, 10.0, 40.0]); + unsized_column.rows[0].cells[3].props.width_pct = None; + let mut absolute = table(0, [40.0, 10.0, 10.0, 40.0]); + absolute.rows[1].cells[0].props.width = Some(100.0); + for t in [unsized_column, absolute] { + let got = starts(t); + let k = got[3] / grid[3]; + near(got, grid.map(|g| g * k)); + } +} + #[test] fn ambiguous_widths_keep_grid() { crate::test_fonts(); diff --git a/docs/gaps.md b/docs/gaps.md index caa3ee583e..1a22b57ddf 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -35,7 +35,7 @@ Floating tables count exact contact with a line's bottom edge (#3977); shapes ke An otherwise empty section at page start retains its line before continuous content. Shared-section page totals and wrapping earlier text around later floating tables remain open. -Consistent cell widths override stale table grid proportions when their totals agree. Conflicting widths, spans and percentages still need the shared-grid algorithm. +Consistent cell widths override stale table grid proportions when their totals agree. Percentage cell widths size their columns whichever rows give them, as in Word: rows that disagree give each column its largest, and a merged cell's percentage is shared by the columns under it (in grid proportions, where Word shares it by their content). Mixed absolute and percentage widths still need the shared-grid algorithm. Protected typing boundary discovery (#3614) counts earlier objects once and uses an editable-ID set when moving through consecutive permission markers. Permission matching, protection enforcement and saved formats are unchanged. This narrows gap #3; broader stability and mutation costs remain. @@ -270,6 +270,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-10-31 | trivial | Preserve recipient columns after an unquoted whitespace-only prefix in a headered CSV (#4249); keep quoted headers, headerless whitespace records and shared CSV parsing. | | 2026-10-31 | trivial | Integrate complete-record recipient CSV delimiter detection (#4249) with current main; preserve leading blank-line detection (#5042), original regressions and readiness estimates. | | 2026-11-01 | trivial | #2437: Preserve finite paragraph-border flow extents and terminal-break keep preflight with current-main changes. Recursive terminal-successor lookahead remains outside scope. Source checks only; primary qualification pending. | +| 2026-10-31 | trivial | Percentage cell widths size their columns whichever rows give them, as measured in Word, rows that disagree giving each column its largest and merged cells sharing theirs; mixed absolute and percentage widths still need the shared-grid algorithm; no ranked gap changed; readiness estimates unchanged | | 2026-10-30 | trivial | Only the PDF sent to the printer omits link annotations; File › Print › Save these pages as PDF (`file.printPdf`) keeps them, like Export (#4734); no ranked gap changed; readiness estimates unchanged | | 2026-10-29 | trivial | The print job's PDF omits link annotations, which the spooler refused to fit to the paper, so documents with links reach the printer (#4734); physical printer output remains to be validated; no ranked gap changed; readiness estimates unchanged | | 2026-10-31 | trivial | Synchronize the existing Proofing pane with main `eecbb8f`; preserve explicit-position lookup, implicit selection, navigation, undo and per-window state; fresh exact-SHA hosted validation pending, readiness unchanged | diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 576caad229..957164306b 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -70,7 +70,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Tables: row border exceptions (`w:tblPrEx/w:tblBorders`) | ✅ | `row_borders_stay_on_row`, `row_nil_overrides_style`: explicit cell borders win; row exceptions precede table styles and table borders | — | | Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | | Tables: row heights (at least/exact), rows split across pages, header rows repeat, Can't Split | ✅ | 2026-10-06, #138; omitted cell-margin edges inherit current table defaults; every cell in a row gets the row's largest top and bottom margin; an exact height covers the top border, top margin and text, the bottom margin comes on top, and an exact row never splits; a row split across pages keeps its cells' bottom margin, border and last space after on the first page, widow/orphan control applies in its cells, each cell continues at the top of the next page and an at-least row keeps its minimum; an at-least row with less room than its minimum on a page that already holds something starts the next page whole (Allow row to break on or off, vAlign centre too), as observed in Word for Mac 2026-10-15 (a row of about 2.6 cm), #1742; that repeated header rows go with it and that a row taller than a page splits from the top of the next page come from the issue and synthetic tests, not a Word check (`…_an_at_least_row_with_no_room_starts_the_next_page_whole_either_way_breaking_is_set`, `…_an_at_least_row_taller_than_a_page_splits_from_the_top_of_the_next_page`, `layout::tests::a_row_shares_its_largest_top_and_bottom_margins`, `…_a_split_row_keeps_its_bottom_margin_and_widow_control`, `…_split_row_cells_each_continue_at_the_top`); a row's `gridAfter` is bounded to 63 columns in native documents too, and repeated header rows stop after 500 000 copied items across a table (hostile documents, #3692); a cell aligned to the middle or bottom of a split row is aligned within the part left on the page when all its text fits there (as tall as the other cells' text there), and runs from the top of the cell otherwise, as measured in Word (`layout::tests::a_middle_or_bottom_cell_of_a_split_row_lines_up_on_the_first_page`); a row whose first part on a page that already holds something would leave a cell empty there, because that cell's first line or inline picture (one line, never split) runs past the room, moves on whole instead of leaving the other cells' text beside the empty cell, so an at-least row grown taller than its minimum by a picture no longer splits off its picture (#4272; inferred from the reporter's Word result and the earlier observation that Word doesn't leave a cell empty for widow control, not yet checked in Word for rows without a minimum; at the top of a page such a row still splits; `layout::tests::an_at_least_row_grown_by_its_picture_moves_on_whole_rather_than_leave_the_picture_behind`, `…_a_picture_row_that_fits_stays_and_text_rows_beside_a_short_picture_still_split`, `…_a_picture_row_too_tall_for_any_page_splits_from_the_top_of_the_next_one`); a row of a nested table marked Can't Split isn't split with its outer row: the outer row moves on whole when that row comes first in it (docxide-pdf `nested-first-row-*-cant1`) and otherwise splits above it (inferred, not yet checked in Word), and on a fresh page a nested row taller than the room still splits; `layout::tests::nested_cant_split::nested_cant_split_row_moves_on_with_its_outer_row`, `…::the_outer_row_splits_above_a_nested_cant_split_row`, `…::the_cut_moves_up_until_no_nested_cant_split_row_runs_through_it`, `…::the_outer_row_breaks_between_nested_cant_split_rows_above_its_bottom_band`, `…::a_bottom_aligned_cell_keeps_its_nested_cant_split_row_whole`, `…::header_rows_go_on_with_a_first_row_whose_nested_cant_split_row_comes_first`, `…::a_kept_row_goes_on_with_a_row_whose_nested_cant_split_row_cant_start_below_it`, `…::a_merged_cell_doesnt_stretch_its_cant_split_row`, `…::nested_cant_split_row_taller_than_a_page_still_splits` | — | -| Tables: autofit to contents/window, fixed widths, Word 2013 edge | 🟡 | #137; #44: AutoFit Contents measures each column's narrowest and widest text and shares the width like Word, once (not live as you type); consistent a percentage width past 100% is kept, as Word does; a table with its own preferred width keeps it, however far past the margin, and only an automatic-width table over 1.5× the text width is squeezed to the margins (Word squeezes it as soon as it is wider) (#1721); cell widths override stale grid proportions when their totals agree (`cell_widths_override_grid`); conflicting widths and spans still differ | 3–5 | +| Tables: autofit to contents/window, fixed widths, Word 2013 edge | 🟡 | #137; #44: AutoFit Contents measures each column's narrowest and widest text and shares the width like Word, once (not live as you type); consistent a percentage width past 100% is kept, as Word does; a table with its own preferred width keeps it, however far past the margin, and only an automatic-width table over 1.5× the text width is squeezed to the margins (Word squeezes it as soon as it is wider) (#1721); cell widths override stale grid proportions when their totals agree (`cell_widths_override_grid`); percentage cell widths size their columns whichever rows give them, cells without a width taking no part, scaled to the table's width (a fixed table without one keeps its grid's width), and past 100% the columns taking their shares left to right until the width runs out, the ones after it getting their longest words, or 2 pt each with their text clipped in a fixed table, as measured in Word (`percentage_cell_widths_size_the_columns_whichever_rows_ask`); conflicting widths and spans still differ | 3–5 | | Floating tables (`w:tblpPr`) | 🟡 | #137; one placed on the page or margin that would cover visible text before it and does not fit below it moves to the next page (#534); empty line-break lines do not count as text; a click below one, outside its cells, goes to the text beside or after it, not to its last row, as checked in Word (#2038); exact line-bottom contact counts for tables only (#3977), both in row-span selection and word skipping; exact-spacing table contact uses the specified height rather than paragraph-mark metrics, with original Source Sans 3 controls in modes 11/12/14/15; expected Word rule from [cyril265's Word for Mac 16.114.1 measurements](https://github.com/storytold/wordcraft/issues/3977#issuecomment-6374217574), not a new Word run of these originals; anchor-order replay remains #3790's scope; other overlap rules untested | 2–3 | | Floating tables (`w:tblpPr`) | 🟡 | #137; one placed on the page or margin that would cover visible text before it and does not fit below it moves to the next page (#534); empty line-break lines do not count as text; a click below one, outside its cells, goes to the text beside or after it, not to its last row, as checked in Word (#2038); the same for a click within 2pt of a cell whose text is turned comes from the issue and synthetic tests, not a check by hand (#4181); other overlap rules untested | 2–3 | | Floating tables (`w:tblpPr`) | 🟡 | #137; one placed on the page or margin that would cover visible text before it and does not fit below it moves to the next page (#534); empty line-break lines do not count as text; a click below one, outside its cells, goes to the text beside or after it, not to its last row, as checked in Word (#2038); exact line-bottom contact counts for tables only (#3977), both in row-span selection and word skipping; exact-spacing table contact uses the specified height rather than paragraph-mark metrics, with original Source Sans 3 controls in modes 11/12/14/15; expected Word rule from [cyril265's Word for Mac 16.114.1 measurements](https://github.com/storytold/wordcraft/issues/3977#issuecomment-6374217574), not a new Word run of these originals; anchor-order replay remains #3790's scope; one with `tblOverlap=never` moved below another keeps its distance from the text's left edge only in Word 2013 layout (mode 15), before it its own left edge, also when its first cell has no left margin (docxide `displaced-anchor-*`); other overlap rules untested | 2–3 | @@ -352,6 +352,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-01 | trivial | #3915: preserve guarded whole-line ordinary-tab alignment with current main. Existing controls retained; source checks only, primary qualification pending. | | 2026-10-25 | trivial | Justified and distributed lines no longer stretch the spaces before a line's first character: Thai official letters indent paragraphs with ~20 spaces, and their first line moved right by up to the line's slack (86 pt in a measured case). Measured in Word with synthetic documents: left, `both`, `distribute` and `thaiDistribute` put the first character at the same place, for Thai and Latin text, at the paragraph start, after a line break and after a tab. A distributed line no longer counts the space it wrapped at, or the manual line break it ends with, so its text reaches the margin as in Word | | 2026-11-01 | trivial | #2437: Preserve finite paragraph-border flow extents and terminal-break keep preflight with current-main changes. Recursive terminal-successor lookahead remains outside scope. Source checks only; primary qualification pending. | +| 2026-10-31 | trivial | Percentage cell widths size their columns whichever rows give them, as measured in Word: rows that disagree giving each column its largest and a merged cell's percentage shared by the columns under it; a header row of percentages over rows without cell widths, autofit or fixed, scaled to the table's width, the text width or a fixed table's grid width, and past 100% the columns taking their shares left to right until the width runs out (the ones after it 2 pt and clipped in a fixed table); conflicting percentages, unsized columns, spans and absolute widths keep the grid | | 2026-10-30 | trivial | Keep with next: a kept heading before a three-line paragraph under widow/orphan control needs room for all three lines, since that paragraph can only move over whole; with room for two, the heading goes to the next page with it instead of staying alone at the bottom, as in Word for Mac 16.93. `layout::tests::keep_with_next_carries_the_heading_when_a_three_line_paragraph_moves_whole` | | 2026-10-28 | trivial | Connector object lookups retain the typed column-selection inputs on current main (#3631); readiness estimates unchanged | | 2026-10-27 | trivial | Connector rerouting indexes laid-out object positions once per batch, preserving page hints, first-match order and same-page glue; synthetic equivalence, geometry and scaling regressions (#3631); routing policy and readiness estimates unchanged | From 1e1bd7e0024feabe0588611f3b99da83a147295a Mon Sep 17 00:00:00 2001 From: pakiat <49967840+pakiat@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:29:51 +0700 Subject: [PATCH 97/99] Fields: PDFs and prints show body PAGEREF pages, as Word fills them in PDFs and prints show body PAGEREF pages as Word fills them in, including PAGEREF in text boxes and notes, with a second pass once the pages are known. Originally authored by @pakiat in #5129. --- ROADMAP.md | 2 + crates/engine/src/cmd/references.rs | 2 + crates/engine/src/cmd/references/fields.rs | 17 +- crates/engine/src/cmd/references/tests.rs | 28 ++ crates/engine/src/io_ext.rs | 8 +- crates/engine/src/lib.rs | 1 + crates/engine/src/locale.rs | 40 ++- crates/engine/src/session/layout.rs | 8 +- crates/engine/src/strict.rs | 8 +- crates/engine/src/tests.rs | 44 +++ crates/layout/src/cache.rs | 7 + crates/layout/src/fields.rs | 26 +- crates/layout/src/headers.rs | 141 +++++++-- crates/layout/src/lib.rs | 31 +- crates/layout/src/para/paragraph.rs | 5 +- crates/layout/src/pass.rs | 30 +- crates/layout/src/tests.rs | 12 +- crates/layout/src/tests/pages.rs | 332 +++++++++++++++++++++ crates/pdf/src/export.rs | 3 +- crates/pdf/src/options.rs | 10 +- crates/pdf/src/tests.rs | 21 ++ crates/ui-egui/src/app.rs | 4 + docs/gaps.md | 1 + docs/layout-parity.md | 6 +- 24 files changed, 740 insertions(+), 47 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e8281f3767..00a89f0299 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -258,6 +258,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-10-31: ODT: headers and footers are saved (they were dropped on every save), each page's header sits where LibreOffice puts it on open, and page numbers, page counts, dates and other text fields open as fields that update and are saved as ODF fields (gap 19). Readiness unchanged. - 2026-10-31: ODT: paragraph spacing, indents and line spacing are read and written, and an ODT's own default spacing (none, single lines) replaces Word's 8 pt after and 1.15 lines, so LibreOffice documents keep their vertical rhythm on open and save (gap 19). Readiness unchanged. - 2026-11-01: PDF export, printing and page images show the body's SEQ, STYLEREF and REF fields with their current results, as Word fills them in when it prints or exports even with Update fields before printing off: a caption numbered 7 when it is the first shows 1 on paper, and a REF to a bookmark the document lacks prints Word's "Error! Reference source not found.". NUMWORDS, FILENAME, the document properties, formulas and locked fields keep their stored results there, as in Word; the editor and the saved document keep every stored result. +- 2026-10-31: PDFs, prints and page images show each `PAGEREF` in the body with the page its bookmark is on, as Word fills them in when it prints or exports, so a table of contents saved with stale page numbers prints the pages its headings are on; on screen they keep their stored result until fields are updated, as in Word, and a locked one keeps it everywhere. A reference to a bookmark the document lacks prints Word's "Error! Bookmark not defined." Readiness unchanged. - 2026-10-28: Print Markup HTML, Markdown and text copies discover comment anchors in one paragraph walk, so unrelated bookmark markers no longer cause repeated prefix scans (#3614). Existing quotes, replies, order and export limits are unchanged; original synthetic semantic and scaling regressions cover the traversal. - 2026-11-04: Table Sort refuses malformed and nonexistent explicit columns before reordering rows (#5531). Omitted column 0, valid columns, header/order/language behavior and Undo/Redo are retained. Original Linux CLI/MCP controls and repeated native/DOCX reopens cover the command; native Word and desktop comparison remain untested. Readiness estimates unchanged. - 2026-10-30: Layout resource caps (#3867, #4385) and linear-time passes (#3866, #4392): repeated table-header rows are capped by item counts, a clipped group counting every nested member, the wrap cache by decoded pixels and the widths a linked text box chain lays out by their lines and items; PDF export, hit testing, tracked-change and clipped-table costs, and long endnote selections no longer grow quadratically. Synthetic regression tests only; no new Word comparison. @@ -996,6 +997,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-07 | trivial | Progress log: `.doc` brace and bracket shapes unfilled by default (#5943) | | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-11-01 | trivial | Progress log: SEQ, STYLEREF and REF fields show fresh results in output | +| 2026-10-31 | trivial | Progress log: PDFs and prints show a table of contents' current page numbers | | 2026-10-29 | trivial | Progress log: Print Markup balloon anchors use one object walk per paragraph (#3614); readiness estimates unchanged | | 2026-10-28 | trivial | Print Markup text-copy comment discovery walks paragraph objects once (#3614); quotes, order, limits and readiness estimates unchanged | | 2026-11-03 | trivial | Progress log: Language pack languages in every language list (CP4.3) | diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs index 9e5c5fead5..b360375119 100644 --- a/crates/engine/src/cmd/references.rs +++ b/crates/engine/src/cmd/references.rs @@ -17,6 +17,8 @@ mod properties; mod toc; use fields::caption; +#[cfg(test)] +use fields::output_fields_with; pub use fields::{ CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq, }; diff --git a/crates/engine/src/cmd/references/fields.rs b/crates/engine/src/cmd/references/fields.rs index eab9e21ed1..eedd16fee3 100644 --- a/crates/engine/src/cmd/references/fields.rs +++ b/crates/engine/src/cmd/references/fields.rs @@ -198,8 +198,9 @@ pub const REFERENCE_NOT_FOUND: &str = "Error! Reference source not found."; /// comment or text box is found too, and a REF to it shows that text as `stored` holds it, its /// own fields not yet refreshed, as Word's output does (measured in Word for Windows). The /// document's bookmarks are looked up once, and each bookmark's text read once, however many -/// fields refer to it. -fn ref_results(doc: &wordcraft_doc::Document, stored: &wordcraft_doc::Document) -> Vec { +/// fields refer to it. `error` is what a REF to a missing bookmark shows ([`REFERENCE_NOT_FOUND`] +/// in English). +fn ref_results(doc: &wordcraft_doc::Document, stored: &wordcraft_doc::Document, error: &str) -> Vec { let mut out = Vec::new(); let mut starts: std::collections::HashMap = std::collections::HashMap::new(); for (name, start) in doc.bookmarks().into_iter().chain(part_bookmarks(doc)) { @@ -220,7 +221,7 @@ fn ref_results(doc: &wordcraft_doc::Document, stored: &wordcraft_doc::Document) let f = FieldCode::parse(instr); let target = f.args.first().map(|s| s.split('\\').next().unwrap_or("").trim_matches('"')).unwrap_or(""); let Some(start) = starts.get(target) else { - out.push((StoryRef::Body, path.clone(), k, REFERENCE_NOT_FOUND.to_string())); + out.push((StoryRef::Body, path.clone(), k, error.to_string())); continue; }; let text = texts.entry(target.to_string()).or_insert_with(|| { @@ -281,7 +282,15 @@ fn changed(doc: &wordcraft_doc::Document, mut results: Vec) -> Vec< /// formulas keep their stored results (measured with Word for Windows, printing and exporting /// fields whose stored results were wrong). The document itself keeps its stored results. /// `None` when every such field already shows its fresh result, so nothing is copied then. +/// A `REF` to a missing bookmark shows Word's error in the interface language +/// ([`crate::set_reference_error`]). pub fn output_fields(doc: &wordcraft_doc::Document) -> Option { + let error = crate::locale::reference_error(); + output_fields_with(doc, error.as_deref().unwrap_or(REFERENCE_NOT_FOUND)) +} + +/// [`output_fields`], with `ref_error` for a `REF` to a missing bookmark. +pub(crate) fn output_fields_with(doc: &wordcraft_doc::Document, ref_error: &str) -> Option { // Numbers first, then the fields that read them: a STYLEREF to a heading holding a SEQ field, // and a REF to a bookmarked caption, show the new number. let seq = changed(doc, seq_results(doc)); @@ -293,7 +302,7 @@ pub fn output_fields(doc: &wordcraft_doc::Document) -> Option>(), ["stale", "stale"], "the document keeps it"); } +/// Word prints a REF's missing-bookmark error in its interface language: output takes the text +/// the shell sets ([`crate::set_reference_error`]), and a REF to a bookmark the document has +/// still shows the bookmark's text. +#[test] +fn a_missing_references_error_is_in_the_interface_language() { + let mut s = Session::new(wordcraft_doc::Document::from_text("Target")); + s.run("select.text", &json!({"text": "Target"})).unwrap(); + s.run("insert.bookmark", &json!({"name": "Here"})).unwrap(); + s.run("caret.docEnd", &json!({})).unwrap(); + for instr in ["REF NoSuchMark \\h", "REF Here \\h"] { + s.run("text.insert", &json!({"text": " "})).unwrap(); + s.run("insert.field", &json!({"instr": instr, "result": "stale"})).unwrap(); + } + let french = "Erreur ! Source du renvoi introuvable."; + let out = output_fields_with(&s.doc, french).expect("both results change"); + let shown: Vec = out + .para(StoryRef::Body, &wordcraft_doc::Path::top(0)) + .unwrap() + .objects + .iter() + .filter_map(|o| match o { + InlineObject::Field { result, .. } => Some(result.clone()), + _ => None, + }) + .collect(); + assert_eq!(shown, [french, "Target"]); +} + /// A REF showing the bookmarked paragraph's number (`\r`, `\n`, `\w`), which output doesn't /// compute, keeps its stored number when printed or exported rather than show the paragraph's /// text; a plain REF to the same bookmark is filled in. diff --git a/crates/engine/src/io_ext.rs b/crates/engine/src/io_ext.rs index f46d2f50ff..ed6c9466d6 100644 --- a/crates/engine/src/io_ext.rs +++ b/crates/engine/src/io_ext.rs @@ -103,7 +103,13 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::ExportOptions) -> Result, String> { let out = crate::cmd::references::output_fields(doc); let doc = out.as_ref().unwrap_or(doc); - let lo = wordcraft_layout::LayoutOptions { comment_balloons: opts.markup && opts.comments, numeral: opts.numeral, ..Default::default() }; + let lo = wordcraft_layout::LayoutOptions { + comment_balloons: opts.markup && opts.comments, + numeral: opts.numeral, + output_page_refs: true, + bookmark_error: crate::locale::bookmark_error(), + ..Default::default() + }; let l = wordcraft_layout::layout(doc, &mut wordcraft_layout::LayoutCache::new(), &lo); let p = l.pages.get(page).ok_or_else(|| format!("no page {}", page + 1))?; if opts.strict { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e5795e534e..88358e7df4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ use serde_json::Value; pub use io::Password; pub use keymap::KeyMap; +pub use locale::{set_bookmark_error, set_reference_error}; pub use ribbon::RibbonLayout; pub use session::{ CellRange, ColumnBlock, DocInfo, DocState, EditSnapshot, FindState, MathEdit, Prefs, Selection, Session, StylesPaneDock, UNDO_LIST_MAX, diff --git a/crates/engine/src/locale.rs b/crates/engine/src/locale.rs index 5d76e2eb87..9f35a49904 100644 --- a/crates/engine/src/locale.rs +++ b/crates/engine/src/locale.rs @@ -1,4 +1,4 @@ -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock, RwLock}; /// The system locale (BCP 47 tag) the shell found at startup, for Numeral › System. pub(super) static SYSTEM_LOCALE: OnceLock = OnceLock::new(); @@ -13,3 +13,41 @@ pub fn set_system_locale(tag: &str) { pub(crate) fn system_locale() -> Option<&'static str> { SYSTEM_LOCALE.get().map(String::as_str) } + +/// What output prints for a page reference to a missing bookmark, in the interface language +/// ([`set_bookmark_error`]); `None` until the shell sets it (English). +static BOOKMARK_ERROR: RwLock>> = RwLock::new(None); + +/// Tell the engine what PDFs, prints and page images show for a page reference to a bookmark the +/// document doesn't have, in the interface language: Word prints "Error! Bookmark not defined." +/// in its own. The shell calls this when its language is set; headless sessions print English. +pub fn set_bookmark_error(text: &str) { + let mut slot = BOOKMARK_ERROR.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if slot.as_deref() != Some(text) { + *slot = Some(Arc::from(text)); + } +} + +/// The text [`set_bookmark_error`] recorded, for output's layout options. +pub(crate) fn bookmark_error() -> Option> { + BOOKMARK_ERROR.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone() +} + +/// What output prints for a `REF` to a missing bookmark, in the interface language +/// ([`set_reference_error`]); `None` until the shell sets it (English). +static REFERENCE_ERROR: RwLock>> = RwLock::new(None); + +/// Tell the engine what PDFs, prints and page images show for a `REF` to a bookmark the document +/// doesn't have, in the interface language: Word prints "Error! Reference source not found." in +/// its own. The shell calls this when its language is set; headless sessions print English. +pub fn set_reference_error(text: &str) { + let mut slot = REFERENCE_ERROR.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if slot.as_deref() != Some(text) { + *slot = Some(Arc::from(text)); + } +} + +/// The text [`set_reference_error`] recorded, for output's `REF` results. +pub(crate) fn reference_error() -> Option> { + REFERENCE_ERROR.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone() +} diff --git a/crates/engine/src/session/layout.rs b/crates/engine/src/session/layout.rs index 2f773e308f..21c26f7099 100644 --- a/crates/engine/src/session/layout.rs +++ b/crates/engine/src/session/layout.rs @@ -74,6 +74,9 @@ impl Session { typing_word: typing, filename: filename.clone(), filepath: filepath.clone(), + // The editor shows a body page reference as stored until fields are updated. + output_page_refs: false, + bookmark_error: None, }; let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts)); let [newest, _] = std::mem::take(&mut self.layout); @@ -155,7 +158,8 @@ impl Session { layout.map(|l| (copy.doc, copy.sel, l)) } - /// A layout for output (PDF, images, print): no proofing marks, print view. + /// A layout for output (PDF, images, print): no proofing marks, print view, and page + /// references in the body showing their bookmarks' pages, as Word prints them. pub fn export_layout(&self) -> Arc { self.export_layout_with(false) } @@ -177,6 +181,8 @@ impl Session { numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)), filename: Some(Arc::from(fn_name.as_str())), filepath: Some(Arc::from(fn_path.as_str())), + output_page_refs: true, + bookmark_error: crate::locale::bookmark_error(), ..Default::default() }; Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts)) diff --git a/crates/engine/src/strict.rs b/crates/engine/src/strict.rs index 223366b81e..45f08d14c0 100644 --- a/crates/engine/src/strict.rs +++ b/crates/engine/src/strict.rs @@ -193,7 +193,13 @@ pub fn strict_report( /// The PDF export's options for `opts`: the one place they are built, shared by the export and /// its strict check. pub(crate) fn pdf_options(opts: &ExportOptions) -> wordcraft_pdf::PdfOptions { - wordcraft_pdf::PdfOptions { include_markup: opts.markup, comments: opts.markup && opts.comments, numeral: opts.numeral, ..Default::default() } + wordcraft_pdf::PdfOptions { + include_markup: opts.markup, + comments: opts.markup && opts.comments, + numeral: opts.numeral, + bookmark_error: crate::locale::bookmark_error(), + ..Default::default() + } } /// What a page image shows: the display options `file.exportPng` renders with. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1181f55c09..bad50faa30 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4929,6 +4929,50 @@ fn toc_page_numbers_are_pageref_fields() { assert_eq!(text(&s), expected); } +/// Output (PDF, print) shows a table of contents' page numbers where the headings now are, as +/// Word fills its `PAGEREF`s in when it prints or exports; the editor shows them as stored until +/// the table is updated, and the document keeps them. +#[test] +fn output_shows_toc_page_numbers_where_the_headings_are() { + let mut s = s(); + run(&mut s, "references.toc", json!({})); + run(&mut s, "caret.docEnd", json!({})); + for name in ["Alpha", "Bravo"] { + run(&mut s, "text.pageBreak", json!({})); + run(&mut s, "text.insert", json!({"text": name})); + run(&mut s, "para.heading1", json!({})); + run(&mut s, "text.newParagraph", json!({})); + } + run(&mut s, "references.updateToc", json!({})); + // Another page before Alpha moves the headings to pages 3 and 4. + let alpha = s + .doc + .body + .iter() + .position(|b| b.as_para().is_some_and(|p| p.props.style.as_deref() == Some("Heading1") && p.text.contains("Alpha"))) + .unwrap(); + s.sel = crate::Selection::caret(Pos::body(alpha, 0)); + run(&mut s, "text.pageBreak", json!({})); + let toc_numbers = |l: &wordcraft_layout::DocLayout| -> Vec { + l.pages[0] + .items + .iter() + .flat_map(|it| match it { + wordcraft_layout::Placed::Lines { para, .. } => para.shown.iter().map(|s| s.1.clone()).collect(), + _ => vec![], + }) + .collect() + }; + assert_eq!(s.export_layout().pages.len(), 4); + assert_eq!(toc_numbers(&s.layout()), ["2", "3"]); + assert_eq!(toc_numbers(&s.export_layout()), ["3", "4"]); + assert!(text(&s).contains("Alpha\t2"), "the document keeps the stored numbers"); + // A page image is laid out as the print job is: it shows the same numbers. + let png = crate::io_ext::render_png(&s.doc, 0, 1.0, &Default::default()).unwrap(); + let printed = wordcraft_render::render_page(&s.doc, &s.export_layout().pages[0], 1.0, &Default::default()).to_png(); + assert!(png == printed, "the page image and the printed page differ"); +} + /// Headings numbered through a list carry their numbers, and the level's separator, into the /// TOC entries. #[test] diff --git a/crates/layout/src/cache.rs b/crates/layout/src/cache.rs index 25234f1f1a..d0fb9cd5a5 100644 --- a/crates/layout/src/cache.rs +++ b/crates/layout/src/cache.rs @@ -107,6 +107,9 @@ pub(crate) fn env_hash(doc: &Document, opts: &LayoutOptions) -> u64 { outline.hash(&mut h); opts.filename.hash(&mut h); opts.filepath.hash(&mut h); + // Output shows page references the editor leaves stored (a missing bookmark's error too). + opts.output_page_refs.hash(&mut h); + opts.bookmark_error.hash(&mut h); h.finish() } @@ -187,3 +190,7 @@ impl Totals { /// The most extra layout passes for page totals in the body: a total that changes the page /// count (its digits pushing text to another page) is tried again, this many times at most. pub(crate) const MAX_TOTAL_PASSES: usize = 3; + +/// The most extra layout passes for output's body `PAGEREF`s: a page number whose digits move a +/// bookmark to another page is tried again, this many times at most. +pub(crate) const MAX_PAGE_REF_PASSES: usize = 3; diff --git a/crates/layout/src/fields.rs b/crates/layout/src/fields.rs index 1719518bd0..b98b69a065 100644 --- a/crates/layout/src/fields.rs +++ b/crates/layout/src/fields.rs @@ -1,6 +1,6 @@ //! Field results computed at layout time (page numbers) and note numbering. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use wordcraft_doc::section::NumFormat; @@ -31,6 +31,17 @@ pub struct FieldCtx { pub bookmark_pages: Arc, /// A key for caches standing for `bookmark_pages` (0 when it's empty). pub bookmarks_key: u64, + /// Output ([`crate::LayoutOptions::output_page_refs`]) with `bookmark_pages` found for the + /// whole document: a `PAGEREF` to a bookmark that is neither there nor in `bookmarks` shows + /// `bookmark_error` instead of its result. Off while the pages aren't known yet (the first + /// pass shows the stored results, the closest guess). + pub output: bool, + /// The names of all the document's bookmarks, for output (see `output`): one in a story that + /// `bookmark_pages` doesn't place (a header, a comment) keeps the field's result. + pub bookmarks: Arc>, + /// What output shows for a `PAGEREF` to a missing bookmark ([`BOOKMARK_NOT_DEFINED`] when + /// empty). + pub bookmark_error: Arc, /// Where a paragraph runs onto later pages: from text offset `.0` on, its fields are on page /// `.1` (ascending offsets). Empty except during the layout of a body paragraph split across /// pages, for its later pages (#1352); nothing else laid out meanwhile sees it. @@ -295,6 +306,15 @@ pub fn field_text_on(instr: &str, result: &str, ctx: &FieldCtx, page: u32) -> (S "SECTION" => (field_number(instr, fmt.unwrap_or(NumFormat::Decimal), ctx.section), true), "PAGEREF" => match pageref_page(instr, ctx) { Some((n, page_format)) => (field_number(instr, fmt.unwrap_or(page_format), n), true), + // Printed or exported, a reference to a bookmark the document lacks shows Word's + // error (measured in Word for Windows). + None if ctx.output + && !has_switch(instr, 'p') + && pageref_target(instr).is_some_and(|t| !ctx.bookmark_pages.contains_key(t) && !ctx.bookmarks.contains(t)) => + { + let text = if ctx.bookmark_error.is_empty() { BOOKMARK_NOT_DEFINED } else { &ctx.bookmark_error }; + (text.to_string(), true) + } None => (result.to_string(), false), }, "TITLE" if result.is_empty() => (apply_case_switch(instr, ctx.title.to_string()), false), @@ -319,6 +339,10 @@ pub fn field_text_on(instr: &str, result: &str, ctx: &FieldCtx, page: u32) -> (S } } +/// What Word prints for a `PAGEREF` to a bookmark the document doesn't have, in English (Word +/// prints it in its interface language: see [`crate::LayoutOptions::bookmark_error`]). +pub const BOOKMARK_NOT_DEFINED: &str = "Error! Bookmark not defined."; + /// Extract the bookmark target from a `PAGEREF` instruction. fn pageref_target(instr: &str) -> Option<&str> { let mut parts = instr.split_whitespace(); diff --git a/crates/layout/src/headers.rs b/crates/layout/src/headers.rs index bf7bce7a83..0793cc1c5b 100644 --- a/crates/layout/src/headers.rs +++ b/crates/layout/src/headers.rs @@ -236,23 +236,83 @@ pub(crate) fn headers_footers_refer_to_pages(doc: &Document) -> bool { }) } -/// Where each bookmark in the body starts: the number and number format of the page it is placed -/// on (with two of the same name, the first in the document). +/// Whether a story laid out with the body (the body itself, text boxes, footnotes and endnotes) +/// shows an unlocked `PAGEREF` field, which output resolves from the paginated document +/// ([`crate::LayoutOptions::output_page_refs`]); a locked one keeps its result, so it needs no +/// extra pass. Headers and footers are filled in after pagination and need none either. +pub(crate) fn flow_refers_to_pages(doc: &Document) -> bool { + use wordcraft_doc::PartKind; + let refers = |story: StoryRef| { + doc.para_paths(story).iter().filter_map(|path| doc.para(story, path)).any(|p| { + p.objects.iter().any(|o| matches!(o, InlineObject::Field { instr, locked, .. } if !*locked && fields::field_name(instr) == "PAGEREF")) + }) + }; + refers(StoryRef::Body) + || doc + .parts + .iter() + .filter(|(_, part)| matches!(part.kind, PartKind::TextBox | PartKind::Footnote | PartKind::Endnote)) + .any(|(id, _)| refers(StoryRef::Part(*id))) +} + +/// The names of all the document's bookmarks, in any story: a `PAGEREF` to one of them that +/// [`bookmark_pages`] can't place keeps its result rather than showing Word's error. +pub(crate) fn bookmark_names(doc: &Document) -> HashSet { + let mut names = HashSet::new(); + let stories = std::iter::once(StoryRef::Body).chain(doc.parts.keys().map(|id| StoryRef::Part(*id))); + for story in stories { + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + for o in &p.objects { + if let InlineObject::BookmarkStart { name } = o { + names.insert(name.clone()); + } + } + } + } + names +} + +/// Where each bookmark in the body, a footnote or an endnote, or in a text box anchored in one of +/// them, starts: the number and number format of the page it is placed on (with two of the same +/// name, the first found). A bookmark in a text box is on the page of the box's anchor (measured +/// in Word for Windows); one in a note, on the page that shows that part of the note. pub(crate) fn bookmark_pages(doc: &Document, pages: &[Page], sections: &[(usize, &SectionProps)]) -> fields::BookmarkPages { + use wordcraft_doc::PartKind; // Each paragraph's bookmarks: name, offset, and its line in the paragraph layout last looked // up (the pieces of a paragraph usually share one). - let mut wanted: HashMap)>> = HashMap::new(); + let mut wanted: Wanted = HashMap::new(); let mut seen = HashSet::new(); - for path in doc.para_paths(StoryRef::Body) { - let Some(p) = doc.para(StoryRef::Body, &path) else { continue }; - if !p.objects.iter().any(|o| matches!(o, InlineObject::BookmarkStart { .. })) { - continue; + let mut stories = vec![StoryRef::Body]; + let mut notes: Vec = + doc.parts.iter().filter(|(_, part)| matches!(part.kind, PartKind::Footnote | PartKind::Endnote)).map(|(id, _)| *id).collect(); + notes.sort_unstable(); + stories.extend(notes.into_iter().map(StoryRef::Part)); + for &story in &stories { + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + if !p.objects.iter().any(|o| matches!(o, InlineObject::BookmarkStart { .. })) { + continue; + } + for (off, o) in p.object_offsets().into_iter().zip(&p.objects) { + if let InlineObject::BookmarkStart { name } = o + && seen.insert(name.as_str()) + { + wanted.entry(story).or_default().entry(path.clone()).or_default().push((name.clone(), off, None)); + } + } } - for (off, o) in p.object_offsets().into_iter().zip(&p.objects) { - if let InlineObject::BookmarkStart { name } = o - && seen.insert(name.as_str()) - { - wanted.entry(path.clone()).or_default().push((name.clone(), off, None)); + } + if doc.parts.values().any(|part| part.kind == PartKind::TextBox) { + let mut boxes = HashSet::new(); + for &story in &stories { + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + for (off, o) in p.object_offsets().into_iter().zip(&p.objects) { + for id in o.text_boxes() { + box_bookmarks(doc, id, (story, &path, off), &mut boxes, &mut wordcraft_doc::BoxBudget::default(), &mut seen, &mut wanted); + } + } } } } @@ -263,8 +323,9 @@ pub(crate) fn bookmark_pages(doc: &Document, pages: &[Page], sections: &[(usize, } let format = sections.get(page.section).map(|(_, s)| s.page_num_format).unwrap_or_default(); for it in &page.items { - let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, .. } = it else { continue }; - let Some(marks) = wanted.get_mut(path) else { continue }; + let Placed::Lines { story, path, para, l0, l1, .. } = it else { continue }; + let Some(paras) = wanted.get_mut(story) else { continue }; + let Some(marks) = paras.get_mut(path) else { continue }; let layout = Arc::as_ptr(para) as usize; marks.retain_mut(|(name, off, line)| { let li = match *line { @@ -282,21 +343,61 @@ pub(crate) fn bookmark_pages(doc: &Document, pages: &[Page], sections: &[(usize, false }); if marks.is_empty() { - wanted.remove(path); + paras.remove(path); + if paras.is_empty() { + wanted.remove(story); + } } } } out } -/// A key for caches standing for `marks` (0 for none). -pub(crate) fn marks_key(marks: &fields::BookmarkPages) -> u64 { - if marks.is_empty() { - return 0; +/// The bookmarks [`bookmark_pages`] looks for, by story and paragraph: name, offset, and the line +/// in the paragraph layout last looked up. +type Wanted = HashMap)>>>; + +/// Add the bookmarks of text box `id`, and of the boxes inside it, to `wanted` at `anchor` (the +/// story, paragraph and offset of the outermost box). A box shown twice, or inside itself, counts +/// once, and the boxes inside one go as deep as layout shows them ([`wordcraft_doc::BoxBudget`]): a +/// bookmark in a box nested deeper has no page. +fn box_bookmarks<'d>( + doc: &'d Document, + id: u32, + anchor: (StoryRef, &Path, usize), + boxes: &mut HashSet, + budget: &mut wordcraft_doc::BoxBudget, + seen: &mut HashSet<&'d str>, + wanted: &mut Wanted, +) { + if boxes.contains(&id) || !budget.enter(id) { + return; } + boxes.insert(id); + let story = StoryRef::Part(id); + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + for o in &p.objects { + if let InlineObject::BookmarkStart { name } = o + && seen.insert(name.as_str()) + { + wanted.entry(anchor.0).or_default().entry(anchor.1.clone()).or_default().push((name.clone(), anchor.2, None)); + } + for inner in o.text_boxes() { + box_bookmarks(doc, inner, anchor, boxes, budget, seen, wanted); + } + } + } + budget.leave(); +} + +/// A key for caches standing for `marks`: 0 while the pages aren't known (`None`), something else +/// once they are, even with no bookmarks (output then shows missing ones as errors). +pub(crate) fn marks_key(marks: Option<&fields::BookmarkPages>) -> u64 { + let Some(marks) = marks else { return 0 }; let mut v: Vec<_> = marks.iter().collect(); v.sort_by(|a, b| a.0.cmp(b.0)); - hash_of(&v) + hash_of(&v).max(1) } pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(usize, &SectionProps)], totals: &Totals) { diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 40151d6363..6178d9ceeb 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -73,7 +73,7 @@ mod table_flow; use boxes::{BOX_INSET_X, BOX_INSET_Y}; use boxes::{BoxInput, BoxLayout, Edges, fit_box, layout_box, push_para}; pub use cache::LayoutCache; -use cache::{MAX_TOTAL_PASSES, Totals}; +use cache::{MAX_PAGE_REF_PASSES, MAX_TOTAL_PASSES, Totals}; #[cfg(test)] use ctx::picture_outline; use ctx::{Ctx, Pass}; @@ -234,6 +234,14 @@ pub struct LayoutOptions { pub filename: Option>, /// Document full path for FILENAME \p fields ([`FieldCtx::filepath`]). pub filepath: Option>, + /// Output (PDF, print, page images): `PAGEREF` fields in the body show the page their + /// bookmark is on, as Word fills them in when it prints or exports. The editor leaves this + /// off: there a body `PAGEREF` keeps its result until fields are updated, as in Word. + pub output_page_refs: bool, + /// What output shows for a `PAGEREF` to a bookmark the document doesn't have: Word prints + /// "Error! Bookmark not defined." in its interface language. `None` is the English text, + /// [`fields::BOOKMARK_NOT_DEFINED`]. + pub bookmark_error: Option>, } /// The word being typed ([`LayoutOptions::typing_word`]): the paragraph by its revision @@ -344,8 +352,15 @@ pub fn layout(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> let mut totals = Totals::first_guess(doc.sections().len()); let mut passes = 0; let (mut early, mut rewraps) = (EarlyFloats::new(), 0); + // Output's `PAGEREF`s in the body, text boxes and notes ([`LayoutOptions::output_page_refs`]) + // show the pages the pass before found for their bookmarks, until those hold (bounded, like + // the totals). The first pass, with no pages found yet, shows their stored results. + let page_refs = opts.output_page_refs && headers::flow_refers_to_pages(doc); + let mut marks: Option> = None; + let mut mark_passes = 0; let mut l = loop { - match layout_pass(doc, cache, opts, ¬e_pages, &totals, passes < MAX_TOTAL_PASSES, (&early, rewraps < MAX_REWRAP_PASSES)) { + match layout_pass(doc, cache, opts, (¬e_pages, marks.as_ref()), &totals, passes < MAX_TOTAL_PASSES, (&early, rewraps < MAX_REWRAP_PASSES)) + { Pass::Again(t) => { totals = t; passes += 1; @@ -364,6 +379,18 @@ pub fn layout(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> continue; } } + if page_refs && mark_passes < MAX_PAGE_REF_PASSES { + let found = headers::bookmark_pages(doc, &l.pages, &doc.sections()); + if marks.as_deref() != Some(&found) { + marks = Some(Arc::new(found)); + mark_passes += 1; + // The page numbers shown can move text to other pages: the page totals and + // footnotes numbered per page get their passes to settle again. + passes = 0; + note_passes = 1; + continue; + } + } break l; } } diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index b6da050323..8186468b43 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -411,7 +411,7 @@ impl<'a> Shaped<'a> { /// A field: a legacy form field, its code in braces, or its result. fn field(&mut self, cx: &Cx, (k, o): (usize, &InlineObject), slot: Slot, rc: &Arc) { - let InlineObject::Field { instr, result, code, .. } = o else { return }; + let InlineObject::Field { instr, result, code, locked, .. } = o else { return }; let env = cx.env; let form = if env.field_codes != *code { None } else { o.legacy_form() }; if let Some(wordcraft_doc::legacy_form::LegacyForm::CheckBox { size, .. }) = form { @@ -426,6 +426,9 @@ impl<'a> Shaped<'a> { shaded.shading = Some(FIELD_SHADING); } self.b.shape_atomic(&field_code_text(instr), slot.start, slot.end, &Arc::new(shaded)); + } else if *locked && crate::fields::field_name(instr) == "PAGEREF" { + // A locked page reference keeps its result, as Word prints and exports it. + self.b.shape_atomic(result, slot.start, slot.end, &linked(rc, instr)); } else { self.field_result(cx, (instr, result), slot, rc); } diff --git a/crates/layout/src/pass.rs b/crates/layout/src/pass.rs index a29b2a700c..af5bc8a8e0 100644 --- a/crates/layout/src/pass.rs +++ b/crates/layout/src/pass.rs @@ -2,9 +2,12 @@ use std::collections::VecDeque; use super::cache::{LayoutCache, Totals, env_hash, hash_of}; use super::ctx::{Ctx, Pass, with_pct_base}; +use super::fields::{BOOKMARK_NOT_DEFINED, BookmarkPages}; use super::floats::{EarlyFloats, WrapArea, early_covered, left_out_objects}; use super::flow::{OutlinePass, place_outline_para, place_para}; -use super::headers::{HfLinks, bookmark_pages, headers_footers, headers_footers_refer_to_pages, marks_key, mirror_even_pages, section_side}; +use super::headers::{ + HfLinks, bookmark_names, bookmark_pages, headers_footers, headers_footers_refer_to_pages, marks_key, mirror_even_pages, section_side, +}; use super::notes::{MAX_NOTE_PAGES, NoteSeps, note_info, place_endnotes}; use super::page::{PageBuilder, body_top_for, foot_top_for, item_bottom}; use super::placed::Placed; @@ -60,12 +63,13 @@ fn reset_cache(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) { cache.used.clear(); } -/// The walk state at the start of a pass, with the note references the body shows. +/// The walk state at the start of a pass, with the note references the body shows and the pages +/// of the bookmarks its `PAGEREF`s show (`None` until output has found them). fn new_ctx<'a>( doc: &'a Document, cache: &'a mut LayoutCache, opts: &'a LayoutOptions, - (note_pages, totals): (&HashMap, &Totals), + (note_pages, marks, totals): (&HashMap, Option<&Arc>, &Totals), ) -> Ctx<'a> { let notes = note_info(doc, opts.hides_deleted(StoryRef::Body), note_pages); let notes_hash = hash_of(&{ @@ -89,6 +93,11 @@ fn new_ctx<'a>( author: doc.core.creator.as_str().into(), filename: opts.filename.clone().unwrap_or_else(|| "".into()), filepath: opts.filepath.clone().unwrap_or_else(|| "".into()), + bookmark_pages: marks.cloned().unwrap_or_default(), + bookmarks_key: marks_key(marks.map(|m| &**m)), + output: opts.output_page_refs && marks.is_some(), + bookmarks: if opts.output_page_refs { Arc::new(bookmark_names(doc)) } else { Arc::default() }, + bookmark_error: opts.bookmark_error.clone().unwrap_or_else(|| BOOKMARK_NOT_DEFINED.into()), ..Default::default() }, notes_hash, @@ -482,8 +491,10 @@ fn fill_headers_footers( ctx.track_totals = false; if headers_footers_refer_to_pages(ctx.doc) { let marks = bookmark_pages(ctx.doc, pages, sections); - ctx.fields.bookmarks_key = marks_key(&marks); + ctx.fields.bookmarks_key = marks_key(Some(&marks)); ctx.fields.bookmark_pages = Arc::new(marks); + // The pages are known now: output shows a reference to a missing bookmark as Word does. + ctx.fields.output = ctx.opts.output_page_refs; } headers_footers(ctx, pages, sections, &found); if ctx.doc.settings.mirror_margins { @@ -515,20 +526,21 @@ fn index_lines(pages: &[Page]) -> HashMap<(StoryRef, Path), Vec<(usize, usize)>> } /// One layout pass, numbering footnotes restarted on each page by `note_pages` ([`note_info`]), -/// with `totals` assumed for the page totals in the body. With `may_repeat`, a pass whose body -/// shows totals that turn out different asks to be done again. Pages start with the wrap areas -/// of the `early` floats; with `may_rewrap`, a pass that finds others asks to be done again. +/// with `totals` assumed for the page totals in the body and `marks` for the pages its `PAGEREF`s +/// show. With `may_repeat`, a pass whose body shows totals that turn out different asks to be +/// done again. Pages start with the wrap areas of the `early` floats; with `may_rewrap`, a pass +/// that finds others asks to be done again. pub(crate) fn layout_pass( doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions, - note_pages: &HashMap, + (note_pages, marks): (&HashMap, Option<&Arc>), totals: &Totals, may_repeat: bool, (early, may_rewrap): (&EarlyFloats, bool), ) -> Pass { reset_cache(doc, cache, opts); - let mut ctx = new_ctx(doc, cache, opts, (note_pages, totals)); + let mut ctx = new_ctx(doc, cache, opts, (note_pages, marks, totals)); let hf = Arc::clone(&ctx.hf); let sections = &hf.sections; let mode = Mode::of(opts.view); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 6f6b28bd55..845f25db9f 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -10784,7 +10784,7 @@ fn footer_page_total_needs_one_body_pass() { d.last_section.footers.default = Some(id); let first = |d: &Document| { let totals = Totals::first_guess(d.sections().len()); - layout_pass(d, &mut LayoutCache::new(), &LayoutOptions::default(), &HashMap::new(), &totals, true, (&EarlyFloats::new(), true)) + layout_pass(d, &mut LayoutCache::new(), &LayoutOptions::default(), (&HashMap::new(), None), &totals, true, (&EarlyFloats::new(), true)) }; assert!(matches!(first(&d), Pass::Done(l) if l.pages.len() == 3), "the footer's total asked for another pass"); // The same field in the body is only known once every page is laid out. @@ -14798,7 +14798,15 @@ fn last_rewrap_pass_keeps_early_floats_clear_of_text() { let one_page = picture_above_anchor(&"Earlier text flows beside the picture placed above its anchor. ".repeat(3), 4, 72.0); for d in [one_page, early_float_across_pages()] { let totals = Totals::first_guess(d.sections().len()); - let pass = layout_pass(&d, &mut LayoutCache::new(), &LayoutOptions::default(), &HashMap::new(), &totals, false, (&EarlyFloats::new(), false)); + let pass = layout_pass( + &d, + &mut LayoutCache::new(), + &LayoutOptions::default(), + (&HashMap::new(), None), + &totals, + false, + (&EarlyFloats::new(), false), + ); let Pass::Done(l) = pass else { panic!("a last pass is done") }; let (under, n) = text_under_shapes(&l); assert_eq!(under, None); diff --git a/crates/layout/src/tests/pages.rs b/crates/layout/src/tests/pages.rs index 46252bac6e..476ff1ed96 100644 --- a/crates/layout/src/tests/pages.rs +++ b/crates/layout/src/tests/pages.rs @@ -345,6 +345,296 @@ fn page_references_in_footers_show_their_bookmarks_page() { assert_eq!(texts, ["9"]); } +/// Output (PDF, print, page images) shows each body `PAGEREF` its bookmark's page, counted from +/// the section's restart, as Word fills them in when it prints or exports; the editor keeps the +/// stored result until fields are updated, and a locked reference keeps it in output too. +/// Measured in Word for Microsoft 365: references stored as "9" to a heading on the third page +/// print and export as 3, or 2 when the second page starts a section numbered from 1; a locked +/// one stays 9, in the body and in a footer. +#[test] +fn page_references_in_the_body_show_their_bookmarks_page_in_output() { + let field = |instr: &str, locked: bool| InlineObject::Field { + instr: instr.into(), + result: "9".into(), + locked, + dirty: false, + code: false, + form: String::new(), + }; + let mut d = Document::from_text("See page \nLocked \nBlank\nHeading"); + for (i, instr, locked) in [(0, "PAGEREF _Toc1 \\h", false), (1, "PAGEREF _Toc1", true)] { + let p = d.para_mut(StoryRef::Body, &Path::top(i)).unwrap(); + let n = p.len(); + p.insert_object(n, field(instr, locked), &Default::default()).unwrap(); + } + for i in [2, 3] { + d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().props.page_break_before = Some(true); + } + let heading = d.para_mut(StoryRef::Body, &Path::top(3)).unwrap(); + heading.insert_object(0, InlineObject::BookmarkStart { name: "_Toc1".into() }, &Default::default()).unwrap(); + let refs = |l: &DocLayout| -> Vec { + l.pages[0] + .items + .iter() + .flat_map(|it| if let Placed::Lines { para, .. } = it { para.shown.iter().map(|s| s.1.clone()).collect() } else { vec![] }) + .collect() + }; + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + // Only an unlocked reference calls for the extra pass: a locked one keeps its result. + assert!(crate::headers::flow_refers_to_pages(&d)); + let mut all_locked = d.clone(); + if let Some(InlineObject::Field { locked, .. }) = all_locked.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.last_mut() { + *locked = true; + } + assert!(!crate::headers::flow_refers_to_pages(&all_locked)); + let l = lay(&d); + assert_eq!(l.pages.len(), 3); + assert_eq!(refs(&l), ["9", "9"]); + assert_eq!(refs(&layout(&d, &mut LayoutCache::new(), &output)), ["3", "9"]); + // The second page starts a section that numbers its pages from 1. + let first = d.last_section.clone(); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().section = Some(Box::new(first)); + d.last_section.page_num_start = Some(1); + let l = layout(&d, &mut LayoutCache::new(), &output); + assert_eq!(l.pages.iter().map(|p| p.number).collect::>(), [1, 1, 2]); + assert_eq!(refs(&l), ["2", "9"]); + assert_eq!(refs(&lay(&d)), ["9", "9"]); + // A footer's references: the unlocked one shows the page, the locked one keeps its result. + let mut fp = Paragraph::new(); + fp.insert_object(0, field("PAGEREF _Toc1", false), &Default::default()).unwrap(); + fp.insert_object(fp.len(), field("PAGEREF _Toc1", true), &Default::default()).unwrap(); + d.last_section.footers.default = Some(d.add_part(PartKind::Footer, vec![para_block(fp)])); + assert_eq!(footer_shown(&lay(&d)).last().map(String::as_str), Some("2/9")); +} + +/// Printed or exported, a reference to a bookmark the document doesn't have shows Word's error, +/// whether or not the document has other bookmarks (measured in Word for Windows: "Error! +/// Bookmark not defined."); the editor keeps the stored result, and so does a reference that +/// shows "above" or "below" (`\p`). +#[test] +fn a_page_reference_to_a_missing_bookmark_shows_words_error_in_output() { + let field = + |instr: &str| InlineObject::Field { instr: instr.into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() }; + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + for other_mark in [false, true] { + let mut d = Document::from_text("See \nAbove \nTarget"); + for (i, instr) in [(0, "PAGEREF NoSuchMark \\h"), (1, "PAGEREF NoSuchMark \\p")] { + let p = d.para_mut(StoryRef::Body, &Path::top(i)).unwrap(); + let n = p.len(); + p.insert_object(n, field(instr), &Default::default()).unwrap(); + } + if other_mark { + let p = d.para_mut(StoryRef::Body, &Path::top(2)).unwrap(); + p.insert_object(0, InlineObject::BookmarkStart { name: "Elsewhere".into() }, &Default::default()).unwrap(); + } + let shown = |l: &DocLayout| -> Vec { + l.pages[0] + .items + .iter() + .flat_map(|it| if let Placed::Lines { para, .. } = it { para.shown.iter().map(|s| s.1.clone()).collect() } else { vec![] }) + .collect() + }; + assert_eq!(shown(&layout(&d, &mut LayoutCache::new(), &output)), [crate::fields::BOOKMARK_NOT_DEFINED, "9"], "other bookmark: {other_mark}"); + assert_eq!(shown(&lay(&d)), ["9", "9"], "the editor, other bookmark: {other_mark}"); + // One cache for the editor's layout and then output's: output doesn't reuse the + // editor's paragraphs, and the editor doesn't reuse output's after it. + let mut cache = LayoutCache::new(); + let editor = LayoutOptions::default(); + assert_eq!(shown(&layout(&d, &mut cache, &editor)), ["9", "9"]); + assert_eq!( + shown(&layout(&d, &mut cache, &output)), + [crate::fields::BOOKMARK_NOT_DEFINED, "9"], + "a shared cache, other bookmark: {other_mark}" + ); + assert_eq!(shown(&layout(&d, &mut cache, &editor)), ["9", "9"], "the editor after output, other bookmark: {other_mark}"); + } +} + +/// Printed or exported, a reference to a bookmark in a text box shows the page of the box's +/// anchor (measured in Word for Windows), not "Error! Bookmark not defined.". +#[test] +fn a_page_reference_to_a_bookmark_in_a_text_box_shows_its_anchors_page_in_output() { + use wordcraft_doc::para::{Float, ShapeKind, Wrap}; + let mut d = Document::from_text("See \nSecond"); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.page_break_before = Some(true); + let mut inner = Paragraph::with_text("Caption", Default::default()); + inner.insert_object(0, InlineObject::BookmarkStart { name: "Boxed".into() }, &Default::default()).unwrap(); + let story = d.add_part(PartKind::TextBox, vec![para_block(inner)]); + let shape = InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: None, + stroke: None, + stroke_width: 0.0, + float: Float { wrap: Wrap::Inline, ..Default::default() }, + story: Some(story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().insert_object(0, shape, &Default::default()).unwrap(); + let field = + InlineObject::Field { instr: "PAGEREF Boxed \\h".into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() }; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + let n = p.len(); + p.insert_object(n, field, &Default::default()).unwrap(); + let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() }); + let shown: Vec = output.pages[0] + .items + .iter() + .flat_map(|it| match it { + Placed::Lines { story: StoryRef::Body, para, .. } => para.shown.iter().map(|s| s.1.clone()).collect(), + _ => vec![], + }) + .collect(); + assert_eq!(shown, ["2"]); +} + +/// The field results shown on page `page` by the lines of `story`. +fn shown_in(l: &DocLayout, page: usize, story: StoryRef) -> Vec { + l.pages[page] + .items + .iter() + .flat_map(|it| match it { + Placed::Lines { story: s, para, .. } if *s == story => para.shown.iter().map(|s| s.1.clone()).collect(), + _ => vec![], + }) + .collect() +} + +/// A page reference field showing `result` until it is updated. +fn pageref(instr: &str, result: &str) -> InlineObject { + InlineObject::Field { instr: instr.into(), result: result.into(), locked: false, dirty: false, code: false, form: String::new() } +} + +/// Three pages, a bookmark "Body" on the third; a text box on the first page and a footnote on +/// the second refer to it, the footnote also to a bookmark that doesn't exist, and holds the +/// bookmark "InNote"; the header holds the bookmark "InHeader". With `body_refs` the first +/// paragraph refers to "InNote" and "InHeader" too. Returns the document and the box's and the +/// note's stories. +fn refs_outside_the_body(body_refs: bool) -> (Document, StoryRef, StoryRef) { + use wordcraft_doc::para::{Float, ShapeKind, Wrap}; + let mut d = Document::from_text("Intro \nSecond\nTarget"); + for i in [1, 2] { + d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().props.page_break_before = Some(true); + } + d.para_mut(StoryRef::Body, &Path::top(2)) + .unwrap() + .insert_object(0, InlineObject::BookmarkStart { name: "Body".into() }, &Default::default()) + .unwrap(); + let mut boxed = Paragraph::with_text("Box ", Default::default()); + boxed.insert_object(boxed.len(), pageref("PAGEREF Body \\h", "9"), &Default::default()).unwrap(); + let box_story = d.add_part(PartKind::TextBox, vec![para_block(boxed)]); + let shape = InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: None, + stroke: None, + stroke_width: 0.0, + float: Float { wrap: Wrap::Inline, ..Default::default() }, + story: Some(box_story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().insert_object(0, shape, &Default::default()).unwrap(); + let mut note = Paragraph::with_text("Note ", Default::default()); + note.insert_object(0, InlineObject::BookmarkStart { name: "InNote".into() }, &Default::default()).unwrap(); + for f in [pageref("PAGEREF Body \\h", "9"), pageref("PAGEREF Gone \\h", "9")] { + note.insert_object(note.len(), f, &Default::default()).unwrap(); + } + let note_id = d.add_part(PartKind::Footnote, vec![para_block(note)]); + d.insert_object(&Pos::body(1, 6), InlineObject::NoteRef { kind: NoteKind::Footnote, id: note_id, custom: String::new() }, &Default::default()) + .unwrap(); + let mut hp = Paragraph::with_text("Header", Default::default()); + hp.insert_object(0, InlineObject::BookmarkStart { name: "InHeader".into() }, &Default::default()).unwrap(); + d.last_section.headers.default = Some(d.add_part(PartKind::Header, vec![para_block(hp)])); + if body_refs { + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + for f in [pageref("PAGEREF InNote \\h", "9"), pageref("PAGEREF InHeader \\h", "9")] { + p.insert_object(p.len(), f, &Default::default()).unwrap(); + } + } + (d, StoryRef::Part(box_story), StoryRef::Part(note_id)) +} + +/// Printed or exported, page references in text boxes and notes show their bookmarks' pages too, +/// also when the body has none (the extra pass is for them as well); a bookmark in a note is on +/// the page that shows the note; a reference to a bookmark that exists where pages aren't found +/// (a header) keeps its result, and only one to a bookmark nowhere in the document shows Word's +/// error. The editor keeps every stored result. +#[test] +fn page_references_outside_the_body_show_pages_in_output() { + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + for body_refs in [false, true] { + let (d, boxed, note) = refs_outside_the_body(body_refs); + assert!(crate::headers::flow_refers_to_pages(&d)); + let l = layout(&d, &mut LayoutCache::new(), &output); + assert_eq!(l.pages.len(), 3); + assert_eq!(shown_in(&l, 0, boxed), ["3"], "the text box, body refs: {body_refs}"); + assert_eq!(shown_in(&l, 1, note), ["3", crate::fields::BOOKMARK_NOT_DEFINED], "the footnote, body refs: {body_refs}"); + let body: Vec = if body_refs { vec!["2".into(), "9".into()] } else { vec![] }; + assert_eq!(shown_in(&l, 0, StoryRef::Body), body, "body refs: {body_refs}"); + let editor = lay(&d); + assert_eq!(shown_in(&editor, 0, boxed), ["9"]); + assert_eq!(shown_in(&editor, 1, note), ["9", "9"]); + } +} + +/// Output shows a reference to a missing bookmark in the text it is given for the interface +/// language (Word prints its error in its own), English without one. +#[test] +fn a_missing_bookmarks_error_is_in_the_interface_language() { + let (d, _, note) = refs_outside_the_body(false); + let french: Arc = "Erreur ! Signet non défini.".into(); + let l = + layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, bookmark_error: Some(french.clone()), ..Default::default() }); + assert_eq!(shown_in(&l, 1, note), ["3", &*french]); +} + +/// The first pass of output, before any bookmark's page is known, shows the stored results (the +/// closest guess: a table of contents isn't stretched by errors), not Word's error. +#[test] +fn outputs_first_pass_shows_stored_page_references() { + let mut d = Document::from_text("See "); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.insert_object(p.len(), pageref("PAGEREF Gone \\h", "9"), &Default::default()).unwrap(); + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + let totals = crate::cache::Totals::first_guess(d.sections().len()); + let first = crate::pass::layout_pass( + &d, + &mut LayoutCache::new(), + &output, + (&std::collections::HashMap::new(), None), + &totals, + true, + (&crate::floats::EarlyFloats::new(), true), + ); + let crate::ctx::Pass::Done(l) = first else { panic!("one page needs no other pass") }; + assert_eq!(shown_in(&l, 0, StoryRef::Body), ["9"]); + assert_eq!(shown_in(&layout(&d, &mut LayoutCache::new(), &output), 0, StoryRef::Body), [crate::fields::BOOKMARK_NOT_DEFINED]); +} + +/// Output's page references can change the page count after the totals settled (here many +/// references to a missing bookmark grow from their stored "9" to Word's error, adding pages): +/// the body's `NUMPAGES` still shows the pages the document ends with. +#[test] +fn output_page_references_that_change_the_page_count_leave_totals_right() { + const REFS: usize = 300; + let mut d = Document::from_text(&" ".repeat(REFS)); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + for off in (1..=REFS).rev() { + p.insert_object(off, pageref("PAGEREF Gone \\h", "9"), &Default::default()).unwrap(); + } + p.insert_object(0, pageref("NUMPAGES", "9"), &Default::default()).unwrap(); + let stored = lay(&d).pages.len(); + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() }); + assert!(l.pages.len() > stored, "{} pages, {stored} with the stored results", l.pages.len()); + assert_eq!(shown_in(&l, 0, StoryRef::Body).first(), Some(&l.pages.len().to_string())); +} + /// The fields' text in each page's footer, joined with "/". fn footer_shown(l: &DocLayout) -> Vec { l.pages @@ -771,3 +1061,45 @@ fn table_cell_page_field_uses_the_section_number_format() { .collect(); assert_eq!(shown, "one"); } + +/// Printed or exported, a reference to a bookmark in a text box nested in text boxes shows the +/// outermost box's anchor page as deep as layout shows the boxes ([`wordcraft_doc::MAX_TEXT_BOX_DEPTH`] +/// levels); one nested deeper, which layout doesn't show, keeps its stored result. +#[test] +fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() { + use wordcraft_doc::para::{Float, ShapeKind, Wrap}; + let shape = |story: u32| InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: None, + stroke: None, + stroke_width: 0.0, + float: Float { wrap: Wrap::Inline, ..Default::default() }, + story: Some(story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + let deepest = wordcraft_doc::MAX_TEXT_BOX_DEPTH + 1; + let mut d = Document::from_text("See \nSecond"); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.page_break_before = Some(true); + // From the deepest box out: box `level` holds bookmark "Level{level}" and the box inside it. + let mut inner: Option = None; + for level in (1..=deepest).rev() { + let mut p = Paragraph::with_text("Box", Default::default()); + p.insert_object(0, InlineObject::BookmarkStart { name: format!("Level{level}") }, &Default::default()).unwrap(); + if let Some(id) = inner { + p.insert_object(p.len(), shape(id), &Default::default()).unwrap(); + } + inner = Some(d.add_part(PartKind::TextBox, vec![para_block(p)])); + } + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().insert_object(0, shape(inner.unwrap()), &Default::default()).unwrap(); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + for level in [1, wordcraft_doc::MAX_TEXT_BOX_DEPTH, deepest] { + let n = p.len(); + p.insert_object(n, pageref(&format!("PAGEREF Level{level} \\h"), "9"), &Default::default()).unwrap(); + } + let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() }); + assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]); +} diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 81b7b94d20..759b3c7ab5 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -9,7 +9,8 @@ use super::{ /// Lay out `doc` and write it as PDF. Without markup the layout is the final text: tracked /// deletions are left out, as in Word's "No Markup" view. With `comments` each page carries the -/// markup area with the comment balloons. +/// markup area with the comment balloons. Page references in the body show their bookmarks' +/// pages, as Word's export fills them in. pub fn export(doc: &Document, opts: &PdfOptions) -> Result, PdfError> { write::guard(|| { let lay = layout(doc, &mut LayoutCache::new(), &opts.layout_options()); diff --git a/crates/pdf/src/options.rs b/crates/pdf/src/options.rs index 7a0f57d8da..5f7baa803c 100644 --- a/crates/pdf/src/options.rs +++ b/crates/pdf/src/options.rs @@ -50,6 +50,10 @@ pub struct PdfOptions { /// How [`export`] shows digits (the Numeral setting; callers resolve `System`, see /// [`NumeralMode::resolve`]). [`export_layout`] keeps the layout it is given. pub numeral: NumeralMode, + /// What [`export`] shows for a page reference to a bookmark the document doesn't have, in the + /// interface language (`None`: Word's English "Error! Bookmark not defined."). [`export_layout`] + /// keeps the layout it is given. + pub bookmark_error: Option>, } /// How many characters of the watermark text the PDF draws. @@ -70,12 +74,15 @@ impl PdfOptions { } } - /// How [`crate::export`] lays a document out for these options. + /// How [`crate::export`] lays a document out for these options. Page references in the body + /// show their bookmarks' pages, as Word's export fills them in. pub fn layout_options(&self) -> wordcraft_layout::LayoutOptions { wordcraft_layout::LayoutOptions { hide_deleted: !self.include_markup, comment_balloons: self.comments, numeral: self.numeral, + output_page_refs: true, + bookmark_error: self.bookmark_error.clone(), ..Default::default() } } @@ -98,6 +105,7 @@ impl Default for PdfOptions { links: true, paper: None, numeral: NumeralMode::Arabic, + bookmark_error: None, } } } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index aab3988cc5..efa7681478 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -3156,6 +3156,27 @@ fn baseline_is_the_most_shared_y() { assert_eq!(baseline(&[(1, 0.0, -0.0), (2, 3.0, 0.0)]), Some(0.0)); } +/// The exported PDF shows a body page reference's page and Word's error for a missing bookmark, +/// as Word's export does, where the document stores "9" for both. +#[test] +fn exported_page_references_show_the_page_or_words_error() { + let field = + |instr: &str| InlineObject::Field { instr: instr.into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() }; + let mut d = Document::from_text("See \nMissing \nTarget"); + for (i, instr) in [(0, "PAGEREF Target"), (1, "PAGEREF NoSuchMark")] { + let p = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(i)).unwrap(); + let n = p.len(); + p.insert_object(n, field(instr), &CharProps::default()).unwrap(); + } + let target = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap(); + target.props.page_break_before = Some(true); + target.insert_object(0, InlineObject::BookmarkStart { name: "Target".into() }, &CharProps::default()).unwrap(); + let text = extract_text(&export(&d, &PdfOptions::default()).unwrap()); + let first = squash(&text[0]); + assert!(first.contains("See 2"), "{first}"); + assert!(first.contains("Missing Error! Bookmark not defined."), "{first}"); +} + #[test] fn the_author_is_left_out_when_personal_information_is_removed() { let mut d = Document::from_text("Private"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index ddfa5f97b1..96dba9b114 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -251,6 +251,10 @@ impl WordApp { crate::language_packs::tick(self); let lang = i18n::Lang::from_pref(&self.ui.language); i18n::set_current(lang); + // PDFs and prints show a page reference or a REF to a missing bookmark in the + // interface's language, as Word prints them in its own. + wordcraft_engine::set_bookmark_error(i18n::tr(lang, "Error! Bookmark not defined.")); + wordcraft_engine::set_reference_error(i18n::tr(lang, "Error! Reference source not found.")); crate::rtl::sync(ctx); // New documents are written in the interface's language when WordCraft can proof it // (a Polish interface: Polish spelling, grammar and hyphenation from the first word). diff --git a/docs/gaps.md b/docs/gaps.md index 1a22b57ddf..a3d2a9ec6a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -240,6 +240,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-11-01 | trivial | #19 narrowed: ODT read and written nearly whole on this branch (styles, tables, notes, comments, tracked changes including formatting, fields, indexes and marks, drawings, charts, embedded objects, forms, ruby, password protection, flat ODT), checked against LibreOffice; what's left listed; estimate 18–27 h → 10–16 h | | 2026-11-01 | trivial | #10 narrowed: text in a turned text box is drawn turned with it on screen and in PNG and PDF (upside down when flipped across, never mirrored); editing it still goes by its upright text; estimate unchanged | +| 2026-10-31 | trivial | PDFs, prints and page images show body PAGEREF fields' pages, so a table of contents prints its headings' pages, as Word does; not a ranked gap; readiness estimates unchanged | | 2026-10-29 | trivial | Print Markup balloon anchor discovery no longer repeats paragraph-prefix scans (#3614); readiness estimates unchanged | | 2026-10-28 | trivial | Print Markup text-copy comment discovery walks paragraph objects once (#3614); quotes, order, limits and readiness estimates unchanged | | 2026-11-04 | trivial | Table Sort rejects malformed or nonexistent explicit columns before mutation; valid columns, the omitted-column default and history are retained (#5531). Readiness estimates unchanged. | diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 957164306b..55c2b611b0 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -101,8 +101,8 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages | — | | Compatibility modes (Word 2003/2007/2010 layout for old files: `w:compat` options) | 🟡 | `allowSpaceOfSameStyleInTable` supported in modes 11/12/14; mode 15 retains contextual suppression. `doNotExpandShiftReturn` keeps justified lines that end in a manual line break short (#3924). `doNotSuppressIndentation` (Word 2003's indent rules; a `.doc`'s `Copts.fWW11IndentRules`): below mode 15 an unnumbered paragraph's line starts right after a floating object that ends before its indent, never in the margin, and not beside a drop cap (#5939); the numbered-paragraph half of the rule is not implemented, and files set it only once craft-libs reads it. Most other legacy compat options remain ignored | 10–20 | | Fields: STYLEREF in headers and footers (running chapter titles) | ✅ | Evaluated per page at layout time: the page's first (or with `\l` last) paragraph of the style, else the nearest before it; style name, id or heading level (a level finds the style named `heading N` whatever its id, so localized documents match, #1286); character styles; `\n \r \w \s \t \p` (`\r` treated as `\w`); body STYLEREF updated with the other fields (#775). Field results with right-to-left text (a Hebrew heading, "פרק א") are laid out with bidi reordering like ordinary text: the result is an isolate taking its first strong letter's direction (else the text's around the field), and each level run is shaped and mirrored in its own direction, so `{ PAGE }` in field-code view and `(Chapter 1)` keep their brackets in right-to-left paragraphs; this covers every field and note mark shown as text (#1670). Header paragraphs are cached on their per-page results, so typing in body text no STYLEREF shows doesn't lay the headers out again (#1286) | — | -| Fields filled in for output: SEQ, STYLEREF, REF in the body | ✅ | PDF export, print jobs and page images lay out a copy whose unlocked SEQ, STYLEREF and REF fields show their current results, as Word does when printing or exporting with Update fields before printing off (measured in Word for Windows with stale stored results); a locked SEQ keeps its result but still counts, its `\r` too, and a SEQ in a tracked deletion keeps its result and doesn't count, with markup shown or hidden (measured in Word for Windows); NUMWORDS, FILENAME, the document properties and formulas keep their stored results, as in Word; REF fields with `\p`, `\r`, `\n` or `\w` (above or below, and paragraph numbers) keep theirs until those are computed, and so does a REF to a bookmark that ends in a later paragraph (Word shows its paragraphs as paragraphs of the result); SEQ numbers are filled in before the STYLEREF and REF fields that read them, so a STYLEREF to a heading holding a SEQ field shows its new number (after F9 too); SEQ fields in text boxes are numbered where their boxes are anchored, after F9 too, and a REF to a bookmark in a text box, header, footer, footnote, endnote or comment shows that text as stored, as in Word; a REF to a bookmark the document lacks prints "Error! Reference source not found."; the document is unchanged (`cmd::references::tests::output_shows_fresh_seq_styleref_and_ref_results`, `cmd::references::tests::output_numbers_text_box_captions_where_their_boxes_are_anchored`, `cmd::references::tests::output_shows_references_to_bookmarks_outside_the_body`, `cmd::references::tests::output_shows_words_error_for_a_reference_to_a_missing_bookmark`, `cmd::references::tests::output_counts_locked_seq_fields_and_not_deleted_ones`) | — | -| Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers, PAGEREF in headers and footers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages; a PAGE field in a paragraph that runs onto a later page (a page break inside it, or a natural split) shows that page's number, the rest of the paragraph broken again for the wider result (#1352); PAGEREF in headers and footers shows its bookmark's page, filled in after pagination like their totals (#1477); in the body it keeps its result until fields are updated | — | +| Fields filled in for output: SEQ, STYLEREF, REF in the body | ✅ | PDF export, print jobs and page images lay out a copy whose unlocked SEQ, STYLEREF and REF fields show their current results, as Word does when printing or exporting with Update fields before printing off (measured in Word for Windows with stale stored results); a locked SEQ keeps its result but still counts, its `\r` too, and a SEQ in a tracked deletion keeps its result and doesn't count, with markup shown or hidden (measured in Word for Windows); NUMWORDS, FILENAME, the document properties and formulas keep their stored results, as in Word; REF fields with `\p`, `\r`, `\n` or `\w` (above or below, and paragraph numbers) keep theirs until those are computed, and so does a REF to a bookmark that ends in a later paragraph (Word shows its paragraphs as paragraphs of the result); SEQ numbers are filled in before the STYLEREF and REF fields that read them, so a STYLEREF to a heading holding a SEQ field shows its new number (after F9 too); SEQ fields in text boxes are numbered where their boxes are anchored, after F9 too, and a REF to a bookmark in a text box, header, footer, footnote, endnote or comment shows that text as stored, as in Word; a REF to a bookmark the document lacks prints "Error! Reference source not found.", which the shell can give in the interface language as Word prints it in its own (English in every language until craft-i18n has the text); the document is unchanged (`cmd::references::tests::output_shows_fresh_seq_styleref_and_ref_results`, `cmd::references::tests::output_numbers_text_box_captions_where_their_boxes_are_anchored`, `cmd::references::tests::output_shows_references_to_bookmarks_outside_the_body`, `cmd::references::tests::output_shows_words_error_for_a_reference_to_a_missing_bookmark`, `cmd::references::tests::output_counts_locked_seq_fields_and_not_deleted_ones`, `cmd::references::tests::a_missing_references_error_is_in_the_interface_language`) | — | +| Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers, PAGEREF in headers and footers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages; a PAGE field in a paragraph that runs onto a later page (a page break inside it, or a natural split) shows that page's number, the rest of the paragraph broken again for the wider result (#1352); PAGEREF in headers and footers shows its bookmark's page, filled in after pagination like their totals (#1477); in the body it keeps its result until fields are updated on screen, and shows its bookmark's page (from the section's restart) in PDFs, prints and page images, as Word fills it in when it prints or exports, so a table of contents prints the pages its headings are on; so do references in text boxes, footnotes and endnotes, and a bookmark in a note is on the page that shows it; a reference to a bookmark the document doesn't have prints Word's "Error! Bookmark not defined." in the interface language, while one to a bookmark in a header or comment keeps its result; a locked PAGEREF keeps its result everywhere | — | | Fields: `\* DollarText`, `\* Hex` and `\* ArabicDash` | 🟡 | `\* DollarText` writes lowercase cardinal text, "and", and the first two decimals over 100 (`{ = 9.20 + 5.35 \* DollarText }` shows "fourteen and 55/100"), `\* Hex` uppercase hexadecimal digits (458 shows "1CA"), and `\* ArabicDash` the number between hyphens (`{ PAGE \* ArabicDash }` shows "- 31 -"), in table formulas and in the page-number, SEQ, PAGEREF, NUMWORDS, NUMCHARS and REVNUM fields; a capitalization switch applies after them (#4226). A result past 999,999 in cardinal or ordinal text, or past 999,999.99 in dollar text, keeps its digits, and so does a negative result or a fractional Hex or ArabicDash result. `layout::fields::tests::dollar_text_hex_and_arabic_dash_switches`, `engine::cmd::table_formula::tests::dollar_text_and_hex_switches_write_the_result`, `engine::tests::table_formula_results_take_dollar_text_and_hex`; not compared with Word | — | | Page-by-page comparison harness against Word | ❌ | Run Word locally on our own synthetic documents, export PDF, compare line breaks; Word output stays under `plan/` (never committed) | 8–12 | @@ -311,6 +311,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-10-29 | trivial | A list item deleted whole under Track Changes shows its number in the deletion's colour and with its mark (struck through by default) with markup, and not at all without (#4828) | | 2026-11-04 | trivial | Headers, footers and note separators of the second and later sections are measured with their own section's document grid and SECTION/SECTIONPAGES values, not the previous section's; a regression from the #4501 refactor (#4683). `layout::tests::pages::a_sections_header_is_measured_without_the_previous_sections_grid` | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | +| 2026-11-04 | trivial | PAGEREF in text boxes and notes shows pages in output; PAGEREF's and REF's missing-bookmark errors in the interface language; readiness estimates unchanged | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | | 2026-11-04 | trivial | Header table measurements and fitted text-box heights use the page section’s PAGE format; cache reuse follows the field context | | 2026-11-03 | trivial | Body PAGE fields in tables use the active section number format; reflow views measure headers and footers with it before body placement | @@ -331,6 +332,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-04 | trivial | Output counts a locked SEQ and not one in a tracked deletion, as Word does; readiness estimates unchanged | | 2026-11-01 | trivial | SEQ fields in text boxes are numbered where their boxes are anchored, in output and after F9, and a REF finds a bookmark in a text box | | 2026-11-01 | trivial | SEQ, STYLEREF and REF fields show fresh results in output; readiness estimates unchanged | +| 2026-10-31 | trivial | Body PAGEREF fields show their bookmarks' pages in PDFs, prints and page images, as Word fills them in when it prints or exports (measured in Word for Microsoft 365: references stored as 9 print and export as 3, or 2 after a section numbered from 1); a locked PAGEREF keeps its result, in the body and in headers and footers; one to a bookmark in a text box shows the page of the box's anchor; one to a bookmark the document lacks prints "Error! Bookmark not defined.", as in Word. `layout::tests::pages::page_references_in_the_body_show_their_bookmarks_page_in_output`, `layout::tests::pages::a_page_reference_to_a_missing_bookmark_shows_words_error_in_output`, `layout::tests::pages::a_page_reference_to_a_bookmark_in_a_text_box_shows_its_anchors_page_in_output`, `pdf::tests::exported_page_references_show_the_page_or_words_error`, `engine::tests::output_shows_toc_page_numbers_where_the_headings_are` | | 2026-10-29 | trivial | Print Markup balloon anchor discovery walks paragraph objects once (#3614); readiness estimates unchanged | | 2026-11-03 | trivial | A decimal tab scans the text after it once, not once per cluster. Separate from the #3412 word-measurement fix | | 2026-10-30 | trivial | Layout work bounds for hostile documents (#3867): header-row repeats budgeted per layout and counting canvas members; picture-outline decode budget charged for cached outlines too, so cold and warm layouts wrap alike; linked-box chains keep exact widths up to a work cap, not 16 widths; `gridAfter` bounded | From 73b999ec8977442638216677f31fa6e25ff670b0 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:30:16 +0100 Subject: [PATCH 98/99] Say in the placeholder when a picture is too large to decode When a picture is too large to decode, the placeholder now says so, instead of a plain broken box. Originally authored by @Silvertree2010 in #5638. --- crates/render/src/lib.rs | 93 ++++++++++++++++++++++++++++++++++++-- crates/render/src/media.rs | 29 ++++++++---- crates/render/src/tests.rs | 79 ++++++++++++++++++++++++++++++++ 3 files changed, 187 insertions(+), 14 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0fecbb23b2..63e802e1a5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -880,11 +880,18 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) { draw_vector(ctx, &v, &r, crop, *alpha, view); return; } - let Some(pm) = pixmap_for(doc, media, *fx) else { - ctx.set_transform(view); - ctx.set_paint(color(fr.opts.ink(Rgb(0xD0, 0xD0, 0xD0)), 1.0)); - ctx.fill_rect(&r); - return; + let pm = match pixmap_for(doc, media, *fx) { + Ok(pm) => pm, + Err(refusal) => { + ctx.set_transform(view); + ctx.set_paint(color(fr.opts.ink(Rgb(0xD0, 0xD0, 0xD0)), 1.0)); + ctx.fill_rect(&r); + // Say why when the picture is fine but too large to decode (#5637). + if let wordcraft_geom::picture::Refusal::TooLarge { width, height } = refusal { + draw_box_label(ctx, fr, view, &r, &too_large_label(width, height)); + } + return; + } }; let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64); let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop); @@ -921,6 +928,82 @@ fn path_extent_ok(view: Affine, path: &kurbo::BezPath) -> bool { path.is_finite() && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_PATH_PIXELS) } +/// A label's lines, shaped once: each glyph with its face, and each line's width at 1 pt. +struct BoxLabel { + lines: Vec<(Vec<(wordcraft_fonts::FaceRef, u32)>, f64)>, + widest: f64, +} + +/// Shapes `lines` in the UI face (with fallbacks). +fn shape_box_label(lines: &[&str]) -> BoxLabel { + let face = wordcraft_fonts::word::resolve("Source Sans 3", false, false).face; + let db = FontDb::global(); + let lines: Vec<_> = lines + .iter() + .map(|line| { + let glyphs: Vec<_> = line + .chars() + .map(|ch| { + let f = if face.glyph_for(ch) == 0 { + db.fallback_for(ch, face.id()).map_or(face, |f| wordcraft_fonts::FaceRef::of(&f)) + } else { + face + }; + (f, f.glyph_for(ch)) + }) + .collect(); + let width = glyphs.iter().map(|(f, gid)| f.advance(*gid) / f.upem.max(1.0)).sum(); + (glyphs, width) + }) + .collect(); + let widest = lines.iter().map(|(_, w)| *w).fold(0.0, f64::max); + BoxLabel { lines, widest } +} + +/// The message in the box of a picture too large to decode, shaped once per picture size (pages +/// are redrawn often). +fn too_large_label(width: u32, height: u32) -> Arc { + static C: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + let cache = C.get_or_init(|| Mutex::new(HashMap::new())); + if let Some(l) = lock(cache).get(&(width, height)) { + return l.clone(); + } + let size = format!("{width} × {height} pixels"); + let label = Arc::new(shape_box_label(&["Picture too large to display", &size, "Resize it to show it"])); + let mut c = lock(cache); + // A handful of refused pictures at most; start over rather than grow without bound. + if c.len() >= 64 { + c.clear(); + } + c.insert((width, height), label.clone()); + label +} + +/// Writes `label` centred in the box `r` (drawn under `view`), at most 10 pt and shrunk to fit; +/// nothing when even 3 pt text wouldn't fit. +fn draw_box_label(ctx: &mut RenderContext, fr: &Frame, view: Affine, r: &kurbo::Rect, label: &BoxLabel) { + let db = FontDb::global(); + let pad = 4.0; + let n = label.lines.len() as f64; + let size = 10.0f64.min((r.width() - 2.0 * pad) / label.widest.max(1e-9)).min((r.height() - 2.0 * pad) / (1.2 * n).max(1e-9)); + if !(size.is_finite() && size >= 3.0) { + return; + } + ctx.set_paint(color(fr.opts.ink(Rgb(0x50, 0x50, 0x50)), 1.0)); + let top = r.center().y - 1.2 * size * n / 2.0; + for (i, (glyphs, w)) in label.lines.iter().enumerate() { + let baseline = top + 1.2 * size * (i as f64 + 0.8); + let mut x = r.center().x - w * size / 2.0; + for (f, gid) in glyphs { + let k = size / f.upem.max(1.0); + ctx.set_transform(view * Affine::translate((x, baseline)) * Affine::scale(k)); + ctx.fill_path(&db.outline(f, *gid)); + x += f.advance(*gid) * k; + } + } + ctx.set_transform(view); +} + fn draw_path(ctx: &mut RenderContext, fr: &Frame, it: &Draw) { let Draw::Path { segs, fill, stroke, stroke_width, dash, cap } = it else { return }; let path = wordcraft_layout::display::seg_path(segs); diff --git a/crates/render/src/media.rs b/crates/render/src/media.rs index 13e9878326..3fa69c40a7 100644 --- a/crates/render/src/media.rs +++ b/crates/render/src/media.rs @@ -1,3 +1,5 @@ +use wordcraft_geom::picture::Refusal; + use super::{Affine, Arc, Document, FontDb, HashMap, Item, Mutex, Page, Picture, Pixmap, PlacedItem, RenderContext, Seg, Shape, Weak, kurbo, peniko}; use craft_metafile::{ClipPath, Tile}; use std::collections::HashSet; @@ -51,8 +53,11 @@ pub(crate) fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } -fn images() -> &'static Mutex>>> { - static C: std::sync::OnceLock>>>> = std::sync::OnceLock::new(); +/// A decoded picture, or why it isn't drawn. +pub(crate) type Decoded = Result, Refusal>; + +fn images() -> &'static Mutex> { + static C: std::sync::OnceLock>> = std::sync::OnceLock::new(); C.get_or_init(|| Mutex::new(MediaCache { map: HashMap::new(), bytes: 0 })) } @@ -75,11 +80,17 @@ pub fn decode_pixmap(bytes: &[u8]) -> Option { /// [`decode_pixmap`] with a picture's brightness and contrast applied (#1711, #1766), under the /// same decode limits. pub fn decode_pixmap_fx(bytes: &[u8], fx: wordcraft_doc::picfx::PicFx) -> Option { + decode_pixmap_checked(bytes, fx).ok() +} + +/// [`decode_pixmap_fx`], with why a picture isn't decoded (#5637). +fn decode_pixmap_checked(bytes: &[u8], fx: wordcraft_doc::picfx::PicFx) -> Result { // The shared probe also charges what the decoder holds beside its output (#3644). - if !wordcraft_geom::picture::probe(bytes).is_ok_and(|p| p.fits(wordcraft_geom::MAX_DECODED_BYTES)) { - return None; + let probe = wordcraft_geom::picture::probe(bytes)?; + if !probe.fits(wordcraft_geom::MAX_DECODED_BYTES) { + return Err(Refusal::TooLarge { width: probe.width, height: probe.height }); } - decode_pixmap_within(bytes, fx, wordcraft_geom::MAX_DECODED_BYTES) + decode_pixmap_within(bytes, fx, wordcraft_geom::MAX_DECODED_BYTES).ok_or_else(|| Refusal::Broken("it could not be decoded".into())) } /// [`decode_pixmap_fx`] with an explicit RGBA byte budget (a small one in tests). @@ -534,7 +545,7 @@ pub(crate) fn draw_page_picture(ctx: &mut RenderContext, doc: &Document, page: & let Some(pic) = &doc.settings.page_picture else { return }; let Some(bytes) = doc.media.get(&pic.media) else { return }; let Some((nw, nh)) = wordcraft_geom::picture::background_size(bytes).map(|(w, h)| (f64::from(w), f64::from(h))) else { return }; - let Some(pm) = pixmap_for(doc, &pic.media, wordcraft_doc::picfx::PicFx::default()) else { return }; + let Ok(pm) = pixmap_for(doc, &pic.media, wordcraft_doc::picfx::PicFx::default()) else { return }; let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64); let (w, h) = (page.w as f64, (page.h as f64).min(1e6)); if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { @@ -568,8 +579,8 @@ pub(crate) fn draw_page_picture(ctx: &mut RenderContext, doc: &Document, page: & ctx.reset_paint_transform(); } -pub(crate) fn pixmap_for(doc: &Document, key: &str, fx: wordcraft_doc::picfx::PicFx) -> Option> { - let bytes = doc.media.get(key)?; +pub(crate) fn pixmap_for(doc: &Document, key: &str, fx: wordcraft_doc::picfx::PicFx) -> Decoded { + let Some(bytes) = doc.media.get(key) else { return Err(Refusal::NotAPicture) }; // Corrected pixels are cached apart from the picture's own (the same picture can be shown // both ways). let fx = fx.clamped(); @@ -578,7 +589,7 @@ pub(crate) fn pixmap_for(doc: &Document, key: &str, fx: wordcraft_doc::picfx::Pi if let Some(v) = lock(images()).get(&cache_key, bytes) { return v; } - let pm = decode_pixmap_fx(bytes, fx).map(|p| Arc::new(cacheable(p))); + let pm = decode_pixmap_checked(bytes, fx).map(|p| Arc::new(cacheable(p))); let size = pm.as_ref().map_or(0, |p| p.width() as usize * p.height() as usize * 4); lock(images()).insert(&cache_key, bytes, pm.clone(), size); pm diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index de00204a30..23652edb79 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -2100,3 +2100,82 @@ fn geometry_bytes_counts_dash_arrays_and_text_records() { let empty = crate::media::geometry_bytes(&pic(vec![])); assert!(bare - empty >= std::mem::size_of::(), "the boxed Text struct is charged: {} bytes", bare - empty); } + +/// The placeholder for a picture `bytes` shown 200 × 150 pt, one row per pixel row: `Some(true)` +/// for dark (text) pixels, `Some(false)` for the grey fill, `None` for anything else. +fn placeholder_pixels(bytes: Vec) -> Vec>> { + let mut d = Document::new(); + let media = d.add_media(bytes, "png"); + let mut p = wordcraft_doc::Paragraph::new(); + let obj = wordcraft_doc::para::InlineObject::Image { + media, + w: 200.0, + h: 150.0, + alt: String::new(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }; + p.insert_object(0, obj, &Default::default()).unwrap(); + d.body = vec![wordcraft_doc::para_block(p)]; + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let opts = RenderOptions::default(); + let rect = page_display(&d, &l.pages[0], &opts.display) + .iter() + .find_map(|i| match i { + Draw::Image { rect, .. } => Some(*rect), + _ => None, + }) + .expect("a picture on the page"); + let img = render_page(&d, &l.pages[0], 1.0, &opts); + ((rect.y.ceil() as u32)..((rect.y + rect.h).floor() as u32)) + .map(|y| { + ((rect.x.ceil() as u32)..((rect.x + rect.w).floor() as u32)) + .map(|x| { + let px = img.pixel(x, y); + if px[..3] == [0xD0; 3] { + Some(false) + } else if px[..3].iter().all(|c| *c < 0x90) { + Some(true) + } else { + None + } + }) + .collect() + }) + .collect() +} + +/// #5637: a picture too large to decode is not just a grey box: the box says why, in three +/// upright lines centred in it. +#[test] +fn a_picture_too_large_to_decode_says_so_in_its_box() { + let huge = ihdr_only_png(8333, 8333); + assert!(decode_pixmap(&huge).is_none(), "the decode budget refuses it"); + let grid = placeholder_pixels(huge); + let (h, w) = (grid.len() as f64, grid[0].len() as f64); + assert!(grid.iter().flatten().any(|p| *p == Some(false)), "the grey placeholder is drawn"); + let inked: Vec = grid.iter().map(|row| row.contains(&Some(true))).collect(); + let rows: Vec = (0..inked.len()).filter(|y| inked[*y]).collect(); + assert!(!rows.is_empty(), "the placeholder carries a message, not a plain grey box"); + // Three lines of text: three bands of inked rows with blank rows between them. + let bands = (0..inked.len()).filter(|y| inked[*y] && (*y == 0 || !inked[*y - 1])).count(); + assert_eq!(bands, 3, "three lines of text, inked rows {rows:?}"); + // Centred both ways; glyphs flipped about their baselines would sit several pixels low. + let (top, bottom) = (rows[0] as f64, *rows.last().unwrap() as f64); + assert!(((top + bottom) / 2.0 - h / 2.0).abs() < 3.0, "centred vertically: rows {top}..{bottom} of {h}"); + let cols: Vec = (0..grid[0].len()).filter(|x| grid.iter().any(|row| row[*x] == Some(true))).collect(); + let (left, right) = (cols[0] as f64, *cols.last().unwrap() as f64); + assert!(((left + right) / 2.0 - w / 2.0).abs() < 3.0, "centred horizontally: columns {left}..{right} of {w}"); + // The first line starts with the stem of an upright "P": its leftmost inked column runs at + // least 5 px down from the line's top. + let first = rows[0]..rows.iter().zip(&rows[1..]).find(|(a, b)| **b != **a + 1).map_or(rows.len(), |(a, _)| *a + 1); + let lead = (0..grid[0].len()).find(|x| grid[first.clone()].iter().any(|row| row[*x] == Some(true))).unwrap(); + let stem = grid[first.clone()].iter().filter(|row| row[lead] == Some(true) || row.get(lead + 1) == Some(&Some(true))).count(); + assert!(stem >= 5, "the first line starts with an upright P stem ({stem} px)"); + // A damaged picture still gets its plain grey placeholder. + let grid = placeholder_pixels(b"\x89PNG\r\n\x1a\njunk".to_vec()); + assert!(grid.iter().flatten().any(|p| *p == Some(false)), "a damaged picture keeps its grey placeholder"); + assert!(!grid.iter().flatten().any(|p| *p == Some(true)), "with no size message"); +} From 7831216b2cea45c636583c3dd29214ffb4979d28 Mon Sep 17 00:00:00 2001 From: naxvog Date: Wed, 18 Nov 2026 10:33:13 +0100 Subject: [PATCH 99/99] Borders: lines meet in closed corners, as in Word Border lines meet in closed corners, as in Word, including after the side-border geometry from #5036. Originally authored by @naxvog in #1757. --- ROADMAP.md | 4 +- crates/layout/src/boxes.rs | 63 ++++++++++++++++++++---------- crates/layout/src/display.rs | 1 + crates/layout/src/display/lines.rs | 44 ++++++++++++++++----- crates/layout/src/display/page.rs | 23 +++++------ crates/layout/src/flow.rs | 12 ++++-- crates/layout/src/page.rs | 8 +--- crates/layout/src/table.rs | 2 +- crates/layout/src/tests.rs | 46 +++++++++++++++++++++- 9 files changed, 148 insertions(+), 55 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 00a89f0299..af21a56cc6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,7 +8,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** trivial (progress log: file formats, codecs and protocols from craft-libs, #778); previously trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** trivial (progress log: border boxes close their corners; previously trivial: progress log: file formats, codecs and protocols from craft-libs, #778); previously trivial (progress log: Get the Missing Fonts); previously trivial (progress log: a deleted list item's number is drawn as deleted text under Track Changes (#4828)); previously trivial (progress log: Save As and Export offer Browse in WordCraft… on Linux/BSD, #3535); previously trivial (progress log: Review › Language can set the whole document's proofing language, #3518); previously trivial (progress log: Auto interface size capped to the screen, #4030); previously trivial (progress log: DOCX section line numbering stays off without a positive `w:countBy`, #6209); previously trivial (progress log: Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf, #6180); previously trivial (Vertical scrollbar track: clicking above the elevator moves one screen up and clicking below it moves one screen down, as in Word (#5853)); previously trivial (progress log: #4501 refactor regressions restored: per-section header grid, ODT default font, link tooltip, #4683); previously trivial (progress log: the window moves by its title bar behind a modal dialog, #5124); previously trivial (progress log: `convert --strict` and `render --strict` refuse a silently incomplete PDF or PNG (#6005, #6008)); ; trivial (progress log: ODT columns stating only their shares); previously trivial (progress log: ODT font size for every script); previously trivial (progress log: ODT text turning off what its style turns on); previously trivial (progress log: edited ODT paragraphs keep custom styles with an outline level); previously trivial (progress log: ODT pictures keep the size their file gives); previously trivial (progress log: ODT frames keep the page they are anchored to); previously trivial (pointer zoom stretches page rasters until it stops); previously trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a turned inline picture whose file keeps no room for the turn keeps its line to its frame); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured); previously trivial (progress log: ODT documents keep their language); previously trivial (progress log: ODT table and row backgrounds) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. @@ -690,6 +690,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-14 | Hebrew and Arabic in exported PDFs copy and search as whole words (#1383): right-to-left glyphs are written left to right as they appear, the order Chrome and Edge (PDFium) and poppler read text back from (checked by hand), instead of in reading order, which they reversed (`שלום` came back as `םולש`, Arabic in pieces). Lam-alef stays whole and vowel marks follow their letters, though Chrome and poppler can still break a fully vowelled word with spaces. The page looks the same. Readers that take glyphs strictly in file order get only plain Hebrew runs right, through `/ReversedChars`; screen readers are unverified | | 2026-10-14 | HTML import (#1381): header cells (``) are bold unless their own CSS says otherwise, and `text-align` on a cell, its row, row group or table aligns the cell's paragraphs (a paragraph's own alignment wins), so `wordcraft-cli convert page.html out.docx` writes the bold header and `w:jc` right-aligned cells. HTML, Markdown and plain text, which give no page size, open on the region's paper (A4 in Italy, Letter in the US) like a new blank document, in the app and in `wordcraft-cli`; documents with their own page size keep it | | 2026-10-14 | Custom page sizes (#1433): Layout › Size ends with More Paper Sizes…, which opens Page Setup's new Paper group — a Paper size list (the named sizes, or Custom size) and Width and Height in the measurement unit; OK sets the size only when it changed, and a wider-than-tall size comes out landscape. `layout.size` now clamps each side to Word's 0.1"–22" and refuses a page the margins don't fit (the margins rule: 36 pt of text room), and Page Setup checks the size and margins together before applying either | +| 2026-10-19 | Border boxes close their corners, as in Word: paragraph, page and character border boxes had a notch at each corner now that lines end flat; top and bottom lines now run on over the side lines, and lines without a neighbour end half their width past the edge | | 2026-10-14 | Bold text in Arial Black and other Black or Heavy fonts looks as in Word: older copies of these fonts (Arial Black in the core fonts) call themselves regular weight, so bold was drawn with an extra synthetic bold; a family named Black/Heavy now counts as that heavy | | 2026-10-14 | German text hyphenates by German rules: runs in German (`de`, `de-DE`, `de-AT`, `de-CH`) use hyph-utf8's German patterns for the reformed spelling (MIT), so automatic hyphenation gives `un-ter-lie-gen-de` and `öf-fent-lich-recht-li-cher` instead of English-pattern breaks like `unterlieg-ende` and `rechtli-cher`; Swiss `ss` splits like any double consonant (`Stras-se`). German still has no spelling or grammar marks (#1564) | | 2026-10-13 | Highlighted text reads on a dark page (View › Switch Modes, #1252): highlights and character shading are dimmed, keeping their hue (yellow turns a dim olive, as in Word), and the text on them is drawn light (coloured text below 4.5:1 is drawn white, and underlines and strikethroughs follow the same rule), instead of white text on bright yellow; light page, print and exports unchanged | @@ -933,6 +934,7 @@ MATH glyphs that reference the same construction now share its immutable variant | Date | Change | Summary | |---|---|---| +| 2026-11-18 | trivial | Progress log: border boxes close their corners | | 2026-10-30 | trivial | Progress log: under Track Changes a list item deleted whole shows its number as deleted text, in the deletion's colour and mark (#4828); readiness unchanged | | 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) | | 2026-11-04 | trivial | Progress log: #4501 refactor regressions restored (#4683) | diff --git a/crates/layout/src/boxes.rs b/crates/layout/src/boxes.rs index 45387a9de2..a7b4e92f1a 100644 --- a/crates/layout/src/boxes.rs +++ b/crates/layout/src/boxes.rs @@ -7,7 +7,7 @@ use super::placed::Placed; use super::table_flow::below; use super::{ Anchor, Arc, Block, Blocks, Border, Document, Float, FloatAlign, HashMap, ParaLayout, Paragraph, Path, Rect, StoryRef, TableFloat, TextDirection, - Wrap, WrapText, para, table, + Wrap, WrapText, display, para, table, }; /// Cell identity is independent of optional table-style formatting. @@ -325,6 +325,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout { if below { edges.bottom = 0.0; } + edges.joined = [above, below]; let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0)) + edges.top; if above { edges.up = (y + lead - prev_end).max(0.0); @@ -638,19 +639,26 @@ fn border_room(b: Option) -> f32 { /// How a piece of a paragraph meets the paragraphs around it: the room taken by its top and /// bottom borders (0: none drawn there — the paragraph goes on from or into one of its border /// group, or it is split there) and how far its shading and side borders reach up to join the -/// paragraph above in its group. +/// paragraph above in its group, and whether it goes on from the paragraph above and into the one +/// below in that group (its side lines don't run on past those ends). #[derive(Clone, Copy, Default)] pub(crate) struct Edges { pub(crate) top: f32, pub(crate) bottom: f32, pub(crate) up: f32, + pub(crate) joined: [bool; 2], } impl Edges { /// A paragraph on its own: its top and bottom borders at its ends. pub(crate) fn own(pl: &ParaLayout, l0: usize, l1: usize) -> Edges { let b = pl.rp.borders.unwrap_or_default(); - Edges { top: if l0 == 0 { border_room(b.top) } else { 0.0 }, bottom: if l1 >= pl.lines.len() { border_room(b.bottom) } else { 0.0 }, up: 0.0 } + Edges { + top: if l0 == 0 { border_room(b.top) } else { 0.0 }, + bottom: if l1 >= pl.lines.len() { border_room(b.bottom) } else { 0.0 }, + up: 0.0, + joined: [false; 2], + } } } @@ -685,23 +693,38 @@ pub(crate) fn push_para( } items.push(Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal }); if let Some(b) = &pl.rp.borders { - // All four lines lie beyond their distance from the text; top and bottom reach the corners. - if let Some(t) = b.top.filter(|t| e.top > 0.0 && t.is_visible()) { - let ty = y - t.space - t.width / 2.0; - items.push(Placed::Rule { x0: lx, y0: ty, x1: rx, y1: ty, border: t }); - } - if let Some(t) = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible()) { - let by = y + h + t.space + t.width / 2.0; - items.push(Placed::Rule { x0: lx, y0: by, x1: rx, y1: by, border: t }); - } - if let Some(t) = b.left.filter(Border::is_visible) { - let bx = lx + t.width / 2.0; - items.push(Placed::Rule { x0: bx, y0: top, x1: bx, y1: bottom, border: t }); - } - if let Some(t) = b.right.filter(Border::is_visible) { - let bx = rx - t.width / 2.0; - items.push(Placed::Rule { x0: bx, y0: top, x1: bx, y1: bottom, border: t }); - } + // All four lines lie beyond their distance from the text (`lx`, `rx`: the side lines' + // outer edges); `box_rules` runs the top and bottom over the side lines to those edges. + let half = |o: Option| o.filter(Border::is_visible).map_or(0.0, |t| t.width / 2.0); + let (cl, cr) = (lx + half(b.left), rx - half(b.right)); + let tb = b.top.filter(|t| e.top > 0.0 && t.is_visible()); + let bb = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible()); + let ty = tb.map_or(top, |t| y - t.space - t.width / 2.0); + let by = bb.map_or(bottom, |t| y + h + t.space + t.width / 2.0); + box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], e.joined); } y + h } + +/// The visible lines of a border box with corners `(x0, y0)` and `(x1, y1)` (`[top, bottom, left, +/// right]`), ending square as Word draws them: a top or bottom line runs on over half the side +/// line it meets, or half its own width where there is none, so single-line boxes close at the +/// corners; a side line runs on to the outer edge of the top or bottom line it meets, or by half +/// its own width where there is none, unless the box goes on there (`joined`: at the top, at the +/// bottom). +pub(crate) fn box_rules(items: &mut Vec, (x0, y0, x1, y1): (f32, f32, f32, f32), sides: [Option; 4], joined: [bool; 2]) { + let [top, bottom, left, right] = sides.map(|b| b.filter(Border::is_visible)); + let half = |t: &Border| display::rule_width(t) / 2.0; + for (t, y) in [(top, y0), (bottom, y1)] { + if let Some(t) = t { + let over = |side: Option| half(&side.unwrap_or(t)); + items.push(Placed::Rule { x0: x0 - over(left), y0: y, x1: x1 + over(right), y1: y, border: t }); + } + } + for (t, x) in [(left, x0), (right, x1)] { + if let Some(t) = t { + let end = |o: Option, joined: bool| if joined { 0.0 } else { half(&o.unwrap_or(t)) }; + items.push(Placed::Rule { x0: x, y0: y0 - end(top, joined[0]), x1: x, y1: y1 + end(bottom, joined[1]), border: t }); + } + } +} diff --git a/crates/layout/src/display.rs b/crates/layout/src/display.rs index 5622c07830..752888bf03 100644 --- a/crates/layout/src/display.rs +++ b/crates/layout/src/display.rs @@ -29,6 +29,7 @@ pub use lines::{mark_text_width, section_break_label}; pub(crate) use objects::inline_rect; pub use objects::seg_path; pub use options::{BalloonMode, ChangeBar, CommentDisplay, DeleteMark, DisplayOptions, FormattingMarks, InsertMark, MarkupOptions}; +pub(crate) use page::rule_width; pub use page::{CHANGE_BAR, ItemDisplay, MOVE_COLOR, object_display, page_display, page_layers, revision_color}; pub use paint::{Paint, Stroke, paint_for}; diff --git a/crates/layout/src/display/lines.rs b/crates/layout/src/display/lines.rs index 22ccbf7dfe..c1d61228e6 100644 --- a/crates/layout/src/display/lines.rs +++ b/crates/layout/src/display/lines.rs @@ -326,16 +326,8 @@ fn draw_glyph_runs(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { let uy = base - st.shift + st.size * 0.12; let ucolor = rc.underline_color.unwrap_or(color); if underline == Underline::Words { - for kk in run_start..end_k { - let Some(c) = pl.clusters.get(kk) else { continue }; - if c.kind != ClKind::Text { - continue; - } - let a = x + line.cl_left(kk).unwrap_or(0.0); - let b = x + line.cl_right(kk).unwrap_or(a - x); - if a < x0 - 0.01 || b > x1 + 0.01 { - continue; // drawn with its own span - } + let words = word_spans(pl, line, (run_start, end_k), x, (x0, x1)); + for (a, b) in words { out.push(Draw::Line { x0: a, y0: uy, x1: b, y1: uy, width: thick, color: ucolor, stroke: Stroke::Solid, alpha, text_bg }); } } else { @@ -403,6 +395,38 @@ fn emphasis_mark(mark: wordcraft_doc::props::EmphasisMark, cx: f32, base: f32, s } } +/// The words among clusters `k0..k1` that lie inside `(x0, x1)`, as their left and right edges: +/// a Words underline draws one line per word, since flat-ended lines per letter would show seams +/// where they meet. +fn word_spans(pl: &ParaLayout, line: &crate::para::Line, (k0, k1): (usize, usize), x: f32, (x0, x1): (f32, f32)) -> Vec<(f32, f32)> { + let mut words: Vec<(f32, f32)> = Vec::new(); + // A space ends a word even when condensed spacing leaves it no width. + let mut apart = true; + for k in k0..k1 { + let Some(c) = pl.clusters.get(k) else { continue }; + // A bookmark or comment anchor inside a word takes no room and doesn't part it. + if c.kind == ClKind::Marker { + continue; + } + if c.kind != ClKind::Text { + apart = true; + continue; + } + let a = x + line.cl_left(k).unwrap_or(0.0); + let b = x + line.cl_right(k).unwrap_or(a - x); + if a < x0 - 0.01 || b > x1 + 0.01 { + apart = true; + continue; // drawn with its own span + } + match words.last_mut() { + Some(w) if !apart && a <= w.1 + 0.01 && b >= w.0 - 0.01 => *w = (w.0.min(a), w.1.max(b)), + _ => words.push((a, b)), + } + apart = false; + } + words +} + fn comment_backgrounds(ctx: &LineContext<'_, '_, '_>, out: &mut Vec) { let Some(para) = ctx.para.filter(|_| ctx.opts.markup && ctx.opts.revisions.comments) else { return }; let mut open: Option = None; diff --git a/crates/layout/src/display/page.rs b/crates/layout/src/display/page.rs index e69f9ec453..8b81a4637b 100644 --- a/crates/layout/src/display/page.rs +++ b/crates/layout/src/display/page.rs @@ -422,27 +422,24 @@ fn border_stroke(s: BorderStyle) -> Stroke { } } +/// The width a border line is drawn at. +pub(crate) fn rule_width(b: &Border) -> f32 { + if b.style == BorderStyle::Thick { b.width.max(1.5) } else { b.width.max(0.25) } +} + /// A border line from `(x0, y0)` to `(x1, y1)` (paragraph rules and character borders). fn rule(x0: f32, y0: f32, x1: f32, y1: f32, b: &Border, alpha: f32) -> Draw { - Draw::Line { - x0, - y0, - x1, - y1, - width: if b.style == BorderStyle::Thick { b.width.max(1.5) } else { b.width.max(0.25) }, - color: b.color.unwrap_or(Rgb::BLACK), - stroke: border_stroke(b.style), - alpha, - text_bg: None, - } + Draw::Line { x0, y0, x1, y1, width: rule_width(b), color: b.color.unwrap_or(Rgb::BLACK), stroke: border_stroke(b.style), alpha, text_bg: None } } /// Closed box around one line segment of a character-border group, widened by `space`. // Note: border drawn outside text advance, reserve width in line breaking if overlap shows. pub(super) fn char_box(b: &Border, x0: f32, x1: f32, top: f32, bottom: f32, alpha: f32, out: &mut Vec) { let (l, r) = (x0 - b.space, x1 + b.space); - out.push(rule(l, top, r, top, b, alpha)); - out.push(rule(l, bottom, r, bottom, b, alpha)); + // The top and bottom lines run on over half the side lines, closing the corners. + let half = rule_width(b) / 2.0; + out.push(rule(l - half, top, r + half, top, b, alpha)); + out.push(rule(l - half, bottom, r + half, bottom, b, alpha)); out.push(rule(l, top, l, bottom, b, alpha)); out.push(rule(r, top, r, bottom, b, alpha)); } diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index f47cb16151..e21847d2df 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -116,8 +116,9 @@ fn with_page_map(ctx: &mut Ctx, map: &mut Vec<(usize, u32)>, f: impl FnOnce(& /// drawn by its first and last paragraph. #[derive(Clone, Copy)] struct Rooms { - /// Joined to the paragraph above. + /// Joined to the paragraph above, and to the one below. above: bool, + below: bool, top: f32, bottom: f32, } @@ -127,7 +128,7 @@ impl Rooms { let above = joined(ctx.doc, &ctx.doc.body, block, block.checked_sub(1), None); let below = joined(ctx.doc, &ctx.doc.body, block, Some(block + 1), None); let own = Edges::own(pl, 0, pl.lines.len()); - Rooms { above, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } } + Rooms { above, below, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } } } } @@ -528,7 +529,12 @@ impl<'a> Flow<'a> { pb.bottom = pb.body_floor().max(placed_bottom).min(pb.orig_bottom); } let mut items = Vec::new(); - let mut edges = Edges { top: if l0 == 0 { rooms.top } else { 0.0 }, bottom: if l1 >= n { rooms.bottom } else { 0.0 }, up: 0.0 }; + let mut edges = Edges { + top: if l0 == 0 { rooms.top } else { 0.0 }, + bottom: if l1 >= n { rooms.bottom } else { 0.0 }, + up: 0.0, + joined: [l0 == 0 && rooms.above, l1 >= n && rooms.below], + }; if l0 == 0 && rooms.above && let Some((page, col, end)) = pb.para_end diff --git a/crates/layout/src/page.rs b/crates/layout/src/page.rs index 14c611f2da..130a08bf07 100644 --- a/crates/layout/src/page.rs +++ b/crates/layout/src/page.rs @@ -1,4 +1,4 @@ -use super::boxes::{BoxInput, layout_box}; +use super::boxes::{BoxInput, box_rules, layout_box}; use super::ctx::{Ctx, with_pin}; use super::floats::{EarlyFloats, WrapArea}; use super::notes::{NOTE_SEP, NOTE_SEP_W, NoteBox, NoteSeps, v_span}; @@ -112,11 +112,7 @@ pub(crate) fn page_border_rules(s: &SectionProps) -> Vec { if let Some(b) = &s.page_borders { let sp = |e: &Option| e.map(|x| x.space).unwrap_or(24.0); let (x0, x1, y0, y1) = (sp(&b.left), s.page_w - sp(&b.right), sp(&b.top), s.page_h - sp(&b.bottom)); - for (e, a, bb) in [(b.top, (x0, y0), (x1, y0)), (b.bottom, (x0, y1), (x1, y1)), (b.left, (x0, y0), (x0, y1)), (b.right, (x1, y0), (x1, y1))] { - if let Some(e) = e.filter(Border::is_visible) { - v.push(Placed::Rule { x0: a.0, y0: a.1, x1: bb.0, y1: bb.1, border: e }); - } - } + box_rules(&mut v, (x0, y0, x1, y1), [b.top, b.bottom, b.left, b.right], [false; 2]); } v } diff --git a/crates/layout/src/table.rs b/crates/layout/src/table.rs index 1372e24a94..05fa3ee531 100644 --- a/crates/layout/src/table.rs +++ b/crates/layout/src/table.rs @@ -841,7 +841,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { let (x0, x1, y0, y1) = (c.x, c.x + c.w, 0.0, rh); // Horizontal edges run on over half of each visible vertical edge, so the corners // close the way Word draws them instead of leaving a notch at thick borders. - let half = |o: Option| o.filter(Border::is_visible).map_or(0.0, |e| e.width / 2.0); + let half = |o: Option| o.filter(Border::is_visible).map_or(0.0, |e| crate::display::rule_width(&e) / 2.0); let (hx0, hx1) = (x0 - half(b.left), x1 + half(b.right)); let top_vis = c.vmerge != VMerge::Continue; if top_vis && let Some(e) = b.top.filter(Border::is_visible) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 845f25db9f..7235186bce 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -3620,7 +3620,51 @@ fn character_border_draws_one_box_around_run() { assert_eq!(horiz.len(), 2); assert_eq!(vert.len(), 2); assert!(horiz.iter().any(|h| (h.1 - top).abs() < 0.01) && horiz.iter().any(|h| (h.1 - bottom).abs() < 0.01), "{lines:?}"); - assert!(horiz.iter().all(|h| (h.0 - gx0).abs() < 0.01 && (h.2 - gx1).abs() < 0.01), "{lines:?} {gx0} {gx1}"); + // Top and bottom run on over half the 0.5 pt side lines, closing the corners. + assert!(horiz.iter().all(|h| (h.0 - (gx0 - 0.25)).abs() < 0.01 && (h.2 - (gx1 + 0.25)).abs() < 0.01), "{lines:?} {gx0} {gx1}"); +} + +#[test] +fn words_underline_draws_one_line_per_word() { + let mut d = Document::from_text("ab cd"); + d.format_range(&Pos::body(0, 0), &Pos::body(0, 5), &|c| c.underline = Some(wordcraft_doc::props::Underline::Words)).unwrap(); + assert_eq!(border_lines(&d).len(), 2, "{:?}", border_lines(&d)); + // A space condensed to no width still parts the words. + d.format_range(&Pos::body(0, 0), &Pos::body(0, 5), &|c| c.spacing = Some(-4.0)).unwrap(); + assert_eq!(border_lines(&d).len(), 2, "{:?}", border_lines(&d)); + // A bookmark between two letters doesn't part them. + let mut d = Document::from_text("ab cd"); + d.insert_object(&Pos::body(0, 1), InlineObject::BookmarkStart { name: "x".into() }, &Default::default()).unwrap(); + let end = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().text.len(); + d.format_range(&Pos::body(0, 0), &Pos::body(0, end), &|c| c.underline = Some(wordcraft_doc::props::Underline::Words)).unwrap(); + assert_eq!(border_lines(&d).len(), 2, "{:?}", border_lines(&d)); +} + +#[test] +fn paragraph_border_lines_meet_in_square_corners() { + use wordcraft_doc::props::{Border, Borders}; + let mut d = Document::from_text("Boxed"); + let (thick, thin) = (Some(Border::single(3.0)), Some(Border::single(1.0))); + d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.borders = Some(Borders { top: thick, left: thin, bottom: thick, ..Borders::default() }); + let lines = border_lines(&d); + let [left] = lines.iter().filter(|l| l.0 == l.2).collect::>()[..] else { panic!("{lines:?}") }; + let horiz: Vec<_> = lines.iter().filter(|l| l.1 == l.3).collect(); + assert_eq!(horiz.len(), 2, "{lines:?}"); + // Word: the 3 pt lines run on over half the 1 pt left line, and end half their own width past + // the right edge, where there is no line (docxide-pdf's samtale and english_town_council_report). + let right = d.last_section.page_w - d.last_section.margin_right; + for h in &horiz { + assert!((h.0 - (left.0 - 0.5)).abs() < 0.01 && (h.2 - (right + 1.5)).abs() < 0.01, "{lines:?} {right}"); + } + // The left line runs on to the top and bottom lines' outer edges; with no top line it ends square. + assert!((left.1 - (horiz[0].1.min(horiz[1].1) - 1.5)).abs() < 0.01 && (left.3 - (horiz[0].1.max(horiz[1].1) + 1.5)).abs() < 0.01, "{lines:?}"); + d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.borders = Some(Borders { left: thin, bottom: thick, ..Borders::default() }); + let lines = border_lines(&d); + let [left] = lines.iter().filter(|l| l.0 == l.2).collect::>()[..] else { panic!("{lines:?}") }; + let [bottom] = lines.iter().filter(|l| l.1 == l.3).collect::>()[..] else { panic!("{lines:?}") }; + assert!((left.3 - (bottom.1 + 1.5)).abs() < 0.01, "{lines:?}"); + let first = lay(&d).pages[0].items.iter().find_map(|i| if let Placed::Lines { y, .. } = i { Some(*y) } else { None }).unwrap(); + assert!((left.1 - (first - 0.5)).abs() < 0.01, "{lines:?} {first}"); } #[test]