diff --git a/ROADMAP.md b/ROADMAP.md index 74950d4982..bc47cb93d9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,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-10-23 · **Change:** trivial (dark-theme interface text on Linux no longer looks semi-bold; previously trivial: page text on Linux is hinted like Firefox draws text there; 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: 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; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** trivial (dark-theme interface text on Linux no longer looks semi-bold; previously trivial: page text on Linux is hinted like Firefox draws text there; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; 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: 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; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** trivial (dark-theme interface text on Linux no longer looks semi-bold; previously trivial: page text on Linux is hinted like Firefox draws text there; previously trivial: English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; 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: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; 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; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. @@ -136,6 +136,8 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-10-23: DOCX: a document whose default font size is unset keeps its size when saved and reopened. The size was left out of the file, and the reader read the missing size as 10 pt while the document resolved it as 11 pt; the file now says 11 pt (`DEFAULT_FONT_SIZE`). Files from other programs without a size are read as before. +- 2026-10-23: Insert › Table: hovering the grid shows the table on the page where it would go, as Word's Live Preview does, and the preview follows the pointer from square to square. It is laid out on a copy of the document, so nothing changes, and Undo has nothing new, until a square is clicked (#3931). - 2026-10-22: Mail merge (#3028): Preview Results has First Record and Last Record buttons and a box with the previewed record number; type a number and press Enter to go there (past either end stops at the first or last record). Finish & Merge is now a menu. Edit Individual Documents… and Print Documents… ask for all records, the current record, or a From and To range by record number, and Print Documents opens Print for the merged document. Scripts get `mailings.first`, `mailings.last`, `mailings.goToRecord`, `mailings.printDocuments` and a `records` choice on `mailings.finish`; a range with no records in it is refused instead of leaving an empty document. - 2026-10-22: Re-routing a group connector keeps its free end at its displayed rotated and flipped position, including after nonuniform group resizing, while the glued end follows its existing connection-site path. Missing target shapes and invalid connection sites keep their transformed endpoints too. Fallback routes that cannot fit the renderer's 4000 pt child-size cap leave the original connector unchanged. Model and engine regressions cover starts, ends, unit/uniform/nonuniform scale, settled reroutes and safe handling of degenerate dimensions and display-size limits; no new native Word comparison. - 2026-10-23: Lists: an empty paragraph whose mark is hidden takes no room and draws no list number, in the body and in table cells, as in Word; the number is still counted, so the next item keeps its place (#3982). diff --git a/crates/doc/src/para.rs b/crates/doc/src/para.rs index 1266b7d4fb..9add66c65a 100644 --- a/crates/doc/src/para.rs +++ b/crates/doc/src/para.rs @@ -311,7 +311,14 @@ pub enum ShapeKind { RightTriangle, Diamond, Line, + /// A block arrow pointing right (`rightArrow`; also stands for the double-headed arrows). Arrow, + /// A block arrow pointing left (`leftArrow`). + ArrowLeft, + /// A block arrow pointing up (`upArrow`). + ArrowUp, + /// A block arrow pointing down (`downArrow`). + ArrowDown, Star, Heart, /// A text box (rectangle with a text story). diff --git a/crates/doc/src/props.rs b/crates/doc/src/props.rs index a73eecde8a..be5addd5d7 100644 --- a/crates/doc/src/props.rs +++ b/crates/doc/src/props.rs @@ -342,6 +342,9 @@ impl Highlight { } } +/// The text size, in points, of a run whose size no style or default sets. +pub const DEFAULT_FONT_SIZE: f32 = 11.0; + /// Character formatting (direct or in a style). `None` = inherit. #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] diff --git a/crates/doc/src/resolve.rs b/crates/doc/src/resolve.rs index dfb84ea9f3..49b6904822 100644 --- a/crates/doc/src/resolve.rs +++ b/crates/doc/src/resolve.rs @@ -78,7 +78,7 @@ impl ResolvedChar { ResolvedChar { // A symbol character is shown in its own font (`w:sym`), whatever the run's font. font: c.shown_font().map(str::to_string).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()), - size: c.size.unwrap_or(11.0).clamp(1.0, 1638.0), + size: c.size.unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0), bold: c.bold.unwrap_or(false), italic: c.italic.unwrap_or(false), underline: c.underline.unwrap_or_default(), @@ -113,7 +113,7 @@ impl ResolvedChar { cs: c.cs.unwrap_or(false), font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()), font_ea: c.font_ea.clone(), - size_cs: c.size_cs.or(c.size).unwrap_or(11.0).clamp(1.0, 1638.0), + size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0), bold_cs: c.bold_cs.or(c.bold).unwrap_or(false), italic_cs: c.italic_cs.or(c.italic).unwrap_or(false), } diff --git a/crates/doc/src/wrap.rs b/crates/doc/src/wrap.rs index add3b5d324..1c235d73e4 100644 --- a/crates/doc/src/wrap.rs +++ b/crates/doc/src/wrap.rs @@ -92,11 +92,7 @@ pub fn shape_outline(kind: ShapeKind, w: f32, h: f32, corner: Option) -> Op ShapeKind::Triangle => vec![(0.5, 0.0), (1.0, 1.0), (0.0, 1.0)], ShapeKind::RightTriangle => vec![(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)], ShapeKind::Diamond => vec![(0.5, 0.0), (1.0, 0.5), (0.5, 1.0), (0.0, 0.5)], - ShapeKind::Arrow => { - // As drawn: the head is half the height long, the shaft 40% of the height thick. - let head = if w > 0.0 { (0.5 * h / w).min(1.0) } else { 0.5 }; - vec![(0.0, 0.3), (1.0 - head, 0.3), (1.0 - head, 0.0), (1.0, 0.5), (1.0 - head, 1.0), (1.0 - head, 0.7), (0.0, 0.7)] - } + ShapeKind::Arrow | ShapeKind::ArrowLeft | ShapeKind::ArrowUp | ShapeKind::ArrowDown => arrow_outline(kind, w, h), ShapeKind::Star => (0..10) .map(|i| { let a = PI * i as f32 / 5.0 - FRAC_PI_2; @@ -126,6 +122,26 @@ pub fn shape_outline(kind: ShapeKind, w: f32, h: f32, corner: Option) -> Op Some(pts) } +/// A block arrow's outline in unit coordinates (0..1 across a `w` × `h` frame), pointing the way +/// `kind` says (right for anything but the left, up and down arrows). The head is half the arrow's +/// thickness long, the shaft 40% of the thickness thick. +pub fn arrow_outline(kind: ShapeKind, w: f32, h: f32) -> Vec<(f32, f32)> { + let vertical = matches!(kind, ShapeKind::ArrowUp | ShapeKind::ArrowDown); + let (len, thick) = if vertical { (h, w) } else { (w, h) }; + let head = if len > 0.0 { (0.5 * thick / len).min(1.0) } else { 0.5 }; + // Pointing right: `u` runs along the arrow from its tail, `v` across it. + let right = [(0.0, 0.3), (1.0 - head, 0.3), (1.0 - head, 0.0), (1.0, 0.5), (1.0 - head, 1.0), (1.0 - head, 0.7), (0.0, 0.7)]; + right + .iter() + .map(|&(u, v)| match kind { + ShapeKind::ArrowLeft => (1.0 - u, v), + ShapeKind::ArrowUp => (v, 1.0 - u), + ShapeKind::ArrowDown => (v, u), + _ => (u, v), + }) + .collect() +} + /// Largest side of the grid [`alpha_outline`] looks at. pub const ALPHA_GRID: usize = 48; @@ -214,6 +230,16 @@ mod tests { assert!(WrapPolygon::from_unit(false, &[(f32::NAN, 0.0), (0.0, 0.0), (1.0, 0.0), (0.5, 1.0)]).is_some_and(|p| p.points.len() == 3)); } + /// #3919: the tip of each block arrow lies on the side it points to. + #[test] + fn arrow_outlines_point_the_right_way() { + let tip = |kind| shape_outline(kind, 100.0, 100.0, None).unwrap()[3]; + assert_eq!(tip(ShapeKind::Arrow), (1.0, 0.5)); + assert_eq!(tip(ShapeKind::ArrowLeft), (0.0, 0.5)); + assert_eq!(tip(ShapeKind::ArrowUp), (0.5, 0.0)); + assert_eq!(tip(ShapeKind::ArrowDown), (0.5, 1.0)); + } + #[test] fn shape_outlines_stay_in_the_frame() { for kind in [ @@ -223,6 +249,9 @@ mod tests { ShapeKind::RightTriangle, ShapeKind::Diamond, ShapeKind::Arrow, + ShapeKind::ArrowLeft, + ShapeKind::ArrowUp, + ShapeKind::ArrowDown, ShapeKind::Star, ShapeKind::Heart, ] { diff --git a/crates/docbin/src/drawing.rs b/crates/docbin/src/drawing.rs index 43e3511894..461d6b372c 100644 --- a/crates/docbin/src/drawing.rs +++ b/crates/docbin/src/drawing.rs @@ -190,7 +190,10 @@ fn leaf(sp: &Sp, w: f32, h: f32, float: Float, b: &Build, pics: &mut Pictures) - 5 => ShapeKind::Triangle, 6 => ShapeKind::RightTriangle, 12 | 187 => ShapeKind::Star, - 13 | 66 | 67 | 68 | 69 => ShapeKind::Arrow, + 13 | 69 => ShapeKind::Arrow, + 66 => ShapeKind::ArrowLeft, + 67 => ShapeKind::ArrowDown, + 68 => ShapeKind::ArrowUp, 20 | 32 => ShapeKind::Line, 74 => ShapeKind::Heart, 202 => ShapeKind::TextBox, diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index c32a3e7fab..acd56b2ef4 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -231,22 +231,11 @@ impl PropCtx { // `w:ascii`, `w:hAnsiTheme` over `w:hAnsi`). let named = |a: &str| k.attr(a).filter(|f| !f.is_empty()).map(str::to_string); let themed = |a: &str| k.attr(a).and_then(|t| self.theme_font(t)); - c.font = - themed("w:asciiTheme").or_else(|| named("w:ascii")).or_else(|| themed("w:hAnsiTheme")).or_else(|| named("w:hAnsi")).or_else( - || { - // `w:eastAsia` and `w:cs` name fonts for other scripts; they stand in for the - // Latin font only when the run is hinted as that script. Otherwise the Latin - // font is inherited (a Normal style with only `w:eastAsia`/`w:cs` keeps the - // `docDefaults` font, as in Word). - match k.attr("w:hint") { - Some("eastAsia") => k.attr("w:eastAsia"), - Some("cs") => k.attr("w:cs"), - _ => None, - } - .filter(|f| !f.is_empty()) - .map(str::to_string) - }, - ); + // `w:eastAsia` and `w:cs` name fonts for other scripts and stay in `font_ea` / + // `font_cs`: `w:hint` only picks between them for ambiguous characters, never for + // Latin letters. A Normal style with only `w:eastAsia`/`w:cs` keeps the + // `docDefaults` font, and so does a hinted run, as in Word. + c.font = themed("w:asciiTheme").or_else(|| named("w:ascii")).or_else(|| themed("w:hAnsiTheme")).or_else(|| named("w:hAnsi")); // The complex-script font (Persian, Arabic, Hebrew text). A `w:cstheme` font is // left to inherit: the theme's per-script fonts aren't read. c.font_cs = k.attr("w:cs").filter(|f| !f.is_empty() && f.len() < 256).map(str::to_string); diff --git a/crates/docx/src/read/shape_style.rs b/crates/docx/src/read/shape_style.rs index 180774effd..e8ccee9198 100644 --- a/crates/docx/src/read/shape_style.rs +++ b/crates/docx/src/read/shape_style.rs @@ -41,9 +41,10 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind { "straightConnector1" => ShapeKind::StraightConnector, "bentConnector2" | "bentConnector3" | "bentConnector4" | "bentConnector5" => ShapeKind::ElbowConnector, "curvedConnector2" | "curvedConnector3" | "curvedConnector4" | "curvedConnector5" => ShapeKind::CurvedConnector, - "rightArrow" | "leftArrow" | "upArrow" | "downArrow" | "leftRightArrow" | "upDownArrow" | "notchedRightArrow" | "stripedRightArrow" => { - ShapeKind::Arrow - } + "rightArrow" | "leftRightArrow" | "upDownArrow" | "notchedRightArrow" | "stripedRightArrow" => ShapeKind::Arrow, + "leftArrow" => ShapeKind::ArrowLeft, + "upArrow" => ShapeKind::ArrowUp, + "downArrow" => ShapeKind::ArrowDown, "star4" | "star5" | "star6" | "star7" | "star8" | "star10" | "star12" | "star16" | "star24" | "star32" => ShapeKind::Star, "heart" => ShapeKind::Heart, _ => ShapeKind::Rectangle, @@ -469,6 +470,15 @@ mod tests { assert_eq!(preset_kind("flowChartDecision"), ShapeKind::Diamond); } + /// #3919: Word's up, down and left block arrows were all read as the right-pointing arrow. + #[test] + fn block_arrows_keep_their_direction() { + assert_eq!(preset_kind("rightArrow"), ShapeKind::Arrow); + assert_eq!(preset_kind("leftArrow"), ShapeKind::ArrowLeft); + assert_eq!(preset_kind("upArrow"), ShapeKind::ArrowUp); + assert_eq!(preset_kind("downArrow"), ShapeKind::ArrowDown); + } + #[test] fn vml_presets_map_like_drawingml_presets() { assert_eq!(vml_preset_kind(13), Some(ShapeKind::Arrow)); @@ -477,7 +487,7 @@ mod tests { assert_eq!(vml_preset_kind(202), Some(ShapeKind::TextBox)); // The nearest shape, as `preset_kind` gives it: left arrow, right triangle, four-point // star, rounded callout, elbow connector, a bevel (its box). - assert_eq!(vml_preset_kind(66), Some(ShapeKind::Arrow)); + assert_eq!(vml_preset_kind(66), Some(ShapeKind::ArrowLeft)); assert_eq!(vml_preset_kind(6), Some(ShapeKind::RightTriangle)); assert_eq!(vml_preset_kind(187), Some(ShapeKind::Star)); assert_eq!(vml_preset_kind(62), Some(ShapeKind::RoundedRectangle)); diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 6dee87df23..1ce49e2099 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -1751,7 +1751,7 @@ impl Reader<'_> { let font = tp .attr("style") .and_then(|s| vml_style(s, "font-family")) - .map(|f| f.trim_matches(|c: char| c == '"' || c == '\'' || c.is_whitespace()).chars().take(100).collect::()) + .map(|f| css_string(f).chars().take(100).collect::()) .filter(|f| !f.is_empty()); // The shapetype's WordArt shape (`o:spt` 136-175) bends the text like DrawingML's warp. let warp = vml_spt(shape, shapetype, type_id) @@ -2231,6 +2231,49 @@ fn vml_style<'a>(style: &'a str, key: &str) -> Option<&'a str> { style.rsplit(';').filter_map(|d| d.split_once(':')).find(|(k, _)| k.trim().eq_ignore_ascii_case(key)).map(|(_, v)| v.trim()) } +/// A `v:textpath` style value with one pair of surrounding quotes removed and the writer's CSS +/// escapes mapped back: `\` + up to six hex digits + one optional space is that character, and +/// `\x` is `x` (#3994; `write::watermark::run` writes them). Only the surrounding pair goes, so a +/// font name that starts or ends with an apostrophe keeps it. Word writes font names raw, and a +/// lone trailing `\` none of CSS would accept stays literal. +fn css_string(v: &str) -> String { + let v = v.trim(); + let v = ['"', '\''].into_iter().find_map(|q| v.strip_prefix(q)?.strip_suffix(q)).unwrap_or(v).trim(); + let mut out = String::with_capacity(v.len()); + let mut chars = v.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + let mut hex = String::new(); + while hex.len() < 6 { + match chars.clone().next() { + Some(h) if h.is_ascii_hexdigit() => { + hex.push(h); + chars.next(); + } + _ => break, + } + } + if hex.is_empty() { + match chars.next() { + Some(e) => out.push(e), + None => out.push('\\'), + } + } else { + if let Some(d) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) { + out.push(d); + } + // One whitespace after the escape is its terminator, not part of the value. + if chars.clone().next().is_some_and(|w| w.is_whitespace()) { + chars.next(); + } + } + } + out +} + /// Placement of a VML shape (ECMA-376 Part 4, VML): `position:absolute` in its style makes it /// float, offset by `left`/`margin-left` and `top`/`margin-top` from the area named by /// `mso-position-horizontal-relative` / `mso-position-vertical-relative` (unless aligned with @@ -2332,7 +2375,7 @@ fn vml_watermark(shape: &El) -> Option { let font = tp .attr("style") .and_then(|s| vml_style(s, "font-family")) - .map(|f| f.trim_matches(|c: char| c == '"' || c == '\'' || c.is_whitespace()).chars().take(100).collect::()) + .map(|f| css_string(f).chars().take(100).collect::()) .filter(|f| !f.is_empty()) .unwrap_or(default.font); let color = shape.attr("fillcolor").and_then(vml_color).unwrap_or(default.color); diff --git a/crates/docx/src/write/mod.rs b/crates/docx/src/write/mod.rs index 7e86019028..4e0a0c09e2 100644 --- a/crates/docx/src/write/mod.rs +++ b/crates/docx/src/write/mod.rs @@ -720,7 +720,15 @@ fn styles_xml(doc: &Document) -> Vec { w.open("w:docDefaults", &[]); w.open("w:rPrDefault", &[]); w.open("w:rPr", &[]); - props::rpr_inner(&mut w, &s.default_chr); + if s.default_chr.size.is_none() { + // The reader reads an omitted `w:sz` as 10 pt, but the resolver falls back to + // DEFAULT_FONT_SIZE, so writing nothing would change the size on reopening. + let mut chr = s.default_chr.clone(); + chr.size = Some(wordcraft_doc::props::DEFAULT_FONT_SIZE); + props::rpr_inner(&mut w, &chr); + } else { + props::rpr_inner(&mut w, &s.default_chr); + } w.close("w:rPr"); w.close("w:rPrDefault"); if s.default_para_present || s.default_para != wordcraft_doc::props::ParaProps::default() { diff --git a/crates/docx/src/write/story.rs b/crates/docx/src/write/story.rs index 131a3fbc65..184fe0f236 100644 --- a/crates/docx/src/write/story.rs +++ b/crates/docx/src/write/story.rs @@ -1069,6 +1069,9 @@ impl Writer<'_> { ShapeKind::ElbowConnector => "bentConnector3", ShapeKind::CurvedConnector => "curvedConnector3", ShapeKind::Arrow => "rightArrow", + ShapeKind::ArrowLeft => "leftArrow", + ShapeKind::ArrowUp => "upArrow", + ShapeKind::ArrowDown => "downArrow", ShapeKind::Star => "star5", ShapeKind::Heart => "heart", }; diff --git a/crates/docx/src/write/watermark.rs b/crates/docx/src/write/watermark.rs index 501f36bc71..998227e6aa 100644 --- a/crates/docx/src/write/watermark.rs +++ b/crates/docx/src/write/watermark.rs @@ -23,8 +23,21 @@ pub(super) fn text(wm: &Watermark) -> Option { pub(super) fn run(wm: &Watermark, n: usize, page: &SectionProps) -> Option { let text = text(wm)?; let [width, height] = wm.frame(page.page_w, page.page_h); - // A font name can't break out of the textpath's CSS-like style. - let font: String = wm.font.chars().filter(|c| !matches!(c, '"' | '\'' | ';' | ':')).take(100).collect(); + // A font name can't break out of the textpath's CSS-like style or make it malformed (#3994): + // the characters a quoted CSS string can't carry raw (`\22 ` is `"`, `\3b ` `;`, `\3a ` `:`, + // `\5c ` `\`) are escaped and control characters are dropped (no font name carries one); the + // reader (`read::story::css_string`) maps the escapes back. An apostrophe is legal inside a + // double-quoted string, so it is kept. + let mut font = String::with_capacity(wm.font.len()); + for c in wm.font.chars().filter(|c| !c.is_control()).take(100) { + match c { + '"' => font.push_str(r"\22 "), + ';' => font.push_str(r"\3b "), + ':' => font.push_str(r"\3a "), + '\\' => font.push_str(r"\5c "), + c => font.push(c), + } + } let font = if font.trim().is_empty() { Watermark::default().font } else { font }; let rotation = if wm.diagonal { "rotation:315;" } else { "" }; let style = format!( diff --git a/crates/docx/tests/it/default_size.rs b/crates/docx/tests/it/default_size.rs new file mode 100644 index 0000000000..b6c4c6d143 --- /dev/null +++ b/crates/docx/tests/it/default_size.rs @@ -0,0 +1,69 @@ +//! The document default font size (`w:docDefaults/w:rPrDefault/w:rPr/w:sz`) across a save and +//! reopen. An unset default is resolved as `DEFAULT_FONT_SIZE`; the writer must say so, because +//! the reader reads an omitted size as 10 pt. +use std::io::{Read, Write}; +use wordcraft_doc::Document; +use wordcraft_doc::props::{CharProps, DEFAULT_FONT_SIZE}; +fn resolved(d: &Document) -> f32 { + d.styles.resolve_char(None, &CharProps::default()).size +} +fn styles_xml(bytes: &[u8]) -> String { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + archive.by_name("word/styles.xml").unwrap().read_to_string(&mut xml).unwrap(); + xml +} +fn defaults(xml: &str) -> &str { + xml.split("").nth(1).unwrap().split("").next().unwrap() +} +#[test] +fn an_unset_default_size_keeps_its_effective_size_across_save_and_reopen() { + let mut d = Document::new(); + d.styles.default_chr.size = None; + assert_eq!(resolved(&d), DEFAULT_FONT_SIZE); + let bytes = wordcraft_docx::write(&d).unwrap(); + assert!(defaults(&styles_xml(&bytes)).contains(r#""#)); + let reopened = wordcraft_docx::read(&bytes).unwrap(); + assert_eq!(resolved(&reopened), DEFAULT_FONT_SIZE); + // Saving again changes nothing further. + let again = wordcraft_docx::read(&wordcraft_docx::write(&reopened).unwrap()).unwrap(); + assert_eq!(resolved(&again), DEFAULT_FONT_SIZE); +} +#[test] +fn an_explicit_default_size_is_written_as_it_is() { + for size in [8.0, 10.0, 11.0, 12.5, 18.0] { + let mut d = Document::new(); + d.styles.default_chr.size = Some(size); + let bytes = wordcraft_docx::write(&d).unwrap(); + assert_eq!(resolved(&wordcraft_docx::read(&bytes).unwrap()), size); + } +} +#[test] +fn a_file_that_omits_the_default_size_is_still_read_as_ten_points() { + // The reader is unchanged: only what WordCraft writes differs. A package without a size + // anywhere keeps its established reading. + let root = r#""#; + let doc = r#"x"#; + let styles = r#""#; + let rels = r#""#; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, body) in [("_rels/.rels", root), ("word/document.xml", doc), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles)] { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(body.as_bytes()).unwrap(); + } + let d = wordcraft_docx::read(&zw.finish().unwrap().into_inner()).unwrap(); + assert_eq!(d.styles.default_chr.size, Some(10.0)); +} +#[test] +fn an_unset_default_size_does_not_take_a_styles_size() { + // The written default is the resolver's own fallback, not what the Normal style resolves to, + // so a style that sets a size keeps it and one that does not still falls back to the default. + let mut d = Document::new(); + d.styles.default_chr.size = None; + if let Some(normal) = d.styles.get_mut("Normal") { + normal.chr.size = Some(14.0); + } + let reopened = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(reopened.styles.default_chr.size, Some(DEFAULT_FONT_SIZE)); + assert_eq!(resolved(&reopened), resolved(&d)); +} diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index cf0c588d5b..eabdd38a9f 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1040,7 +1040,7 @@ fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() { #[test] fn style_rfonts_without_ascii_inherits_doc_defaults_font() { // Issue #93: Normal names only East Asian / complex-script fonts, so Latin text keeps the - // docDefaults font. A run hinted as East Asian still uses its East Asian font. + // docDefaults font. A run hinted as East Asian keeps its East Asian font in `font_ea` (#4031). let styles = format!( r#" @@ -1051,9 +1051,28 @@ fn style_rfonts_without_ascii_inherits_doc_defaults_font() { let d = wordcraft_docx::read(&docx(body, &[("rId1", "styles", "styles.xml")], &[("word/styles.xml", &styles)])).unwrap(); assert_eq!(d.styles.get("Normal").unwrap().chr.font, None); let ps = paras(&d); - let font = |p: &Paragraph| d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props).font; - assert_eq!(font(ps[0]), "Calibri"); - assert_eq!(font(ps[1]), "SimSun"); + let rc = |p: &Paragraph| d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props); + assert_eq!(rc(ps[0]).font, "Calibri"); + assert_eq!((rc(ps[1]).font.as_str(), rc(ps[1]).font_ea.as_deref()), ("Calibri", Some("SimSun"))); +} + +#[test] +fn hinted_east_asian_or_cs_font_does_not_replace_the_latin_font() { + // Issue #4031: `w:hint` only picks the font for ambiguous characters, so a run with + // `w:eastAsia` + `w:hint="eastAsia"` and no `w:ascii` keeps the style's Latin font for its + // Latin text; the East Asian / complex-script fonts stay in their own fields. + let styles = format!( + r#" + +"# + ); + let body = r#"corn strawmodel fluids"#; + let d = wordcraft_docx::read(&docx(body, &[("rId1", "styles", "styles.xml")], &[("word/styles.xml", &styles)])).unwrap(); + let p = paras(&d)[0]; + let ea = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props); + assert_eq!((ea.font.as_str(), ea.font_ea.as_deref()), ("Times New Roman", Some("宋体"))); + let cs = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[1].props); + assert_eq!((cs.font.as_str(), cs.font_cs.as_str()), ("Times New Roman", "Arial")); } #[test] @@ -2387,7 +2406,7 @@ fn vml_preset_shapes_are_drawn() { assert_eq!(kind(15), Some((ShapeKind::Rectangle, false))); assert_eq!(kind(16), Some((ShapeKind::Diamond, false))); assert_eq!(kind(17), Some((ShapeKind::Ellipse, false))); - assert_eq!(shape(18), Some((ShapeKind::Arrow, 60.0, 20.0, Some(Rgb(0xFF, 0xA5, 0x00)), black, 0.75, true, false))); + assert_eq!(shape(18), Some((ShapeKind::ArrowLeft, 60.0, 20.0, Some(Rgb(0xFF, 0xA5, 0x00)), black, 0.75, true, false))); assert_eq!(kind(19), Some((ShapeKind::Rectangle, false))); assert_eq!(kind(20), Some((ShapeKind::Star, false))); assert_eq!(shape(21), None); @@ -2458,12 +2477,12 @@ fn vml_nearest_preset_shape_survives_saving() { let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap(); let mut xml = String::new(); std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); - assert!(xml.contains(r#"prst="rightArrow""#), "{xml}"); + assert!(xml.contains(r#"prst="leftArrow""#), "{xml}"); let again = wordcraft_docx::read(&saved).unwrap(); assert!( matches!( ¶s(&again)[0].objects[..], - [InlineObject::Shape { kind: ShapeKind::Arrow, w: 60.0, h: 20.0, fill: Some(Fill::Solid { color: Rgb(0xFF, 0xA5, 0x00), .. }), .. }] + [InlineObject::Shape { kind: ShapeKind::ArrowLeft, w: 60.0, h: 20.0, fill: Some(Fill::Solid { color: Rgb(0xFF, 0xA5, 0x00), .. }), .. }] ), "{:?}", paras(&again)[0].objects diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index 80475e3b08..c3661f2c31 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -7,6 +7,7 @@ mod complex_script_inheritance; mod content_control_save_cost; mod content_controls; mod custom_xml; +mod default_size; mod drawing_payload; mod east_asian_lang; mod east_asian_layout; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 681c52d6dc..8ba6cc0d61 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -1545,6 +1545,33 @@ fn watermark_roundtrips() { } } +/// #3994: a watermark font name round-trips through the textpath's CSS-like style whatever it +/// carries — apostrophes, semicolons, colons, quotes, backslashes. Before, those characters +/// were deleted (the font was saved under a different name) and a trailing backslash escaped +/// the style's closing quote. +#[test] +fn watermark_font_roundtrips_through_the_textpath_style() { + for font in ["Georgia", "Bob's Serif", "A;Named:Font", "Quote\"Inside", "Ends with \\", "All \"of\" ;it: 'here\\", "'Serif'", "Trailing'"] { + let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]); + d.settings.watermark = Some(Watermark { font: font.into(), ..Default::default() }); + assert_eq!(rt(&d).settings.watermark.map(|w| w.font), Some(font.into()), "{font:?}"); + } +} + +/// #3994: the written textpath style stays well-formed CSS whatever the font name: control +/// characters are dropped (no font name carries one) and a backslash or quote is a CSS escape +/// (`\5c `, `\22 `) instead of escaping the string's closing quote. +#[test] +fn watermark_font_name_writes_wellformed_css() { + let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]); + d.settings.watermark = Some(Watermark { font: "Ends with \\ and \n\"quoted\"".into(), ..Default::default() }); + let bytes = wordcraft_docx::write(&d).unwrap(); + let hdr = part_xml(&bytes, "word/header1.xml"); + let style = hdr.split("v:textpath style=\"").nth(1).and_then(|s| s.split('"').next()).unwrap_or_default(); + assert!(!style.contains('\n'), "control characters are dropped: {style}"); + assert!(style.contains(r#"font-family:"Ends with \5c and \22 quoted\22 ";"#), "CSS escapes: {style}"); +} + /// #1290: a document without headers gains one default header holding only the watermark (an /// empty paragraph once read back); saving again neither adds another nor duplicates the shape. #[test] diff --git a/crates/engine/src/cmd/mailings.rs b/crates/engine/src/cmd/mailings.rs index ac5d8719ea..16b62df43a 100644 --- a/crates/engine/src/cmd/mailings.rs +++ b/crates/engine/src/cmd/mailings.rs @@ -524,7 +524,16 @@ fn insert_field(s: &mut Session, instr: &str, placeholder: &str) -> CmdResult { /// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs). pub fn parse_csv(text: &str) -> Vec> { let first = text.lines().next().unwrap_or(""); - let sep = [',', ';', '\t'].into_iter().max_by_key(|c| first.matches(*c).count()).unwrap_or(','); + let mut quoted = false; + let mut unquoted = String::new(); + for c in first.chars() { + if c == '"' { + quoted = !quoted; + } else if !quoted { + unquoted.push(c); + } + } + let sep = [',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(','); let mut rows = Vec::new(); let mut row = Vec::new(); let mut cell = String::new(); @@ -1180,13 +1189,24 @@ fn envelope_size(v: &Value) -> Result<(f32, f32), CmdError> { .ok_or_else(|| CmdError::Params(format!("unknown envelope size `{name}`"))) } +/// Longest label or envelope address text accepted. +const MAX_LABEL_TEXT: usize = 2_000; + +/// An optional label/envelope text parameter, rejected when longer than `MAX_LABEL_TEXT` characters. +fn label_text(v: &Value, key: &str) -> Result, CmdError> { + match p::str(v, key) { + Some(t) if t.chars().count() > MAX_LABEL_TEXT => Err(CmdError::Params(format!("`{key}` is longer than {MAX_LABEL_TEXT} characters"))), + t => Ok(t.map(str::to_string)), + } +} + /// Envelopes: a landscape page with the return address at the top left and the delivery address /// in the middle. As a new document, or (`add`) as a section of its own at the start of this one. fn envelopes(s: &mut Session, v: &Value) -> CmdResult { - let delivery = p::str(v, "delivery").map(str::to_string).unwrap_or_else(|| { + let delivery = label_text(v, "delivery")?.unwrap_or_else(|| { if s.merge.rows.is_empty() { "Recipient Name\nStreet Address\nCity, ST 00000".into() } else { address_block(s, s.merge.record) } }); - let ret = p::str(v, "return").unwrap_or("").to_string(); + let ret = label_text(v, "return")?.unwrap_or_default(); let (w, h) = envelope_size(v)?; let sect = SectionProps { page_w: w, @@ -1408,7 +1428,7 @@ fn labels(s: &mut Session, v: &Value) -> CmdResult { (at("row").min(rows), at("col").min(cols)) }); let from_rec = single.is_none() && p::bool(v, "fromRecipients").unwrap_or(!s.merge.rows.is_empty() && p::str(v, "text").is_none()); - let text = p::str(v, "text").unwrap_or("Name\nAddress\nCity, ST 00000").to_string(); + let text = label_text(v, "text")?.unwrap_or_else(|| "Name\nAddress\nCity, ST 00000".into()); let (page_w, page_h) = if prod.paper == "A4" { (595.3, 841.9) } else { (612.0, 792.0) }; let h_gap = (prod.h_pitch - prod.width).max(0.0); let v_gap = (prod.v_pitch - prod.height).max(0.0); @@ -1481,6 +1501,12 @@ mod tests { assert_eq!(parse_csv("a;b\n1;2")[1], vec!["1", "2"]); } + #[test] + fn csv_delimiter_ignores_quoted_text() { + let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n"); + assert_eq!(r, vec![vec!["Name, first, last", "City"], vec!["Ann", "Paris"]]); + } + #[test] fn merge_end_to_end() { let mut s = Session::new(Document::new()); @@ -1723,6 +1749,17 @@ mod tests { assert!(!s.doc.parts.contains_key(&hdr), "the template header is replaced by the letters' copies"); } + #[test] + fn label_and_envelope_text_is_capped() { + let mut s = Session::new(Document::new()); + let long = "x".repeat(2001); + assert!(matches!(s.run("mailings.labels", &json!({"text": long})), Err(CmdError::Params(_)))); + assert!(matches!(s.run("mailings.envelopes", &json!({"delivery": long})), Err(CmdError::Params(_)))); + assert!(matches!(s.run("mailings.envelopes", &json!({"return": long})), Err(CmdError::Params(_)))); + s.run("mailings.labels", &json!({"text": "x".repeat(2000), "rows": 40, "cols": 10})).unwrap(); + assert!(s.doc.plain_text(StoryRef::Body).chars().count() <= 400 * 2000 + 400 * 20); + } + #[test] fn envelopes_and_labels() { let mut s = Session::new(Document::new()); diff --git a/crates/engine/src/cmd/outline.rs b/crates/engine/src/cmd/outline.rs index ea13fc1dbf..0cf5727cbb 100644 --- a/crates/engine/src/cmd/outline.rs +++ b/crates/engine/src/cmd/outline.rs @@ -3,7 +3,7 @@ //! Line Only, Show Text Formatting. What's collapsed and shown is view state ([`OutlineState`]), //! never saved in the document; level changes and moves are ordinary undoable edits. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; use std::hash::{Hash, Hasher}; use serde::{Deserialize, Serialize}; @@ -464,10 +464,20 @@ pub(crate) fn move_shown(s: &mut Session, up: bool) -> Option { /// text; one whose text changed in place stays collapsed), and in Outline view a caret the /// outline doesn't show (in collapsed text, or past a body paragraph's first line) moves on to /// the nearest place it does, in the direction it was going. -pub(crate) fn after_command(s: &mut Session, before: &Selection) { - if !s.view.outline.collapsed.is_empty() { +/// `changed` says whether the document changed (its revision moved); if not, nothing moved. +pub(crate) fn after_command(s: &mut Session, before: &Selection, changed: bool) { + if changed && !s.view.outline.collapsed.is_empty() { let hashes: Vec> = (0..s.doc.body.len()).map(|i| text_hash(&s.doc, i)).collect(); let levels = ol::levels(&s.doc); + // The headings not yet taken, by text hash. + let mut by_hash: HashMap> = HashMap::new(); + for (j, h) in hashes.iter().enumerate() { + if let Some(h) = h + && levels.get(j).is_some_and(|l| *l < BODY) + { + by_hash.entry(*h).or_default().insert(j); + } + } let mut used = BTreeSet::new(); let mut out = Vec::new(); for (i, h) in std::mem::take(&mut s.view.outline.collapsed) { @@ -476,10 +486,22 @@ pub(crate) fn after_command(s: &mut Session, before: &Selection) { let found = if free(i, &used) && same(i) { Some(i) } else { - (0..levels.len()).filter(|j| free(*j, &used) && same(*j)).min_by_key(|j| j.abs_diff(i)).or_else(|| free(i, &used).then_some(i)) + // The nearest free heading with the same text (the earlier one on a tie). + let nearest = by_hash.get(&h).and_then(|set| { + let below = set.range(..=i).next_back().copied(); + let above = set.range(i..).next().copied(); + match (below, above) { + (Some(b), Some(a)) => Some(if a.abs_diff(i) < b.abs_diff(i) { a } else { b }), + (b, a) => b.or(a), + } + }); + nearest.or_else(|| free(i, &used).then_some(i)) }; if let Some(j) = found { used.insert(j); + if let Some(set) = hashes.get(j).copied().flatten().and_then(|hj| by_hash.get_mut(&hj)) { + set.remove(&j); + } out.push((j, hashes.get(j).copied().flatten().unwrap_or(h))); } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 511573ec61..9428d3ed6a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -673,6 +673,10 @@ impl Session { } pub fn new(doc: Document) -> Self { + Self::with_registry(doc, Arc::new(crate::cmd::registry())) + } + + fn with_registry(doc: Document, registry: Arc) -> Self { let start = doc.start_of(StoryRef::Body); let bib_style = doc_bib_style(&doc); Session { @@ -692,7 +696,7 @@ impl Session { find: FindState::default(), goal_x: None, page_hint: 0, - registry: Arc::new(crate::cmd::registry()), + registry, author: "WordCraft User".into(), initials: String::new(), painter: None, @@ -876,6 +880,12 @@ impl Session { /// The current layout (recomputed when the document or view changed). pub fn layout(&mut self) -> Arc { + let typing = self.typing_word(); + self.layout_with(typing) + } + + /// [`Session::layout`] with `typing` as the word being typed. + fn layout_with(&mut self, typing: Option) -> Arc { let mode = if self.view.read_mode { ViewMode::Read } else { self.view.mode }; let width = match mode { ViewMode::Read => self.view.read_width, @@ -889,7 +899,6 @@ impl Session { let hide_deleted = !self.view.show_markup; let deleted = (hide_deleted, self.prefs.markup.hidden_deletions(), self.revisions_in_balloons()); let outline = (mode == ViewMode::Outline).then(|| self.view.outline.view()); - let typing = self.typing_word(); if let Some((r, w, h, m, sp, l, pf, o, hd, n, t)) = &self.layout && *r == self.rev && (*w == width || mode == ViewMode::Print) @@ -966,6 +975,41 @@ impl Session { let (start, end) = typed_range(&self.doc.para_at(&at)?.text, at.off)?; Some(TypedWord { at, start, end }) } + /// The page as command `id` would leave it, for a live preview (Insert › Table's grid, #3931): + /// the command runs on a copy of the document, with this caret and view, and the copy is laid + /// out. The copy comes back with its layout, which is drawn from it: the layout's paragraph + /// paths name the copy's paragraphs, not this document's, and so is the copy's selection, + /// which is where the caret would be. The document, the selection, the undo history and Repeat + /// are untouched. `None` when the command fails or isn't allowed here. + pub fn preview_layout(&mut self, id: &str, params: &Value) -> Option<(Document, Selection, Arc)> { + // The word being typed keeps going without a squiggle on the preview: the command moves + // the copy's caret off it and may split its paragraph, so it is found again by its place. + let typing = self.typing_word(); + let at = self.sel.focus.clone(); + let mut copy = Session::with_registry(self.doc.clone(), self.registry.clone()); + copy.sel = self.sel.clone(); + copy.column = self.column.clone(); + copy.widened = self.widened.clone(); + copy.view = self.view.clone(); + copy.prefs = self.prefs.clone(); + copy.path = self.path.clone(); + copy.file_name = self.file_name.clone(); + copy.author = self.author.clone(); + copy.system_region = self.system_region.clone(); + copy.editing_lang = self.editing_lang.clone(); + // The copy shares the paragraph layouts, so only what the command changed is laid out. + std::mem::swap(&mut copy.cache, &mut self.cache); + let layout = copy.run(id, params).is_ok().then(|| { + let typing = typing.and_then(|t| { + let p = copy.doc.para_at(&at)?; + (t.end <= p.len()).then_some(wordcraft_layout::TypingWord { rev: p.rev, ..t }) + }); + copy.layout_with(typing) + }); + std::mem::swap(&mut copy.cache, &mut self.cache); + layout.map(|l| (copy.doc, copy.sel, l)) + } + /// A layout for output (PDF, images, print): no proofing marks, print view. pub fn export_layout(&self) -> Arc { self.export_layout_with(false) @@ -1515,6 +1559,7 @@ impl Session { let default_language_before = self.prefs.default_language.clone(); let run = spec.run; let mutates = spec.mutates; + let rev_before = self.rev; let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::cmd::column::dispatch(self, id, mutates, run, params))); let mut result = match result { Ok(r) => r, @@ -1559,7 +1604,7 @@ impl Session { self.note_edit(); } // Outline view: collapsed headings follow edits; the caret stays where it shows. - crate::cmd::outline::after_command(self, &sel_before); + crate::cmd::outline::after_command(self, &sel_before, self.rev != rev_before); // Extra selected objects last until something else is edited or selected; formatting // them keeps them selected, as in Word. if !matches!(id, "select.addObject" | "arrange.ungroup" | "shape.fill" | "shape.effects") && (spec.mutates || self.sel != sel_before) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 44747c0ab9..75bb875b94 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1674,6 +1674,73 @@ fn tables_commands() { assert!(s.run("table.merge", &json!({})).is_err()); } +/// #3931: the page as a command would leave it, laid out without running it on the document: +/// Insert › Table's grid previews the table it would insert. The document, the caret, the undo +/// history and Repeat stay as they were. +#[test] +fn preview_layout_shows_a_command_without_running_it() { + let mut s = Session::new(wordcraft_doc::Document::from_text("Lanterns")); + run(&mut s, "caret.docEnd", json!({})); + let (doc, sel, rev) = (s.doc.clone(), s.sel.clone(), s.rev()); + let cells = |l: &wordcraft_layout::DocLayout| l.index.keys().filter(|(st, p)| *st == StoryRef::Body && p.0.len() == 4).count(); + let (_, _, preview) = s.preview_layout("insert.table", &json!({"rows": 4, "cols": 3})).expect("a table can be inserted here"); + assert_eq!(cells(&preview), 12, "four rows of three cells"); + // At the caret: after "Lanterns", the second block. + let tables: std::collections::BTreeSet = + preview.index.keys().filter(|(st, p)| *st == StoryRef::Body && p.0.len() == 4).map(|(_, p)| p.0[0]).collect(); + assert_eq!(tables, [1].into(), "the table goes where the caret is"); + assert_eq!(s.doc, doc); + assert_eq!((&s.sel, s.rev(), s.dirty), (&sel, rev, false)); + assert!(!s.can_undo() && s.last_command.is_none()); + assert_eq!(cells(&s.layout()), 0, "the page itself has no table"); + assert!(s.preview_layout("no.such", &json!({})).is_none()); +} + +/// #3931 review: the preview comes back with the document it was laid out from. The table moves +/// the paragraphs after the caret down a block, so this document would draw the layout's +/// paragraphs from the wrong blocks, or from none. +#[test] +fn preview_layout_comes_with_the_document_it_lays_out() { + let mut s = Session::new(wordcraft_doc::Document::from_text("Lanterns\nKites")); + run(&mut s, "caret.docStart", json!({})); + run(&mut s, "caret.end", json!({})); + let (doc, _, preview) = s.preview_layout("insert.table", &json!({"rows": 2, "cols": 2})).expect("a table can be inserted here"); + for (story, path) in preview.index.keys().filter(|(st, _)| *st == StoryRef::Body) { + assert!(doc.para(*story, path).is_some(), "{path:?} names a paragraph of the previewed document"); + } + let kites = preview.index.keys().find(|(st, p)| *st == StoryRef::Body && doc.para(*st, p).is_some_and(|p| p.text == "Kites")); + assert!(kites.is_some_and(|(_, p)| p.0.len() == 1 && p.0[0] > 1), "Kites is laid out after the table: {kites:?}"); + assert_eq!(s.doc.plain_text(StoryRef::Body), "Lanterns\nKites", "the document itself has no table"); +} + +/// #3931 review: the word being typed has no spelling squiggle on the preview either, though +/// the table moves the copy's caret off it and splits its paragraph. +#[test] +fn preview_layout_keeps_the_word_being_typed_unmarked() { + let mut s = Session::new(wordcraft_doc::Document::from_text("helo")); + s.view.proofing = true; + run(&mut s, "caret.docEnd", json!({})); + run(&mut s, "text.insert", json!({"text": " wrld"})); + let marks = |l: &wordcraft_layout::DocLayout, doc: &wordcraft_doc::Document| -> Vec { + let text = &doc.para(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap().text; + l.pages[0] + .items + .iter() + .filter_map(|i| match i { + wordcraft_layout::Placed::Lines { para, path, .. } if path.0 == [0] => { + Some(para.issues.iter().filter(|i| !i.2).map(|i| text[i.0..i.1].to_string()).collect::>()) + } + _ => None, + }) + .flatten() + .collect() + }; + let doc = s.doc.clone(); + assert_eq!(marks(&s.layout(), &doc), ["helo"], "the page itself: only the finished word is marked"); + let (copy, _, preview) = s.preview_layout("insert.table", &json!({"rows": 2, "cols": 2})).unwrap(); + assert_eq!(marks(&preview, ©), ["helo"]); +} + #[test] fn delete_row_on_a_merge_start_promotes_the_cell_below() { use wordcraft_doc::props::VMerge; @@ -7736,6 +7803,37 @@ fn outline_collapse_hides_descendants_and_expand_restores() { assert_eq!(s.selected_text(), "One\na\nTwo\nb"); } +/// #3621: with thousands of collapsed headings, an Enter above them (which shifts every index) +/// finds them again without scanning the document once per heading, and a caret move doesn't +/// redo the matching. +#[test] +fn outline_many_collapsed_headings_stay_fast_after_edits() { + const N: usize = 8000; + let text: Vec = (0..N).flat_map(|i| [format!("Heading {i}"), format!("body {i}")]).collect(); + let mut d = wordcraft_doc::Document::from_text(&text.join("\n")); + for i in 0..N { + let p = d.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2 * i)).unwrap(); + p.props.style = Some("Heading1".into()); + } + let mut s = Session::new(d); + run(&mut s, "view.outline", json!({})); + run(&mut s, "outline.showLevel1", json!({})); + s.sel = crate::Selection::caret(Pos::body(0, 0)); + run(&mut s, "outline.collapse", json!({})); + let collapsed_texts = + |s: &Session| -> Vec { s.view.outline.collapsed.iter().map(|(i, _)| s.doc.body[*i].as_para().unwrap().text.clone()).collect() }; + let before = collapsed_texts(&s); + assert_eq!(before.len(), N, "every heading is collapsed"); + s.sel = crate::Selection::caret(Pos::body(1, 0)); + for _ in 0..10 { + run(&mut s, "text.newParagraph", json!({})); + } + for _ in 0..20 { + run(&mut s, "caret.right", json!({})); + } + assert_eq!(collapsed_texts(&s), before, "the same headings stay collapsed"); +} + /// #745: layout keeps a picture's size, so pictures read from HTML, Markdown, ODT or RTF at /// their pixel size are fitted to the text width when the file is opened (and when pasted), /// keeping their proportions; small pictures keep their size. diff --git a/crates/formats/src/sheet.rs b/crates/formats/src/sheet.rs index 49cc1259fa..520fca2f80 100644 --- a/crates/formats/src/sheet.rs +++ b/crates/formats/src/sheet.rs @@ -724,7 +724,8 @@ fn number(x: f64) -> String { return x.to_string(); } if x.fract() == 0.0 && x.abs() < 1e15 { - return format!("{x:.0}"); + // `+ 0.0` turns negative zero into positive zero, which would print as "-0". + return format!("{:.0}", x + 0.0); } let rounded: f64 = format!("{x:.14e}").parse().unwrap_or(x); if rounded.abs() >= 1e15 || rounded.abs() < 1e-9 { format!("{rounded:E}") } else { rounded.to_string() } @@ -1006,6 +1007,11 @@ mod tests { use super::*; use std::io::Write; + #[test] + fn negative_zero_formats_as_zero() { + assert_eq!(number(-0.0), "0"); + } + fn zip(entries: &[(&str, &str)]) -> Vec { let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index e6072e91d4..c4898c3cfa 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -692,20 +692,10 @@ fn shape_path(kind: ShapeKind, r: &Rect, corner: Option) -> Option { pb.move_to(x0, y0); pb.line_to(x1, y1); } - ShapeKind::Arrow => { - let h = r.h; - poly( - &mut pb, - &[ - (x0, cy - h * 0.2), - (x1 - h * 0.5, cy - h * 0.2), - (x1 - h * 0.5, y0), - (x1, cy), - (x1 - h * 0.5, y1), - (x1 - h * 0.5, cy + h * 0.2), - (x0, cy + h * 0.2), - ], - ) + ShapeKind::Arrow | ShapeKind::ArrowLeft | ShapeKind::ArrowUp | ShapeKind::ArrowDown => { + let pts: Vec<(f32, f32)> = + wordcraft_doc::wrap::arrow_outline(kind, r.w, r.h).iter().map(|&(u, v)| (x0 + u * r.w, y0 + v * r.h)).collect(); + poly(&mut pb, &pts) } ShapeKind::Star => { let pts: Vec<(f32, f32)> = (0..10) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 92315bc598..146a6c0c39 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -426,6 +426,9 @@ fn shapes_have_paths() { ShapeKind::Star, ShapeKind::Heart, ShapeKind::Arrow, + ShapeKind::ArrowLeft, + ShapeKind::ArrowUp, + ShapeKind::ArrowDown, ShapeKind::Line, ShapeKind::Diamond, ShapeKind::Triangle, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 285df4bfdc..e5c416eef8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1228,17 +1228,13 @@ pub fn shape_path(kind: ShapeKind, r: kurbo::Rect, corner: Option) -> BezPa p.line_to((r.x1, r.y1)); p } - ShapeKind::Arrow => { - let h = r.height(); - poly(&[ - (r.x0, cy - h * 0.2), - (r.x1 - h * 0.5, cy - h * 0.2), - (r.x1 - h * 0.5, r.y0), - (r.x1, cy), - (r.x1 - h * 0.5, r.y1), - (r.x1 - h * 0.5, cy + h * 0.2), - (r.x0, cy + h * 0.2), - ]) + ShapeKind::Arrow | ShapeKind::ArrowLeft | ShapeKind::ArrowUp | ShapeKind::ArrowDown => { + let (w, h) = (r.width(), r.height()); + let pts: Vec<(f64, f64)> = wordcraft_doc::wrap::arrow_outline(kind, w as f32, h as f32) + .iter() + .map(|&(u, v)| (r.x0 + f64::from(u) * w, r.y0 + f64::from(v) * h)) + .collect(); + poly(&pts) } ShapeKind::Star => { let mut pts = Vec::new(); @@ -2288,9 +2284,18 @@ mod tests { #[test] fn shapes_have_paths() { let r = kurbo::Rect::new(0.0, 0.0, 10.0, 10.0); - for k in - [ShapeKind::Rectangle, ShapeKind::Ellipse, ShapeKind::FlowchartOr, ShapeKind::Star, ShapeKind::Heart, ShapeKind::Arrow, ShapeKind::Line] - { + for k in [ + ShapeKind::Rectangle, + ShapeKind::Ellipse, + ShapeKind::FlowchartOr, + ShapeKind::Star, + ShapeKind::Heart, + ShapeKind::Arrow, + ShapeKind::ArrowLeft, + ShapeKind::ArrowUp, + ShapeKind::ArrowDown, + ShapeKind::Line, + ] { assert!(!shape_path(k, r, None).elements().is_empty()); } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ccf8a9c16c..499c52b225 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -201,8 +201,19 @@ pub struct CanvasState { pub(crate) tab_drag: Option, /// Whether the I-beam over the page is drawn rather than the system's (`ibeam`). pub(crate) drawn_ibeam: bool, + /// The rows and columns hovered in Insert › Table's grid this frame: the page shows that + /// table where it would go (#3931). Set by the grid each frame, taken by [`show`]. + pub(crate) table_preview: Option<(usize, usize)>, + /// The last previewed table's layout, the copy of the document it was laid out from and the + /// copy's selection, with + /// what it was laid out for (rows, columns, document id, revision, selection, and the + /// document's own layout, which a view change replaces), so a still pointer doesn't lay the + /// document out every frame. Set only while the page shows the preview. + table_preview_layout: Option<(TablePreviewKey, wordcraft_doc::Document, wordcraft_engine::Selection, std::sync::Arc)>, } +type TablePreviewKey = ((usize, usize, u64, u64, wordcraft_engine::Selection), std::sync::Arc); + impl CanvasState { /// Stop a text-selection drag when the pointer gesture becomes an object drag. pub(crate) fn cancel_text_drag(&mut self) { @@ -313,6 +324,8 @@ impl Default for CanvasState { tab_kind: Default::default(), tab_drag: None, drawn_ibeam: crate::ibeam::DRAWN, + table_preview: None, + table_preview_layout: None, } } } @@ -940,6 +953,47 @@ fn drawing_grid_step(spacing: f32, scale: f32) -> f32 { /// Draw the document canvas in the space `ui` has left, one frame: the pages, caret, selection /// and rulers, with the mouse editing and the pointer shape over them. +/// The layout the page shows: the document's own, or with the table Insert › Table's grid is +/// hovering over (#3931). The preview is laid out on a copy, so the document and its undo history +/// change only when a square is clicked. +fn shown_layout(app: &mut WordApp) -> std::sync::Arc { + let Some((rows, cols)) = app.canvas.table_preview.take() else { + app.canvas.table_preview_layout = None; + return app.session.layout(); + }; + // The caret can move, or the view change, with the grid still hovered: the table then goes + // somewhere else, or the page is laid out to another width. + let key = ((rows, cols, app.session.document_id(), app.session.rev(), app.session.sel.clone()), app.session.layout()); + if let Some((k, _, _, l)) = &app.canvas.table_preview_layout + && k.0 == key.0 + && std::sync::Arc::ptr_eq(&k.1, &key.1) + { + return l.clone(); + } + match app.session.preview_layout("insert.table", &json!({"rows": rows, "cols": cols})) { + Some((doc, sel, l)) => { + app.canvas.table_preview_layout = Some((key, doc, sel, l.clone())); + l + } + None => { + app.canvas.table_preview_layout = None; + app.session.layout() + } + } +} + +/// The document the pages of [`shown_layout`] are drawn from: the previewed copy while the page +/// shows Insert › Table's preview, whose paragraph paths are the layout's (#3931). +fn page_doc(app: &WordApp) -> &wordcraft_doc::Document { + app.canvas.table_preview_layout.as_ref().map_or(&app.session.doc, |(_, doc, _, _)| doc) +} + +/// The previewed copy's selection while the page shows Insert › Table's preview: the caret and +/// selection are drawn from it, as the document's own name other places in the preview's layout. +fn preview_sel(app: &WordApp) -> Option<&wordcraft_engine::Selection> { + app.canvas.table_preview_layout.as_ref().map(|(_, _, sel, _)| sel) +} + pub fn show(app: &mut WordApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let full = ui.available_rect_before_wrap(); @@ -1001,7 +1055,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { app.canvas.alt_code.clear(); } crate::ink::replay_tick(app, ui.ctx()); - let layout = app.session.layout(); + let layout = shown_layout(app); if let Some(anchor) = reflow_anchor && let Some(page) = reading_anchor_page(&layout, &anchor) { @@ -1089,7 +1143,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { } } // Where the selection really ends, also when it took whole table cells. - let caret = layout.caret_on(&app.session.sel_ends().focus, app.session.page_hint); + let caret = layout.caret_on(&preview_sel(app).unwrap_or(app.session.sel_ends()).focus, app.session.page_hint); // Editing a header/footer (or a note) dims the body; once per frame, for every page. let dim_body = dims_body(app, &layout); if let Some(c) = caret @@ -1278,7 +1332,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { opts.hinting &= hinted; // Only on the page it is on: the `Pos` can't match an object of another page. opts.display.hide_object = hidden.as_ref().filter(|(page, _)| *page == i).map(|(_, p)| p.clone()); - let img = wordcraft_render::render_page(&app.session.doc, page, scale_px, &opts); + let img = wordcraft_render::render_page(page_doc(app), page, scale_px, &opts); let ci = page_image(&img); match app.canvas.textures.get_mut(&i) { Some((k, tex)) => { @@ -1338,7 +1392,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { // The tiny subtraction avoids a 1px overshoot from round-tripping f32 // pixels through page points and render_area's ceil() conversion. let img = wordcraft_render::render_area( - &app.session.doc, + page_doc(app), page, 0.0, start_px as f32 / scale_px, @@ -1461,8 +1515,9 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { } else { balloons(app, ui, &painter, &rects, &layout, geo.scale, view_rect); } - // Find › Reading Highlight. - let marks: Vec<(Pos, Pos)> = app.session.find_highlights().iter().take(5000).cloned().collect(); + // Find › Reading Highlight. Its places are the document's, not the preview's. + let marks: Vec<(Pos, Pos)> = + if preview_sel(app).is_some() { Vec::new() } else { app.session.find_highlights().iter().take(5000).cloned().collect() }; for (a, b) in &marks { for (pi, r) in layout.selection_rects(&app.session.doc, a, b, app.session.page_hint) { if let Some(pr) = rects.get(pi) { @@ -1475,7 +1530,14 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { // Selection (a selected object shows its frame instead): whole table cells shade the // cells (an empty one too), a column selection each row's piece, text running into or // across a table the whole cells of the rows it takes. - let selected: Vec<_> = if crate::objects::selected(app).is_some() { + let selected: Vec<_> = if let Some(sel) = preview_sel(app) { + let (a, b) = sel.ordered(); + if a == b { + Vec::new() + } else { + wordcraft_engine::cmd::table_mouse::selection_rects(&layout, page_doc(app), &a, &b, app.session.page_hint) + } + } else if crate::objects::selected(app).is_some() { Vec::new() } else if let Some(range) = app.session.cell_range() { wordcraft_engine::cmd::table_mouse::cell_rects(&layout, &app.session.doc, range) @@ -1589,7 +1651,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { } } if !math_caret - && let Some(c) = layout.caret_on(&app.session.sel.focus, app.session.page_hint) + && let Some(c) = layout.caret_on(&preview_sel(app).unwrap_or(&app.session.sel).focus, app.session.page_hint) && let Some(pr) = rects.get(c.page) { let scale = layout.pages.get(c.page).map_or(geo.scale, |page| page_screen_scale(*pr, page, geo.scale)); @@ -1642,7 +1704,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) { [pos2(x.round() + 0.5, y0), pos2(x.round() + 0.5, y1)] }; // The caret glides and fades like Word's (`caret_glide`). - let shown = app.session.sel.is_collapsed() && focused; + let shown = preview_sel(app).unwrap_or(&app.session.sel).is_collapsed() && focused; let look = crate::caret_glide::look(app, ui, content_origin, &geo, bar, shown, since, on); if shown && look.opacity > 0.0 { let color = preedit_color.unwrap_or_else(|| caret_color(app)); @@ -3676,6 +3738,89 @@ mod tests { use super::*; use crate::table_resize::tests::{H, cell, screen, steps, table_window}; + /// #3931: while Insert › Table's grid asks for a preview the page is laid out with that + /// table; the document, its revision and undo history stay as they were, and without a + /// request the page is the document's own again. + #[test] + fn the_page_shows_the_table_the_grid_previews() { + let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default()); + let cells = |l: &DocLayout| l.index.keys().filter(|(st, p)| *st == StoryRef::Body && p.0.len() == 4).count(); + let (doc, rev) = (app.session.doc.clone(), app.session.rev()); + app.canvas.table_preview = Some((2, 3)); + assert_eq!(cells(&shown_layout(&mut app)), 6); + assert_eq!(app.canvas.table_preview, None, "a request lasts one frame"); + assert_eq!((&app.session.doc, app.session.rev(), app.session.can_undo()), (&doc, rev, false)); + app.canvas.table_preview = Some((2, 3)); + let again = shown_layout(&mut app); + app.canvas.table_preview = Some((2, 3)); + assert!(std::sync::Arc::ptr_eq(&again, &shown_layout(&mut app)), "a still pointer reuses the preview"); + assert_eq!(cells(&shown_layout(&mut app)), 0, "no request: the document's own page"); + } + + /// #3931 review: the preview's pages are drawn from the copy they were laid out from. The + /// table moves "Kites" down a block, so the document's own block there is not its paragraph. + #[test] + fn the_previewed_pages_are_drawn_from_the_previewed_document() { + let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns\nKites")), crate::Services::default()); + app.session.run("caret.end", &json!({})).unwrap(); + app.canvas.table_preview = Some((2, 2)); + let layout = shown_layout(&mut app); + let text = |doc: &wordcraft_doc::Document, story, path| doc.para(story, path).map(|p| p.text.clone()); + let mut kites = 0; + for it in layout.pages.iter().flat_map(|p| &p.items) { + let Placed::Lines { story, path, .. } = it else { continue }; + let shown = text(page_doc(&app), *story, path); + assert!(shown.is_some(), "{path:?} names a paragraph of the drawn document"); + kites += usize::from(shown.as_deref() == Some("Kites")); + } + assert_eq!(kites, 1, "Kites is drawn as itself"); + assert_eq!(shown_layout(&mut app).index, app.session.layout().index); + assert!(std::ptr::eq(page_doc(&app), &app.session.doc), "no preview: the document's own pages"); + } + + /// #3931 review: with a selection the table replaces it in the copy, so the page draws the + /// copy's caret, in the table, and no selection: the document's selection names text that has + /// moved in the preview's layout. + #[test] + fn the_preview_draws_the_copy_caret_and_selection() { + let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns\nKites")), crate::Services::default()); + app.session.sel = wordcraft_engine::Selection { anchor: Pos::body(0, 3), focus: Pos::body(1, 2) }; + app.canvas.table_preview = Some((2, 2)); + let layout = shown_layout(&mut app); + let sel = preview_sel(&app).expect("the preview's selection").clone(); + assert!(sel.is_collapsed(), "the table took the selection's place"); + assert_ne!(sel, app.session.sel); + let c = layout.caret_on(&sel.focus, 0).expect("the caret is on the preview's page"); + assert!(layout.pages[c.page].items.iter().any(|it| matches!(it, Placed::Lines { path, .. } if path.0.len() == 4 && *path == sel.focus.path))); + assert!(sel.focus.path.cell().is_some(), "the caret is in the table"); + assert_eq!(shown_layout(&mut app).index, app.session.layout().index); + assert!(preview_sel(&app).is_none(), "no preview: the document's own selection"); + } + + /// #3931 review: the preview is laid out again when the caret moves or the view changes with + /// the grid still hovered, so the page shows the table where a click would put it, at the + /// view's width. + #[test] + fn the_preview_follows_the_caret_and_the_view() { + let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns\nKites")), crate::Services::default()); + let tables = + |l: &DocLayout| l.index.keys().filter(|(st, p)| *st == StoryRef::Body && p.0.len() == 4).map(|(_, p)| p.0[0]).collect::>(); + app.session.run("caret.docEnd", &json!({})).unwrap(); + app.canvas.table_preview = Some((2, 2)); + let at_end = tables(&shown_layout(&mut app)); + app.session.run("caret.docStart", &json!({})).unwrap(); + app.canvas.table_preview = Some((2, 2)); + let at_start = tables(&shown_layout(&mut app)); + assert_ne!(at_start, at_end, "the caret moved: so did the table"); + let (_, _, fresh) = app.session.preview_layout("insert.table", &json!({"rows": 2, "cols": 2})).unwrap(); + assert_eq!(at_start, tables(&fresh)); + app.session.view.mode = wordcraft_layout::ViewMode::Web; + app.session.view.web_width = 300.0; + app.canvas.table_preview = Some((2, 2)); + let web = shown_layout(&mut app); + assert_eq!(web.pages[0].w, app.session.layout().pages[0].w, "laid out at the Web view's width"); + } + /// A window-following layout size (#1876, Read Mode): applied at once on entry or when forced, /// held while the window is dragged, applied once the size has been still for the settle time. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7dddc372a1..34c8f18ef1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -326,9 +326,61 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>) -> Value { let _ = (&png, path); #[cfg(not(target_arch = "wasm32"))] { - if let Err(e) = std::fs::write(path, &png) { - return json!({"ok": false, "error": format!("{path}: {e}")}); + if !path.to_ascii_lowercase().ends_with(".png") { + return json!({"ok": false, "error": format!("{path}: a screenshot path must end in .png")}); + } + if let Err(e) = wordcraft_engine::io::write_file(path, &png) { + return json!({"ok": false, "error": e}); } } json!({"ok": true, "result": {"path": path, "width": w, "height": h}}) } + +#[cfg(test)] +mod screenshot_tests { + use super::save_screenshot; + + struct Cleanup(std::path::PathBuf); + + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn screenshot_path_must_be_png_and_does_not_follow_symlinks() { + let dir = std::env::temp_dir().join(format!("wc-shot-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let _cleanup = Cleanup(dir.clone()); + let img = egui::ColorImage::filled([2, 2], egui::Color32::RED); + + let txt = dir.join("shot.txt"); + let r = save_screenshot(&img, txt.to_str()); + assert_eq!(r["ok"], false); + assert!(!txt.exists()); + + let png = dir.join("shot.png"); + let r = save_screenshot(&img, png.to_str()); + assert_eq!(r["ok"], true); + assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG")); + + #[cfg(unix)] + { + let victim = dir.join("victim.txt"); + std::fs::write(&victim, "keep").unwrap(); + let link = dir.join("link.png"); + std::os::unix::fs::symlink(&victim, &link).unwrap(); + let _ = save_screenshot(&img, link.to_str()); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep"); + } + + let other = dir.join("other"); + std::fs::create_dir_all(&other).unwrap(); + let roots = wordcraft_engine::file_access::AutomationRoots::new(None, Some(&other)).unwrap(); + let outside = dir.join("outside.png"); + let r = wordcraft_engine::file_access::confine(roots.as_ref(), || save_screenshot(&img, outside.to_str())); + assert_eq!(r["ok"], false); + assert!(!outside.exists()); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2135b50036..35ef212353 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -315,6 +315,8 @@ pub enum Dialog { offset: f32, /// The selection already has a phonetic guide (Remove is offered). existing: bool, + /// Ask the Ruby text box for the keyboard on the first frame (once, so Tab and clicks still move it). + focus: bool, }, NewStyle { name: String, @@ -1208,6 +1210,7 @@ impl Dialog { size: f("size"), offset: f("offset"), existing: v.get("existing").and_then(Value::as_bool).unwrap_or(false), + focus: true, } } "newStyle" => Dialog::NewStyle { name: "Style1".into(), based_on: "Normal".into(), back: false }, @@ -1353,7 +1356,7 @@ impl Dialog { } } -/// Grid picker for Insert › Table (hover to size, click to insert). +/// Grid picker for Insert › Table (hover to size and preview on the page, click to insert). pub fn table_grid_picker(ui: &mut Ui, app: &mut WordApp) { let t = Tokens::get(ui.ctx()); let id = egui::Id::new("table_picker_hover"); @@ -1388,9 +1391,16 @@ pub fn table_grid_picker(ui: &mut Ui, app: &mut WordApp) { } }); ui.data_mut(|d| d.insert_temp(id, new_hover)); + if new_hover != hover { + // The page may already be drawn this frame (Focus drops the ribbon over it afterwards). + ui.ctx().request_repaint(); + } if let Some((r, c)) = clicked { let _ = app.run("insert.table", json!({"rows": r, "cols": c})); ui.close(); + } else if new_hover.0 > 0 { + // Word's Live Preview: the page shows the hovered table until a square is clicked. + app.canvas.table_preview = Some(new_hover); } } @@ -1935,14 +1945,11 @@ fn body(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { mixed, .. } => { - ui.horizontal(|ui| { - for (k, name) in ["Indents and Spacing", "Line and Page Breaks", "Asian Typography"].into_iter().enumerate() { - if ui.selectable_label(*tab as usize == k, tl!(name)).clicked() { - *tab = k as u8; - } - } - }); - ui.separator(); + let names = ["Indents and Spacing", "Line and Page Breaks", "Asian Typography"].map(|n| tl!(n).to_string()); + if let Some(k) = crate::widgets::dialog_tabs(ui, &names, *tab as usize) { + *tab = k as u8; + } + ui.add_space(6.0); match *tab { 0 => { ui.label(egui::RichText::new(tl!("General")).font(semibold(12.5))); @@ -2040,15 +2047,14 @@ fn body(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { Dialog::Tabs { form } => crate::dialogs_para::tabs(app, ui, form), Dialog::Borders { form } => crate::dialogs_para::borders(app, ui, form), Dialog::Find { query, replace, match_case, whole_word, regex, extra, tab, goto_what, goto_target, message, focus } => { - ui.horizontal(|ui| { - for (t, label) in [(FindTab::Find, "Find"), (FindTab::Replace, "Replace"), (FindTab::GoTo, "Go To")] { - if ui.selectable_label(*tab == t, tl!(label)).clicked() && *tab != t { - *tab = t; - message.clear(); - } - } - }); - ui.separator(); + const FIND_TABS: [(FindTab, &str); 3] = [(FindTab::Find, "Find"), (FindTab::Replace, "Replace"), (FindTab::GoTo, "Go To")]; + let names = FIND_TABS.map(|(_, l)| tl!(l).to_string()); + let current = FIND_TABS.iter().position(|(t, _)| t == tab).unwrap_or(0); + if let Some((t, _)) = crate::widgets::dialog_tabs(ui, &names, current).and_then(|k| FIND_TABS.get(k)) { + *tab = *t; + message.clear(); + } + ui.add_space(6.0); if *tab == FindTab::GoTo { return goto_body(app, ui, goto_what, goto_target, message); } @@ -2491,7 +2497,7 @@ fn body(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { } ok || cancel } - Dialog::Phonetic { base, ruby, align, size, offset, existing } => { + Dialog::Phonetic { base, ruby, align, size, offset, existing, focus } => { // Base and ruby text are usually Chinese or Japanese: fonts for them load from the next frame. app.want_system_cjk = true; const ALIGNS: [(&str, &str); 6] = [ @@ -2507,7 +2513,11 @@ fn body(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { ui.label(egui::RichText::new(base.as_str()).strong()); ui.end_row(); ui.label(tl!("Ruby text:")); - ui.text_edit_singleline(ruby); + let r = ui.text_edit_singleline(ruby); + // Typing goes to the Ruby text box, not the selected text in the document (#3914). + if std::mem::take(focus) { + r.request_focus(); + } ui.end_row(); ui.label(tl!("Alignment:")); let shown = ALIGNS.iter().find(|(k, _)| k == align).map_or("Center", |(_, l)| l); @@ -2699,15 +2709,11 @@ fn body(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { } Dialog::About { tab } => { ui.set_width(660.0); - ui.horizontal(|ui| { - for (i, l) in ["About", "Contributors", "Models"].into_iter().enumerate() { - let i = i as u8; - if ui.selectable_label(*tab == i, tl!(l)).clicked() { - *tab = i; - } - } - }); - ui.separator(); + let names = ["About", "Contributors", "Models"].map(|n| tl!(n).to_string()); + if let Some(i) = crate::widgets::dialog_tabs(ui, &names, *tab as usize) { + *tab = i as u8; + } + ui.add_space(6.0); match *tab { 1 => crate::credits::contributors_ui(ui), 2 => crate::credits::models_ui(ui), @@ -4107,6 +4113,44 @@ mod tests { use wordcraft_doc::props::Align; use wordcraft_engine::Session; + /// #3931: hovering Insert › Table's grid asks the page for a preview of that table (rows by + /// columns) and changes nothing; leaving the grid drops it; a click inserts the table with no + /// preview left over for the page to show on top of it. + #[test] + fn the_table_grid_previews_the_hovered_table_until_the_click() { + use egui_kittest::kittest::Queryable; + let a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default()); + let mut h = + egui_kittest::Harness::builder().with_size(vec2(400.0, 400.0)).build_ui_state(|ui, app: &mut WordApp| table_grid_picker(ui, app), a); + h.run_steps(2); + let spacing = h.ctx.global_style().spacing.clone(); + let top = h.get_by_label("Insert Table").rect(); + // Squares are 16 points with 2 between, in grid columns at least `interact_size` wide: + // the middle of row 3, column 4. + let col = spacing.interact_size.x.max(16.0) + 2.0; + let at = egui::pos2(top.left() + 3.0 * col + 8.0, top.bottom() + spacing.item_spacing.y + 2.0 * 18.0 + 8.0); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(2); + assert_eq!(h.state().canvas.table_preview, Some((3, 4)), "three rows of four columns"); + assert!(h.query_by_label("4×3 Table").is_some(), "the label reads columns × rows"); + assert!(h.state().session.doc.body.iter().all(|b| b.as_table().is_none()) && !h.state().session.can_undo()); + h.event(egui::Event::PointerMoved(egui::pos2(390.0, 390.0))); + h.state_mut().canvas.table_preview = None; + h.run_steps(2); + assert_eq!(h.state().canvas.table_preview, None, "off the grid nothing is previewed"); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(2); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + // The page takes the request every frame; here nothing does. + h.state_mut().canvas.table_preview = None; + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.step(); + let t = h.state().session.doc.body.iter().find_map(|b| b.as_table()).expect("the click inserts the table"); + assert_eq!((t.rows.len(), t.cols()), (3, 4)); + assert_eq!(h.state().canvas.table_preview, None, "the inserted table isn't previewed again"); + } + /// Go To's page box (#712): a number, +n / -n from the current page (a typographic minus /// too), empty for the next page; anything else is refused. #[test] @@ -4311,6 +4355,30 @@ mod tests { assert_eq!(serde_json::to_value(&h.state().session.doc).unwrap(), before, "search does not change the document"); } + /// #3914: the Phonetic Guide dialog opens with the keyboard in its Ruby text box, so typing + /// fills the box and does not replace the selected text in the document. + #[test] + fn phonetic_guide_ruby_box_takes_the_keyboard_on_open() { + let mut app = app_with("Unchanged document"); + app.dialog = Some(Dialog::Phonetic { + base: "Unchanged".into(), + ruby: String::new(), + align: "center".into(), + size: 12.0, + offset: 0.0, + existing: false, + focus: true, + }); + let mut h = app_harness(app); + h.run_steps(4); + h.event(egui::Event::Text("ab".into())); + h.run_steps(2); + match h.state().dialog.as_ref() { + Some(Dialog::Phonetic { ruby, .. }) => assert_eq!(ruby, "ab", "the typed text reaches the Ruby text box"), + _ => panic!("the Phonetic Guide dialog is still open"), + } + } + /// #2986: a box that keeps the keyboard asks for focus only while it lacks it. `request_focus` /// always interrupts IME; on X11 that recreates the XIM context, and Search asking every frame /// left fcitx taking no keys at all. Once the box has focus, no frame interrupts, and typing lands; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 26996c2561..4d6bbc4bf9 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1299,6 +1299,48 @@ pub fn icon_menu_item(ui: &mut Ui, icon: &str, text: &str, shortcut: &str, min_w resp } +/// A strip of dialog tabs. The active tab joins the page below it. +/// Returns the index of the tab the user clicked. +pub fn dialog_tabs(ui: &mut Ui, labels: &[String], selected: usize) -> Option { + const H: f32 = 26.0; + let t = Tokens::get(ui.ctx()); + let page = ui.visuals().window_fill; + let need: f32 = labels.iter().map(|l| ui.painter().layout_no_wrap(l.clone(), regular(12.5), t.text).size().x + 27.0).sum::() + 1.0; + ui.set_min_width(need); + let origin = ui.cursor().min; + let width = ui.available_width(); + let base_y = origin.y + H; + let base = ui.painter().add(egui::Shape::Noop); + let top = CornerRadius { nw: 5, ne: 5, sw: 0, se: 0 }; + let mut x = origin.x; + let mut clicked = None; + for (i, label) in labels.iter().enumerate() { + let on = i == selected; + let galley = ui.painter().layout_no_wrap(label.clone(), regular(12.5), t.text); + let w = galley.size().x + 28.0; + let r = Rect::from_min_max(pos2(x, origin.y + 2.0), pos2(x + w, base_y)); + let resp = ui.interact(r, ui.id().with(("dialog_tab", i)), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, on, label)); + let hover = ui.ctx().animate_bool_responsive(resp.id.with("hover"), resp.hovered()); + let fill = if on { page } else { page.lerp_to_gamma(t.border, 0.14 + 0.1 * hover) }; + let p = ui.painter(); + let shown = if on { r } else { Rect::from_min_max(pos2(r.min.x, r.min.y + 2.0), r.max) }; + p.rect(shown, top, fill, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + if on { + p.rect_filled(Rect::from_min_max(pos2(r.min.x + 1.0, base_y - 1.0), pos2(r.max.x - 1.0, base_y + 1.0)), 0.0, page); + } + let color = if on { t.text } else { t.text.gamma_multiply(0.8) }; + p.galley(pos2(r.center().x - galley.size().x / 2.0, r.center().y - galley.size().y / 2.0), galley, color); + if resp.clicked() && !on { + clicked = Some(i); + } + x += w - 1.0; + } + ui.allocate_space(vec2(width, H + 1.0)); + ui.painter().set(base, egui::Shape::line_segment([pos2(origin.x, base_y), pos2(origin.x + width, base_y)], Stroke::new(1.0, t.border))); + clicked +} + #[cfg(test)] mod tests { use super::*; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2662e3488c..2e72fc6fe5 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-10-23 · **Change:** trivial (dark-theme interface text on Linux and the BSDs no longer looks semi-bold; previously trivial: page text on Linux and the BSDs is hinted like FreeType's hintslight; 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-10-23 · **Change:** trivial (dark-theme interface text on Linux and the BSDs no longer looks semi-bold; previously trivial: page text on Linux and the BSDs is hinted like FreeType's hintslight; previously trivial: Insert › Table's grid previews the hovered table on the page, #3931; 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 Recovery discovery no longer interrupts an explicitly created or opened document. Older copies remain in File › Recover, whose buttons use the interface palette. See [local recovery](recovery.md). @@ -78,6 +78,7 @@ Footnote and endnote editing keeps body and note text at normal opacity, on ligh | Date | Change | Summary | |---|---|---| +| 2026-10-23 | trivial | Insert › Table: hovering the grid shows the table on the page, at the caret, as Word's Live Preview does; it follows the pointer and is laid out on a copy, so the document and Undo change only when a square is clicked (#3931) | | 2026-10-22 | trivial | Mail merge: First Record, Last Record, a record number box, and record choices for Edit Individual Documents and Print Documents (#3028) | | 2026-10-22 | trivial | While editing a header, a single click in the footer (or the reverse, or another page's own header) edits that one with the caret where clicked; the click was placed in the header being edited, and the view scrolled back to it, so a double-click on the footer rarely landed | | 2026-10-18 | trivial | Explicit New/Open is not interrupted by startup recovery discovery; older copies stay available and Recover follows the interface theme. |