Merge upstream/main into PR #2596

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76
2026-11-08 05:19:14 +01:00
co-authored by Claude Opus 5.5
55 changed files with 1666 additions and 118 deletions
+17 -1
View File
File diff suppressed because one or more lines are too long
+7
View File
@@ -14,6 +14,10 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.SenuraMalaka]
real_name = "Senura Dissanayake"
sync_github_name = true
[people.divyanshu2074]
real_name = "Divyanshu Gupta"
sync_github_name = true
@@ -197,3 +201,6 @@ display_name = "entropybeater"
[people.helenkwok]
real_name = "Helen Kwok"
[people.ashokram-si]
real_name = "Ashok Ram"
+23
View File
@@ -186,6 +186,11 @@ pub struct Float {
/// top. 0 = unknown, drawn in document order (objects inserted here, or from other formats).
#[serde(skip_serializing_if = "is_zero_u32")]
pub z: u32,
/// Turned, but the file keeps no room for the turn (`wp:effectExtent` missing or zero, as
/// files from other tools have): Word then keeps an inline one's line to its frame and lets
/// the turned object overhang it (see [`Float::line_pad`]). Cleared by [`Float::set_spin`].
#[serde(skip_serializing_if = "is_false")]
pub bare_turn: bool,
}
/// Longest alternative text kept (characters): hostile files and commands are capped.
@@ -241,6 +246,7 @@ impl Float {
self.rot = wordcraft_geom::normalize_degrees(s.deg);
self.flip_h = s.flip_h;
self.flip_v = s.flip_v;
self.bare_turn = false;
}
/// How far a `w` × `h` frame's rotated bounds reach past it on each side (x, y): the room a
/// rotated object takes beyond its frame (zero unrotated; negative where the turned object
@@ -250,6 +256,23 @@ impl Float {
let (bw, bh) = self.spin().extent(w, h);
((bw - w) / 2.0, (bh - h) / 2.0)
}
/// A [`Float::bare_turn`] still inline and without effects room: made floating, or given room
/// for a shadow or glow since, it saves, and so lays out, with the turn's room again.
pub fn is_bare_turn(&self) -> bool {
self.bare_turn && self.wrap == Wrap::Inline && self.effect_extent() == [0.0; 4]
}
/// The room an inline `w` × `h` object's line keeps past its frame on each side (x, y) for its
/// turn: its rotated bounds ([`Float::spin_pad`]) — or, for a [`Float::is_bare_turn`], none, except
/// that Word 2013+ layout (`modern`) exchanges the frame's width and height from 45° up to 135°
/// and from 225° up to 315°.
pub fn line_pad(&self, w: f32, h: f32, modern: bool) -> (f32, f32) {
if !self.is_bare_turn() {
return self.spin_pad(w, h);
}
let (w, h) = (wordcraft_geom::finite(w).clamp(0.0, 4000.0), wordcraft_geom::finite(h).clamp(0.0, 4000.0));
let deg = wordcraft_geom::normalize_degrees(self.rot);
if modern && ((45.0..135.0).contains(&deg) || (225.0..315.0).contains(&deg)) { ((h - w) / 2.0, (w - h) / 2.0) } else { (0.0, 0.0) }
}
/// The effect extents, finite and clamped (left, top, right, bottom).
pub fn effect_extent(&self) -> [f32; 4] {
self.effect.map(|v| if v.is_finite() { v.clamp(0.0, 1584.0) } else { 0.0 })
+2 -1
View File
@@ -27,7 +27,8 @@ pub use char_props::{
};
pub use color::{Rgb, TextColor};
pub use para_props::{
Align, Border, BorderStyle, Borders, LineSpacing, NumRef, ParaProps, TAB_POS_EPS, TabAlign, TabLeader, TabStop, TextAlignment, TextFrame,
Align, Border, BorderStyle, Borders, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, TAB_POS_EPS, TabAlign, TabLeader, TabStop,
TextAlignment, TextFrame,
};
pub use table_props::{
CellPicture, CellProps, HeightRule, PictureRepeat, RowProps, TableFloat, TableLook, TableProps, TextDirection, TextVert, VAlign, VMerge,
+65
View File
@@ -26,6 +26,67 @@ impl Align {
}
}
/// Paragraph-level text flow (`w:pPr/w:textDirection`, ECMA-376 §17.3.1.41).
///
/// Kept separate from [`super::TextDirection`], whose three values model the table-cell direction
/// control. These values preserve the exact OOXML direction through JSON and DOCX saves.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ParagraphTextDirection {
LrTb,
LrTbV,
Tb,
TbRl,
TbRlV,
TbLr,
TbLrV,
BtLr,
TbV,
Rl,
RlV,
Lr,
LrV,
}
impl ParagraphTextDirection {
pub fn from_ooxml(value: &str) -> Option<Self> {
match value {
"lrTb" => Some(Self::LrTb),
"lrTbV" => Some(Self::LrTbV),
"tb" => Some(Self::Tb),
"tbRl" => Some(Self::TbRl),
"tbRlV" => Some(Self::TbRlV),
"tbLr" => Some(Self::TbLr),
"tbLrV" => Some(Self::TbLrV),
"btLr" => Some(Self::BtLr),
"tbV" => Some(Self::TbV),
"rl" => Some(Self::Rl),
"rlV" => Some(Self::RlV),
"lr" => Some(Self::Lr),
"lrV" => Some(Self::LrV),
_ => None,
}
}
pub fn ooxml(self) -> &'static str {
match self {
Self::LrTb => "lrTb",
Self::LrTbV => "lrTbV",
Self::Tb => "tb",
Self::TbRl => "tbRl",
Self::TbRlV => "tbRlV",
Self::TbLr => "tbLr",
Self::TbLrV => "tbLrV",
Self::BtLr => "btLr",
Self::TbV => "tbV",
Self::Rl => "rl",
Self::RlV => "rlV",
Self::Lr => "lr",
Self::LrV => "lrV",
}
}
}
/// Vertical alignment of characters of different sizes on a line (`w:textAlignment`,
/// ECMA-376 §17.3.1.39).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -391,6 +452,9 @@ pub struct ParaProps {
pub suppress_line_numbers: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bidi: Option<bool>,
/// Paragraph text direction (`w:textDirection`); `None` inherits from the paragraph style.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_direction: Option<ParagraphTextDirection>,
/// Drop cap: lines to drop (0 = none) — applies to the first character(s).
#[serde(skip_serializing_if = "Option::is_none")]
pub drop_cap: Option<u8>,
@@ -462,6 +526,7 @@ impl ParaProps {
}
fn overlay_script_layout(&mut self, patch: &ParaProps) {
overlay_fields!(self, patch; bidi, text_direction, kinsoku, word_wrap, overflow_punct, top_line_punct, auto_space_de, auto_space_dn);
overlay_fields!(self, patch; bidi, kinsoku, word_wrap, overflow_punct, top_line_punct, auto_space_de, auto_space_dn, text_alignment);
}
pub fn overlaid(mut self, patch: &ParaProps) -> ParaProps {
+3
View File
@@ -260,6 +260,9 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) ->
};
let mut doc = Document::new();
// Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default
// 15 would apply Word 2013+ justification and line-breaking rules to them.
doc.settings.compat_mode = 11;
if let Some(core) = metadata::read(&mut comp) {
doc.core = core;
}
+9
View File
@@ -337,6 +337,15 @@ fn empty_document_gets_a_paragraph() {
assert_eq!(doc.body.len(), 1);
}
#[test]
fn a_doc_opens_in_word_97_2003_compatibility_mode() {
let f = text_doc(&[Piece { compressed: false, text: "body\r".into() }], &[], 0);
let doc = read(&f).expect("opens");
// Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and
// line breaking.
assert_eq!(doc.settings.compat_mode, 11);
}
#[test]
fn header_text_stays_out_of_body() {
let f = text_doc(
+3 -2
View File
@@ -5,8 +5,8 @@ use std::collections::HashMap;
use wordcraft_doc::para::cap_alt;
use wordcraft_doc::props::{
Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, LineSpacing, NumRef,
ParaProps, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextAlignment, TextColor, TextDirection, Underline,
VAlign, VMerge, VertAlign,
ParaProps, ParagraphTextDirection, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextAlignment, TextColor,
TextDirection, Underline, VAlign, VMerge, VertAlign,
};
use wordcraft_doc::section::{
Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, MAX_CHAR_SPACE, MAX_GRID_PITCH, NotePos, NoteProps, NoteRestart, NumFormat,
@@ -338,6 +338,7 @@ impl PropCtx {
"w:suppressAutoHyphens" => p.suppress_hyphens = Some(on_off(k)),
"w:suppressLineNumbers" => p.suppress_line_numbers = Some(on_off(k)),
"w:bidi" => p.bidi = Some(on_off(k)),
"w:textDirection" => p.text_direction = k.attr("w:val").and_then(ParagraphTextDirection::from_ooxml),
"w:kinsoku" => p.kinsoku = Some(on_off(k)),
"w:wordWrap" => p.word_wrap = Some(on_off(k)),
"w:overflowPunct" => p.overflow_punct = Some(on_off(k)),
+5
View File
@@ -41,6 +41,7 @@ impl Reader<'_> {
}
let source = self.keep_embedded(c.child("a:graphic")?, rels, &[])?;
float.set_spin(xfrm_spin(content.child("w14:xfrm")));
float.bare_turn = !anchored && float.rot != 0.0 && float.effect == [0.0; 4];
let (px, py) = float.spin_pad(w, h);
for (e, p) in float.effect.iter_mut().zip([px, py, px, py]) {
if *e != 0.0 {
@@ -106,7 +107,11 @@ impl Reader<'_> {
self.set_shape_id(&mut obj, c.child("wp:docPr").and_then(|p| p.attr("id")));
// Word's effect extent also covers a rotated object's overhang; the model keeps that
// apart (it follows from the angle), so take it back out.
// Shadow or glow room the file didn't record: saving records it (and the turn's room).
let fx_room = matches!(&obj, InlineObject::Shape { effects, .. } if effects.extent() != [0.0; 4]);
if let Some(f) = obj.float_mut() {
// None recorded: Word keeps an inline one's line to the frame (see `Float::bare_turn`).
f.bare_turn = !anchored && !fx_room && f.rot != 0.0 && f.effect == [0.0; 4];
let (px, py) = f.spin_pad(w, h);
for (e, p) in f.effect.iter_mut().zip([px, py, px, py]) {
// Zero adds no effects room when rotation contracts this axis.
+9
View File
@@ -224,6 +224,15 @@ impl Reader<'_> {
{
let id = self.read_textbox(sc, t, rels);
if let Some(part) = self.doc.parts.get_mut(&id) {
// Text direction (#5193), as Word reads it: `mso-layout-flow-alt:bottom-to-top` is
// `vert270` whatever `layout-flow` says; otherwise `layout-flow:vertical…` (also
// `vertical-ideographic`, our `eaVert`) is `vert`, and anything else horizontal.
let tb_style = tb.attr("style").unwrap_or("");
if vml_style(tb_style, "mso-layout-flow-alt").is_some_and(|v| v.eq_ignore_ascii_case("bottom-to-top")) {
part.body.vert = wordcraft_doc::props::TextVert::Vert270;
} else if vml_style(tb_style, "layout-flow").is_some_and(|v| v.to_ascii_lowercase().starts_with("vertical")) {
part.body.vert = wordcraft_doc::props::TextVert::Vert;
}
// Internal margins `inset="l,t,r,b"` (ECMA-376 Part 4 §19.1.2.22), each one left
// out keeping Word's default; a bare number is in EMUs, VML's base unit.
// `o:insetmode="auto"` leaves them to the application.
+3 -2
View File
@@ -499,8 +499,9 @@ impl super::Writer<'_> {
}
}
"wp:effectExtent" => {
// Word's effect extent also covers a rotated object's overhang (its rotated bounds).
let (px, py) = float.spin_pad(w, h);
// Word's effect extent also covers a rotated object's overhang (its rotated bounds),
// unless the file it came from kept none.
let (px, py) = if float.is_bare_turn() { (0.0, 0.0) } else { float.spin_pad(w, h) };
let [el, et, er, eb] = float.effect_extent();
let ext = [el + px, et + py, er + px, eb + py].map(emu);
e.attrs.retain(|(k, _)| !matches!(k.as_str(), "l" | "t" | "r" | "b"));
+3
View File
@@ -287,6 +287,9 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha
if let Some(a) = p.align {
w.val("w:jc", align_val(a));
}
if let Some(direction) = p.text_direction {
w.val("w:textDirection", direction.ooxml());
}
if let Some(t) = p.text_alignment {
w.val("w:textAlignment", t.ooxml());
}
+3 -2
View File
@@ -298,8 +298,9 @@ impl Writer<'_> {
}
}
w.empty("wp:extent", &[("cx", &cx), ("cy", &cy)]);
// Word's effect extent also covers a rotated object's overhang (its rotated bounds).
let (px, py) = float.spin_pad(iw, ih);
// Word's effect extent also covers a rotated object's overhang (its rotated bounds), unless
// the file it came from kept none.
let (px, py) = if float.is_bare_turn() { (0.0, 0.0) } else { float.spin_pad(iw, ih) };
let [el, et, er, eb] = float.effect_extent();
let [el, et, er, eb] = [el + px, et + py, er + px, eb + py].map(emu);
w.empty("wp:effectExtent", &[("l", &el), ("t", &et), ("r", &er), ("b", &eb)]);
+48
View File
@@ -4354,6 +4354,54 @@ fn zero_effects_stay_zero_rotated() {
}
}
/// A turned picture whose file keeps no room for the turn (no or a zero `wp:effectExtent`) is
/// marked so its line keeps to its frame as in Word, and saves that way; one with the room keeps
/// its rotated bounds.
#[test]
fn bare_turns_are_kept_through_a_save() {
let pic = |effects: &str| {
format!(
r#"<w:p><w:r><w:drawing><wp:inline><wp:extent cx="1524000" cy="762000"/>{effects}<wp:docPr id="1" name="Synthetic picture"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm rot="2700000"><a:off x="0" y="0"/><a:ext cx="1524000" cy="762000"/></a:xfrm></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
)
};
let read =
|body: &str| wordcraft_docx::read(&docx(body, &[("rId1", "image", "media/marker.png")], &[("word/media/marker.png", "synthetic")])).unwrap();
let bare = |d: &Document| paras(d)[0].objects[0].frame().unwrap().2.bare_turn;
for effects in ["", r#"<wp:effectExtent l="0" t="0" r="0" b="0"/>"#] {
let d = read(&pic(effects));
assert!(bare(&d), "{effects:?}");
let out = wordcraft_docx::write(&d).unwrap();
let body = text(&unzip(&out), "word/document.xml");
assert_eq!(attr_values(&body, "wp:effectExtent", "t"), ["0"]);
assert!(bare(&wordcraft_docx::read(&out).unwrap()));
}
// 120 × 60 pt at 45°: Word's rotated-bounds room, 3.64 pt wider and 33.64 pt taller each side.
let d = read(&pic(r#"<wp:effectExtent l="46210" t="427210" r="46210" b="427210"/>"#));
assert!(!bare(&d));
let mut d = read(&pic(""));
let f = first_object(&mut d).float_mut().unwrap();
f.set_spin(wordcraft_geom::Spin::new(30.0, false, false));
assert!(!f.bare_turn, "turned here: the rotated bounds again");
// A shadow's room added later: saved, and so laid out, with the turn's room again.
let mut d = read(&pic(""));
let f = first_object(&mut d).float_mut().unwrap();
f.effect = [2.0; 4];
assert!(!f.is_bare_turn());
let out = wordcraft_docx::write(&d).unwrap();
assert_ne!(attr_values(&text(&unzip(&out), "word/document.xml"), "wp:effectExtent", "t"), ["0"]);
// Made floating: saved with the turn's room, so it opens again as an ordinary turn.
let mut d = read(&pic(""));
let f = first_object(&mut d).float_mut().unwrap();
f.wrap = wordcraft_doc::para::Wrap::Square;
assert!(!f.is_bare_turn());
let out = wordcraft_docx::write(&d).unwrap();
assert_ne!(attr_values(&text(&unzip(&out), "word/document.xml"), "wp:effectExtent", "t"), ["0"]);
assert!(!bare(&wordcraft_docx::read(&out).unwrap()));
// Only inline ones: a floating one keeps text clear of its rotated bounds as before.
let anchored = pic("").replace("<wp:inline>", "<wp:anchor>").replace("</wp:inline>", "</wp:anchor>");
assert!(!bare(&read(&anchored)));
}
/// The math namespace, declared on the math element itself (the fixture root doesn't).
const M_NS: &str = r#"xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math""#;
+3 -2
View File
@@ -6,8 +6,8 @@ use wordcraft_doc::fill::Fill;
use wordcraft_doc::numbering::ListKind;
use wordcraft_doc::para::{Anchor, Float, FloatAlign, NoteKind, ShapeKind, Wrap};
use wordcraft_doc::props::{
Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, Rgb, RowProps, TabAlign, TabLeader,
TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign,
Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, RowProps,
TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign,
};
use wordcraft_doc::section::{Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, NumFormat, PageVAlign, SectionProps, SectionStart};
use wordcraft_doc::styles::{Style, StyleKind};
@@ -195,6 +195,7 @@ fn every_para_prop_round_trips() {
suppress_hyphens: Some(true),
suppress_line_numbers: Some(true),
bidi: Some(false),
text_direction: Some(ParagraphTextDirection::TbRl),
drop_cap: None,
drop_cap_margin: None,
drop_cap_distance: None,
@@ -18,6 +18,25 @@ fn docx(body: &str) -> Vec<u8> {
zw.finish().unwrap().into_inner()
}
fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
let mut bytes = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let document_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
for (name, value) in [
("_rels/.rels", root.as_bytes()),
("word/_rels/document.xml.rels", document_rels.as_bytes()),
("word/document.xml", doc.as_bytes()),
("word/styles.xml", styles.as_bytes()),
] {
bytes.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
bytes.write_all(value).unwrap();
}
bytes.finish().unwrap().into_inner()
}
fn document_xml(bytes: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut s = String::new();
@@ -59,3 +78,52 @@ fn explicit_horizontal_direction_is_kept_in_sections_and_cells() {
let plain = wordcraft_docx::read(&docx(r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr/>"#)).unwrap();
assert!(!document_xml(&wordcraft_docx::write(&plain).unwrap()).contains("textDirection"));
}
#[test]
fn paragraph_text_direction_round_trips_through_two_saves_and_json() {
use wordcraft_doc::props::ParaProps;
use wordcraft_doc::props::ParagraphTextDirection;
let values = ["lrTb", "lrTbV", "tb", "tbRl", "tbRlV", "tbLr", "tbLrV", "btLr", "tbV", "rl", "rlV", "lr", "lrV"];
let mut body: String =
values.iter().map(|value| format!(r#"<w:p><w:pPr><w:textDirection w:val="{value}"/></w:pPr><w:r><w:t>{value}</w:t></w:r></w:p>"#)).collect();
body.push_str(r#"<w:p><w:r><w:t>Inherited</w:t></w:r></w:p>"#);
let d = wordcraft_docx::read(&docx(&body)).unwrap();
let paras: Vec<_> = d.body.iter().filter_map(|b| b.as_para()).collect();
for (para, value) in paras.iter().zip(values) {
assert_eq!(para.props.text_direction, ParagraphTextDirection::from_ooxml(value), "{value}");
}
assert_eq!(paras[values.len()].props.text_direction, None);
let json = serde_json::to_value(&paras[0].props).unwrap();
assert_eq!(json["textDirection"], "lrTb");
let decoded: ParaProps = serde_json::from_value(json).unwrap();
assert_eq!(decoded.text_direction, Some(ParagraphTextDirection::LrTb));
let first = wordcraft_docx::write(&d).unwrap();
let xml = document_xml(&first);
for value in values {
assert!(xml.contains(&format!(r#"<w:textDirection w:val="{value}"/>"#)), "{xml}");
}
assert_eq!(xml.matches("w:textDirection").count(), values.len(), "inherited direction stays absent: {xml}");
let second = wordcraft_docx::write(&wordcraft_docx::read(&first).unwrap()).unwrap();
let twice = document_xml(&second);
assert_eq!(twice.matches("w:textDirection").count(), values.len(), "{twice}");
for value in values {
assert!(twice.contains(&format!(r#"<w:textDirection w:val="{value}"/>"#)), "{twice}");
}
}
#[test]
fn paragraph_style_text_direction_is_preserved_and_direct_value_overrides_it() {
let styles = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:styleId="Vertical"><w:name w:val="Vertical"/><w:pPr><w:textDirection w:val="tbRl"/></w:pPr></w:style></w:styles>"#;
let body = r#"<w:p><w:pPr><w:pStyle w:val="Vertical"/></w:pPr><w:r><w:t>Style</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Vertical"/><w:textDirection w:val="lrTb"/></w:pPr><w:r><w:t>Override</w:t></w:r></w:p>"#;
let d = wordcraft_docx::read(&docx_with_styles(body, styles)).unwrap();
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
assert_eq!(xml.matches(r#"<w:pStyle w:val="Vertical"/>"#).count(), 2, "both paragraphs keep their style: {xml}");
assert!(xml.contains(r#"<w:pStyle w:val="Vertical"/><w:textDirection w:val="lrTb"/>"#), "direct horizontal is explicit: {xml}");
assert_eq!(xml.matches("w:textDirection").count(), 1, "only the direct paragraph writes a direction: {xml}");
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
let mut styles_xml = String::new();
z.by_name("word/styles.xml").unwrap().read_to_string(&mut styles_xml).unwrap();
assert!(styles_xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "style value survives: {styles_xml}");
}
+12 -1
View File
@@ -132,6 +132,15 @@ fn vml_text_boxes_keep_their_inset_fit_and_anchor() {
shape("", r#"o:insetmode="auto" inset="0,0,0,0""#),
// In a group, a member's margins go with that member's text, not an empty box's before it.
format!(r#"<w:p><w:r><w:pict><v:group style="width:100pt;height:40pt"><v:shape><v:textbox inset="9pt,9pt,9pt,9pt"/></v:shape><v:shape><v:textbox inset="0,0,0,0">{content}</v:textbox></v:shape></v:group></w:pict></w:r></w:p>"#),
// Text direction (#5193), as Word for Windows reads it: `vertical` and
// `vertical-ideographic` are `vert`; a `bottom-to-top` alt is `vert270` with any
// `layout-flow` or none; `horizontal-ideographic` stays horizontal.
shape("", r#"style="layout-flow:vertical""#),
shape("", r#"style="layout-flow:vertical;mso-layout-flow-alt:bottom-to-top;mso-next-textbox:#Text Box 4""#),
shape("", r#"style="layout-flow:vertical-ideographic""#),
shape("", r#"style="mso-layout-flow-alt:bottom-to-top""#),
shape("", r#"style="layout-flow:horizontal;mso-layout-flow-alt:bottom-to-top""#),
shape("", r#"style="layout-flow:horizontal-ideographic""#),
]
.concat();
let doc = format!(
@@ -140,13 +149,15 @@ fn vml_text_boxes_keep_their_inset_fit_and_anchor() {
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let d = wordcraft_docx::read(&zip(&[("_rels/.rels", rels), ("word/document.xml", doc.as_bytes())])).unwrap();
let bodies: Vec<TextBody> = boxes(&d).iter().map(|id| d.parts[id].body).collect();
assert_eq!(bodies.len(), 6);
assert_eq!(bodies.len(), 12);
assert_eq!(bodies[0].inset, Some([0, 0, 0, 0]));
assert_eq!((bodies[1].inset, bodies[1].auto_fit, bodies[1].anchor), (Some([36_000, 45_720, 25_400, 45_720]), true, VAlign::Center));
assert_eq!(bodies[2], TextBody::default());
assert_eq!((bodies[3].inset, bodies[3].anchor), (Some([12_700, 45_720, 0, wordcraft_doc::MAX_TEXT_BOX_INSET]), VAlign::Bottom));
assert_eq!(bodies[4].inset, None);
assert_eq!(bodies[5].inset, Some([0, 0, 0, 0]));
let verts: Vec<TextVert> = bodies[6..].iter().map(|b| b.vert).collect();
assert_eq!(verts, [TextVert::Vert, TextVert::Vert270, TextVert::Vert, TextVert::Vert270, TextVert::Vert270, TextVert::Horz]);
// Saved and read again, they stay.
let back = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
let again: Vec<TextBody> = boxes(&back).iter().map(|id| back.parts[id].body).collect();
+13 -4
View File
@@ -102,7 +102,9 @@ struct SeqCount {
/// The fresh results of the unlocked SEQ fields in the body and in the text boxes anchored there
/// ([`update_seq`]). A text box's fields count where the box is anchored, before the fields after
/// the anchor in its paragraph and after those before it (measured in Word for Windows).
/// the anchor in its paragraph and after those before it (measured in Word for Windows). A locked
/// SEQ keeps its result but still counts, `\r` included; a SEQ in a tracked deletion keeps its
/// result and doesn't count, with markup shown or not (measured in Word for Windows, exporting).
fn seq_results(doc: &wordcraft_doc::Document) -> Vec<FieldResult> {
let mut count = SeqCount::default();
for path in doc.para_paths(StoryRef::Body) {
@@ -120,7 +122,11 @@ fn seq_results(doc: &wordcraft_doc::Document) -> Vec<FieldResult> {
/// Number the SEQ fields of paragraph `p` (at `path` in `story`) and of the text boxes anchored in it.
fn count_seq(doc: &wordcraft_doc::Document, story: StoryRef, path: &Path, p: &Paragraph, count: &mut SeqCount) {
for (k, o) in p.objects.iter().enumerate() {
// The runs come in order and the objects by offset, so one cursor walks the deleted ranges.
let mut deleted = p.deleted_ranges().into_iter().peekable();
for (k, (off, o)) in p.objects_with_offsets().enumerate() {
while deleted.next_if(|r| r.end <= off).is_some() {}
let in_deletion = deleted.peek().is_some_and(|r| r.contains(&off));
for id in o.text_boxes() {
if count.boxes.insert(id) {
let part = StoryRef::Part(id);
@@ -131,9 +137,9 @@ fn count_seq(doc: &wordcraft_doc::Document, story: StoryRef, path: &Path, p: &Pa
}
}
}
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
let InlineObject::Field { instr, locked, .. } = o else { continue };
let f = FieldCode::parse(instr);
if f.name != "SEQ" {
if f.name != "SEQ" || in_deletion {
continue;
}
let Some(id) = f.args.first() else { continue };
@@ -149,6 +155,9 @@ fn count_seq(doc: &wordcraft_doc::Document, story: StoryRef, path: &Path, p: &Pa
} else if !f.has('c') {
n.0 = n.0.saturating_add(1);
}
if *locked {
continue;
}
let fmt = wordcraft_layout::fields::format_switch(instr).unwrap_or_default();
let r = if f.has('h') { String::new() } else { wordcraft_layout::fields::field_number(instr, fmt, n.0) };
count.out.push((story, path.clone(), k, r));
+39
View File
@@ -793,6 +793,45 @@ fn output_shows_references_to_bookmarks_outside_the_body() {
assert_eq!(results, expected);
}
/// Printed or exported, a locked SEQ keeps its result but still counts, its `\r` too, and a SEQ
/// in a tracked deletion keeps its result and doesn't count (measured in Word for Windows,
/// exporting with markup shown and hidden: Del 1, 9, 2; Lock 1, 7, 3; R 7, 6).
#[test]
fn output_counts_locked_seq_fields_and_not_deleted_ones() {
let mut s = Session::new(wordcraft_doc::Document::from_text(""));
let fields_in = ["SEQ Del", "SEQ Del", "SEQ Del", "SEQ Lock", "SEQ Lock", "SEQ Lock", "SEQ R \\r 5", "SEQ R"];
for instr in fields_in {
s.run("insert.field", &json!({"instr": instr, "result": "9"})).unwrap();
s.run("text.insert", &json!({"text": " "})).unwrap();
}
let top = wordcraft_doc::Path::top(0);
let para = s.doc.para_mut(StoryRef::Body, &top).unwrap();
for (k, o) in para.objects.iter_mut().enumerate() {
if let InlineObject::Field { result, locked, .. } = o {
*locked = matches!(k, 4 | 6);
*result = if *locked { "7" } else { "9" }.into();
}
}
para.touch();
// The second Del field is a tracked deletion.
let off = s.doc.para(StoryRef::Body, &top).unwrap().object_offsets()[1];
let at = |off| Pos { story: StoryRef::Body, path: top.clone(), off };
s.doc.format_range(&at(off), &at(off + '\u{FFFC}'.len_utf8()), &|c| c.del = Some(1)).unwrap();
let out = output_fields(&s.doc).expect("the stale results change");
let shown: Vec<String> = out
.para(StoryRef::Body, &top)
.unwrap()
.objects
.iter()
.filter_map(|o| match o {
InlineObject::Field { result, .. } => Some(result.clone()),
_ => None,
})
.collect();
assert_eq!(shown, ["1", "9", "2", "1", "7", "3", "7", "6"]);
assert!(fields(&s).iter().all(|f| f.1 == "9" || f.1 == "7"), "the document keeps its results");
}
/// Printed or exported, a REF to a bookmark the document doesn't have shows Word's error
/// (measured in Word for Windows: "Error! Reference source not found."); the editor and the
/// document keep the stored result, and a REF showing "above" or "below" (`\p`) keeps it too.
+14 -5
View File
@@ -54,11 +54,20 @@ fn resolve_para(
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
// of a story or cell can't go, so it just stops being a revision.
if ((del.is_some() && accept) || (ins.is_some() && !accept))
&& (crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)?)
{
return Ok(());
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
// mark carries a section break goes whole too: its section joins the following one, as when
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
if (del.is_some() && accept) || (ins.is_some() && !accept) {
let sectioned = story == StoryRef::Body
&& path.0.len() == 1
&& s.doc.para(story, path).is_some_and(|p| p.is_empty() && p.section.is_some())
&& crate::cmd::has_next_para(s, story, path);
if sectioned {
s.doc.remove_section_break(path.last());
}
if crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)? {
return Ok(());
}
}
let para = s.doc.para_mut(story, path)?;
para.mark.ins = None;
+2 -2
View File
@@ -771,8 +771,8 @@ pub fn list_dir(path: &std::path::Path, max: usize) -> Result<(Vec<DirEntry>, bo
#[cfg(not(target_arch = "wasm32"))]
pub fn package_title(path: &std::path::Path, max_file: u64, max_part: u64) -> Option<String> {
crate::file_access::check_read(&path.to_string_lossy()).ok()?;
let file = std::fs::File::open(path).ok()?;
if file.metadata().ok()?.len() > max_file {
let (file, meta) = open_regular_file(path).ok()?;
if meta.len() > max_file {
return None;
}
wordcraft_docx::package_title(std::io::BufReader::new(file), max_part)
+2 -2
View File
@@ -390,7 +390,7 @@ impl Session {
let at = self.others.iter().position(|d| d.document_id == id).ok_or_else(|| unknown(id))?;
let mut d = self.others.swap_remove(at);
self.swap_doc(&mut d);
self.view.read_page_color = self.prefs.read_page_color;
self.view.follow_prefs(&self.prefs);
self.others.push(d);
Ok(())
}
@@ -471,7 +471,7 @@ impl Session {
doc.ensure_nonempty();
let mut view = self.view.clone();
view.outline.collapsed.clear();
view.read_page_color = self.prefs.read_page_color;
view.follow_prefs(&self.prefs);
let mut d = DocState::new(doc, untitled, view);
let id = d.document_id;
self.order.push(id);
+1 -1
View File
@@ -32,7 +32,7 @@ impl Session {
self.hf_return = None;
self.go_back_step = 0;
self.view.outline.collapsed.clear();
self.view.read_page_color = self.prefs.read_page_color;
self.view.follow_prefs(&self.prefs);
// A copy the replaced document kept stays in the recovery list.
#[cfg(not(target_arch = "wasm32"))]
{
+1 -1
View File
@@ -135,7 +135,7 @@ impl Session {
let current = document_id == self.document_id && rev == self.rev;
self.sel = sel;
self.view = view;
self.view.read_page_color = self.prefs.read_page_color;
self.view.follow_prefs(&self.prefs);
self.pending = pending;
self.goal_x = goal_x;
self.page_hint = page_hint;
+78
View File
@@ -5747,6 +5747,39 @@ fn opening_a_named_pipe_or_device_is_refused_without_blocking() {
assert!(device.unwrap_err().contains("not a file"));
}
#[cfg(unix)]
#[test]
fn reading_a_template_title_from_a_named_pipe_is_refused_without_blocking() {
let dir = scratch_dir("template-title-fifo");
let fifo = dir.join("pipe.dotx");
let made = std::process::Command::new("mkfifo").arg(&fifo).status();
if !made.is_ok_and(|s| s.success()) {
let _ = std::fs::remove_dir_all(&dir);
eprintln!("mkfifo unavailable; skipping");
return;
}
let (tx, rx) = std::sync::mpsc::channel();
let path = fifo.clone();
std::thread::spawn(move || {
let title = crate::io::package_title(&path, 64 << 20, 64 << 10);
let _ = tx.send(title);
});
let result = rx.recv_timeout(std::time::Duration::from_secs(10));
if result.is_err() {
// Unblock a stuck reader so the test thread can finish.
let _ = std::os::unix::fs::OpenOptionsExt::custom_flags(std::fs::OpenOptions::new().write(true), libc::O_NONBLOCK).open(&fifo);
}
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(result.expect("reading a template title blocked on a named pipe"), None);
}
#[cfg(unix)]
#[test]
fn html_picture_that_is_a_named_pipe_is_skipped_without_blocking() {
@@ -12787,3 +12820,48 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.sel.focus.path.0[0] > 6, "Page Down extends the selection a page on: {:?}", s.sel.focus);
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
/// Issue #5667's document: `Intro`, then an inserted `Appendix` paragraph whose mark carries a
/// section break (Normal, indented), then `Body` in Heading 1. The whole of `Appendix` is
/// tracked as an insertion by `rev`, or as a deletion when `delete`.
fn sectioned_revision(delete: bool) -> Session {
use wordcraft_doc::{Revision, RevisionKind};
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAppendix\nBody"));
run(&mut s, "caret.set", json!({"pos": {"block": 2, "off": 0}}));
run(&mut s, "para.style", json!({"style": "Heading1"}));
let kind = if delete { RevisionKind::Delete } else { RevisionKind::Insert };
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None });
s.doc.last_section.margin_left = 72.0;
let mut sect = s.doc.last_section.clone();
sect.margin_left = 144.0;
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![1])).unwrap();
let len = p.len();
p.format(0, len, &|c| if delete { c.del = Some(0) } else { c.ins = Some(0) }).unwrap();
if delete {
p.mark.del = Some(0)
} else {
p.mark.ins = Some(0)
}
p.props.indent_left = Some(36.0);
p.section = Some(Box::new(sect));
s
}
#[test]
fn resolving_away_an_empty_paragraph_with_a_section_break_keeps_the_next_paragraphs_properties() {
// #5667: the resolved paragraph was left empty but kept for its section break, so the next
// paragraph joined it and took its properties (Normal, its indent). It goes whole instead,
// as an empty paragraph without a break does, and its section joins the following one.
for (delete, cmd) in [(false, "review.rejectAll"), (true, "review.acceptAll")] {
let mut s = sectioned_revision(delete);
assert_eq!(s.doc.sections().len(), 2);
run(&mut s, cmd, json!({}));
assert_eq!(body_texts(&s), ["Intro", "Body"], "{cmd}");
let body = s.doc.para(StoryRef::Body, &wordcraft_doc::Path(vec![1])).unwrap();
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "{cmd}: Body keeps its style");
assert_eq!(body.props.indent_left, None, "{cmd}: and not the removed paragraph's indent");
assert!(s.doc.body.iter().filter_map(|b| b.as_para()).all(|p| p.section.is_none()), "{cmd}: the break went with it");
assert_eq!(s.doc.sections().len(), 1, "{cmd}");
assert_eq!(s.doc.last_section.margin_left, 72.0, "{cmd}: the following section's setup stays");
}
}
+48
View File
@@ -346,3 +346,51 @@ fn input_method_joins_stay_with_their_window() {
assert_eq!(text(&s).trim(), "Hello", "B's typing is its own undo step");
drop(a);
}
/// Check spelling as you type is one setting for the app, not one per open document (#5740):
/// turned off (File › Options › Proofing, or Review's command) with one document active, it is off
/// in the others too, and switching to another document doesn't turn it back on, so what is saved
/// for the next run is what was chosen, whichever document is active then.
#[test]
fn check_spelling_is_one_setting_for_every_open_document() {
let mut s = s();
let a = s.document_id();
run(&mut s, "file.new", json!({}));
let b = s.document_id();
run(&mut s, "file.new", json!({}));
let c = s.document_id();
assert!(s.view.proofing);
s.activate(a).unwrap();
run(&mut s, "file.options", json!({"checkSpelling": false}));
for id in [b, c, a] {
s.activate(id).unwrap();
assert!(!s.view.proofing, "off in document {id}");
assert!(!s.prefs.check_spelling);
}
run(&mut s, "review.proofing", json!({"value": true}));
for id in [b, c] {
s.activate(id).unwrap();
assert!(s.view.proofing, "back on in document {id}");
}
// A document opened now starts with the setting as it is.
run(&mut s, "review.proofing", json!({"value": false}));
run(&mut s, "file.new", json!({}));
assert!(!s.view.proofing);
}
/// A window's view put back after Check spelling as you type changed in another window takes the
/// setting as it is now, not as it was when the window's view was taken (#5740): every view made
/// active follows the saved preference.
#[test]
fn a_window_view_put_back_follows_the_spelling_setting() {
let mut s = s();
assert!(s.view.proofing);
let held = s.take_view();
run(&mut s, "file.options", json!({"checkSpelling": false}));
s.put_view(held);
assert!(!s.view.proofing, "the view taken with spelling on comes back with it off");
let held = s.take_view();
run(&mut s, "review.proofing", json!({"value": true}));
s.put_view(held);
assert!(s.view.proofing);
}
+11
View File
@@ -161,6 +161,17 @@ fn default_read_zoom() -> f32 {
1.0
}
impl ViewState {
/// Take the app-wide settings a view keeps a copy of from the saved preferences: Read Mode's
/// page colour and Check spelling as you type (#5740). A view made active goes through this
/// (a document switched to, opened or made, a window's view put back), so a change made while
/// another view was active holds in this one too.
pub(crate) fn follow_prefs(&mut self, prefs: &crate::prefs::Prefs) {
self.read_page_color = prefs.read_page_color;
self.proofing = prefs.check_spelling;
}
}
impl Default for ViewState {
fn default() -> Self {
ViewState {
+21
View File
@@ -427,6 +427,27 @@ mod tests {
const RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#;
#[test]
fn workbook_sheets_find_their_relationships_by_index() {
// Every sheet searched every relationship; 4,096 sheets over 20,000 relationships.
let sheets: String = (0..MAX_SHEETS).map(|i| format!(r#"<sheet name="S{i}" sheetId="{i}" r:id="rId{i}"/>"#)).collect();
let wb = format!(
r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>{sheets}</sheets></workbook>"#
);
let mut rels = String::from(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
// A chart sheet sharing a worksheet's id doesn't hide it.
rels.push_str(r#"<Relationship Id="rId0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/c.xml"/>"#);
for i in 0..20_000 {
rels.push_str(&format!(
r#"<Relationship Id="rId{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{i}.xml"/>"#
));
}
rels.push_str("</Relationships>");
let names = sheet_names(&zip(&[("_rels/.rels", RELS), ("xl/workbook.xml", &wb), ("xl/_rels/workbook.xml.rels", &rels)])).unwrap();
assert_eq!(names.len(), MAX_SHEETS);
assert_eq!(names.first().map(String::as_str), Some("S0"));
}
fn xlsx(sheet1: &str) -> Vec<u8> {
let wb = r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><workbookPr/><sheets><sheet name="People" sheetId="1" r:id="rId1"/><sheet name="Chart" sheetId="2" r:id="rId9"/><sheet name="Notes" sheetId="3" r:id="rId2"/></sheets></workbook>"#;
let wb_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="/xl/worksheets/sheet2.xml"/><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet1.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
+7 -8
View File
@@ -83,14 +83,13 @@ fn workbook(pkg: &mut Package<'_>) -> Result<Workbook, String> {
}
}
});
let sheets = listed
.into_iter()
.filter_map(|(name, id)| {
// Worksheets only: chart and dialog sheets hold no cells.
let r = rels.iter().find(|r| r.id == id && r.kind.ends_with("/worksheet"))?;
Some(SheetRef { name, path: r.target.clone() })
})
.collect();
// Worksheets only: chart and dialog sheets hold no cells. Indexed by id once (the first
// relationship with an id wins), not searched for every sheet.
let mut worksheets: HashMap<&str, &str> = HashMap::new();
for r in rels.iter().filter(|r| r.kind.ends_with("/worksheet")) {
worksheets.entry(r.id.as_str()).or_insert(r.target.as_str());
}
let sheets = listed.into_iter().filter_map(|(name, id)| Some(SheetRef { name, path: worksheets.get(id.as_str())?.to_string() })).collect();
let part = |suffix: &str| rels.iter().find(|r| r.kind.ends_with(suffix)).map(|r| r.target.clone());
Ok(Workbook { sheets, date1904, shared: part("/sharedStrings"), styles: part("/styles") })
}
+12 -1
View File
@@ -637,9 +637,20 @@ fn inline_objects(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
}
let cx = x + line.cl_left(k).unwrap_or(0.0);
let obj = para.and_then(|p| p.objects.get(oi));
let rect = inline_rect(obj, cx, base, c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k));
let modern = doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT;
let rect = inline_rect(obj, cx, base, c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern);
let spin = obj.and_then(InlineObject::frame).map(|(_, _, f)| f.spin()).unwrap_or_default();
match obj {
// A turn its line keeps no room for overhangs the line; Word cuts it at the line's top
// and bottom, not at its sides.
Some(o @ (InlineObject::Image { .. } | InlineObject::Shape { .. } | InlineObject::Group { .. }))
if o.frame().is_some_and(|(w, h, f)| f.is_bare_turn() && f.spin_pad(w, h).1 > f.line_pad(w, h, modern).1 + 0.01) =>
{
let mut items = Vec::new();
object_draws(o, rect, Spin::default(), alpha, opts, &mut items);
let band = Rect::new(rect.x - 4000.0, ctx.top, rect.w + 8000.0, (ctx.bottom - ctx.top).max(0.0));
out.push(Draw::Clip { rect: band, items });
}
Some(o @ (InlineObject::Image { .. } | InlineObject::Shape { .. } | InlineObject::Group { .. })) => {
object_draws(o, rect, Spin::default(), alpha, opts, out)
}
+5 -4
View File
@@ -487,8 +487,9 @@ pub(crate) fn effects_in(effects: wordcraft_doc::effects::ShapeEffects, spin: Sp
/// `obj_h` above the baseline and `obj_d` below it): inside the room kept for its effects.
/// A rotated one's unrotated frame, centred in that room.
///
/// `line` is the room a horizontal rule is placed in, from `cx`.
pub(crate) fn inline_rect(obj: Option<&InlineObject>, cx: f32, base: f32, adv: f32, (obj_h, obj_d): (f32, f32), line: f32) -> Rect {
/// `line` is the room a horizontal rule is placed in, from `cx`; `modern`: Word 2013+ layout
/// (see [`wordcraft_doc::para::Float::line_pad`]).
pub(crate) fn inline_rect(obj: Option<&InlineObject>, cx: f32, base: f32, adv: f32, (obj_h, obj_d): (f32, f32), line: f32, modern: bool) -> Rect {
let frame = obj.and_then(InlineObject::frame);
let [l, t, r, b] = frame.map_or([0.0; 4], |(_, _, float)| float.effect_extent());
// Lowered further than its height, it is drawn with its top on the baseline (Word).
@@ -503,9 +504,9 @@ pub(crate) fn inline_rect(obj: Option<&InlineObject>, cx: f32, base: f32, adv: f
return Rect::new(hr.left(room.x, line, rw), room.y, rw, room.h);
}
let Some((w, h, float)) = frame.filter(|(_, _, f)| f.rot != 0.0) else { return room };
// The room is the rotated bounds of the frame: undo the rotation.
// The room is what the line kept for the turned frame: undo that.
let (w, h) = (wordcraft_geom::finite(w).clamp(1.0, 4000.0), wordcraft_geom::finite(h).clamp(1.0, 4000.0));
let (bw, _) = float.spin().extent(w, h);
let bw = w + 2.0 * float.line_pad(w, h, modern).0;
let k = if bw > 0.0 { room.w / bw } else { 1.0 };
let (fw, fh) = (w * k, h * k);
Rect::new(room.x + (room.w - fw) / 2.0, room.y + (room.h - fh) / 2.0, fw, fh)
+2 -1
View File
@@ -751,7 +751,8 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
}
} else {
let cx = x + line.cl_left(k).unwrap_or(0.0);
display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k))
let modern = ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT;
display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern)
};
let (mut behind, mut front) = (Vec::new(), Vec::new());
let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front };
+16 -10
View File
@@ -397,7 +397,7 @@ impl<'a> Shaped<'a> {
// The line makes room for effects (shadows) around the picture too, and
// for a rotated one's bounds, as Word does.
let [el, et, er, eb] = float.effect_extent();
let (px, py) = float.spin_pad(w * s, h * s);
let (px, py) = float.line_pad(w * s, h * s, env.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT);
let tall = h * s + et + eb + 2.0 * py;
// Lowered further than its height, its top stays on the baseline while the line
// reaches as far down as the lowering (Word, measured: a 6 pt picture lowered 30 pt
@@ -837,21 +837,27 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
}
// Word breaks after a hyphen even when a digit follows ("2016-" / "2022"), where UAX #14
// keeps a hyphen and a number together (LB25): add those positions back. Only U+002D before
// ASCII digits is added here; a non-breaking hyphen (U+2011) and a minus sign (U+2212) stay
// unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
// ("Dataprotection-" / "/Secrecyviolation", #3408), where LB13 forbids a break before the
// slash: add those positions back. Word keeps "fitness-/1589" whole, so a slash before a digit
// gains no break. Only U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign
// (U+2212) stay unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
let hyphen_breaks: Vec<usize> = text
.match_indices('-')
.filter_map(|(pos, _)| {
let i = pos + 1;
text.get(i..).and_then(|t| t.chars().next()).is_some_and(|n| n.is_ascii_digit()).then_some(i)
let mut next = text.get(i..).unwrap_or_default().chars();
match next.next() {
Some(n) if n.is_ascii_digit() => Some(i),
Some('/') => next.next().is_some_and(char::is_alphabetic).then_some(i),
_ => None,
}
})
.collect();
if !hyphen_breaks.is_empty() {
found.extend(hyphen_breaks);
found.sort_unstable();
found.dedup();
}
found.extend(hyphen_breaks);
// The breaks added above come after UAX #14's: put them back in order.
found.sort_unstable();
found.dedup();
// Myanmar has no spaces between words: it wraps between syllables.
if text.chars().any(|c| matches!(u32::from(c), 0x1000..=0x109F | 0xA9E0..=0xA9FF | 0xAA60..=0xAA7F)) {
found.extend(wordcraft_doc::cluster::myanmar_breaks(text));
+27 -9
View File
@@ -2,7 +2,7 @@ use std::collections::VecDeque;
use super::cache::{LayoutCache, Totals, env_hash, hash_of};
use super::ctx::{Ctx, Pass, with_pct_base};
use super::floats::{EarlyFloats, WrapArea, early_covered};
use super::floats::{EarlyFloats, WrapArea, early_covered, left_out_objects};
use super::flow::{OutlinePass, place_outline_para, place_para};
use super::headers::{HfLinks, bookmark_pages, headers_footers, headers_footers_refer_to_pages, marks_key, mirror_even_pages, section_side};
use super::notes::{MAX_NOTE_PAGES, NoteSeps, note_info, place_endnotes};
@@ -10,9 +10,10 @@ use super::page::{PageBuilder, body_top_for, foot_top_for, item_bottom};
use super::placed::Placed;
use super::table_flow::place_table;
use super::{
Arc, Block, Counters, DocLayout, Document, FieldCtx, HashMap, LayoutOptions, Page, Path, SectionProps, SectionStart, StoryRef, TextDirection,
ViewMode, balloons, para, vertical,
Arc, Block, Counters, DocLayout, Document, FieldCtx, HashMap, InlineObject, LayoutOptions, Page, Paragraph, Path, SectionProps, SectionStart,
StoryRef, TextDirection, ViewMode, balloons, para, vertical,
};
use wordcraft_doc::legacy_form::LegacyForm;
/// How the view lays the document out: `web` for the continuous views, `reflow` for those and
/// the reading view, which both ignore the sections' page geometry.
@@ -127,18 +128,35 @@ fn section_marks(doc: &Document, opts: &LayoutOptions, sections: &[(usize, &Sect
end.checked_sub(1).and_then(|i| doc.body.get(i)).and_then(|b| b.as_para()).is_some_and(|p| p.section.is_some() && p.text.is_empty())
});
if !opts.show_hidden {
quiet.extend(
doc.body
.iter()
.enumerate()
.filter_map(|(i, b)| b.as_para().filter(|p| p.mark.hidden == Some(true) && p.plain_text().is_empty()).map(|_| i)),
);
quiet.extend(doc.body.iter().enumerate().filter_map(|(i, b)| {
b.as_para().filter(|p| p.mark.hidden == Some(true) && p.plain_text().is_empty() && !has_inline_content(doc, opts, p)).map(|_| i)
}));
}
quiet.sort_unstable();
quiet.dedup();
(stacked, quiet)
}
/// An in-line picture, shape or chart, a note reference mark, or a field shown as something other
/// than its result, is visible content with no plain text, so its line keeps its room even when
/// the paragraph mark is hidden (#5288). Not one the layout leaves out (a hidden drawing, or one
/// in hidden or deleted text).
fn has_inline_content(doc: &Document, opts: &LayoutOptions, p: &Paragraph) -> bool {
let left_out = left_out_objects(doc, p, None, opts.show_hidden, opts.hides_deleted(StoryRef::Body));
// As the paragraph layout shows a field: its code, a legacy check box, a drop-down's entry.
let shown_field = |o: &InlineObject| match o {
InlineObject::Field { code, .. } => {
*code != opts.field_codes
|| o.legacy_form().is_some_and(|f| matches!(f, LegacyForm::CheckBox { .. }) || f.shown_text().is_some_and(|t| !t.is_empty()))
}
_ => false,
};
p.objects
.iter()
.enumerate()
.any(|(k, o)| !left_out(k) && (matches!(o, InlineObject::NoteRef { .. }) || (o.frame().is_some() && !o.is_floating()) || shown_field(o)))
}
/// The page the continuous views lay out on: the first section's, as wide as the window (and as
/// high in the reading view), with small margins and one column.
fn reflow_sect(first: &SectionProps, opts: &LayoutOptions) -> SectionProps {
+62 -7
View File
@@ -94,7 +94,62 @@ fn row_keeps_next(row: &table::RowLayout) -> bool {
.unwrap_or(false)
}
fn row_can_start(row: &wordcraft_doc::Row, laid: &table::RowLayout, room: f32, page_height: f32) -> bool {
/// The cut that leaves every row of a nested table marked "can't split" whole: just below the
/// top of the highest such row the cut at `room` runs through, moved up again while it runs
/// through another one (Word moves such a row on with the rest of the outer row, observed in the
/// docxide-pdf `nested-first-row-*-cant1` cases). Like the split itself, a row "runs through"
/// the cut when it ends below the room left for text there, above the row's bottom band; the cut
/// goes that band below the row's top, so the text and rows ending at its top stay.
/// shortcut: the moved row's side borders and shading keep that band's height on the page, and
/// on the next page its cell area and shading start that band less its top margin below its
/// first line (clicks there miss the cell). Only an explicit bottom cell margin or a thick outer
/// border shows it, never Word's defaults; upgrade with a separate drawing cut in split_row that
/// moves a nested cell starting between the limit and the cut whole from its top.
fn nested_keep_cut(doc: &wordcraft_doc::Document, row: &table::RowLayout, room: f32) -> f32 {
let own = row.items.iter().filter_map(|it| if let Placed::Cell { table, .. } = it { Some(table.0.len()) } else { None }).min();
// Each nested row's top and bottom when it can't split. A vertically merged cell runs past
// its own row, so a row ends where its shortest cell does.
let mut bands: std::collections::BTreeMap<(StoryRef, &[u32], usize), Option<(f32, f32)>> = std::collections::BTreeMap::new();
// The split runs a cell aligned to the middle or bottom from its top: so do its bands.
let mut shift = vec![0.0f32; row.items.len()];
for al in row.cells.iter().filter_map(|c| c.align.as_ref()) {
shift.get_mut(al.content.clone()).into_iter().flatten().for_each(|d| *d = al.dy);
}
for (it, &dy) in row.items.iter().zip(&shift) {
let Placed::Cell { rect, table, row: r, story, .. } = it else { continue };
if Some(table.0.len()) <= own {
continue;
}
let rect = Rect { y: rect.y - dy, ..*rect };
let band = bands
.entry((*story, table.0.as_slice(), *r))
.or_insert_with(|| doc.table(*story, table).and_then(|t| t.rows.get(*r)).filter(|r| r.props.cant_split).map(|_| (rect.y, rect.bottom())));
if let Some((top, bottom)) = band {
*top = top.min(rect.y);
*bottom = bottom.min(rect.bottom());
}
}
let below = row.bottom.clamp(0.0, room.max(0.0));
let mut bands: Vec<(f32, f32)> = bands.into_values().flatten().collect();
// From the lowest top up: once the cut moves up to a row, the rows starting below it are
// wholly under it, and a row the old cut ran through still runs through the new one.
bands.sort_by(|a, b| b.0.total_cmp(&a.0));
let mut cut = room;
for (top, bottom) in bands {
let limit = cut - below;
if top < limit && bottom > limit + 0.01 {
cut = top + below;
}
}
cut
}
/// [`table::split_row_keeping_cells`] that doesn't split a nested "can't split" row either.
fn split_keeping_nested(doc: &wordcraft_doc::Document, row: &table::RowLayout, room: f32) -> Option<(table::RowLayout, table::RowLayout)> {
table::split_row_keeping_cells(row, nested_keep_cut(doc, row, room))
}
fn row_can_start(doc: &wordcraft_doc::Document, row: &wordcraft_doc::Row, laid: &table::RowLayout, room: f32, page_height: f32) -> bool {
if laid.height <= room + 0.01 {
return true;
}
@@ -104,7 +159,7 @@ fn row_can_start(row: &wordcraft_doc::Row, laid: &table::RowLayout, room: f32, p
if row.props.height_rule == HeightRule::AtLeast && row.props.height.is_some_and(|h| h > room + 0.01 && h <= page_height + 0.01) {
return false;
}
table::split_row_keeping_cells(laid, room).is_some()
split_keeping_nested(doc, laid, room).is_some()
}
pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc::Table, block: usize, body_top: f32) {
@@ -187,8 +242,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
{
let room = pb.bottom - pb.y - tl.rows.iter().take(first).map(|r| r.height).sum::<f32>();
let splittable = !t.rows.get(first).is_some_and(|r| r.props.cant_split);
if row.height + row.edge > room + 0.01 && (short_of_min(first, room) || !(splittable && table::split_row_keeping_cells(row, room).is_some()))
{
if row.height + row.edge > room + 0.01 && (short_of_min(first, room) || !(splittable && split_keeping_nested(ctx.doc, row, room).is_some())) {
pb.advance(block, body_top);
}
}
@@ -223,7 +277,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
}
let (Some(next), Some(laid)) = (t.rows.get(end), tl.rows.get(end)) else { return false };
let page_height = pb.bottom - body_top - repeated_height;
height <= page_height + 0.01 && !row_can_start(next, laid, pb.bottom - pb.y - height, page_height)
height <= page_height + 0.01 && !row_can_start(ctx.doc, next, laid, pb.bottom - pb.y - height, page_height)
});
// A row another row follows needs room for the border below it too (measured in Word).
if pb.y + cur.height + cur.edge <= pb.bottom + 0.01 && !defer_kept {
@@ -238,8 +292,9 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
let moves_on = first_part && short_of_min(ri, room);
let split = match (splittable && !moves_on && !defer_kept, first_part) {
(false, _) => None,
(true, true) => table::split_row_keeping_cells(cur, room),
(true, false) => table::split_row(cur, room),
(true, true) => split_keeping_nested(ctx.doc, cur, room),
// On a fresh page, a nested row taller than the room splits rather than overflowing.
(true, false) => table::split_row(cur, nested_keep_cut(ctx.doc, cur, room)).or_else(|| table::split_row(cur, room)),
};
match split {
Some((a, b)) => {
+178 -4
View File
@@ -13,6 +13,7 @@ mod grid;
mod ligature;
pub(crate) mod linear;
mod nbsp;
mod nested_cant_split;
mod numeral;
mod pages;
mod styleref;
@@ -5593,7 +5594,7 @@ fn inline_picture_keeps_room_for_its_effects() {
assert_eq!((c.adv, c.obj_h), (124.0, 89.0), "picture plus effect extents");
// Drawn inside that room.
let obj = picture(100.0, 50.0, shadow);
let r = display::inline_rect(Some(&obj), 10.0, 200.0, c.adv, (c.obj_h, c.obj_d), c.adv);
let r = display::inline_rect(Some(&obj), 10.0, 200.0, c.adv, (c.obj_h, c.obj_d), c.adv, true);
assert_eq!((r.x, r.y, r.w, r.h), (16.0, 123.0, 100.0, 50.0));
}
@@ -5620,22 +5621,67 @@ fn an_inline_picture_moves_with_its_runs_position() {
let (c, line, _) = line_of(-30.0);
assert_eq!((c.obj_h, c.obj_d), (0.0, 30.0));
assert!(line.top + line.height - line.baseline >= 30.0 - 0.01, "{line:?}");
let r = display::inline_rect(Some(&picture(40.0, 30.0, Default::default())), 0.0, 100.0, c.adv, (c.obj_h, c.obj_d), c.adv);
let r = display::inline_rect(Some(&picture(40.0, 30.0, Default::default())), 0.0, 100.0, c.adv, (c.obj_h, c.obj_d), c.adv, true);
assert_eq!((r.y, r.h), (100.0, 30.0));
// Lowered further than that: the line reaches as far down, the picture's top staying on the
// baseline (Word).
let (c, line, _) = line_of(-500.0);
assert_eq!((c.obj_h, c.obj_d), (-470.0, 500.0));
assert!(line.top + line.height - line.baseline >= 500.0 - 0.01, "{line:?}");
let r = display::inline_rect(Some(&picture(40.0, 30.0, Default::default())), 0.0, 100.0, c.adv, (c.obj_h, c.obj_d), c.adv);
let r = display::inline_rect(Some(&picture(40.0, 30.0, Default::default())), 0.0, 100.0, c.adv, (c.obj_h, c.obj_d), c.adv, true);
assert_eq!((r.y, r.h), (100.0, 30.0));
// Raised: it stands clear of the baseline, as tall as before.
let (c, _, _) = line_of(6.0);
assert_eq!((c.obj_h, c.obj_d), (36.0, -6.0));
let r = display::inline_rect(Some(&picture(40.0, 30.0, Default::default())), 0.0, 100.0, c.adv, (c.obj_h, c.obj_d), c.adv);
let r = display::inline_rect(Some(&picture(40.0, 30.0, Default::default())), 0.0, 100.0, c.adv, (c.obj_h, c.obj_d), c.adv, true);
assert_eq!((r.y, r.h), (64.0, 30.0));
}
/// A turned inline picture whose file kept no room for the turn: Word keeps its line to the frame
/// (Word 2007 layout) or to the frame with width and height exchanged near a quarter turn (Word
/// 2013+), and the picture overhangs it. One with room recorded takes its rotated bounds.
#[test]
fn bare_turned_inline_picture_keeps_its_frame() {
let room = |rot: f32, bare_turn: bool, compat: u32| {
let mut d = Document::from_text("");
d.settings.compat_mode = compat;
let float = wordcraft_doc::para::Float { rot, bare_turn, ..Default::default() };
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(std::sync::Arc::make_mut) {
p.insert_object(0, picture(120.0, 60.0, float), &Default::default()).unwrap();
}
let l = lay(&d);
let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() };
let c = para.clusters.iter().find(|c| matches!(c.kind, para::ClKind::Object(_))).unwrap();
// Drawn unscaled, centred in that room.
let obj = picture(120.0, 60.0, wordcraft_doc::para::Float { rot, bare_turn, ..Default::default() });
let r = display::inline_rect(Some(&obj), 0.0, 200.0, c.adv, (c.obj_h, c.obj_d), c.adv, compat >= 15);
assert_eq!((r.w, r.h), (120.0, 60.0), "{rot}° bare {bare_turn} compat {compat}");
assert_eq!((r.x + r.w / 2.0, r.y + r.h / 2.0), (c.adv / 2.0, 200.0 - c.obj_h / 2.0));
// Only a bare turn that overhangs its line is cut, at the line's top and bottom.
let overhangs =
bare_turn && (c.obj_h as f64) < 120.0 * (rot as f64).to_radians().sin().abs() + 60.0 * (rot as f64).to_radians().cos().abs() - 0.1;
let clips: Vec<Rect> = display::page_display(&d, &l.pages[0], &Default::default())
.iter()
.filter_map(|i| if let display::Draw::Clip { rect, .. } = i { Some(*rect) } else { None })
.collect();
assert_eq!(clips.len(), usize::from(overhangs), "{rot}° bare {bare_turn} compat {compat}: {clips:?}");
if let Some(band) = clips.first() {
assert!(band.h >= c.obj_h && band.w > 4000.0, "{band:?}");
}
(c.adv.round(), c.obj_h.round())
};
assert_eq!(room(90.0, true, 12), (120.0, 60.0));
assert_eq!(room(45.0, true, 12), (120.0, 60.0));
assert_eq!(room(180.0, true, 12), (120.0, 60.0));
assert_eq!(room(90.0, true, 15), (60.0, 120.0));
assert_eq!(room(45.0, true, 15), (60.0, 120.0));
assert_eq!(room(135.0, true, 15), (120.0, 60.0));
assert_eq!(room(270.0, true, 15), (60.0, 120.0));
// Room recorded (Word's own files, WordCraft's turns): the rotated bounds, in any layout.
assert_eq!(room(90.0, false, 12), (60.0, 120.0));
assert_eq!(room(45.0, false, 15), (127.0, 127.0));
}
/// Tops of the body text lines drawn on page one, in order.
fn line_tops(l: &DocLayout) -> Vec<f32> {
l.pages[0].items.iter().filter_map(|i| if let Placed::Lines { y, story: StoryRef::Body, .. } = i { Some(*y) } else { None }).collect()
@@ -10285,6 +10331,79 @@ fn an_empty_continuous_section_mark_takes_no_room() {
assert_eq!(new_page[1].0, 1, "a next-page section starts a page: {new_page:?}");
}
/// A hidden mark closing a section before a continuous one, holding only an in-line picture:
/// the picture keeps its line, so the next section starts below it, not over it (#5288). A
/// floating picture there still leaves the mark quiet, and so does a hidden one or one in hidden
/// text.
#[test]
fn a_hidden_mark_with_an_inline_picture_keeps_its_room() {
use wordcraft_doc::para::{Float, ShapeKind};
use wordcraft_doc::section::{SectionProps, SectionStart};
// Where Pb starts, and the bottom of the closing mark's picture (none: no picture).
let tops = |float: Option<Float>, run: CharProps| {
let mut d = Document::from_text("Pa\n\nPb");
let closer = d.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
closer.mark.hidden = Some(true);
closer.section = Some(Box::new(SectionProps::default()));
d.last_section.start = SectionStart::Continuous;
if let Some(float) = float {
let shape = InlineObject::Shape {
kind: ShapeKind::Rectangle,
w: 144.0,
h: 72.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float,
story: None,
effects: Default::default(),
freeform: None,
extra: Default::default(),
};
d.insert_object(&Pos::body(1, 0), shape, &run).unwrap();
}
let l = lay(&d);
let bottom = l.object(&Pos::body(1, 0), 0).map(|o| o.rect.bottom());
(l.caret(&Pos::body(2, 0)).unwrap(), bottom)
};
let wrapped = |wrap| Some(Float { wrap, ..Default::default() });
let (empty, _) = tops(None, CharProps::default());
let (pb, bottom) = tops(wrapped(Wrap::Inline), CharProps::default());
let bottom = bottom.unwrap();
assert_eq!(pb.page, 0, "the continuous section stays on the page: {pb:?}");
assert!(pb.top >= empty.top + 72.0 - 0.01, "Pb starts below the 72 pt picture: {pb:?} vs {empty:?}");
assert!(pb.top >= bottom - 0.01, "Pb starts below the picture's frame: {pb:?} vs {bottom}");
let (floating, drawn) = tops(wrapped(Wrap::InFrontOfText), CharProps::default());
assert!(drawn.is_some(), "the floating picture is drawn");
assert!((floating.top - empty.top).abs() < 0.01, "a floating picture leaves the mark quiet: {floating:?} vs {empty:?}");
let (hidden, _) = tops(Some(Float { hidden: true, ..Default::default() }), CharProps::default());
assert!((hidden.top - empty.top).abs() < 0.01, "a hidden picture leaves the mark quiet: {hidden:?} vs {empty:?}");
let (in_hidden_text, _) = tops(wrapped(Wrap::Inline), CharProps { hidden: Some(true), ..Default::default() });
assert!((in_hidden_text.top - empty.top).abs() < 0.01, "a picture in hidden text leaves the mark quiet: {in_hidden_text:?} vs {empty:?}");
}
/// A hidden closing mark holding only a legacy check box (a FORMCHECKBOX field, empty result):
/// the box is drawn with a line's room, so the next section starts below it (#5288).
#[test]
fn a_hidden_mark_with_a_check_box_keeps_its_room() {
use wordcraft_doc::section::{SectionProps, SectionStart};
let top = |boxed: bool| {
let mut d = Document::from_text("Pa\n\nPb");
let closer = d.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
closer.mark.hidden = Some(true);
closer.section = Some(Box::new(SectionProps::default()));
d.last_section.start = SectionStart::Continuous;
if boxed {
let form = r#"<w:ffData><w:name w:val="Box"/><w:checkBox><w:sizeAuto/></w:checkBox></w:ffData>"#.to_string();
let field = InlineObject::Field { instr: "FORMCHECKBOX".into(), result: String::new(), locked: false, dirty: false, code: false, form };
d.insert_object(&Pos::body(1, 0), field, &Default::default()).unwrap();
}
lay(&d).caret(&Pos::body(2, 0)).unwrap()
};
let (empty, boxed) = (top(false), top(true));
assert!(boxed.top >= empty.top + 8.0, "Pb starts a line below the check box: {boxed:?} vs {empty:?}");
}
/// Empty marks closing continuous sections one after another each keep their line while it
/// fits; only one right after text is quiet. Past the page's bottom they stay there, so the text
/// after the run starts the next page. Measured in Word (#3907): "Start", N such marks, "End":
@@ -13505,6 +13624,61 @@ fn a_non_breaking_hyphen_and_a_minus_sign_stay_unbreakable() {
}
}
/// #3408: Word breaks a compound right after a hyphen that a slash follows ("Dataprotection-" /
/// "/Secrecyviolation"), where UAX #14 forbids a break before the slash. The first width that
/// wraps must break after the hyphen, not move the compound whole, and the slash stays with its
/// word. Table auto-fit reads the same break, so such a column no longer widens to the compound.
/// Word keeps "fitness-/1589" whole: a slash before a digit gains no break.
#[test]
fn a_hyphen_before_a_slash_is_a_break_opportunity_like_word() {
let digits = "Deed fitness-/1589";
let mut wrapped = false;
for m in 100..=540 {
let mut d = Document::from_text(digits);
d.last_section.margin_right = m as f32;
let l = lay(&d);
let lines: Vec<&str> = l.pages[0]
.items
.iter()
.filter_map(|it| if let Placed::Lines { para, l0, l1, .. } = it { Some(&para.lines[*l0..*l1]) } else { None })
.flatten()
.map(|line| &digits[line.start..line.stop])
.collect();
if lines.len() >= 2 {
assert_eq!(lines, ["Deed ", "fitness-/1589"], "the first wrap breaks at the space, not after the hyphen");
wrapped = true;
break;
}
}
assert!(wrapped, "no width in the sweep wrapped the digit case");
let text = "Deed Dataprotection-/Secrecyviolation";
for m in 100..=540 {
let mut d = Document::from_text(text);
d.last_section.margin_right = m as f32;
let l = lay(&d);
let lines: Vec<String> = l.pages[0]
.items
.iter()
.filter_map(|it| {
if let Placed::Lines { para, l0, l1, .. } = it {
Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string()).collect::<Vec<_>>())
} else {
None
}
})
.flatten()
.collect();
if lines.len() < 2 {
continue; // still fits on one line at this width
}
assert_eq!(lines[0], "Deed Dataprotection-", "the first wrap breaks after the hyphen: {lines:?}");
assert_eq!(lines[1], "/Secrecyviolation", "the slash starts the next line with its word: {lines:?}");
return;
}
panic!("no width in the sweep wrapped the paragraph");
}
#[test]
fn layout_cache_invalidates_on_changed_filename() {
let mut doc = Document::new();
@@ -0,0 +1,213 @@
//! A row of a nested table marked "can't split" moves on with its outer row, as in Word
//! (docxide-pdf `nested-first-row-*-cant1`): the outer row splits only above it.
use crate::*;
use wordcraft_doc::{Table, para_block};
fn one_line_paras(what: &str, n: usize) -> Vec<Arc<Block>> {
(0..n)
.map(|i| {
let mut p = Paragraph::with_text(&format!("{what} {i}"), Default::default());
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
para_block(p)
})
.collect()
}
/// A filler paragraph pushed `push` points down, then a one-row table whose cells each hold
/// `prefix` one-line paragraphs and a nested table of one row with `nested` of them. Returns,
/// per cell, the prefix lines and the nested lines on each page.
fn lines_per_page(push: f32, cells: &[(usize, usize)], cant_split: bool) -> Vec<(Vec<usize>, Vec<usize>)> {
let mut d = Document::from_text("Filler");
if let Some(Block::Para(p)) = d.body.first_mut().map(Arc::make_mut) {
p.props.space_before = Some(push);
}
let mut outer = Table::new(1, cells.len(), 440.0);
for (cell, &(prefix, nested)) in outer.rows[0].cells.iter_mut().zip(cells) {
let mut inner = Table::new(1, 1, 200.0);
inner.rows[0].props.cant_split = cant_split;
inner.rows[0].cells[0].blocks = one_line_paras("Nested", nested);
cell.blocks = one_line_paras("Prefix", prefix);
cell.blocks.push(Arc::new(Block::Table(inner)));
cell.blocks.push(para_block(Paragraph::with_text("", Default::default())));
}
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(outer)).unwrap();
let mut c = LayoutCache::new();
let l = layout(&d, &mut c, &LayoutOptions::default());
let count = |cell: u32, nested: bool| -> Vec<usize> {
l.pages
.iter()
.map(|pg| {
pg.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, l0, l1, .. } => {
let p = &path.0;
let hit = if nested {
p.len() == 7 && p[..3] == [1, 0, cell] && p[4..6] == [0, 0]
} else {
p.len() == 4 && p[..3] == [1, 0, cell]
};
hit.then_some(l1 - l0)
}
_ => None,
})
.sum()
})
.collect()
};
(0..cells.len() as u32).map(|c| (count(c, false), count(c, true))).collect()
}
#[test]
fn nested_cant_split_row_moves_on_with_its_outer_row() {
let split = &lines_per_page(520.0, &[(0, 20)], false)[0].1;
assert!(split[0] > 0 && split[1] > 0, "a splittable nested row splits with its outer row: {split:?}");
assert_eq!(lines_per_page(520.0, &[(0, 20)], true)[0].1[..2], [0, 20], "a can't-split nested row moves on whole");
}
#[test]
fn the_outer_row_splits_above_a_nested_cant_split_row() {
// About 22 lines of room: the nested row (lines 10 to 40) runs through it.
let cell = &lines_per_page(340.0, &[(10, 30)], true)[0];
assert!(cell.0[0] > 0, "the text above the nested row stays: {cell:?}");
assert_eq!(cell.1[..2], [0, 30], "the nested row moves on whole: {cell:?}");
}
#[test]
fn the_cut_moves_up_until_no_nested_cant_split_row_runs_through_it() {
// Room for about 22 lines. Only cell 0's nested row (lines 10 to 40) runs through it; the
// cut at its top then runs through cell 1's (lines 5 to 13), which moves on whole too.
let cells = lines_per_page(340.0, &[(10, 30), (5, 8)], true);
assert_eq!(cells[0].1[..2], [0, 30], "{cells:?}");
assert_eq!(cells[1].1[..2], [0, 8], "{cells:?}");
assert!(cells[0].0[0] > 0 && cells[1].0[0] > 0, "the text above both stays: {cells:?}");
}
#[test]
fn nested_cant_split_row_taller_than_a_page_still_splits() {
let pages = &lines_per_page(520.0, &[(0, 60)], true)[0].1;
assert_eq!(pages[0], 0, "it leaves the partly filled page: {pages:?}");
assert_eq!(pages.iter().sum::<usize>(), 60, "every line is placed once: {pages:?}");
assert!(pages.iter().filter(|&&n| n > 0).count() >= 2, "it runs on over pages instead of into the margin: {pages:?}");
}
#[test]
fn the_outer_row_breaks_between_nested_cant_split_rows_above_its_bottom_band() {
let mut nested = Table::new(40, 1, 200.0);
nested.props.cell_margins = Some([0.0; 4]);
for (i, row) in nested.rows.iter_mut().enumerate() {
row.props.cant_split = true;
row.cells[0].blocks = one_line_paras(&format!("Row {i}"), 2);
}
let mut outer = Table::new(1, 1, 400.0);
// A bottom margin: the part left on the page keeps it below the last row there.
outer.props.cell_margins = Some([0.0, 5.4, 4.0, 5.4]);
outer.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(nested)), empty()];
let l = lay_pushed(520.0, outer);
let pages = per_page(&l, |p| p.len() == 7 && p[..4] == [1, 0, 0, 0]);
assert!(pages[0] > 0, "the rows that fit stay on the page: {pages:?}");
assert_eq!(pages.iter().sum::<usize>(), 80, "every line is placed once: {pages:?}");
for r in 0..40u32 {
let on: Vec<usize> = per_page(&l, |p| p.len() == 7 && p[..5] == [1, 0, 0, 0, r]);
assert_eq!(on.iter().filter(|&&n| n > 0).count(), 1, "row {r} stays on one page: {on:?}");
}
}
fn empty() -> Arc<Block> {
para_block(Paragraph::with_text("", Default::default()))
}
/// A nested table of one row, marked "can't split", with `lines` one-line paragraphs.
fn kept_nested(lines: usize) -> Arc<Block> {
let mut t = Table::new(1, 1, 200.0);
t.rows[0].props.cant_split = true;
t.rows[0].cells[0].blocks = one_line_paras("Nested", lines);
Arc::new(Block::Table(t))
}
/// Lay out a filler paragraph pushed `push` points down, then `outer`.
fn lay_pushed(push: f32, outer: Table) -> DocLayout {
let mut d = Document::from_text("Filler");
if let Some(Block::Para(p)) = d.body.first_mut().map(Arc::make_mut) {
p.props.space_before = Some(push);
}
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(outer)).unwrap();
let mut c = LayoutCache::new();
layout(&d, &mut c, &LayoutOptions::default())
}
/// The lines on each page of the body paragraphs whose path `hit` picks.
fn per_page(l: &DocLayout, hit: impl Fn(&[u32]) -> bool) -> Vec<usize> {
l.pages
.iter()
.map(|pg| {
pg.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, l0, l1, .. } => hit(&path.0).then_some(l1 - l0),
_ => None,
})
.sum()
})
.collect()
}
#[test]
fn a_bottom_aligned_cell_keeps_its_nested_cant_split_row_whole() {
// Cell 1 sits at the bottom of the row as laid out, but the split runs it from its top,
// where its nested row (lines 2 to 32) runs through the room of about 22 lines.
let mut outer = Table::new(1, 2, 440.0);
outer.rows[0].cells[0].blocks = one_line_paras("Tall", 50);
outer.rows[0].cells[1].props.valign = Some(wordcraft_doc::props::VAlign::Bottom);
let mut blocks = one_line_paras("Prefix", 2);
blocks.extend([kept_nested(30), empty()]);
outer.rows[0].cells[1].blocks = blocks;
let l = lay_pushed(340.0, outer);
let nested = per_page(&l, |p| p.len() == 7 && p[..4] == [1, 0, 1, 2]);
assert_eq!(nested[..2], [0, 30], "the nested row moves on whole: {nested:?}");
}
#[test]
fn header_rows_go_on_with_a_first_row_whose_nested_cant_split_row_comes_first() {
let mut outer = Table::new(2, 1, 400.0);
outer.rows[0].props.header = true;
outer.rows[0].cells[0].blocks = one_line_paras("Header", 1);
outer.rows[1].cells[0].blocks = vec![kept_nested(20), empty()];
let l = lay_pushed(520.0, outer);
let header = per_page(&l, |p| p == [1, 0, 0, 0]);
assert_eq!(header[0], 0, "the header row doesn't stay alone at the page bottom: {header:?}");
assert_eq!(per_page(&l, |p| p.len() == 7 && p[..4] == [1, 1, 0, 0])[..2], [0, 20]);
}
#[test]
fn a_kept_row_goes_on_with_a_row_whose_nested_cant_split_row_cant_start_below_it() {
let mut outer = Table::new(2, 1, 400.0);
let mut kept = one_line_paras("Kept", 1);
if let Some(Block::Para(p)) = kept.first_mut().map(Arc::make_mut) {
p.props.keep_next = Some(true);
}
outer.rows[0].cells[0].blocks = kept;
outer.rows[1].cells[0].blocks = vec![kept_nested(20), empty()];
let l = lay_pushed(520.0, outer);
let kept = per_page(&l, |p| p == [1, 0, 0, 0]);
assert_eq!(kept[..2], [0, 1], "the kept row moves on with the next one: {kept:?}");
}
#[test]
fn a_merged_cell_doesnt_stretch_its_cant_split_row() {
// Row 0 can't split; its first cell is merged down into row 1, which can and runs through
// the room. The cut stays in row 1.
let mut nested = Table::new(2, 2, 300.0);
nested.rows[0].props.cant_split = true;
nested.rows[0].cells[0].props.vmerge = wordcraft_doc::props::VMerge::Restart;
nested.rows[1].cells[0].props.vmerge = wordcraft_doc::props::VMerge::Continue;
nested.rows[0].cells[0].blocks = one_line_paras("Merged", 1);
nested.rows[0].cells[1].blocks = one_line_paras("Short", 1);
nested.rows[1].cells[1].blocks = one_line_paras("Long", 20);
let mut outer = Table::new(1, 1, 400.0);
outer.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(nested)), empty()];
let l = lay_pushed(520.0, outer);
let long = per_page(&l, |p| p.len() == 7 && p[..6] == [1, 0, 0, 0, 1, 1]);
assert!(long[0] > 0 && long[1] > 0, "the splittable row splits: {long:?}");
}
+1
View File
@@ -208,6 +208,7 @@ fn links_out_of_a_root_are_refused() {
}
/// The names in `dir`, sorted.
#[cfg(unix)]
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
+44 -21
View File
@@ -166,6 +166,15 @@ impl Exporter<'_> {
}
s.pop();
}
// A turned picture cut at its line's top and bottom.
Draw::Clip { rect, items } => {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.rotated_pictures(s, it);
}
s.pop();
}
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| {
@@ -177,6 +186,40 @@ impl Exporter<'_> {
}
}
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
/// (structure entry `idx`), pictures and figures on their own, anything else an artifact.
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) {
match d {
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// A picture marked decorative: an artifact screen readers skip.
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
// A rotated inline picture, or a rotated group holding pictures: turned as a
// whole, each picture tagged on its own (see `rotated_pictures`).
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d),
// A clip (a turned picture cut at its line, an exact-height cell's lines, a canvas's
// members): each draw in it tagged as it would be outside it.
Draw::Clip { rect, items } => {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.line_item(s, it, idx);
}
s.pop();
}
// A turned text box's line: still the paragraph's text. A rotated shape
// without text falls to the artifacts below.
Draw::Rotated { items, .. } if items.iter().any(holds_text) => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// An inline chart, diagram or described shape: its text is part of the figure, not the paragraph.
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| {
for d in inner {
me.draw(s, d);
}
}),
_ => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
}
}
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
if let Some(c) = self.doc.settings.page_color
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
@@ -221,27 +264,7 @@ impl Exporter<'_> {
Placed::Lines { story, path, para, .. } => {
let idx = self.entry(*story, path, para);
for d in &draws {
match d {
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// A picture marked decorative: an artifact screen readers skip.
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
// A rotated inline picture, or a rotated group holding pictures: turned as a
// whole, each picture tagged on its own (see `rotated_pictures`).
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d),
// A turned text box's line: still the paragraph's text. A rotated shape
// without text falls to the artifacts below.
Draw::Rotated { items, .. } if items.iter().any(holds_text) => {
self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d))
}
// An inline chart, diagram or described shape: its text is part of the figure, not the paragraph.
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| {
for d in inner {
me.draw(s, d);
}
}),
_ => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
}
self.line_item(s, d, idx);
}
}
Placed::Image { story, path, off, .. } => {
+3 -2
View File
@@ -5,11 +5,12 @@ pub(crate) fn graphic_alt(alt: &str, kind: GraphicKind) -> &str {
if alt.trim().is_empty() { kind.noun() } else { alt }
}
/// A picture, or a rotation holding one at any depth (a rotated group's turned members).
/// A picture, or a rotation or clip holding one at any depth (a rotated group's turned members, a
/// turned picture cut at its line).
pub(crate) fn holds_picture(d: &Draw) -> bool {
match d {
Draw::Image { .. } => true,
Draw::Rotated { items, .. } => items.iter().any(holds_picture),
Draw::Rotated { items, .. } | Draw::Clip { items, .. } => items.iter().any(holds_picture),
_ => false,
}
}
+39
View File
@@ -1190,6 +1190,8 @@ fn decorative_pictures_are_artifacts_not_figures() {
let cases = [
("inline", Float::default()),
("rotated inline", Float { rot: 30.0, ..Default::default() }),
// Turned with no room kept for it: drawn cut at its line (a clip), still tagged.
("bare turned inline", Float { rot: 45.0, bare_turn: true, ..Default::default() }),
("floating", floating.clone()),
("rotated floating", Float { rot: 30.0, ..floating }),
];
@@ -1202,6 +1204,43 @@ fn decorative_pictures_are_artifacts_not_figures() {
}
}
/// A row of exact height cuts its cell's lines (one clip around them): text and a picture in
/// it are tagged as they are in a row that fits, the text as the paragraph's, the picture as a
/// Figure with its alt text.
#[test]
fn a_clipped_cell_tags_its_text_and_picture() {
let raw = |exact: bool| {
let mut d = Document::new();
let media = d.add_media(red_right_half_emf(), "emf");
let mut p = Paragraph::with_text("Cell text ", CharProps::default());
let n = p.len();
let obj = InlineObject::Image {
media,
w: 70.0,
h: 70.0,
alt: "A red square".into(),
float: Default::default(),
crop: [0.0; 4],
ole: None,
fx: Default::default(),
};
p.insert_object(n, obj, &CharProps::default()).unwrap();
let mut t = Table::new(1, 1, 300.0);
t.rows[0].cells[0].blocks = vec![para_block(p)];
if exact {
t.rows[0].props.height = Some(30.0);
t.rows[0].props.height_rule = wordcraft_doc::props::HeightRule::Exact;
}
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::with_text("Below", CharProps::default()))];
String::from_utf8_lossy(&export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap()).into_owned()
};
let (fits, cut) = (raw(false), raw(true));
assert!(cut.contains("/Alt(A red square)"), "the picture in the cut cell is a Figure with its alt text");
// The same marked content either way: the cut cell's text is not dropped as an artifact.
assert_eq!(cut.matches("/MCID").count(), fits.matches("/MCID").count());
assert_eq!(cut.matches("/S/P").count(), fits.matches("/S/P").count());
}
/// In a rotated group, each picture is tagged on its own: the decorative one is an artifact, the
/// other stays a Figure with its alt text.
#[test]
+18 -13
View File
@@ -184,23 +184,28 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
}
});
});
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.ribbon).inner_margin(egui::Margin::symmetric(40, 30))).show(ui, |ui| {
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.ribbon).inner_margin(egui::Margin::symmetric(0, 30))).show(ui, |ui| {
// The side padding sits inside the pages, so the scroll area reaches the window's edge.
let pad = egui::Frame::NONE.inner_margin(egui::Margin::symmetric(40, 0));
// The Print page fills the pane and scrolls its settings and its preview itself (#1156).
if app.ui.backstage_page == "print" {
crate::rtl::root(ui, |ui| export_page(app, ui));
pad.show(ui, |ui| crate::rtl::root(ui, |ui| export_page(app, ui)));
return;
}
egui::ScrollArea::vertical().show(ui, |ui| {
crate::rtl::root(ui, |ui| match app.ui.backstage_page.as_str() {
"home" => home_page(app, ui),
"new" => new_page(app, ui),
"open" => open_page(app, ui),
"saveAs" => save_as_page(app, ui),
"info" => info_page(app, ui),
"recover" => recovery_page(app, ui),
"print" | "export" => export_page(app, ui),
"options" => crate::options::page(app, ui),
_ => home_page(app, ui),
// Full width, so the bar sits at the window's edge and the wheel works over the whole page (#5282).
egui::ScrollArea::vertical().auto_shrink([false, true]).show(ui, |ui| {
pad.show(ui, |ui| {
crate::rtl::root(ui, |ui| match app.ui.backstage_page.as_str() {
"home" => home_page(app, ui),
"new" => new_page(app, ui),
"open" => open_page(app, ui),
"saveAs" => save_as_page(app, ui),
"info" => info_page(app, ui),
"recover" => recovery_page(app, ui),
"print" | "export" => export_page(app, ui),
"options" => crate::options::page(app, ui),
_ => home_page(app, ui),
})
})
});
});
+52
View File
@@ -1054,3 +1054,55 @@ fn backstage_save_as_sidebar_opens_save_as_page() {
h.run_steps(4);
assert_eq!(h.state().ui.backstage_page, "saveAs");
}
/// Scrolls the File page with the wheel at `x` and returns doc0.docx's top before and after,
/// plus the rectangle of the page's vertical scrollbar.
fn file_page_wheel_at(x: f32) -> (f32, f32, egui::Rect) {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.ui.recent = (0..12).map(|i| format!("/docs/doc{i}.docx")).collect();
a.run("ui.backstage", json!({"value": true, "page": "home"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 500.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
let bar = h
.query_all_by_role(egui::accesskit::Role::ScrollBar)
.map(|n| n.rect())
.filter(|r| r.height() > r.width())
.max_by(|a, b| a.height().total_cmp(&b.height()))
.expect("the File page's vertical scrollbar");
let before = h.get_by_label("doc0.docx").rect();
h.event(egui::Event::PointerMoved(egui::pos2(x, 300.0)));
h.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -200.0),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
source: egui::MouseWheelSource::Unknown,
});
h.run_steps(4);
(before.min.y, h.get_by_label("doc0.docx").rect().min.y, bar)
}
/// #5282: the File page scrolls with the wheel over its right side.
#[test]
fn the_file_page_scrolls_with_the_wheel_over_its_right_side() {
let (before, after, _) = file_page_wheel_at(1300.0);
assert!(after < before - 1.0, "expected doc0.docx to scroll up: before={before}, after={after}");
}
/// #5282: the scroll area reaches the window's right edge, so its bar sits there and the wheel
/// works there too.
#[test]
fn the_file_page_scrolls_with_the_wheel_at_the_window_edge() {
// The harness keeps an 8 point margin, so the window edge is at x=1432.
let (before, after, bar) = file_page_wheel_at(1428.0);
assert!(after < before - 1.0, "expected doc0.docx to scroll up at the edge: before={before}, after={after}");
assert!((bar.right() - 1432.0).abs() < 1.0, "expected the scrollbar at the window edge: {bar:?}");
}
+1
View File
@@ -15,6 +15,7 @@ use crate::WordApp;
use crate::theme::{Tokens, regular, semibold};
mod balloons;
mod column_ruler;
mod context_menu;
#[cfg(test)]
pub(crate) use context_menu::issue_heading;
+343
View File
@@ -0,0 +1,343 @@
//! The caret section's text columns on the horizontal ruler (#5197): the space between each two
//! columns is shaded like the margins, and its edges are dragged to change the columns' widths
//! and spacing, through `layout.columns`. As in Word for Mac, the space has no grip of its own
//! in the middle: only its edges drag.
use serde_json::Value;
use wordcraft_doc::section::SectionProps;
use wordcraft_doc::{Pos, StoryRef};
use super::{DocLayout, Rect, Sense, Tokens, Ui, WordApp, json, pos2};
/// Which edge of the space between two columns a drag grabs, in reading order: the end of the
/// column before it or the start of the column after it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum GapGrip {
End,
Start,
}
/// The narrowest column a drag leaves: a quarter inch, as the Columns dialog allows.
const MIN_COLUMN: f32 = 18.0;
/// The widest space a drag leaves between two columns, as the Columns dialog allows.
const MAX_SPACE: f32 = 300.0;
/// The caret section's columns on a page, for the ruler.
pub(super) struct ColumnGaps {
/// The caret's section.
sect: SectionProps,
/// The page x of the section's text area's left edge.
origin: f32,
/// Each space between two neighbouring columns in reading order: its (left, right) page x.
gaps: Vec<(f32, f32)>,
}
/// The spaces between the caret section's columns on page `pi`: none outside the main text or
/// Print Layout (where text runs in one column), in a table (whose own markers take the ruler),
/// in a section of one column, for a selection across sections (a drag would set the columns of
/// each) or when the caret isn't on that page (the ruler stays put while the whole document is
/// selected).
pub(super) fn column_gaps(app: &WordApp, layout: &DocLayout, pi: usize) -> Option<ColumnGaps> {
let sel = &app.session.sel;
if sel.focus.story != StoryRef::Body || sel.anchor.story != StoryRef::Body {
return None;
}
if app.session.view.mode != wordcraft_layout::ViewMode::Print || app.session.view.read_mode {
return None;
}
if sel.focus.path.cell().is_some() || crate::table_ruler::text_area(app, layout, pi).is_some() {
return None;
}
let doc = &app.session.doc;
let section = |p: &Pos| doc.section_index_of(p.path.0.first().copied().unwrap_or(0) as usize);
if section(&sel.anchor) != section(&sel.focus) {
return None;
}
if layout.caret_on(&sel.focus, pi).map(|c| c.page) != Some(pi) {
return None;
}
let sect = wordcraft_engine::cmd::page::sect(&app.session);
if sect.columns.count <= 1 {
return None;
}
let page = layout.pages.get(pi)?;
// A continuous section can change the margins on the page: its columns start at its own
// margin, moved as the page's text area is (on an even page of a mirrored layout, #2914).
let sections = app.session.doc.sections();
let (_, page_sect) = sections.get(page.section)?;
let origin = page.body.x + sect.margin_left + sect.gutter - page_sect.margin_left - page_sect.gutter;
let gaps = gaps_of(&sect).into_iter().map(|(l, r)| (origin + l, origin + r)).collect();
Some(ColumnGaps { sect, origin, gaps })
}
/// Each space between two neighbouring columns of `s` in reading order, as (left, right) points
/// from the text area's left edge.
fn gaps_of(s: &SectionProps) -> Vec<(f32, f32)> {
s.column_boxes()
.windows(2)
.filter_map(|w| match w {
// Leftwards in a right-to-left section.
[(ax, aw), (bx, bw)] => Some(if bx >= ax { (ax + aw, *bx) } else { (bx + bw, *ax) }),
_ => None,
})
.collect()
}
/// Shades the spaces between the columns on the ruler `bar`, over the white text area.
pub(super) fn draw(painter: &egui::Painter, cg: &ColumnGaps, bar: Rect, x0: f32, scale: f32, t: &Tokens) {
for (l, r) in &cg.gaps {
let (sl, sr) = (x0 + l * scale, x0 + r * scale);
if sr > sl {
painter.rect_filled(Rect::from_min_max(pos2(sl, bar.min.y), pos2(sr, bar.max.y)), 0.0, t.ruler_margin);
}
}
}
/// The drag zones of the spaces between the columns: each of their edges, none over a tab
/// stop's marker (`tabs`), which keeps its own drag. Registered after the tab stops (whose
/// set-a-stop zone spans the text area) and before the indent markers, which keep the pointer
/// where they overlap. Columns the command wouldn't take back get no zones.
pub(super) fn handles(app: &mut WordApp, ui: &Ui, cg: &ColumnGaps, bar: Rect, x0: f32, scale: f32, tabs: &[Rect]) {
if !draggable(&cg.sect) {
return;
}
let rtl = cg.sect.rtl;
for (gap, (l, r)) in cg.gaps.iter().enumerate() {
let (sl, sr) = (x0 + l * scale, x0 + r * scale);
// Left to right, the space's left edge ends the column before it; right to left, it
// starts the column after it.
let (left, right) = if rtl { (GapGrip::Start, GapGrip::End) } else { (GapGrip::End, GapGrip::Start) };
// A narrow space is split at its middle, so both edges can be grabbed.
let mid = (sl + sr) / 2.0;
let zones = [
(left, Rect::from_min_max(pos2(sl - 3.0, bar.min.y), pos2((sl + 3.0).min(mid), bar.max.y))),
(right, Rect::from_min_max(pos2((sr - 3.0).max(mid), bar.min.y), pos2(sr + 3.0, bar.max.y))),
];
for (grip, zone) in zones {
if tabs.iter().any(|t| t.intersects(zone)) {
continue;
}
let r =
ui.interact(zone, ui.scope_id().with(("ruler_column", gap, grip)), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
let r = if r.dragged() { r } else { r.on_hover_text(tl!("Column Edge")) };
if r.dragged()
&& let Some(pp) = r.interact_pointer_pos()
{
let v = (pp.x - x0) / scale - cg.origin;
let at = if rtl { cg.sect.text_width() - v } else { v };
let Some(params) = column_drag(&cg.sect, gap, grip, at) else { continue };
if !r.drag_started() {
app.session.join_next_undo();
}
let _ = app.run_keep_view("layout.columns", params);
}
}
}
}
/// The `layout.columns` parameters after dragging `grip` of the space after column `gap` (in
/// reading order) to `at` points from the text area's start edge (its right edge in a
/// right-to-left section). Equal columns stay equal, so every space changes, as in Word for Mac;
/// between unequal columns only the column at that edge and the space change. Columns stay at
/// least a quarter inch wide and the space 0–300 pt, snapped to 1/16 inch. `None` when there is
/// no such space or `at` is junk.
pub(crate) fn column_drag(s: &SectionProps, gap: usize, grip: GapGrip, at: f32) -> Option<Value> {
let n = s.columns.count as usize;
if !at.is_finite() || !draggable(s) || gap + 1 >= n {
return None;
}
let tw = s.text_width();
let sep = s.columns.separator;
if s.columns.widths.len() != n {
// Column k is w wide and starts at k·(w + space), w = (tw − (n − 1)·space) / n: solved
// for the space that puts the edge at `at`.
let (i, nf) = (gap as f32, n as f32);
let space = match grip {
GapGrip::End => ((i + 1.0) * tw - at * nf) / (nf - 1.0 - i),
_ => at * nf / (i + 1.0) - tw,
};
let most = ((tw - MIN_COLUMN * nf) / (nf - 1.0)).clamp(0.0, MAX_SPACE);
// Snapped, and at the limit the last 1/16 inch below it.
let space = (space / 4.5).round() * 4.5;
let space = if space > most { (most / 4.5).floor() * 4.5 } else { space.max(0.0) };
return Some(json!({"count": n, "space": space, "separator": sep, "apply": "section"}));
}
// Unequal columns: (width, space after) each.
let mut cols = s.columns.widths.clone();
let start: f32 = cols.iter().take(gap).map(|(w, sp)| w + sp).sum();
let (&(w0, sp), &(w1, sp1)) = (cols.get(gap)?, cols.get(gap + 1)?);
let at = (at / 4.5).round() * 4.5;
let (end0, start1, end1) = (start + w0, start + w0 + sp, start + w0 + sp + w1);
let (w0, sp, w1) = match grip {
GapGrip::End => {
// `max` and `min` rather than `clamp`, which panics on bounds from a hostile file.
let e = at.min(start1.max(start + MIN_COLUMN)).max((start + MIN_COLUMN).max(start1 - MAX_SPACE));
(e - start, start1 - e, w1)
}
GapGrip::Start => {
let b = at.min((end1 - MIN_COLUMN).min(end0 + MAX_SPACE)).max(end0);
(w0, b - end0, end1 - b)
}
};
if let Some(c) = cols.get_mut(gap) {
*c = (w0, sp);
}
if let Some(c) = cols.get_mut(gap + 1) {
*c = (w1, sp1);
}
Some(json!({"widths": cols.iter().map(|(w, sp)| [*w, *sp]).collect::<Vec<_>>(), "separator": sep, "apply": "section"}))
}
/// Whether `layout.columns` takes the section's columns back after a drag: 2–12 columns, unequal
/// ones each at least a quarter inch wide with 0–300 pt after it and no wider together than the
/// text. A file can hold others (up to 45 columns, any widths); their spaces are shown, not
/// dragged.
fn draggable(s: &SectionProps) -> bool {
let n = s.columns.count as usize;
let widths = &s.columns.widths;
if !(2..=12).contains(&n) {
return false;
}
if widths.len() != n {
return true;
}
// The last column has no space after it (the command drops one).
let space = |i: usize, sp: f32| if i + 1 == n { 0.0 } else { sp };
let total: f32 = widths.iter().enumerate().map(|(i, (w, sp))| w + space(i, *sp)).sum();
total <= s.text_width() + 1.0 && widths.iter().enumerate().all(|(i, (w, sp))| *w >= MIN_COLUMN && (0.0..=MAX_SPACE).contains(&space(i, *sp)))
}
#[cfg(test)]
mod tests {
use super::*;
use wordcraft_doc::section::Columns;
/// Letter paper with inch margins: 468 pt of text.
fn letter(columns: Columns) -> SectionProps {
SectionProps { page_w: 612.0, page_h: 792.0, margin_left: 72.0, margin_right: 72.0, gutter: 0.0, columns, ..Default::default() }
}
fn equal(count: u32, space: f32) -> SectionProps {
letter(Columns { count, space, ..Default::default() })
}
fn widths(v: &Value) -> Vec<(f32, f32)> {
v["widths"].as_array().into_iter().flatten().map(|c| (c[0].as_f64().unwrap_or(0.0) as f32, c[1].as_f64().unwrap_or(0.0) as f32)).collect()
}
/// #5197: two equal columns half an inch apart leave a space from 216 to 252 pt.
#[test]
fn the_spaces_between_columns_are_where_the_columns_are_not() {
assert_eq!(gaps_of(&equal(2, 36.0)), vec![(216.0, 252.0)]);
assert_eq!(gaps_of(&equal(3, 36.0)), vec![(132.0, 168.0), (300.0, 336.0)]);
assert!(gaps_of(&equal(1, 36.0)).is_empty(), "one column, no space");
// Right to left, the first column is on the right: the same spaces, read leftwards.
let rtl = SectionProps { rtl: true, ..equal(3, 36.0) };
assert_eq!(gaps_of(&rtl), vec![(300.0, 336.0), (132.0, 168.0)]);
let unequal = letter(Columns { count: 2, space: 18.0, widths: vec![(100.0, 18.0), (350.0, 0.0)], ..Default::default() });
assert_eq!(gaps_of(&unequal), vec![(100.0, 118.0)]);
}
/// #5197: dragging an edge of the space between equal columns keeps them equal and changes
/// the spacing, so the dragged edge lands at the pointer.
#[test]
fn dragging_an_edge_between_equal_columns_changes_the_spacing() {
let s = equal(2, 36.0);
// The first column's end, from 216 to 207: 9 pt more space each side, 18 in all.
let v = column_drag(&s, 0, GapGrip::End, 207.0).unwrap_or_default();
assert_eq!(v, json!({"count": 2, "space": 54.0, "separator": false, "apply": "section"}));
// The second column's start, from 252 to 261: the same.
assert_eq!(column_drag(&s, 0, GapGrip::Start, 261.0).unwrap_or_default()["space"], 54.0);
// Past the middle the space closes; it never goes negative.
assert_eq!(column_drag(&s, 0, GapGrip::End, 400.0).unwrap_or_default()["space"], 0.0);
// At most 300 pt: 297, the last 1/16 inch below it.
assert_eq!(column_drag(&s, 0, GapGrip::End, 0.0).unwrap_or_default()["space"], 297.0);
// And it never leaves a column narrower than a quarter inch.
let narrow = equal(12, 0.0);
let most = (468.0 - 18.0 * 12.0) / 11.0;
let space = column_drag(&narrow, 0, GapGrip::End, 0.0).unwrap_or_default()["space"].as_f64().unwrap_or(0.0) as f32;
assert!(space <= most, "{space} leaves every column a quarter inch ({most})");
assert_eq!(space % 4.5, 0.0, "{space} is on the 1/16 inch grid at the limit too");
// Three columns: the second space's start edge, from 336 to 345.
let s = equal(3, 36.0);
assert_eq!(column_drag(&s, 1, GapGrip::Start, 345.0).unwrap_or_default()["space"], 49.5);
}
/// #5197: between unequal columns only the column at the dragged edge and the space change.
#[test]
fn dragging_between_unequal_columns_changes_its_neighbours() {
let s = letter(Columns { count: 3, space: 18.0, widths: vec![(100.0, 18.0), (200.0, 18.0), (132.0, 0.0)], ..Default::default() });
// The first column's end, 100 → 90: it narrows and the space after it widens.
assert_eq!(widths(&column_drag(&s, 0, GapGrip::End, 90.0).unwrap_or_default()), vec![(90.0, 28.0), (200.0, 18.0), (132.0, 0.0)]);
// The third column's start, 336 → 300, back into the second column: it stops at the
// second column's end (318), the space closes and the third column takes it.
assert_eq!(widths(&column_drag(&s, 1, GapGrip::Start, 300.0).unwrap_or_default()), vec![(100.0, 18.0), (200.0, 0.0), (150.0, 0.0)]);
// The second column's start, 118 → 1000: the column never gets narrower than a quarter
// inch.
assert_eq!(widths(&column_drag(&s, 0, GapGrip::Start, 1000.0).unwrap_or_default()), vec![(100.0, 200.0), (18.0, 18.0), (132.0, 0.0)]);
}
/// Junk positions and spaces that aren't there change nothing.
#[test]
fn column_drags_ignore_junk() {
let s = equal(2, 36.0);
assert!(column_drag(&s, 0, GapGrip::End, f32::NAN).is_none());
assert!(column_drag(&s, 1, GapGrip::End, 100.0).is_none(), "two columns have one space");
assert!(column_drag(&equal(1, 36.0), 0, GapGrip::Start, 100.0).is_none());
assert!(column_drag(&equal(13, 0.0), 0, GapGrip::End, 10.0).is_none(), "more columns than the command takes");
// Unequal widths from a file that the command wouldn't take back aren't dragged.
let narrow = letter(Columns { count: 2, widths: vec![(5.0, 0.0), (463.0, 0.0)], ..Default::default() });
assert!(column_drag(&narrow, 0, GapGrip::End, 30.0).is_none(), "a column under a quarter inch");
let wide = letter(Columns { count: 2, widths: vec![(100.0, 400.0), (50.0, 0.0)], ..Default::default() });
assert!(column_drag(&wide, 0, GapGrip::End, 90.0).is_none(), "a space over 300 pt");
let over = letter(Columns { count: 2, widths: vec![(300.0, 18.0), (300.0, 0.0)], ..Default::default() });
assert!(column_drag(&over, 0, GapGrip::End, 290.0).is_none(), "wider than the text");
let last = letter(Columns { count: 2, widths: vec![(200.0, 18.0), (250.0, 999.0)], ..Default::default() });
assert!(column_drag(&last, 0, GapGrip::End, 190.0).is_some(), "the last column's space after it doesn't count");
}
/// Through the command: a drag's result is applied to the caret's section, keeps the line
/// between columns, and is one undo step.
#[test]
fn a_column_drag_sets_the_sections_columns() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("one two three")), Default::default());
app.run("layout.columns", json!({"count": 2, "separator": true})).unwrap();
let before = wordcraft_engine::cmd::page::sect(&app.session);
// The first column's end, 9 pt to the left: 18 pt more space, the columns still equal.
let end = before.column_boxes()[0].0 + before.column_boxes()[0].1;
let params = column_drag(&before, 0, GapGrip::End, end - 9.0).unwrap();
app.run("layout.columns", params).unwrap();
let after = wordcraft_engine::cmd::page::sect(&app.session);
assert_eq!(after.columns.count, 2);
assert!(after.columns.widths.is_empty(), "the columns stay equal");
assert_eq!(after.columns.space, before.columns.space + 18.0);
assert!(after.columns.separator, "the line between the columns stays");
let boxes = after.column_boxes();
assert!((boxes[0].1 - (end - 9.0)).abs() < 0.01, "the edge is at the pointer: {boxes:?}");
let laid = app.session.layout();
let page = laid.pages.first().unwrap();
let cg = column_gaps(&app, &laid, 0).unwrap();
assert_eq!(cg.gaps.len(), 1);
assert!((cg.gaps[0].0 - (page.body.x + boxes[0].1)).abs() < 0.01, "the ruler's space starts where the first column ends");
assert!(app.session.undo());
assert_eq!(wordcraft_engine::cmd::page::sect(&app.session).columns, before.columns);
}
/// A drag sets the columns of every section the selection touches, so a selection across
/// sections gets no spaces on the ruler; nor does a page the caret isn't on.
#[test]
fn no_column_spaces_for_a_selection_across_sections_or_another_page() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("one\ntwo")), Default::default());
app.run("caret.docEnd", json!({})).unwrap();
app.run("layout.break", json!({"kind": "nextPage"})).unwrap();
app.run("layout.columns", json!({"count": 2, "apply": "section"})).unwrap();
let laid = app.session.layout();
assert_eq!(laid.pages.len(), 2);
assert!(column_gaps(&app, &laid, 1).is_some(), "the caret's page shows the second section's columns");
assert!(column_gaps(&app, &laid, 0).is_none(), "the first page has one column");
app.run("select.all", json!({})).unwrap();
let laid = app.session.layout();
assert!(column_gaps(&app, &laid, 1).is_none(), "the selection runs into a section of one column");
}
}
+10
View File
@@ -24,6 +24,11 @@ pub(super) fn rulers(app: &mut WordApp, ui: &mut Ui, h: Rect, v: Rect, rects: &[
hp.rect_filled(bar, 0.0, t.ruler_margin);
let text = Rect::from_min_max(pos2(x0 + page.body.x * scale, bar.min.y), pos2(x0 + page.body.right() * scale, bar.max.y));
hp.rect_filled(text, 0.0, t.ruler);
// The spaces between the caret section's text columns, shaded like the margins (#5197).
let columns = super::column_ruler::column_gaps(app, layout, pi);
if let Some(cg) = &columns {
super::column_ruler::draw(&hp, cg, bar, x0, scale, &t);
}
let rp = app.session.doc.para_at(&app.session.sel.focus).map(|para| app.session.doc.styles.resolve_para(&para.props));
// Graduations in the File › Options unit.
let (unit, div, step) = ruler_scale(app.session.units());
@@ -101,6 +106,11 @@ pub(super) fn rulers(app: &mut WordApp, ui: &mut Ui, h: Rect, v: Rect, rects: &[
// spans the text area, so a border marker keeps its drag) and before the indent markers,
// which keep the pointer where they overlap.
crate::table_ruler::columns(app, ui, layout, pi, bar, x0, scale);
// Outside a table, the spaces between the text columns, in the same order (#5197).
if let Some(cg) = &columns {
let tabs = crate::ruler_tabs::marker_rects(app, bar, &px, &rp.tabs);
super::column_ruler::handles(app, ui, cg, bar, x0, scale, &tabs);
}
// Dragging the left-indent marker.
let id = ui.scope_id().with("ruler_left");
let mr = Rect::from_center_size(pos2(left, bar.max.y - 3.0), vec2(12.0, 12.0));
+1 -1
View File
@@ -694,7 +694,7 @@ pub fn style_gallery(app: &mut WordApp, ui: &mut Ui, state: &Value) {
/// Style sets shown in the Design tab's gallery, in order.
const STYLE_SETS: [&str; 7] = ["default", "basic", "lines", "shaded", "casual", "centered", "minimalist"];
/// Width of one gallery thumbnail, points.
const STYLE_SET_W: f32 = 56.0;
pub const STYLE_SET_W: f32 = 56.0;
/// Width the whole gallery takes with the ribbon's 1 pt item spacing.
pub const STYLE_SET_GALLERY_W: f32 = STYLE_SETS.len() as f32 * (STYLE_SET_W + 1.0) - 1.0;
+3 -2
View File
@@ -3,11 +3,12 @@ use super::{CONTENT_H, Rect, Sense, Target, Ui, WordApp, big, group, json, menu_
/// The Design tab's style set gallery in a box of its own, sized from its thumbnails and clipped
/// to it, with a gap on each side: the Colors and Fonts column can't be drawn over, or cut by,
/// the thumbnails (#638). Returns the box and the space the thumbnails used.
/// the thumbnails (#638). In a right-to-left interface, the thumbnails lay out from the right
/// (#5750). Returns the box and the space the thumbnails used.
pub(super) fn style_set_box(app: &mut WordApp, ui: &mut Ui) -> (Rect, Rect) {
ui.add_space(4.0);
let (gallery, _) = ui.allocate_exact_size(vec2(crate::previews::STYLE_SET_GALLERY_W, CONTENT_H), Sense::hover());
let mut gui = ui.new_child(egui::UiBuilder::new().max_rect(gallery).layout(egui::Layout::left_to_right(egui::Align::Min)));
let mut gui = ui.new_child(egui::UiBuilder::new().max_rect(gallery).layout(crate::rtl::row_layout(ui, egui::Align::Min)));
gui.set_clip_rect(gallery.intersect(ui.clip_rect()));
gui.spacing_mut().item_spacing = vec2(1.0, 1.0);
crate::previews::style_set_gallery(app, &mut gui);
+43
View File
@@ -113,6 +113,49 @@ fn design_style_set_gallery_stays_in_its_box() {
assert!(next_x >= gallery.right() + 8.0 - 0.01, "{next_x} {gallery:?}");
}
/// #5750: in a right-to-left interface, the Design tab's style-set gallery lays out from the
/// right: the first style set ("default") is at the right edge, the remaining thumbnails read to
/// the left, and the next controls start after a gap to the left of the gallery.
#[test]
fn design_style_set_gallery_reads_from_the_right_in_rtl() {
crate::i18n::set_current(crate::i18n::fixture_lang("ar", "\tHome\tالرئيسية\n"));
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
let mut seen = None;
let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 200.0)).build_ui(|ui| {
crate::rtl::root(ui, |ui| {
crate::rtl::horizontal_top(ui, |ui| {
let (gallery, used) = style_set_box(&mut app, ui);
seen = Some((gallery, used, ui.cursor().max.x));
});
});
});
h.run_steps(2);
let tiles: Vec<Rect> = h.ctx.viewport(|v| {
v.prev_pass
.widgets
.layers()
.flat_map(|(_, w)| w.iter())
.filter(|w| (w.rect.width() - crate::previews::STYLE_SET_W).abs() < 0.1 && (w.rect.height() - CONTENT_H).abs() < 0.1)
.map(|w| w.rect)
.collect()
});
drop(h);
crate::i18n::set_current(crate::i18n::Lang::EN);
let (gallery, used, next_x) = seen.unwrap();
assert!((gallery.width() - crate::previews::STYLE_SET_GALLERY_W).abs() < 0.01);
assert!(used.left() >= gallery.left() - 0.01, "{used:?} {gallery:?}");
assert!(used.right() <= gallery.right() + 0.01, "{used:?} {gallery:?}");
assert!(next_x <= gallery.left() - 8.0 + 0.01, "{next_x} {gallery:?}");
assert_eq!(tiles.len(), 7, "7 style set tiles");
assert!((tiles[0].right() - gallery.right()).abs() < 0.01, "default tile at the right edge: {tiles:?} {gallery:?}");
assert!((tiles[6].left() - gallery.left()).abs() < 0.01, "minimalist tile at the left edge: {tiles:?} {gallery:?}");
for i in 1..tiles.len() {
assert!(tiles[i].right() <= tiles[i - 1].left(), "tile {i} is to the left of tile {}", i - 1);
}
}
/// #2738: Home › Underline's drop-down: every line sample is a named entry (assistive
/// technology, tooltips) that applies its own style; Words only, None and Underline Color ›
/// Automatic do what they say.
+45
View File
@@ -5837,6 +5837,51 @@ fn check_spelling_survives_restart() {
assert!(second.session.prefs.check_spelling, "the live spelling setting and its saved copy agree");
}
/// With several documents open, turning Check spelling as you type off in one keeps it off in the
/// others, and the next run starts with it off whichever document was active when the settings
/// were saved (#5740: it came back on every time the file was opened again).
#[test]
fn check_spelling_off_survives_a_switch_and_a_restart() {
let mut first = app();
let a = first.session.document_id();
first.run("file.new", json!({})).unwrap();
first.run("file.options", json!({"checkSpelling": false})).unwrap();
first.session.activate(a).unwrap();
assert!(!first.session.view.proofing, "off in the other document too");
let saved = serde_json::to_vec(&first.prefs()).unwrap();
let mut second = app();
second.apply_prefs(serde_json::from_slice(&saved).unwrap());
assert!(!second.session.view.proofing && !second.session.prefs.check_spelling);
}
/// The same across windows: Check spelling as you type turned off in a second window on a document
/// stays off when the first window's own view of it comes back, in a window on another document,
/// back in the second window, and in the saved settings (#5740).
#[test]
fn check_spelling_off_in_a_second_window_stays_off_in_every_window() {
let mut a = app();
let first = a.windows.shown();
a.new_window();
let second = a.windows.shown();
assert_ne!(first, second, "View › New Window opened a window with its own view");
a.run("file.options", json!({"checkSpelling": false})).unwrap();
assert!(a.enter_window(first));
assert!(!a.session.view.proofing, "the first window's own view, put back, follows the setting");
a.run("file.new", json!({})).unwrap();
assert!(!a.session.view.proofing, "a new document's window");
assert!(a.enter_window(second));
assert!(!a.session.view.proofing, "back in the second window");
assert!(a.enter_window(first));
assert!(!a.session.view.proofing);
let saved = serde_json::to_vec(&a.prefs()).unwrap();
let mut b = app();
b.apply_prefs(serde_json::from_slice(&saved).unwrap());
assert!(!b.session.view.proofing && !b.session.prefs.check_spelling, "saved off, whichever window was drawn");
}
#[test]
fn prefs_without_user_name_keep_default() {
let mut a = app();
+3 -1
View File
@@ -131,7 +131,7 @@ Measured by grepping `crates/docx/src/read` and `src/write` for the OOXML elemen
| DrawingML shapes and text boxes (`wps:`) | ✅ | ✅ | Preset geometries subset (callouts and flowchart boxes drawn as the nearest shape, #611); `flowChartOr` draws a circle with horizontal and vertical spokes; rounded rectangles keep their own corner (`roundRect` `adj`: read, written back, drawn on screen and in PDF, #1476); fill and outline from the shape or from the theme through its style references (`a:fillRef`/`a:lnRef`, #611), scheme, preset, system, scRGB and HSL colours; rotation and flips (`a:xfrm` `rot`/`flipH`/`flipV`, pictures and groups too, #332), the effect extent covering the rotated bounds; `wps:bodyPr` `vert` and `anchor`, internal margins (`lIns`/`tIns`/`rIns`/`bIns`) and Resize shape to fit text (`a:spAutoFit`: the text is never cut, #743), linked text boxes (`wps:txbx/@id`, `wps:linkedTxbx` `id`/`seq`, #369); text warps (`a:prstTxWarp` with adjust values, all 41 presets kept; unknown ones dropped), connectors (`straightConnector1`, `bentConnector2`–`5`, `curvedConnector2`–`5` read; 3-segment forms written) with glued ends (`wps:cNvCnPr` `a:stCxn`/`a:endCxn`; the glued shapes keep their drawing ids) and arrowheads (`a:headEnd`/`a:tailEnd` with their `type`, `w` and `len` kept; drawn as triangles 2, 3 or 5 times the line's width long and wide, as Word does), including custom-geometry paths (#416); fills with transparency (`a:alpha`) and gradients (`a:gradFill`: up to 10 stops each with its transparency, `a:lin` angle and `scaled`, `a:path` circle/rect/shape with `fillToRect`, `tileRect`, `rotWithShape`, `flip`) read and written as stated, also through the theme's fill styles (`a:fillRef` 1–999 `a:fillStyleLst`, 1001+ `a:bgFillStyleLst`, `phClr` in the reference's colour; written as the resolved fill), outline gradients kept (drawn in their middle stop) (#1500). Drawn: linear and circular; rectangular and shape-following paths drawn circular; `tileRect`/`flip` not drawn; pattern fills drawn and saved as their foreground colour. Hidden drawings (`wp:docPr/@hidden`, a group member's `cNvPr/@hidden`) are kept and saved but neither drawn nor laid out, nor exported to other formats, as in Word for Windows; `.doc` and RTF shapes don't read their hidden flag yet |
| Freeform shapes (`a:custGeom`: `a:moveTo`, `a:lnTo`, Bézier curves flattened) and WordCraft ink | ✅ | ✅ | Ink is written as a freeform `wps:wsp` in a `wp:anchor` (round caps, alpha for highlighter) and recognised again by its drawing name (#307). It is saved as a custom-geometry shape, not as Word's own ink (InkML in `w14:contentPart`), so Word shows WordCraft ink as a freeform shape it can move and recolour but not erase with its ink eraser; arcs drawn straight |
| Group shapes (`wpg:`), drawing canvas (`wpc:`) | ✅ | ✅ | Groups (#267) and canvases (#344) with pictures, shapes, freeforms (custom geometry, #743; a path drawn back to its start without `a:close` is filled, as in Word) and text boxes; nested groups flattened; members' `a:grpFill` takes their group's fill, and a canvas background (`wpc:bg`) may be a gradient or transparent (#1500). The canvas schema has no transform, so a turned or flipped canvas keeps its turn in our own `wpc:extLst` extension (`urn:wordcraft:canvas-xfrm`; Word shows it unturned). Legacy VML canvases (`v:group editas="canvas"`) aren't read as canvases |
| VML (`w:pict`, `v:shape`, `v:textbox`) | 🟡 | 🟡 | Pictures, text boxes, lines (with arrowheads, their kind, width and length kept), rectangles and ovals, best effort (#242, #611); `v:fill` opacity and gradients (`type="gradient"`/`gradientRadial`, `color2`, `colors`, `angle`, `focus`, `focusposition`, `o:opacity2`), saved as DrawingML (#1500). Preset shapes (`v:shape` whose `o:spt`, own or from its `v:shapetype`, or Word's shapetype id `_x0000_tNN`, names a preset; [MS-ODRAW] §2.4.24 numbers) are drawn and saved like the DrawingML preset of the same shape: exactly for rectangle, rounded rectangle, ellipse, diamond, isosceles triangle, five-point star, right arrow, line and straight connector, heart, text box, and the flowchart process, decision and connector; the others as their nearest shape, as for DrawingML (left/up/down arrows as the arrow, right triangle as the triangle, callouts as their box). Picture frames without a picture aren't drawn. Fill, outline and size come from the shape, else its shapetype; text inside keeps the shape around it (#1377). Adjust values (`adj`) aren't read: presets use WordCraft's proportions. Text boxes keep their internal margins (`inset`, unless `o:insetmode="auto"`), Resize shape to fit text (`mso-fit-shape-to-text`) and vertical alignment (`v-text-anchor`). Hidden shapes (`visibility:hidden`, like DrawingML's `wp:docPr/@hidden`) are kept and saved but neither drawn nor laid out, as in Word for Windows (Word for Mac draws them). Picture `gain` and `blacklevel` on `v:imagedata` (Word's picture watermark "Washout") are read as brightness and contrast (#1711). Saving as DOCX writes them as DrawingML `a:lum`; saving as Word 2003 XML writes them back as VML `gain`/`blacklevel` (transparency has no place on `v:imagedata` and is dropped there). Not read: vertical text (`layout-flow`) Word's text watermark (a `v:textpath` shape in a header or footer, recognised by Word's `PowerPlusWaterMarkObject` id or by being centred on the page both ways) becomes the document's watermark: text, font, fill colour, semitransparent (`v:fill` `opacity`) and diagonal (any turn); drawn with WordCraft's own size and angle, on every page even when only some sections' headers (or only the first-page header) have it (#1290). Saving writes the watermark back the same way: a `v:textpath` shape centred on the margins, behind the text, at the start of every header's first paragraph; a section whose pages would show no header gets a header holding only the watermark (default, and first-page or even-page ones when those are on), while sections linked to an earlier header stay linked. Freeforms (`v:shape` with its own `path`: moves, lines, Béziers and closes in its `coordsize`/`coordorigin` space, `nf`/`ns`, `v:stroke` opacity) are read as freeforms and saved as DrawingML custom geometry; fill opacity kept (no fill at 0); arcs are drawn straight; shapes whose path uses formulas (`@n`) and paths inherited from a `v:shapetype` aren't read. Word signature lines (Insert › Signature Line: a VML picture with an `o:signatureline`) are shown as their picture and saved back whole with it, at the size set in WordCraft, so they stay signable in Word instead of becoming plain pictures. Other VML is written only for OLE object pictures and signature lines. Other VML WordArt (Word 2007's: `v:textpath` in the body, or a header logo) becomes a text box without fill or outline holding its `string`, in the textpath's font, the shape's fill colour and a size from the shape's height; its WordArt shape (`o:spt` 136–175) becomes the DrawingML text warp of the same shape (#2875). Its outline, shadow and 3-D effects aren't read |
| VML (`w:pict`, `v:shape`, `v:textbox`) | 🟡 | 🟡 | Pictures, text boxes, lines (with arrowheads, their kind, width and length kept), rectangles and ovals, best effort (#242, #611); `v:fill` opacity and gradients (`type="gradient"`/`gradientRadial`, `color2`, `colors`, `angle`, `focus`, `focusposition`, `o:opacity2`), saved as DrawingML (#1500). Preset shapes (`v:shape` whose `o:spt`, own or from its `v:shapetype`, or Word's shapetype id `_x0000_tNN`, names a preset; [MS-ODRAW] §2.4.24 numbers) are drawn and saved like the DrawingML preset of the same shape: exactly for rectangle, rounded rectangle, ellipse, diamond, isosceles triangle, five-point star, right arrow, line and straight connector, heart, text box, and the flowchart process, decision and connector; the others as their nearest shape, as for DrawingML (left/up/down arrows as the arrow, right triangle as the triangle, callouts as their box). Picture frames without a picture aren't drawn. Fill, outline and size come from the shape, else its shapetype; text inside keeps the shape around it (#1377). Adjust values (`adj`) aren't read: presets use WordCraft's proportions. Text boxes keep their internal margins (`inset`, unless `o:insetmode="auto"`), Resize shape to fit text (`mso-fit-shape-to-text`) and vertical alignment (`v-text-anchor`). Hidden shapes (`visibility:hidden`, like DrawingML's `wp:docPr/@hidden`) are kept and saved but neither drawn nor laid out, as in Word for Windows (Word for Mac draws them). Picture `gain` and `blacklevel` on `v:imagedata` (Word's picture watermark "Washout") are read as brightness and contrast (#1711). Saving as DOCX writes them as DrawingML `a:lum`; saving as Word 2003 XML writes them back as VML `gain`/`blacklevel` (transparency has no place on `v:imagedata` and is dropped there). Text-box text direction is read as Word reads it: `mso-layout-flow-alt:bottom-to-top` as `vert270` whatever `layout-flow` says, else `layout-flow:vertical` or `vertical-ideographic` as `vert`, else horizontal (#5193). Word's text watermark (a `v:textpath` shape in a header or footer, recognised by Word's `PowerPlusWaterMarkObject` id or by being centred on the page both ways) becomes the document's watermark: text, font, fill colour, semitransparent (`v:fill` `opacity`) and diagonal (any turn); drawn with WordCraft's own size and angle, on every page even when only some sections' headers (or only the first-page header) have it (#1290). Saving writes the watermark back the same way: a `v:textpath` shape centred on the margins, behind the text, at the start of every header's first paragraph; a section whose pages would show no header gets a header holding only the watermark (default, and first-page or even-page ones when those are on), while sections linked to an earlier header stay linked. Freeforms (`v:shape` with its own `path`: moves, lines, Béziers and closes in its `coordsize`/`coordorigin` space, `nf`/`ns`, `v:stroke` opacity) are read as freeforms and saved as DrawingML custom geometry; fill opacity kept (no fill at 0); arcs are drawn straight; shapes whose path uses formulas (`@n`) and paths inherited from a `v:shapetype` aren't read. Word signature lines (Insert › Signature Line: a VML picture with an `o:signatureline`) are shown as their picture and saved back whole with it, at the size set in WordCraft, so they stay signable in Word instead of becoming plain pictures. Other VML is written only for OLE object pictures and signature lines. Other VML WordArt (Word 2007's: `v:textpath` in the body, or a header logo) becomes a text box without fill or outline holding its `string`, in the textpath's font, the shape's fill colour and a size from the shape's height; its WordArt shape (`o:spt` 136–175) becomes the DrawingML text warp of the same shape (#2875). Its outline, shadow and 3-D effects aren't read |
| Alt text of drawings (`wp:docPr`/`cNvPr` `descr` and `title`, decorative mark `adec:decorative` from [MS-ODRAWXML]) and tables (`w:tblCaption`, `w:tblDescription`) | ✅ | ✅ | Pictures, shapes, text boxes, groups and their members, charts and SmartArt; OLE objects get theirs written into the kept XML (#386) |
| Charts (`c:chart`), SmartArt (`dgm`) | ✅ | ✅ | Drawn from the chart's cached data and SmartArt's stored drawing (#292), with data labels (`c:showVal`); their text (title, axis labels, legend) is drawn in the document's body font, and characters it lacks (Chinese in Calibri's substitute) in a fallback face that covers them, one face per run as in body text (#4720); a chart of only types not drawn yet (radar, stock, bubble, surface, 3-D, pie of pie) shows a placeholder in its frame with its title and type (#998). Charts made in WordCraft (Insert › Chart, #409) are written as a `c:chartSpace` part with their data as literals (`c:strLit`/`c:numLit`, no embedded workbook, so Word shows them and offers to create a workbook on Edit Data) and read back as editable; a chart part holding anything more (any chart from Word, or one re-saved by Word) stays read-only. Saved back as read, with every part they reach (chart, embedded workbook, colours and style; diagram data, layout, quick style, colours and drawing) and their content types; a moved or resized one keeps its new frame, and a pasted copy gets its own parts (#319). SmartArt made in WordCraft (#497) is written from its model: data (`dgm:dataModel` points and connections), our own layout, quick-style and colour definitions under the built-in layout identifiers, and a `dsp:drawing` with every shape placed; it reads back editable only when its data part is exactly what WordCraft writes |
| OLE objects (`w:object`: embedded or linked files, ActiveX) | 🟡 | ✅ | Shown as their picture (VML or DrawingML); saved back whole with the embedding and picture parts, at the size, rotation and flips set in WordCraft (#319, #332). Can't be opened or edited |
@@ -321,6 +321,8 @@ For field results, the engine parser treats a backslash in quoted arguments as e
## Revision history
> 2026-11-07 · VML text boxes: `mso-layout-flow-alt:bottom-to-top` reads as `vert270` with any `layout-flow`, and `layout-flow:vertical` or `vertical-ideographic` otherwise as `vert`, so a compatibility-mode header's turned text box is drawn turned (#5193, `it::text_boxes::vml_text_boxes_keep_their_inset_fit_and_anchor`).
> 2026-11-03 · Section `w:chapStyle` values preserve the full unsigned-byte range, including 10, while values above 255 are rejected.
| 2026-10-30 | trivial | DOCX section metadata now preserves independent printer trays, section endnote suppression, chapter numbering settings, and footnote columns through native JSON and repeated save/reopen |
+9 -2
View File
File diff suppressed because one or more lines are too long
+11 -5
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -114,6 +114,7 @@ formatting of the text before the cursor. Not yet compared side by side in Word.
| Backspace at a paragraph start / Delete at a paragraph end (tracking on) | the paragraph mark is marked deleted (still shown); the caret moves before it (Backspace) or past it (Delete). Accept joins the paragraphs, Reject keeps them. A mark you inserted yourself is just removed | `tracked_enter_and_backspace_track_the_paragraph_mark`, `tests::tracked_backspace_and_delete_mark_a_paragraph_break_deleted` |
| Delete a range from the end of one paragraph into a later one (tracking on) | the paragraph marks and text in the range are tracked deletions. Accept All removes exactly those, so the paragraph after the range stays a paragraph of its own; Reject All restores everything. Typing into an empty paragraph and rejecting leaves that paragraph | `tests::accept_all_after_a_tracked_delete_from_a_paragraph_end_keeps_the_next_paragraph`, `tests::reject_all_after_typing_into_an_empty_paragraph_keeps_the_paragraph` |
| Backspace just after a section break / Delete just before it | the break goes and the two paragraphs join; the text before it takes the following section's page setup (Word's documented behaviour: a break holds the setup of the section before it); headers and footers the following section showed by linking to the previous one stay. Delete at the end of the last paragraph removes a break on its mark too, with no paragraph to join (with Track Changes on it still does nothing there). Undo brings the break back. Breaks read from a .docx and breaks inserted here alike (#2127) | `backspace_and_delete_remove_a_section_break`, `delete_removes_a_section_break_on_the_last_paragraph` |
| Accept All / Reject All of a paragraph left empty, whose mark carries a section break (tracking on, or a Compare result) | the paragraph goes whole and its section joins the following one, as when the break is deleted; the next paragraph keeps its own style and numbering, as for an empty paragraph without a break (#5667) | `resolving_away_an_empty_paragraph_with_a_section_break_keeps_the_next_paragraphs_properties` |
| Select All, then Delete or Backspace | the whole document goes, tables included, also when it starts with a table; one empty paragraph is left | `select_all_then_delete_removes_tables` |
| Backspace / Delete with a whole table selected (Select Table, or every cell dragged over) | Backspace removes the table, like Delete Table (one undo step; with tracking on its text is marked deleted and the structure stays); the caret goes to the paragraph after it. Delete clears the cells and keeps the table (each cell as below). A nested table goes on its own and leaves the cell's paragraph; a table that was the only block leaves one empty paragraph | `backspace_with_the_whole_table_selected_removes_the_table`, `delete_with_the_whole_table_selected_clears_the_cells_and_keeps_the_table`, `backspace_on_a_selected_nested_table_removes_only_it`, `backspace_on_a_selected_table_that_is_the_only_block_leaves_an_empty_paragraph`, `tracked_backspace_on_a_selected_table_marks_its_text_deleted_like_delete_table` |
| Backspace / Delete with a table and the paragraph before or after it selected | both remove the table, whatever end the selection starts in; the text around joins. Any table the selection covers whole goes, at any nesting level | `delete_or_backspace_with_the_table_and_the_paragraph_after_selected_removes_the_table`, `delete_or_backspace_with_the_paragraph_before_and_the_table_selected_removes_the_table` |
@@ -589,6 +590,7 @@ this correction; native Windows interaction and Microsoft Word remain untested.
|---|---|---|
| 2026-11-04 | trivial | Ctrl+K on a selection: a changed Text to display replaces the selected text before it is linked |
| 2026-10-30 | trivial | Equations: `\int` + Space waits for its limits; `_x^y` then Space builds them, Space alone builds the operator without, typing goes into its operand, and Enter or an arrow key builds it without going into the operand (#4917). Review: any character that can't continue `\name` corrects it (`\int_0^1`, `\alpha+`), and `∫∫` takes the operand into the inner operator; the Word rows are now observed in Word for Windows on #4938, Enter, arrows and `∫∫` are not |
| 2026-11-06 | trivial | Track Changes: resolving away an empty paragraph with a section break removes it whole; the next paragraph keeps its style (#5667) |
| 2026-11-03 | trivial | Alt+numpad codes type their character in text boxes too (Find what, dialog fields), not the digits or nothing (#4403) |
| 2026-11-03 | trivial | Find smart-quoted text with a keyboard apostrophe (#5388); exact search modes and replacement spelling preserved. |
| 2026-11-01 | minor | English spelling by dialect from SCOWL 2026: typed British, Canadian and Australian text, modern words and ordinals pinned (#40, #520, #1281, #1045; CP2) |
+3 -1
View File
@@ -42,9 +42,10 @@ Document title opens Rename Document; the account badge opens Options › Genera
| Backstage (Home, New, Open, Info, Save As, Print, Share, Export, Options) | Home and New separate (#254), Info properties kept (#268), Options in Word's panes with working settings (#485), Print page with preview, page range and copies (#641); Return on the Print page prints, as in Word, whose ⌘P opens on Print as the default button (not while a field or list on the page has the keyboard); launched with nothing to open, the app starts on Home (the Start screen: Blank document, templates, Recent; no document is open until one is picked or opened, so Esc or Back shows an empty window with the ribbon greyed out but for Help, #1129; File › Options works there, AutoCorrect Options included, #4585), with File › Options › General › Start-up to turn it off (#766); Info › Inspect Document finds and removes hidden text by its effective formatting (direct, character or paragraph style) in every story: body, headers, footers, notes, comments and text boxes, and lists what it couldn't reach (#1344); File › New, Open, the mailings and personal templates open their document beside the open ones, so they ask nothing; File › Close (Mod+W, Mod+F4) closes the shown document and keeps the window, showing the next open document, or no page after the last one, as Word does; the window's close button asks about each document with unsaved changes in turn, showing it, and Cancel stops the quit (#1712); each side-menu item has an icon, drawn in code (#1714); Info › Properties › Advanced Properties… opens the Custom Document Properties dialog (#2982); New lists personal templates (`.dotx`/`.dotm`) from the user templates folder under Personal, a subfolder per category, and its search covers them; a click makes an untitled document attached to the template; Save As › Save as Word Template starts in that folder; the folder is set in Options › Advanced › File locations (#2852; no thumbnails yet, no workgroup templates) | | 68% | 4–6 |
| Rulers: indents, tabs, margins, table columns | indents draggable (one undo, #62); tab stops: corner selector (Left/Center/Right/Decimal/Bar), click to set, drag to move, drag off to clear, per-kind markers, Alt skips the snap, one undo step per gesture, double-click opens the Tabs dialog (#320); table column and row markers drag their borders (one undo) and in a cell the indents are measured from it (#700); the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, never closer than 30 px, the small ticks never closer than 4 px, the text keeps its size), give way to an indent, tab or column marker on them, and the margins get ticks only; both rulers span the caret's page at its own scale in every layout (one column, One Page, Multiple Pages) and follow the caret to another page (#1878) | ✅ | 92% | 1 |
| On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text. Inside a Drawing Canvas a click picks the member under it (shape, picture or text box) on its own, its frame and handles shown inside the canvas frame; it is dragged, resized, turned and nudged inside the canvas, and Shape Format, Delete, Cut and Copy act on it alone; a click in a text box member's text puts the caret there (#2637, `objects::tests::clicking_and_dragging_inside_a_canvas_works_on_its_members`). Not yet: Shift+click on several members, dragging a member out of its canvas, drag-selecting a text box member's text, members of a turned canvas | ✅ | 75% | — |
| Rulers: indents, tabs, margins, table columns | indents draggable (one undo, #62); tab stops: corner selector (Left/Center/Right/Decimal/Bar), click to set, drag to move, drag off to clear, per-kind markers, Alt skips the snap, one undo step per gesture, double-click opens the Tabs dialog (#320); table column and row markers drag their borders (one undo) and in a cell the indents are measured from it (#700); the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, never closer than 30 px, the small ticks never closer than 4 px, the text keeps its size), give way to an indent, tab or column marker on them, and the margins get ticks only; both rulers span the caret's page at its own scale in every layout (one column, One Page, Multiple Pages) and follow the caret to another page (#1878); in a section of several text columns the spaces between them are shaded like the margins (Print Layout, in the main text outside tables, with the selection in one section), an edge dragged changes the spacing (equal columns stay equal, as in Word for Mac), one undo step per drag (#5197) | ✅ | 92% | 1 |
| On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text | ✅ | 75% | — |
| On-canvas objects: select, drag, Ctrl+drag to copy, Ctrl+Shift+drag to copy along an axis, resize handles, nudge | ✅ tested (#228, #1014); Ctrl/Command+Shift on a selected floating picture, shape or text box copies along the dominant horizontal or vertical axis, with guides only along the free axis; the original and clipboard stay, the duplicate is selected, and the drop is one undo step. Inline copies still follow the text insertion cursor (#4764). Synthetic Linux pointer/render tests only; native desktop and Word untested; an In Line with Text object drags within the text as in Word: a dashed insertion cursor follows the pointer through the text and the drop (or Ctrl+drop copy) lands there, still inline (#2233, #2234) | ✅ | 75% | — |
| Rotation handle, crop handles on canvas, alignment guides, smart guides | rotation handle (Shift: 15° steps), pictures and shapes without text stories preview their content turning while the pointer is held; release commits one `arrange.rotation` command and Escape cancels (#2277); text boxes retain a frame-only rotation preview, with text staying upright; turned frames resize along their axes (#332), and the arrow over each handle turns with the frame to the nearest of the four resize arrows (#3932); crop handles: Picture Format › Crop puts the picture in crop mode, black crop handles trim a side (a corner, two) keeping the scale and the visible part in place, the cropped-away part shows dimmed, Esc/Enter/a click outside/Crop again keep the crop, one undo step per drag (unturned pictures; no Crop to Shape, Aspect Ratio or Fill/Fit); alignment guides, our own design: a moved picture, shape or text box snaps its left, centre or right (top, middle or bottom) to the page's edges and centre, the margins and the other floating objects on the page within 6 screen points, x and y independently, turned objects by their rotated bounds, with a thin line across the page for each guide while dragging; Alt moves freely; File › Options › Advanced › Editing (`ui.alignmentGuides`) turns them off. Smart guides missing | Word for Mac 16.113.4 shows no guide lines and snaps inconsistently (to the page's left edge, not its top, right or bottom; Word check K); Word for Windows' guides not observed | 75% | 1–2 |
| On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text | ✅ | 75% | — |
| On-canvas objects: select, drag, Ctrl+drag to copy, Ctrl+Shift+drag to copy along an axis, resize handles, nudge | ✅ tested (#228, #1014); Ctrl/Command+Shift on a selected floating picture, shape or text box copies along the dominant horizontal or vertical axis, with guides only along the free axis; the original and clipboard stay, the duplicate is selected, and the drop is one undo step. Inline copies still follow the text insertion cursor (#4764). Synthetic Linux pointer/render tests only; native desktop and Word untested; an In Line with Text object drags within the text as in Word: a bold insertion cursor (solid, twice the caret's width) follows the pointer through the text and the drop (or Ctrl+drop copy) lands there, still inline (#2233, #2234, #4195) | ✅ | 75% | — |
| Rotation handle, crop handles on canvas, alignment guides, smart guides | rotation handle (Shift: 15° steps), pictures and shapes without text stories preview their content turning while the pointer is held; release commits one `arrange.rotation` command and Escape cancels (#2277); text boxes retain a frame-only rotation preview, with text staying upright; turned frames resize along their axes (#332); crop handles: Picture Format › Crop puts the picture in crop mode, black crop handles trim a side (a corner, two) keeping the scale and the visible part in place, the cropped-away part shows dimmed, Esc/Enter/a click outside/Crop again keep the crop, one undo step per drag (unturned pictures; no Crop to Shape, Aspect Ratio or Fill/Fit); alignment guides, our own design: a moved picture, shape or text box snaps its left, centre or right (top, middle or bottom) to the page's edges and centre, the margins and the other floating objects on the page within 6 screen points, x and y independently, turned objects by their rotated bounds, with a thin line across the page for each guide while dragging; Alt moves freely; File › Options › Advanced › Editing (`ui.alignmentGuides`) turns them off. Smart guides missing | Word for Mac 16.113.4 shows no guide lines and snaps inconsistently (to the page's left edge, not its top, right or bottom; Word check K); Word for Windows' guides not observed | 75% | 1–2 |
| Tables on the page: drag column and row borders, resize handle past the bottom-right corner; select columns, rows and cells; "+" insert buttons; move handle | ✅ resize cursors, dashed guide, one undo step per drag, selection kept; Shift moves one column; Esc cancels (#217); Ctrl shares the change among the columns on the right, the left edge moves a left-aligned table's indent (a centred or right-aligned one keeps its alignment), a border of cells selected across moves only in their rows, Alt shows the column widths on the ruler (#711); double-click a column border to AutoFit it (a nested table's within the cell around it, #971); selection arrows above a column, left of a row and along a cell's left edge (a drag selects more; the cells are shaded and a column is edited cell by cell); "+" left of a row border and above a column border; move handle past the top-left corner (a click selects the table, a drag floats it where it's dropped); both handles also show while the caret is in the table, as in Word (#2428); an ordinary drag, Shift+arrows or Shift+click from one cell into another select the rectangle of whole cells between them, and into or out of a table whole rows, their cells shaded whole (#971). Missing: a single selected cell's border; The Cell Size Height and Width boxes set every selected row and column (#1242). | ✅ | 95% | 1 |
@@ -118,6 +119,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
| 2026-10-17 | trivial | Drawing Canvas members are selected with a click and dragged, resized, turned, nudged, formatted, deleted and copied on their own inside the canvas; a click in a text box member's text puts the caret there (#2637) |
| 2026-11-05 | trivial | On-canvas objects: dragging an In Line with Text picture, shape or text box shows a bold, solid insertion cursor, twice the caret's width, as in Word; the dashed one was hard to see (#4195) |
| 2026-10-28 | trivial | Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged. |
| 2026-11-01 | trivial | Rulers: the spaces between text columns are shaded on the horizontal ruler (Print Layout, in the main text outside tables, with the selection in one section); dragging an edge changes the spacing; equal columns stay equal, as in Word for Mac (#5197) |
| 2026-10-31 | trivial | Dialogs are modal (#3859): while one is open, clicks on the ribbon, File or the page, typing and shortcuts do nothing, as in Word. Find and Replace, Symbol, Mark Index Entry, Cross-reference and Insert Merge Field stay modeless, as in Word for Mac. A press beside a modal dialog shakes it a little, or flashes its border with animation effects off, so it is clear why nothing behind it reacts |
| 2026-10-17 | trivial | Copy and Cut put RTF beside the text and HTML on the system clipboard, for programs that read RTF rather than HTML (Windows "Rich Text Format", macOS `public.rtf`, Wayland `text/rtf`; an X11 copy stays text and HTML, since arboard owns the selection there; a copy of only pictures or shapes carries no HTML or RTF, so pasting it back keeps every detail); Paste reads another program's RTF on macOS and X11 too, as on Windows and Wayland |
| 2026-11-04 | trivial | Table Sort rejects malformed or nonexistent explicit columns before mutation; valid columns, the omitted-column default and history are retained (#5531). Readiness estimates unchanged. |