//! Tests of the layout of tables, with the layout test harness of `layout/testing.rs`.
use f_office_fonts::{FamilyName, FontId};
use f_office_paint::{DisplayList, FillRule, Item, Page, PathCommand, PathItem, Point, Rgb};
use f_office_units::Length;
use super::{CellFloor, Sides, align, band, heavier, row_height};
use crate::body::Sections;
use crate::grid::DOT;
use crate::layout::testing::{
Fake, NORMAL, SINGLE, at, base, base_context, du, find, find_all, indented, lay_out,
on_base_with, p, pass_on, pass_with, pass_with_header, rects, table, x_du,
};
use crate::layout::{EarlierPass, Layout, SectionLayout};
use crate::numbering::Numbering;
use crate::props::{Border, BorderParts, Color};
use crate::quirks::{ExactRowMargin, RightToLeftEdge};
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::table::{HeightRule, Region, VerticalAlign};
use crate::tests::{HEADER_REFERENCE, package};
use crate::text::{Shaper, ShaperSettings};
use crate::{ChosenFace, Fonts};
mod cell_drawings;
mod cell_room;
mod clips;
mod dashes;
mod floating_lefts;
mod floating_tables;
mod floating_tops;
mod keeps;
mod pages;
mod spaced_breaks;
mod top_dots;
mod top_room;
mod trials;
mod turned;
/// Lays out a body on a device of 600 dots per inch whose table lines are centered on their
/// grid lines (`TableLines::RoundsCenters`).
fn lay_out_centered_lines(body: &str, styles: &str, mode: Option<u32>) -> DisplayList {
let target = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::TableLines::RoundsCenters)
});
pass_with(body, (styles, mode), None, Numbering::default(), target).list
}
fn font_of(list: &DisplayList, ch: char) -> FontId {
run_of(list, ch).font
}
fn run_of(list: &DisplayList, ch: char) -> &f_office_paint::GlyphRun {
list.pages()
.iter()
.flat_map(Page::items)
.find_map(|item| match item {
Item::Glyphs(run) if run.text.contains(ch) => Some(run),
_ => None,
})
.unwrap()
}
#[test]
fn takes_the_cell_margins_and_borders_of_a_row_s_exceptions() {
// The table has 108 twip cell margins, a top border and lines between its rows. The first
// row has no top border for itself (`w:tblPrEx`), and the second row a left cell margin
// of 400 twips.
let first = r#"<w:tblPrEx><w:tblBorders><w:top w:val="none"/></w:tblBorders></w:tblPrEx>"#;
let second =
r#"<w:tblPrEx><w:tblCellMar><w:left w:w="400" w:type="dxa"/></w:tblCellMar></w:tblPrEx>"#;
let body = format!(
r#"<w:tbl><w:tblPr><w:tblBorders><w:top {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{first}<w:tc>{}</w:tc></w:tr><w:tr>{second}<w:tc>{}</w:tc></w:tr><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>"#,
p("a"),
p("b"),
p("c")
);
let list = lay_out(&body, NORMAL, None);
let x = |ch| x_du(find(&list, ch).1);
assert_eq!(x('b') - x('a'), du(400 - 108));
assert_eq!(x('c'), x('a'));
// The first row starts at the 1440 twip margin without a line, and its text right there.
assert!(rects(&list, 0).iter().all(|r| r.1 != du(1440)));
assert_eq!(find(&list, 'a').2, base(1440));
// The lines between the rows stay.
assert_eq!(rects(&list, 0).len(), 2);
}
#[test]
fn hangs_the_first_cell_margin_into_the_margin_before_mode_15() {
let list = lay_out(
&(table("", &[2000, 3000], &[("", &[&p("a"), &p("b")])]) + &p("c")),
NORMAL,
Some(14),
);
// The text of the first cell sits at the 1440 twip margin, and the second cell starts at
// 1440 - 108 + 2000 twips.
assert_eq!(find(&list, 'a'), (0, 1440 * 1270, base(1440)));
let (_, x, y) = find(&list, 'b');
assert_eq!((x_du(x), y), (du(3440), base(1440)));
// The paragraph after the table starts below the 200 twip row.
assert_eq!(find(&list, 'c').2, base(1640));
assert_eq!(rects(&list, 0), Vec::new());
}
#[test]
fn takes_the_widths_of_grid_columns_without_a_width_from_the_cells() {
// A table across the 9,360 twip text width, whose first cell asks for 25%.
let row = |first: &str| {
format!(
"<w:tr><w:tc><w:tcPr>{first}</w:tcPr>{}</w:tc><w:tc>{}</w:tc></w:tr>",
p("a"),
p("b")
)
};
let whole = r#"<w:tblPr><w:tblW w:w="5000" w:type="pct"/></w:tblPr>"#;
let quarter = row(r#"<w:tcW w:w="1250" w:type="pct"/>"#);
let at = |body: &str| {
let list = lay_out(&(body.to_owned() + &p("c")), NORMAL, Some(15));
(find(&list, 'a'), find(&list, 'b'))
};
let written = |grid: &[i64]| table("", grid, &[("", &[&p("a"), &p("b")])]);
// An empty grid takes the 25% and the rest.
let empty =
format!("<w:tbl>{whole}<w:tblGrid><w:gridCol/><w:gridCol/></w:tblGrid>{quarter}</w:tbl>");
assert_eq!(at(&empty), at(&written(&[2340, 7020])));
// Without a grid and without cell widths, the columns share the table's width.
let shared = format!("<w:tbl>{whole}{}</w:tbl>", row(""));
assert_eq!(at(&shared), at(&written(&[4680, 4680])));
}
/// A table of two cells with single borders on all sides, followed by a paragraph.
fn bordered() -> String {
let borders = format!(
"<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
);
table(&borders, &[2000, 3000], &[("", &[&p("a"), &p("b")])]) + &p("c")
}
#[test]
fn puts_the_outer_edge_of_the_left_border_at_the_indent_from_mode_15() {
let list = lay_out(&bordered(), NORMAL, Some(15));
// Half the 10 twip border, then the 108 twip margin. The top border comes above the text.
let (_, x, y) = find(&list, 'a');
assert_eq!((x_du(x), y), (du(1440 + 5 + 108), base(1440 + 10)));
let (_, x, _) = find(&list, 'b');
assert_eq!(x_du(x), du(1445 + 2000 + 108));
// The bottom border comes below the last row.
assert_eq!(find(&list, 'c').2, base(1440 + 10 + 200 + 10));
let old = lay_out(&bordered(), NORMAL, None);
let (_, x, _) = find(&old, 'a');
assert_eq!(x_du(x), 300);
}
#[test]
fn puts_a_nested_table_at_the_outer_edge_of_its_left_border_in_every_mode() {
let borders = format!("<w:tblBorders><w:left {SINGLE}/></w:tblBorders>");
let inner = table(&borders, &[2000], &[("", &[&p("a")])]);
let cell = inner + &p("b");
let outer = table("", &[4000], &[("", &[&cell])]) + &p("c");
let list = lay_out(&outer, NORMAL, Some(14));
// Before mode 15, the outer table's text sits at the margin, but the nested table puts the
// outer edge of its 10 twip border there and its text after half that and the margin.
assert_eq!(x_du(find(&list, 'b').1), du(1440));
assert_eq!(x_du(find(&list, 'a').1), du(1440 + 5 + 108));
}
#[test]
fn starts_the_text_after_the_left_border_without_a_left_margin() {
// No style sets cell margins, so the text of each cell starts after its 10 twip border.
let list = lay_out(&bordered(), "", Some(12));
assert_eq!(x_du(find(&list, 'a').1), du(1440 + 10));
assert_eq!(x_du(find(&list, 'b').1), du(1440 + 2000 + 10));
// A left margin of 0 that the table sets keeps the text on the grid line.
let zero = bordered().replace(
"<w:tblBorders>",
r#"<w:tblCellMar><w:left w:w="0" w:type="dxa"/></w:tblCellMar><w:tblBorders>"#,
);
let list = lay_out(&zero, "", Some(12));
assert_eq!(x_du(find(&list, 'a').1), du(1440));
}
#[test]
fn draws_borders_around_the_cells() {
let list = lay_out(&bordered(), NORMAL, Some(15));
let rects = rects(&list, 0);
// The lines run between the junctions, and each junction is a square of its own: two at
// a corner of the table, where two lines end, and one where a line runs on.
let square = |x: i64, y: i64| rects.iter().filter(|r| **r == (x, y, 2, 2)).count();
let (bottom, middle, right) = (du(1650), du(1440 + 2000), du(1440 + 5000));
assert_eq!(
[square(300, 300), square(middle, 300), square(right, 300)],
[2, 1, 2]
);
assert_eq!(
[
square(300, bottom),
square(middle, bottom),
square(right, bottom)
],
[2, 1, 2]
);
// The left border, two device dots wide, runs from below the top line to the bottom one.
assert!(rects.contains(&(300, 302, 2, bottom - 302)));
// The top line runs from the left line to the line between the cells, and on from there.
assert!(rects.contains(&(302, 300, middle - 302, 2)));
assert!(rects.contains(&(middle + 2, 300, right - middle - 2, 2)));
assert_eq!(rects.len(), 17);
}
#[test]
fn leaves_out_a_hidden_row_that_shows_nothing_with_its_lines() {
let borders = format!(
"<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders>"
);
let hidden_mark = r"<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr></w:p>";
let hidden_text = r"<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:rPr><w:vanish/></w:rPr><w:t>h</w:t></w:r></w:p>";
let laid = |body: &str| lay_out(body, NORMAL, Some(15));
// A table of one hidden row that shows nothing is not there: the paragraph after it stands
// where it stands without the table, and no line is drawn.
let alone = p("a") + &table(&borders, &[2000], &[("<w:hidden/>", &[hidden_mark])]) + &p("c");
let list = laid(&alone);
assert_eq!(find(&list, 'c'), find(&laid(&(p("a") + &p("c"))), 'c'));
assert_eq!(rects(&list, 0), [] as [(i64, i64, i64, i64); 0]);
// Above a row that shows, the table is that row alone, with its top line.
let one = laid(&(table(&borders, &[2000], &[("", &[&p("b")])]) + &p("c")));
let b = p("b");
let rows = [("<w:hidden/>", &[hidden_text][..]), ("", &[b.as_str()][..])];
let above = laid(&(table(&borders, &[2000], &rows) + &p("c")));
assert_eq!(rects(&above, 0), rects(&one, 0));
assert_eq!(find(&above, 'c'), find(&one, 'c'));
// A hidden row whose text shows stays, and so does a row that shows its row-end mark.
let shown = laid(&(table(&borders, &[2000], &[("<w:hidden/>", &[&p("b")])]) + &p("c")));
assert_eq!(rects(&shown, 0), rects(&one, 0));
let mark_shown = laid(&(table(&borders, &[2000], &[("", &[hidden_mark])]) + &p("c")));
assert_ne!(rects(&mark_shown, 0), [] as [(i64, i64, i64, i64); 0]);
}
/// The rectangles of page `page` that are drawn more than once and are not junction squares,
/// which Word draws once for each line that ends there: the lines drawn twice.
fn doubled_lines(list: &DisplayList, page: usize) -> Vec<(i64, i64, i64, i64)> {
let rects = rects(list, page);
let mut doubled: Vec<_> = rects
.iter()
.filter(|r| r.2 != r.3 && rects.iter().filter(|s| s == r).count() > 1)
.copied()
.collect();
doubled.sort_unstable();
doubled.dedup();
doubled
}
#[test]
fn draws_the_line_that_two_cells_or_two_rows_share_once() {
// Two rows of two cells, with every border: the line between the cells is the right
// border of the first cell and the left border of the second, and the line between the
// rows the top border of the second row, which takes the bottom border of the first.
let borders = format!(
"<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideH {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
);
let rows: [(&str, &[&str]); 2] = [("", &[&p("a"), &p("b")]), ("", &[&p("c"), &p("d")])];
let list = lay_out(&table(&borders, &[2000, 3000], &rows), NORMAL, Some(15));
assert_eq!(doubled_lines(&list, 0), []);
// The line between the cells runs down each row once, between the squares.
let middle = du(1440 + 2000);
let between: Vec<_> = rects(&list, 0)
.into_iter()
.filter(|r| r.0 == middle && r.2 == 2 && r.3 > 2)
.collect();
assert_eq!(between.len(), 2, "{between:?}");
}
#[test]
fn draws_the_line_between_two_cells_of_the_last_row_once_when_one_has_no_bottom() {
// One row of two cells with every border, but the second cell takes away its bottom: the
// line between the cells is the first cell's right border, which ends with its bottom
// line, and the second cell's left border, which ends at the row's bottom.
let borders = format!(
"<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
);
let open = format!(
r#"<w:tcPr><w:tcBorders><w:bottom w:val="nil"/></w:tcBorders></w:tcPr>{}"#,
p("b")
);
let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &open])];
let list = lay_out(&table(&borders, &[2000, 3000], &rows), NORMAL, Some(15));
assert_eq!(doubled_lines(&list, 0), []);
// The line between the cells runs once from the square at the top to the square of the
// first cell's bottom line.
let middle = du(1440 + 2000);
let between: Vec<_> = rects(&list, 0)
.into_iter()
.filter(|r| r.0 == middle && r.2 == 2 && r.3 > 2)
.collect();
assert_eq!(between, [(middle, 302, 2, du(1650) - 302)]);
}
#[test]
fn lays_the_cells_of_a_right_to_left_table_out_from_the_right() {
let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &p("b"), &p("c")])];
let ltr = lay_out(&table("", &[2000, 3000, 4000], &rows), NORMAL, Some(15));
let rtl = lay_out(
&table("<w:bidiVisual/>", &[2000, 3000, 4000], &rows),
NORMAL,
Some(15),
);
// Left to right, "a" comes first; right to left, "c" comes first and "a" last.
let x = |list: &DisplayList, ch| find(list, ch).1;
assert!(x(<r, 'a') < x(<r, 'b') && x(<r, 'b') < x(<r, 'c'));
assert!(x(&rtl, 'c') < x(&rtl, 'b') && x(&rtl, 'b') < x(&rtl, 'a'));
// The column of the margins holds the 9,000 twip table at its right: the first cell's
// grid line on the right is at the right margin of 12,240 - 1,440 twips, so "a" starts a
// cell margin right of the cell's left grid line, 2,000 twips further left.
assert_eq!(x_du(x(&rtl, 'a')), du(12_240 - 1_440 - 2_000 + 108));
}
#[test]
fn draws_the_outer_lines_of_a_right_to_left_table_around_its_cells() {
let borders = format!(
"<w:bidiVisual/><w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
);
let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &p("b")])];
let list = lay_out(&table(&borders, &[2000, 3000], &rows), NORMAL, Some(15));
let rects = rects(&list, 0);
assert!(rects.iter().all(|r| r.2 > 0 && r.3 > 0), "{rects:?}");
// The lines at the table's top run from the outer edge of its left line to the outer edge
// of its right line, as in a table from left to right.
let left = rects.iter().map(|r| r.0).min();
let right = rects.iter().map(|r| r.0 + r.2).max();
let top = rects.iter().map(|r| r.1).min();
let at_top: Vec<_> = rects.iter().filter(|r| Some(r.1) == top).collect();
assert_eq!(at_top.iter().map(|r| r.0).min(), left, "{rects:?}");
assert_eq!(at_top.iter().map(|r| r.0 + r.2).max(), right, "{rects:?}");
}
#[test]
fn starts_a_right_to_left_table_wider_than_the_text_at_the_left_margin() {
let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &p("b")])];
let wide = |properties: &str, section: &str, mode: u32| {
let body = table(properties, &[3000, 7000], &rows) + section;
lay_out(&body, NORMAL, Some(mode))
};
let x = |list: &DisplayList, ch| x_du(find(list, ch).1);
// In a left-to-right section the table of 10,000 twips goes over the left margin: its
// right grid line is at the right margin.
let list = wide("<w:bidiVisual/>", "", 15);
assert_eq!(x(&list, 'a'), du(12_240 - 1_440 - 3_000 + 108));
// So it does in a right-to-left section in mode 14, where the grid lies a cell margin
// further out.
let section = "<w:sectPr><w:bidi/></w:sectPr>";
let list = wide("<w:bidiVisual/>", section, 14);
assert_eq!(x(&list, 'a'), du(12_240 - 1_440 - 3_000 + 2 * 108));
// In a right-to-left section from mode 15 its left grid line stays at the left margin,
// also with an indent that moves its leading edge to the right, and when centered.
for properties in [
"<w:bidiVisual/>",
r#"<w:bidiVisual/><w:tblInd w:w="-226" w:type="dxa"/>"#,
r#"<w:bidiVisual/><w:jc w:val="center"/>"#,
] {
let list = wide(properties, section, 15);
assert_eq!(x(&list, 'b'), du(1_440 + 108));
assert_eq!(x(&list, 'a'), du(1_440 + 7_000 + 108));
}
}
#[test]
fn moves_a_right_to_left_table_in_by_the_lines_of_its_first_and_last_cell_where_the_quirk_says() {
let line = |side: &str, eighths: u32| {
if eighths == 0 {
format!(r#"<w:{side} w:val="nil"/>"#)
} else {
format!(r#"<w:{side} w:val="single" w:sz="{eighths}"/>"#)
}
};
let cell = |own: &str, text: &str| {
format!(
"<w:tcPr><w:tcBorders>{own}</w:tcBorders></w:tcPr>{}",
p(text)
)
};
// The place of "c", in the last cell at the table's left end beside its 1 pt line that the
// file calls right, in a right-to-left table of mode 15 whose line that the file calls left
// is `left` and whose lines between cells are `inside` eighths of a point wide, with the
// own lines `second` of the second cell and `last` of the last.
let x = |edge: RightToLeftEdge, (left, inside): (u32, u32), (second, last): (&str, &str)| {
let props = format!(
"<w:bidiVisual/><w:tblBorders><w:top {SINGLE}/>{}<w:bottom {SINGLE}/>{}{}</w:tblBorders>",
line("left", left),
line("right", 8),
line("insideV", inside)
);
let cells = [p("a"), cell(second, "b"), cell(last, "c")];
let rows: [(&str, &[&str]); 1] = [("", &[&cells[0], &cells[1], &cells[2]])];
let body = table(&props, &[2000, 3000, 4000], &rows);
let target = crate::layout::testing::target_at(600, |configuration| {
configuration.with_variant(edge)
});
let pass = pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
target,
);
x_du(find(&pass.list, 'c').1)
};
// A 3 pt line at the leading edge and nil lines between cells: the line between the first
// two cells moves nothing, and the leading line moves the table half its width, 30 twips.
let (between, leading) = (
RightToLeftEdge::BetweenCells,
RightToLeftEdge::LeadingAndInside,
);
assert_eq!(
x(between, (24, 0), ("", "")) - x(leading, (24, 0), ("", "")),
du(30)
);
// With lines of 3 pt between cells, the second cell's own nil line toward the first moves
// nothing, and the last cell's own nil line that the file calls left takes their half, 30
// twips, away.
let (own_nil, plain) = (line("left", 0), x(leading, (8, 24), ("", "")));
assert_eq!(x(leading, (8, 24), (&own_nil, "")), plain);
assert_eq!(x(leading, (8, 24), ("", &own_nil)) - plain, du(30));
}
#[test]
fn moves_a_floating_right_to_left_table_left_by_the_line_of_its_last_cell_where_the_quirk_says() {
let line = |side: &str, eighths: u32| {
if eighths == 0 {
format!(r#"<w:{side} w:val="nil"/>"#)
} else {
format!(r#"<w:{side} w:val="single" w:sz="{eighths}"/>"#)
}
};
// The place of "c", in the last cell at the table's left end, in a right-to-left table of
// mode 15 that floats 720 twips right of the margin, whose line that the file calls left is
// `left` and whose lines between cells are `inside` eighths of a point wide, with the own
// lines `last` of the last cell.
let x = |edge: RightToLeftEdge, (left, inside): (u32, u32), last: &str| {
let props = format!(
r#"<w:tblpPr w:vertAnchor="text" w:horzAnchor="margin" w:tblpX="720" w:tblpY="1"/><w:bidiVisual/><w:tblBorders><w:top {SINGLE}/>{}<w:bottom {SINGLE}/>{}{}</w:tblBorders>"#,
line("left", left),
line("right", 8),
line("insideV", inside)
);
let own = format!(
"<w:tcPr><w:tcBorders>{last}</w:tcBorders></w:tcPr>{}",
p("c")
);
let cells = [p("a"), p("b"), own];
let rows: [(&str, &[&str]); 1] = [("", &[&cells[0], &cells[1], &cells[2]])];
let body = table(&props, &[2000, 3000, 4000], &rows) + &p("after");
let target = crate::layout::testing::target_at(600, |configuration| {
configuration.with_variant(edge)
});
let pass = pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
target,
);
x_du(find(&pass.list, 'c').1)
};
let (between, leading) = (
RightToLeftEdge::BetweenCells,
RightToLeftEdge::LeadingAndInside,
);
// With lines of 3 pt between cells, the earlier rule moves the table right by half the line
// between its first two cells, 30 twips, and the quirk moves it left by half the last
// cell's line toward the cell before it, 30 twips.
assert_eq!(x(between, (8, 24), "") - x(leading, (8, 24), ""), du(60));
// The line at the leading edge moves nothing.
assert_eq!(x(leading, (24, 8), ""), x(leading, (8, 8), ""));
// The last cell's own nil line takes the half of the lines between cells away.
let own_nil = line("left", 0);
assert_eq!(
x(leading, (8, 24), &own_nil) - x(leading, (8, 24), ""),
du(30)
);
}
#[test]
fn draws_the_bottom_of_a_cell_with_no_cell_below_it() {
let borders = format!(
"<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideH {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
);
let rows: [(&str, &[&str]); 3] = [
("", &[&p("a"), &p("b")]),
// The second row leaves out the second grid column.
(r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
("", &[&p("d"), &p("e")]),
];
let body = table(&borders, &[2000, 3000], &rows) + &p("f");
let list = lay_out(&body, NORMAL, Some(15));
let rects = rects(&list, 0);
// Below "b", where the second row has no cell, a line runs from the line between the cells
// to the right edge of the table, at the top of the second row.
let second_row = du(1440 + 10 + 200);
let line = |r: &&(i64, i64, i64, i64)| r.3 == 2 && r.2 > du(2900) && r.2 < du(3100);
let lines: Vec<i64> = rects.iter().filter(line).map(|r| r.1).collect();
// One line above "b", one below it, one above "e" and one below it.
assert_eq!(lines.len(), 4);
assert!(lines.contains(&second_row));
}
/// The colors of the vertical lines of the first page of `body` with the quirk `ends`, as
/// their red and green channels and their left edge in dots, from left to right and from the
/// top down.
fn vertical_colors(body: &str, ends: crate::quirks::RowEndBorders) -> Vec<(u8, u8, i64, i64)> {
let target = on_base_with(|p| p.with_variant(ends));
vertical_lines(body, NORMAL, &target)
}
/// The colors of the vertical lines of the first page of `body` with the styles `styles` on
/// `target`, as their red and green channels and their left edge in dots, from left to right
/// and from the top down.
fn vertical_lines(
body: &str,
styles: &str,
target: &(crate::grid::Device, crate::quirks::Quirks),
) -> Vec<(u8, u8, i64, i64)> {
let list = pass_with(body, (styles, None), None, Numbering::default(), *target).list;
let mut lines: Vec<(u8, u8, i64, i64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) if r.height.units() > 4 * r.width.units() => {
Some((r.color.r, r.color.g, r.x.units() / DOT, r.y.units() / DOT))
}
_ => None,
})
.collect();
lines.sort_by_key(|line| (line.2, line.3));
lines
}
#[test]
fn gives_a_rows_last_cell_the_outer_right_border_on_a_target_that_does() {
// Three rows of two grid columns; the second row leaves out the second column. The table's
// outer right border is red and its inside vertical border green. Under `RowEnds`, the
// second row's one cell takes the red line on its right, where the grid's columns meet;
// under `GridEdges`, the green one, as between two cells.
let borders = format!(
r#"<w:tblBorders><w:right {SINGLE} w:color="FF0000"/><w:insideV {SINGLE} w:color="00FF00"/></w:tblBorders>"#
);
let rows: [(&str, &[&str]); 3] = [
("", &[&p("a"), &p("b")]),
(r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
("", &[&p("d"), &p("e")]),
];
let body = table(&borders, &[2000, 3000], &rows);
let red = |lines: &[(u8, u8, i64, i64)]| lines.iter().filter(|l| l.0 == 0xFF).count();
let green = |lines: &[(u8, u8, i64, i64)]| lines.iter().filter(|l| l.1 == 0xFF).count();
let ends = vertical_colors(&body, crate::quirks::RowEndBorders::RowEnds);
assert_eq!((red(&ends), green(&ends)), (3, 2), "{ends:?}");
// The red line of the second row stands where the green lines of the other rows stand.
let middle: Vec<_> = ends.iter().filter(|l| l.2 == ends[0].2).collect();
assert_eq!(middle.len(), 3, "{ends:?}");
assert_eq!(middle[1].0, 0xFF, "{ends:?}");
let edges = vertical_colors(&body, crate::quirks::RowEndBorders::GridEdges);
assert_eq!((red(&edges), green(&edges)), (2, 3), "{edges:?}");
}
#[test]
fn gives_the_side_lines_of_a_style_region_to_its_outer_cells_only_on_a_target_that_does() {
// The header row's region sets red left and right lines and no line between its cells
// (`w:insideV` nil), and the table no lines of its own. Under `Blocks`, the header row draws
// red lines only at the table's left and right; under `EachCell`, each of its three cells
// takes both red lines, which stand at all four grid lines. The second row draws none.
let style = format!(
r#"{NORMAL}<w:style w:type="table" w:styleId="Head"><w:basedOn w:val="TableNormal"/>
<w:tblStylePr w:type="firstRow"><w:tcPr><w:tcBorders><w:left {SINGLE} w:color="FF0000"/>
<w:right {SINGLE} w:color="FF0000"/><w:insideV w:val="nil"/></w:tcBorders></w:tcPr></w:tblStylePr></w:style>"#
);
let look = r#"<w:tblStyle w:val="Head"/><w:tblLook w:firstRow="1"/>"#;
let rows: [(&str, &[&str]); 2] = [
("", &[&p("a"), &p("b"), &p("c")]),
("", &[&p("d"), &p("e"), &p("f")]),
];
let body = table(look, &[2000, 2000, 2000], &rows);
let lines = |regions| {
let target = on_base_with(|p| p.with_variant(regions));
vertical_lines(&body, &style, &target)
};
let blocks = lines(crate::quirks::StyleRegionBorders::Blocks);
assert_eq!(blocks.len(), 2, "{blocks:?}");
assert!(blocks.iter().all(|line| line.0 == 0xFF), "{blocks:?}");
let each = lines(crate::quirks::StyleRegionBorders::EachCell);
assert_eq!(each.len(), 4, "{each:?}");
}
#[test]
fn gives_a_rows_first_cell_after_grid_before_the_outer_left_border_on_a_target_that_does() {
// The second row starts after the first grid column. The table's outer left border is
// red and its inside vertical border green; the second row's one cell takes the red line
// on its left under `RowEnds`, and the green one under `GridEdges`.
let borders = format!(
r#"<w:tblBorders><w:left {SINGLE} w:color="FF0000"/><w:insideV {SINGLE} w:color="00FF00"/></w:tblBorders>"#
);
let rows: [(&str, &[&str]); 3] = [
("", &[&p("a"), &p("b")]),
(r#"<w:gridBefore w:val="1"/>"#, &[&p("c")]),
("", &[&p("d"), &p("e")]),
];
let body = table(&borders, &[2000, 3000], &rows);
let count = |lines: &[(u8, u8, i64, i64)]| {
(
lines.iter().filter(|l| l.0 == 0xFF).count(),
lines.iter().filter(|l| l.1 == 0xFF).count(),
)
};
assert_eq!(
count(&vertical_colors(
&body,
crate::quirks::RowEndBorders::RowEnds
)),
(3, 2)
);
assert_eq!(
count(&vertical_colors(
&body,
crate::quirks::RowEndBorders::GridEdges
)),
(2, 3)
);
}
#[test]
fn applies_the_row_height_rules() {
let margins = r#"<w:tblCellMar><w:top w:w="20" w:type="dxa"/><w:bottom w:w="40" w:type="dxa"/></w:tblCellMar>"#;
let rows: &[(&str, &[&str])] = &[
(r#"<w:trHeight w:val="600"/>"#, &[&p("a")]),
(r#"<w:trHeight w:val="400" w:hRule="exact"/>"#, &[&p("b")]),
(r#"<w:trHeight w:val="900" w:hRule="auto"/>"#, &[&p("c")]),
(r#"<w:trHeight w:val="100" w:hRule="atLeast"/>"#, &[&p("d")]),
];
let list = lay_out(&(table(margins, &[2000], rows) + &p("e")), NORMAL, None);
// At least 600 twips without the margins, exactly 400 twips with the top margin, and the
// content with its margins.
assert_eq!(find(&list, 'a').2, base(1440 + 20));
assert_eq!(find(&list, 'b').2, base(2100 + 20));
assert_eq!(find(&list, 'c').2, base(2520 + 20));
assert_eq!(find(&list, 'd').2, base(2780 + 20));
assert_eq!(find(&list, 'e').2, base(3040));
}
#[test]
fn aligns_cell_content_vertically() {
let cell = |align: &str, text: &str| {
format!(r#"<w:tcPr><w:vAlign w:val="{align}"/></w:tcPr>{}"#, p(text))
};
let rows: &[(&str, &[&str])] = &[(
r#"<w:trHeight w:val="1000"/>"#,
&[
&cell("bottom", "a"),
&cell("center", "b"),
&cell("top", "c"),
],
)];
let list = lay_out(&table("", &[2000, 2000, 2000], rows), NORMAL, None);
assert_eq!(find(&list, 'a').2, base(1440 + 800));
assert_eq!(find(&list, 'b').2, base(1440 + 400));
assert_eq!(find(&list, 'c').2, base(1440));
}
#[test]
fn aligns_cells_as_their_table_style_says() {
// The style centers its cells and puts those of the first row at the bottom; a cell's own
// `w:vAlign` wins over both.
let style = format!(
r#"{NORMAL}<w:style w:type="table" w:styleId="Mid"><w:basedOn w:val="TableNormal"/>
<w:tcPr><w:vAlign w:val="center"/></w:tcPr>
<w:tblStylePr w:type="firstRow"><w:tcPr><w:vAlign w:val="bottom"/></w:tcPr></w:tblStylePr></w:style>"#
);
let look = r#"<w:tblStyle w:val="Mid"/><w:tblLook w:firstRow="1"/>"#;
let top = format!(r#"<w:tcPr><w:vAlign w:val="top"/></w:tcPr>{}"#, p("b"));
let rows: &[(&str, &[&str])] = &[
(r#"<w:trHeight w:val="1000"/>"#, &[&p("a"), &top]),
(r#"<w:trHeight w:val="1000"/>"#, &[&p("c"), &p("d")]),
];
let list = lay_out(&table(look, &[2000, 2000], rows), &style, None);
assert_eq!(find(&list, 'a').2, base(1440 + 800));
assert_eq!(find(&list, 'b').2, base(1440));
assert_eq!(find(&list, 'c').2, base(2440 + 400));
assert_eq!(find(&list, 'd').2, base(2440 + 400));
}
#[test]
fn grows_the_last_row_of_a_merged_region() {
let restart = format!(
r#"<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>{}{}{}"#,
p("a"),
p("b"),
p("c")
);
let rows: &[(&str, &[&str])] = &[
("", &[&restart, &p("d")]),
(
"",
&[&format!("<w:tcPr><w:vMerge/></w:tcPr>{}", p("x")), &p("e")],
),
];
let list = lay_out(&(table("", &[2000, 2000], rows) + &p("f")), NORMAL, None);
assert_eq!(find(&list, 'c').2, base(1440 + 400));
assert_eq!(find(&list, 'e').2, base(1640));
// The second row grows so that the merged cell fits, and the continuing cell shows
// nothing.
assert_eq!(find(&list, 'f').2, base(2040));
assert_eq!(find_all(&list, 'x'), Vec::new());
}
#[test]
fn centers_a_merged_cell_over_its_region() {
let restart = format!(
r#"<w:tcPr><w:vMerge w:val="restart"/><w:vAlign w:val="center"/></w:tcPr>{}"#,
p("a")
);
let rows: &[(&str, &[&str])] = &[
("", &[&restart, &p("b")]),
("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("c")]),
("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("d")]),
];
let list = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
// The region is 600 twips tall and the cell 200, so the cell moves down 200 twips. The
// move is rounded on its own.
assert_eq!(find(&list, 'a').2, base(1440) + du(200));
assert_eq!(find(&list, 'd').2, base(1840));
}
#[test]
fn applies_the_regions_of_the_table_style() {
let style = format!(
r#"{NORMAL}<w:style w:type="table" w:styleId="Fancy"><w:basedOn w:val="TableNormal"/>
<w:tblPr><w:tblStyleRowBandSize w:val="1"/></w:tblPr>
<w:tblStylePr w:type="firstRow"><w:rPr><w:b/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="nwCell"><w:rPr><w:i/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="band1Horz"><w:tcPr><w:tcBorders><w:top w:val="single" w:sz="8"/></w:tcBorders></w:tcPr></w:tblStylePr>
<w:tblStylePr w:type="lastCol"><w:rPr><w:i/></w:rPr></w:tblStylePr></w:style>"#
);
let look = r#"<w:tblStyle w:val="Fancy"/><w:tblLook w:firstRow="1" w:firstColumn="1" w:lastColumn="0" w:noVBand="1"/>"#;
let rows: &[(&str, &[&str])] = &[
("", &[&p("a"), &p("b")]),
("", &[&p("c"), &p("d")]),
("", &[&p("e"), &p("f")]),
("", &[&p("g"), &p("h")]),
];
let list = lay_out(&table(look, &[2000, 2000], rows), &style, None);
assert_eq!(font_of(&list, 'a'), FontId::from_index(3));
assert_eq!(font_of(&list, 'b'), FontId::from_index(1));
assert_eq!(font_of(&list, 'd'), FontId::from_index(0));
// The bands start below the first row: the second and the fourth rows get a top border.
assert_eq!(find(&list, 'c').2, base(1640 + 20));
assert_eq!(find(&list, 'e').2, base(1860));
assert_eq!(find(&list, 'g').2, base(2060 + 20));
}
#[test]
fn draws_a_line_where_one_of_two_cells_has_one() {
let above = format!(
r#"<w:tcPr><w:tcBorders><w:bottom w:val="single" w:sz="8"/></w:tcBorders></w:tcPr>{}"#,
p("a")
);
let below = format!(
r#"<w:tcPr><w:tcBorders><w:top w:val="nil"/></w:tcBorders></w:tcPr>{}"#,
p("b")
);
let rows: &[(&str, &[&str])] = &[("", &[&above]), ("", &[&below])];
let list = lay_out(&table("", &[2000], rows), NORMAL, None);
assert_eq!(find(&list, 'b').2, base(1640 + 20));
assert_eq!(rects(&list, 0).len(), 1);
}
#[test]
fn places_nested_tables_in_their_cell() {
let inner = table(
r#"<w:tblInd w:w="200" w:type="dxa"/>"#,
&[1000],
&[("", &[&p("n")])],
);
let rows: &[(&str, &[&str])] = &[("", &[&(inner + &p("o"))])];
let list = lay_out(&table("", &[3000], rows), NORMAL, None);
// The nested table does not hang its 108 twip margin out of its indent.
let (_, x, y) = find(&list, 'n');
assert_eq!((x_du(x), y), (du(1440 + 200 + 108), base(1440)));
assert_eq!(find(&list, 'o').2, base(1640));
}
#[test]
fn aligns_tables_between_the_margins() {
let center = table(r#"<w:jc w:val="center"/>"#, &[2000], &[("", &[&p("a")])]);
let end = table(r#"<w:jc w:val="right"/>"#, &[2000], &[("", &[&p("b")])]);
let list = lay_out(&(center + &end), NORMAL, None);
let (_, x, _) = find(&list, 'a');
assert_eq!(x_du(x), du(1440 + 3680 + 108));
// Before mode 15, a right-aligned table extends its trailing cell margin past the right column
// edge so the last cell's text lines up with the column margin.
let (_, x, _) = find(&list, 'b');
assert_eq!(x_du(x), du(1440 + 7360 + 108 + 108));
}
#[test]
fn takes_columns_from_the_cells_without_a_grid_and_skips_grid_columns() {
let no_grid = r#"<w:tbl><w:tr><w:tc><w:tcPr><w:tcW w:w="1000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"#;
let list = lay_out(no_grid, NORMAL, None);
let (_, x, _) = find(&list, 'b');
assert_eq!(x_du(x), du(1332 + 1000 + 108));
let skipped = table(
"",
&[1000, 2000],
&[
(r#"<w:gridBefore w:val="1"/>"#, &[&p("c")]),
("", &[&p("d"), &p("e")]),
],
);
let list = lay_out(&skipped, NORMAL, None);
let (_, x, _) = find(&list, 'c');
assert_eq!(x_du(x), du(1332 + 1000 + 108));
// A missing grid line falls back to the last one.
let short = table("", &[1000], &[("", &[&p("f"), &p("g")])]);
let list = lay_out(&short, NORMAL, None);
let (_, x, _) = find(&list, 'g');
assert_eq!(x_du(x), du(1332 + 1000 + 108));
}
#[test]
fn picks_the_wider_line() {
let line = |eighths| {
Some(Border::new(
BorderParts::single(Length::from_eighth_points(eighths).unwrap()),
Length::ZERO,
Color::Auto,
))
};
assert_eq!(heavier(line(4), line(8)), line(8));
assert_eq!(heavier(line(8), line(4)), line(8));
let red = line(4).map(|b| Border {
color: Color::Rgb([255, 0, 0]),
..b
});
assert_eq!(heavier(line(4), red), line(4));
assert_eq!(heavier(None, line(4)), line(4));
assert_eq!(heavier(line(4), None), line(4));
assert_eq!(heavier(None, None), None);
}
#[test]
fn moves_content_down_for_its_alignment() {
let shifts = [
(Some(VerticalAlign::Center), 9),
(Some(VerticalAlign::Bottom), 9),
(Some(VerticalAlign::Bottom), -9),
(Some(VerticalAlign::Center), -9),
(Some(VerticalAlign::Top), 9),
(None, 9),
]
.map(|(a, free)| align(a, Length::from_units(free)).units());
assert_eq!(shifts, [4, 9, 0, 0, 0, 0]);
let bands = [0, 1, 3].map(|i| band(i, Region::Band1Horz, Region::Band2Horz));
assert_eq!(
bands,
[Region::Band1Horz, Region::Band2Horz, Region::Band2Horz]
);
}
#[test]
fn computes_row_heights() {
let at = Length::from_units;
let margins = Sides {
top: at(2),
left: Length::ZERO,
bottom: at(3),
right: Length::ZERO,
};
let cells = [(at(10), margins), (at(20), Sides::default())];
let height = |h: i64, rule| Some((at(h), rule));
let quirks = with_margin(ExactRowMargin::AddsTopMargin);
let row = |rule| row_height(at(1), &cells, rule, &quirks).units();
assert_eq!(row(None), 21);
assert_eq!(row(height(30, HeightRule::Auto)), 21);
assert_eq!(row(height(30, HeightRule::AtLeast)), 36);
assert_eq!(row(height(5, HeightRule::AtLeast)), 21);
assert_eq!(row(height(5, HeightRule::Exact)), 7);
let none = row_height(at(1), &[], None, &quirks);
assert_eq!(none, at(1));
}
#[test]
fn a_row_of_exact_height_adds_the_cell_margin_that_the_target_asks_for() {
// A cell with a top margin of 2 and a bottom margin of 3 under an exact height of 5: the
// row adds its top margin on one target and its bottom margin on another, and a row of
// minimum height adds both on each.
let at = Length::from_units;
let margins = Sides {
top: at(2),
left: Length::ZERO,
bottom: at(3),
right: Length::ZERO,
};
let cells = [(at(4), margins)];
let row =
|rule, margin| row_height(at(1), &cells, Some((at(5), rule)), &with_margin(margin)).units();
assert_eq!(row(HeightRule::Exact, ExactRowMargin::AddsTopMargin), 7);
assert_eq!(row(HeightRule::Exact, ExactRowMargin::AddsBottomMargin), 8);
assert_eq!(row(HeightRule::AtLeast, ExactRowMargin::AddsTopMargin), 11);
assert_eq!(
row(HeightRule::AtLeast, ExactRowMargin::AddsBottomMargin),
11
);
}
/// The quirks of the base target with `margin` as the rule for a row of exact height.
fn with_margin(margin: ExactRowMargin) -> crate::quirks::Quirks {
crate::layout::testing::on_base_with(|p| p.with_variant(margin)).1
}
/// A table style that marks each region in its own way: the column bands indent, the row bands
/// add space before, the first and last columns are bold and italic, the first row is in
/// capitals, and the last row and the corner cells have their own sizes.
const REGIONS: &str = r#"<w:style w:type="table" w:styleId="Regions"><w:basedOn w:val="TableNormal"/>
<w:pPr><w:jc w:val="left"/></w:pPr>
<w:tblPr><w:tblStyleRowBandSize w:val="2"/><w:tblStyleColBandSize w:val="2"/></w:tblPr>
<w:tblStylePr w:type="band1Vert"><w:pPr><w:ind w:left="100"/></w:pPr></w:tblStylePr>
<w:tblStylePr w:type="band2Vert"><w:pPr><w:ind w:left="200"/></w:pPr></w:tblStylePr>
<w:tblStylePr w:type="band1Horz"><w:pPr><w:spacing w:before="20"/></w:pPr></w:tblStylePr>
<w:tblStylePr w:type="band2Horz"><w:pPr><w:spacing w:before="40"/></w:pPr></w:tblStylePr>
<w:tblStylePr w:type="firstCol"><w:rPr><w:b/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="lastCol"><w:rPr><w:i/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="firstRow"><w:rPr><w:caps/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="lastRow"><w:rPr><w:sz w:val="30"/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="nwCell"><w:rPr><w:sz w:val="24"/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="neCell"><w:rPr><w:sz w:val="26"/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="swCell"><w:rPr><w:sz w:val="28"/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="seCell"><w:rPr><w:sz w:val="32"/></w:rPr></w:tblStylePr></w:style>"#;
/// A table of six rows and six columns of 1000 twips in the regions style, with one letter in
/// each cell, row by row.
fn regions() -> DisplayList {
let letters: Vec<String> = ('a'..='z')
.chain('0'..='9')
.map(|c| p(&c.to_string()))
.collect();
let rows: Vec<Vec<&str>> = letters
.chunks(6)
.map(|row| row.iter().map(String::as_str).collect())
.collect();
let rows: Vec<(&str, &[&str])> = rows.iter().map(|r| ("", r.as_slice())).collect();
let look = r#"<w:tblStyle w:val="Regions"/><w:tblLook w:firstRow="1" w:lastRow="1" w:firstColumn="1" w:lastColumn="1" w:noHBand="0" w:noVBand="0"/>"#;
let style = format!("{NORMAL}{REGIONS}");
lay_out(&table(look, &[1000; 6], &rows), &style, None)
}
/// The text start of a cell in the regions table: its grid line, its margin and an indent.
fn column(index: i64, indent: i64) -> i64 {
indented(1332 + 1000 * index + 108, indent)
}
#[test]
fn bands_columns_and_rows_in_groups() {
let list = regions();
// Row 1 holds g to l, row 3 holds s to x. Column bands of two start after column 0. The
// first and last columns are in no column band, and the last row in no row band.
let row1 = base(1700 + 20);
let found = ['g', 'h', 'i', 'j', 'l', 't', '6'].map(|ch| at(&list, ch));
let expected = [
(column(0, 0), row1),
(column(1, 100), row1),
(column(2, 100), row1),
(column(3, 200), row1),
(column(5, 0), row1),
(column(1, 100), base(2140 + 40)),
// At 15 pt the single line of 62.5 device dots rounds up, so the baseline sits the
// descent of 12.5 units, rounded to 13, above its bottom.
(
column(2, 100),
f_office_units::div_round(
2620 * Length::UNITS_PER_TWIP + 300 * Length::UNITS_PER_TWIP - 13 * DOT,
DOT,
),
),
];
assert_eq!(found, expected);
assert_eq!(at(&list, 'n').1, base(1920 + 20));
assert_eq!(at(&list, 'z').1, base(2380 + 40));
}
#[test]
fn formats_the_first_and_last_rows_columns_and_corners() {
let list = regions();
let size = |ch| run_of(&list, ch).size;
let points =
|half: i64| crate::grid::base_device().snap(Length::from_half_points(half).unwrap());
// The first row is in capitals, the first column bold and the last column italic.
assert_eq!(font_of(&list, 'A'), FontId::from_index(1));
assert_eq!(
(font_of(&list, 'C'), size('C')),
(FontId::from_index(0), points(20))
);
assert_eq!(font_of(&list, 'F'), FontId::from_index(2));
assert_eq!(
(font_of(&list, 'm'), size('m')),
(FontId::from_index(1), points(20))
);
assert_eq!(
(font_of(&list, 'r'), size('r')),
(FontId::from_index(2), points(20))
);
// The corner cells win over the last row.
assert_eq!(
[size('A'), size('F'), size('4'), size('9'), size('6')],
[24, 26, 28, 32, 30].map(points)
);
}
#[test]
fn region_alignment_overrides_direct_start_without_style_jc() {
let styles = format!(
r#"{NORMAL}
<w:style w:type="paragraph" w:styleId="ParaLeft"><w:pPr><w:jc w:val="left"/></w:pPr></w:style>
<w:style w:type="paragraph" w:styleId="ParaCenter"><w:pPr><w:jc w:val="center"/></w:pPr></w:style>
<w:style w:type="table" w:styleId="FirstColRight"><w:basedOn w:val="TableNormal"/>
<w:tblStylePr w:type="firstCol"><w:pPr><w:jc w:val="right"/></w:pPr></w:tblStylePr></w:style>
<w:style w:type="table" w:styleId="WholeRight"><w:basedOn w:val="TableNormal"/>
<w:pPr><w:jc w:val="right"/></w:pPr></w:style>"#
);
let cell_x = |tbl_style: &str, ppr: &str| {
let look = format!(r#"<w:tblStyle w:val="{tbl_style}"/><w:tblLook w:firstColumn="1"/>"#);
let cell = format!("<w:p><w:pPr>{ppr}</w:pPr><w:r><w:t>a</w:t></w:r></w:p>");
let body = table(&look, &[3000, 1000], &[("", &[&cell, &p("b")])]);
find(&lay_out(&body, &styles, None), 'a').1
};
let right = cell_x("FirstColRight", "");
let left = cell_x("WholeRight", r#"<w:jc w:val="left"/>"#);
let center = cell_x("FirstColRight", r#"<w:jc w:val="center"/>"#);
assert!(left < center && center < right, "{left} {center} {right}");
// Direct `left` / `start` yields to conditional `firstCol` alignment when the style sets no
// `w:jc`, but wins over whole-table `w:jc`, paragraph-style `w:jc`, and non-default direct
// alignments.
for (tbl_style, ppr, want) in [
("FirstColRight", r#"<w:jc w:val="left"/>"#, right),
("FirstColRight", r#"<w:jc w:val="start"/>"#, right),
("FirstColRight", r#"<w:pStyle w:val="ParaLeft"/>"#, left),
("FirstColRight", r#"<w:pStyle w:val="ParaCenter"/>"#, center),
(
"FirstColRight",
r#"<w:pStyle w:val="ParaCenter"/><w:jc w:val="left"/>"#,
left,
),
("WholeRight", "", right),
("WholeRight", r#"<w:jc w:val="left"/>"#, left),
] {
assert_eq!(cell_x(tbl_style, ppr), want, "{tbl_style} {ppr}");
}
// Under `w:bidi`, direct `jc="left"` (logical start) yields to `firstCol`'s `jc="right"`
// (logical end = physical left).
assert_eq!(
cell_x("FirstColRight", r#"<w:bidi/><w:jc w:val="left"/>"#),
cell_x("FirstColRight", r#"<w:bidi/><w:jc w:val="right"/>"#),
);
}
#[test]
fn leaves_out_the_hidden_end_of_cell_mark() {
// A cell of "a" and an empty paragraph: with `w:hideMark`, the paragraph after the table
// lies where it lies after a cell of "a" alone; without it, a line lower.
let after = |cell: &str| {
let body = table("", &[2000], &[("", &[cell])]) + &p("z");
find(&lay_out(&body, NORMAL, None), 'z').2
};
let alone = after(&p("a"));
let hidden = after(&format!("<w:tcPr><w:hideMark/></w:tcPr>{}<w:p/>", p("a")));
let shown = after(&format!("{}<w:p/>", p("a")));
assert_eq!(hidden, alone);
assert!(shown > alone, "{shown} {alone}");
// A last paragraph with text keeps its line.
let two = after(&format!(
"<w:tcPr><w:hideMark/></w:tcPr>{}{}",
p("a"),
p("b")
));
assert_eq!(two, shown);
}
#[test]
fn leaves_out_the_empty_paragraph_after_a_nested_table() {
// A cell of a nested table and an empty paragraph: the paragraph after the outer table
// lies where it lies after a cell that is one empty paragraph shorter.
let nested = table("", &[1000], &[("", &[&p("n")])]);
let after = |cell: &str| {
let body = table("", &[2000], &[("", &[cell])]) + &p("z");
find(&lay_out(&body, NORMAL, None), 'z').2
};
let ends = after(&format!("{nested}<w:p/>"));
let text = after(&format!("{nested}{}", p("a")));
assert!(text > ends, "{text} {ends}");
// Of two empty paragraphs after the nested table, both keep their lines.
let two = after(&format!("{nested}<w:p/><w:p/>"));
assert_eq!(two - text, text - ends);
// An empty paragraph before the nested table keeps its line too.
let before = after(&format!("<w:p/>{nested}<w:p/>"));
assert_eq!(before, after(&format!("{}{nested}<w:p/>", p("a"))));
assert!(before > ends, "{before} {ends}");
}
#[test]
fn gives_cell_paragraphs_the_table_style() {
let style = format!(
r#"{NORMAL}<w:style w:type="table" w:styleId="Big"><w:basedOn w:val="TableNormal"/><w:pPr><w:ind w:left="300"/></w:pPr><w:rPr><w:b/></w:rPr></w:style>"#
);
let body = table(r#"<w:tblStyle w:val="Big"/>"#, &[2000], &[("", &[&p("a")])]);
let list = lay_out(&body, &style, None);
assert_eq!(font_of(&list, 'a'), FontId::from_index(1));
assert_eq!(at(&list, 'a').0, indented(1440, 300));
}
#[test]
fn keeps_a_continuing_cell_in_the_first_row() {
let rows: &[(&str, &[&str])] = &[("", &[&format!("<w:tcPr><w:vMerge/></w:tcPr>{}", p("a"))])];
let list = lay_out(&table("", &[2000], rows), NORMAL, None);
assert_eq!(at(&list, 'a').1, base(1440));
}
#[test]
fn takes_the_wider_line_from_the_neighbor() {
let left = format!(
"<w:tcPr><w:tcBorders><w:right {SINGLE}/></w:tcBorders></w:tcPr>{}",
p("a")
);
let right = format!(
r#"<w:tcPr><w:tcBorders><w:left w:val="single" w:sz="24"/></w:tcBorders></w:tcPr>{}"#,
p("b")
);
let list = lay_out(
&table("", &[2000, 2000], &[("", &[&left, &right])]),
NORMAL,
None,
);
// Both cells take the 3 pt line, centered on the grid line between them, and it is drawn
// once. It is 13 device dots wide, and the odd unit lies left of the grid line.
let wide = (du(3332) - 7, 300, du(60), du(200));
assert_eq!(rects(&list, 0), vec![wide]);
}
#[test]
fn uses_the_outer_borders_at_the_edges() {
let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="16"/><w:right w:val="single" w:sz="24"/><w:insideH w:val="single" w:sz="8"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>"#;
let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &p("b")]), ("", &[&p("c"), &p("d")])];
let list = lay_out(&table(borders, &[2000, 2000], rows), NORMAL, None);
// A 2 pt top border above the first row, a 1 pt one above the second.
assert_eq!(at(&list, 'a').1, base(1440 + 40));
assert_eq!(at(&list, 'c').1, base(1640 + 40 + 20));
let rects = rects(&list, 0);
// The line between the cells is 0.5 pt, and the right edge 3 pt, with its odd device
// unit left of the grid line. Both run from below the top line.
let top = du(1440) + du(40);
assert!(rects.contains(&(du(3332) - 1, top, 2, du(240) - du(40))));
assert!(rects.contains(&(du(5332) - 7, top, du(60), du(240) - du(40))));
}
#[test]
fn starts_a_table_below_the_space_after_the_paragraph_before_it() {
let before = r#"<w:p><w:pPr><w:spacing w:after="100"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
let list = lay_out(
&(before.to_owned() + &table("", &[2000], &[("", &[&p("b")])])),
NORMAL,
None,
);
assert_eq!(at(&list, 'b').1, base(1640 + 100));
}
#[test]
fn counts_the_space_after_the_last_paragraph_of_a_cell() {
let cell = r#"<w:p><w:pPr><w:spacing w:after="300"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
let list = lay_out(
&(table("", &[2000], &[("", &[cell])]) + &p("b")),
NORMAL,
None,
);
assert_eq!(at(&list, 'b').1, base(1440 + 200 + 300));
}
/// The table style of [`NORMAL`], the default paragraph style `Normal` and the style `Other`.
const WITH_OTHER: &str = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Other"><w:name w:val="Other"/><w:basedOn w:val="Normal"/></w:style>"#;
#[test]
fn leaves_out_the_space_at_a_cells_edges_of_a_contextual_default_paragraph() {
let cell = |props: &str| format!("<w:p><w:pPr>{props}</w:pPr><w:r><w:t>a</w:t></w:r></w:p>");
let styles = format!("{NORMAL}{WITH_OTHER}");
let places = |props: &str| {
let list = lay_out(
&(table("", &[2000], &[("", &[&cell(props)])]) + &p("b")),
&styles,
None,
);
(at(&list, 'a').1, at(&list, 'b').1)
};
let spaced = r#"<w:spacing w:before="100" w:after="300"/>"#;
let contextual = format!("{spaced}<w:contextualSpacing/>");
// A paragraph of the default style with contextual spacing lies as one without space
// before, and the cell ends as one without space after.
let after_only = places(r#"<w:spacing w:after="300"/>"#);
assert_eq!(places(&contextual), (after_only.0, places("").1));
// A paragraph of another style keeps both spaces.
assert_eq!(
places(&format!(r#"<w:pStyle w:val="Other"/>{contextual}"#)),
places(spaced)
);
assert_ne!(places(spaced), places(""));
}
#[test]
fn compares_cell_edge_contextual_spacing_against_backing_stream_neighbors() {
let styles = format!("{NORMAL}{WITH_OTHER}");
let para = |style: Option<&str>, props: &str, text: &str| {
let style_xml = style.map_or_else(String::new, |s| format!(r#"<w:pStyle w:val="{s}"/>"#));
format!("<w:p><w:pPr>{style_xml}{props}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
};
let row_step = |c1: &str, c2: &str| {
let body = table(
"",
&[2000, 2000],
&[("", &[c1, c2]), ("", &[&p("r"), &p("s")])],
);
let list = lay_out(&body, &styles, None);
at(&list, 'r').1 - at(&list, 'a').1
};
let after = r#"<w:spacing w:after="240"/><w:contextualSpacing/>"#;
let zero_after = r#"<w:spacing w:after="0"/>"#;
let before = r#"<w:spacing w:before="240"/><w:contextualSpacing/>"#;
// Non-last cell drops space after when the next cell starts with the same style, and keeps it
// before a different style (even for Normal).
let dropped_after = row_step(
¶(Some("Other"), after, "a"),
¶(Some("Other"), zero_after, "b"),
);
let kept_after = row_step(
¶(Some("Other"), after, "a"),
¶(None, zero_after, "b"),
);
assert_eq!(kept_after - dropped_after, du(240));
let normal_before_other = row_step(
¶(None, after, "a"),
¶(Some("Other"), zero_after, "b"),
);
assert_eq!(normal_before_other, kept_after);
// Non-first cell drops space before when the previous cell ends with the same style, and keeps
// it after a different style (even for Normal).
let sibling_gap = |c1: &str, c2: &str| {
let body = table("", &[2000, 2000], &[("", &[c1, c2])]);
let list = lay_out(&body, &styles, None);
at(&list, 'b').1 - at(&list, 'a').1
};
assert_eq!(
sibling_gap(
¶(Some("Other"), "", "a"),
¶(Some("Other"), before, "b")
),
0
);
assert_eq!(
sibling_gap(¶(None, "", "a"), ¶(Some("Other"), before, "b")),
du(240)
);
assert_eq!(
sibling_gap(¶(Some("Other"), "", "a"), ¶(None, before, "b")),
du(240)
);
// Row 0 cell 0 compares space before against the paragraph immediately preceding the table.
let top_gap = |r1c1: &str| {
let body = para(Some("Other"), "", "x")
+ &table("", &[2000, 2000], &[("", &[r1c1, ¶(None, "", "b")])]);
let list = lay_out(&body, &styles, None);
at(&list, 'a').1 - at(&list, 'b').1
};
assert_eq!(top_gap(¶(Some("Other"), before, "a")), 0);
assert_eq!(top_gap(¶(None, before, "a")), du(240));
}
#[test]
fn lays_out_a_merged_cell_s_lines_from_its_aligned_top_on_a_target_that_does() {
use crate::quirks::MergedCellLines;
// A centered merged cell over two rows of exact heights holds two lines, and a single row
// of the summed height holds the same lines. Each twip that the second row grows moves the
// centering shift by a fortieth of a point, across the dots of 0.12 pt.
let centered = r#"<w:vAlign w:val="center"/>"#;
let lines = p("a") + &p("b");
let starts = format!(r#"<w:tcPr><w:vMerge w:val="restart"/>{centered}</w:tcPr>{lines}"#);
let goes_on = format!("<w:tcPr><w:vMerge/>{centered}</w:tcPr><w:p/>");
let alone = format!("<w:tcPr>{centered}</w:tcPr>{lines}");
let exact = |twips: u32| format!(r#"<w:trHeight w:val="{twips}" w:hRule="exact"/>"#);
let places = |body: &str, rule| {
let target = crate::layout::testing::target_at(600, |p| p.with_variant(rule));
let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
(find(&list, 'a').2, find(&list, 'b').2)
};
let mut apart = 0;
for step in 0..6 {
let (first, second) = (exact(300), exact(600 + step));
let merged = table("", &[2000], &[(&first, &[&starts]), (&second, &[&goes_on])]);
let single = table("", &[2000], &[(&exact(900 + step), &[&alone])]);
let wanted = places(&single, MergedCellLines::FromAlignedTop);
let from_top = places(&merged, MergedCellLines::FromAlignedTop);
assert_eq!(from_top, wanted, "step {step}");
apart += usize::from(places(&merged, MergedCellLines::MovedAsBlock) != wanted);
}
// Moved as one block by the rounded shift, the lines lie a dot off at some steps.
assert!(apart > 0);
}
/// How far up the page the baseline of the first 'b' of `body`, below `header` on every page,
/// lies at 600 dots per inch with whole twips held as the nearest 1/4,096 pt, against held
/// exactly.
fn held_one_dot_up(header: Option<&str>, body: &str) -> i64 {
held_one_dot_up_on(&Fake, header, body)
}
/// [`held_one_dot_up`] with the faces of `fonts`.
fn held_one_dot_up_on(fonts: &dyn Fonts, header: Option<&str>, body: &str) -> i64 {
use crate::quirks::TwipLengthUnit;
let baseline = |unit| {
let (device, quirks) = crate::layout::testing::target_at(600, |p| p.with_variant(unit));
let list = pass_on(
body,
(NORMAL, None),
header,
Numbering::default(),
(device, quirks, EarlierPass::default()),
&(fonts, ShaperSettings::base()),
);
run_of(&list.list, 'b').glyphs.first().unwrap().y.units()
};
baseline(TwipLengthUnit::HalfEmus) - baseline(TwipLengthUnit::Nearest4096ths)
}
/// The fake faces with a single line of 1.111 of the size, 900 of the em's 1,000 units above
/// the baseline and 211 below: at 10 pt a line of 222.2 twips, which is not whole twips.
struct Tall;
impl Fonts for Tall {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
Fake.face(family, bold, italic).map(|mut face| {
face.metrics.hhea_ascender = 900;
face.metrics.hhea_descender = -211;
face.metrics.descent = 211;
face.metrics.line_top = 900;
face.metrics.script_top = 900;
face
})
}
fn glyph(&self, font: FontId, ch: char) -> Option<u32> {
Fake.glyph(font, ch)
}
fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
Fake.advance(font, glyph)
}
}
/// A table of one row of at least `height` twips whose cell, aligned to `align`, holds
/// `paragraph`.
fn aligned_row(height: u32, align: &str, paragraph: &str) -> String {
let row = format!(r#"<w:trHeight w:val="{height}"/>"#);
let cell = format!(r#"<w:tcPr><w:vAlign w:val="{align}"/></w:tcPr>{paragraph}"#);
let rows: &[(&str, &[&str])] = &[(&row, &[&cell])];
table("", &[2000], rows)
}
#[test]
fn starts_the_twips_rest_of_a_cell_s_text_at_its_top() {
// Below a first row of exactly 318 twips at the top margin of 1,440 twips, the second row's
// text top lies 1,758 twips from the page's top, 87.9 pt, exactly on half a dot of 600 dots
// per inch (732.5 dots). Held as the nearest 1/4,096 pt, that length lies above the half,
// so the cell's exact line goes up the page; held exactly, the half goes down.
let first = r#"<w:trHeight w:val="318" w:hRule="exact"/>"#;
let line = r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
let body = table("", &[2000], &[(first, &[&p("a")]), ("", &[line])]);
assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}
#[test]
fn carries_the_twips_rest_through_the_rows_of_a_table() {
// Two rows of exactly 243 twips at the top margin of 1,440 twips put the third row's text
// top 1,926 twips from the page's top, 96.3 pt, exactly on half a dot of 600 dots per inch
// (802.5 dots). Entered one by one, each row lies 0.4 of a 1/4,096 pt short, so the sum
// lies 0.8 of one short and the cell's exact line goes up the page. Held as one length,
// 1,926 twips lie 0.2 of one past, and held exactly the half goes down.
let exact = r#"<w:trHeight w:val="243" w:hRule="exact"/>"#;
let line = r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
let rows: &[(&str, &[&str])] = &[(exact, &[&p("a")]), (exact, &[&p("a")]), ("", &[line])];
let body = table("", &[2000], rows);
assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}
#[test]
fn carries_the_rests_that_the_cells_of_a_row_start() {
// Below a header that ends 1,500 twips from the page's top, the body's top has no twips
// rest, so neither has the first row's top. Its cell starts the rest at its text top as one
// length (0 at 1,500 twips), and its exact line of 243 twips enters 0.4 of a 1/4,096 pt
// short. The second row carries the rest at the first row's end and adds its own line, so
// the third row's text top, 1,986 twips from the page's top, exactly on half a dot of 600
// dots per inch (827.5 dots), lies 0.8 of one short and the cell's exact line goes up the
// page. Started anew there as one length, 1,986 twips lie 0.2 past, and held exactly the
// half goes down.
let exact = |text| {
format!(
r#"<w:p><w:pPr><w:spacing w:line="{}" w:lineRule="exact"/></w:pPr><w:r><w:t>{}</w:t></w:r></w:p>"#,
if text == "b" { 240 } else { 243 },
text
)
};
let (a, b) = (exact("a"), exact("b"));
let rows: &[(&str, &[&str])] = &[("", &[&a]), ("", &[&a]), ("", &[&b])];
let body = table("", &[2000], rows);
let header = r#"<w:p><w:pPr><w:spacing w:line="780" w:lineRule="exact"/></w:pPr><w:r><w:t>h</w:t></w:r></w:p>"#;
assert_eq!(
held_one_dot_up(Some(header), &body),
Length::UNITS_PER_INCH / 600
);
}
#[test]
fn rounds_a_single_top_with_the_rest_that_its_row_carries() {
// As in `carries_the_twips_rest_through_the_rows_of_a_table`, the third row's text top lies
// 1,926 twips from the page's top, on half a dot, with a carried rest 0.8 of a 1/4,096 pt
// short. The box of the single line there takes that rest and goes up the page. As one
// length 1,926 twips lie 0.2 past, and held exactly the half goes down.
let exact = r#"<w:trHeight w:val="243" w:hRule="exact"/>"#;
let rows: &[(&str, &[&str])] = &[(exact, &[&p("a")]), (exact, &[&p("a")]), ("", &[&p("b")])];
let body = table("", &[2000], rows);
assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}
#[test]
fn rounds_a_single_top_above_its_space_before() {
// A row of exactly 330 twips at the top margin puts the second row's text top 1,770 twips
// from the page's top, on half a dot, with a carried rest of 0, so the place as one length
// decides it, down the page. The single line there has 43 twips of space before, which
// enter 0.4 of a 1/4,096 pt short, but its box holds that space, so its top keeps the rest
// above it and goes down too, as held exactly.
let exact = r#"<w:trHeight w:val="330" w:hRule="exact"/>"#;
let spaced = r#"<w:p><w:pPr><w:spacing w:before="43"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
let rows: &[(&str, &[&str])] = &[(exact, &[&p("a")]), ("", &[spaced])];
let body = table("", &[2000], rows);
assert_eq!(held_one_dot_up(None, &body), 0);
}
#[test]
fn moves_every_cell_of_a_bottom_aligned_row() {
let cell = |text| format!(r#"<w:tcPr><w:vAlign w:val="bottom"/></w:tcPr>{}"#, p(text));
let rows: &[(&str, &[&str])] = &[(r#"<w:trHeight w:val="600"/>"#, &[&cell("a"), &cell("b")])];
let list = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
assert_eq!(at(&list, 'a').1, base(1440 + 400));
assert_eq!(at(&list, 'b').1, base(1440 + 400));
}
#[test]
fn moves_the_underline_of_a_centered_merged_cell() {
let restart = r#"<w:tcPr><w:vMerge w:val="restart"/><w:vAlign w:val="center"/></w:tcPr><w:p><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>a</w:t></w:r></w:p>"#;
let rows: &[(&str, &[&str])] = &[
("", &[restart, &p("b")]),
("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("c")]),
];
let centered = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
let top = restart.replace(r#"<w:vAlign w:val="center"/>"#, "");
let rows: &[(&str, &[&str])] = &[
("", &[&top, &p("b")]),
("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("c")]),
];
let plain = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
// The underline moves down 100 twips with the text.
assert_eq!(rects(¢ered, 0)[0].1, rects(&plain, 0)[0].1 + du(100));
}
#[test]
fn gives_a_continuing_cell_the_height_of_its_margins() {
let margins = r#"<w:tblCellMar><w:top w:w="300" w:type="dxa"/><w:bottom w:w="300" w:type="dxa"/></w:tblCellMar>"#;
let rows: &[(&str, &[&str])] = &[
(
"",
&[&format!(
r#"<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>{}"#,
p("a")
)],
),
("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>"]),
];
let list = lay_out(&(table(margins, &[2000], rows) + &p("b")), NORMAL, None);
// Each row is as tall as the 600 twips of an empty cell's margins.
assert_eq!(at(&list, 'b').1, base(1440 + 1200));
}
#[test]
fn draws_hairline_borders_one_device_dot_wide() {
let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="0"/><w:left w:val="single" w:sz="0"/></w:tblBorders>"#;
let list = lay_out(&table(borders, &[2000], &[("", &[&p("a")])]), NORMAL, None);
// The top line ends at the right grid line, rounded to the device grid. It starts right of
// the left line, which starts below it, and where both end the corner is a square, drawn
// once for each of them.
assert_eq!(
rects(&list, 0),
vec![
(du(1332) + 1, 300, du(3332) - du(1332) - 1, 1),
(du(1332), 301, 1, du(200) - 1),
(du(1332), 300, 1, 1),
(du(1332), 300, 1, 1)
]
);
}
#[test]
fn draws_paragraph_borders_and_leaders_in_cells() {
let cell = r#"<w:p><w:pPr><w:ind w:left="100" w:right="200"/><w:pBdr><w:top w:val="single" w:sz="4"/></w:pBdr><w:tabs><w:tab w:val="right" w:leader="dot" w:pos="1000"/></w:tabs></w:pPr><w:r><w:tab/><w:t>a</w:t></w:r></w:p>"#;
let list = lay_out(&table("", &[3000], &[("", &[cell])]), NORMAL, None);
// The border runs between the indents inside the cell's text column, from 6 device dots
// before the left one to 6 after the right one, with its ends on the device grid.
let border = rects(&list, 0)[0];
let (left, right) = (du(1540) - 6, du(1540 + 2484) + 6);
assert_eq!((border.0, border.2), (left, right - left));
// Dots of 100 twips fill the tab up to the right-aligned text before the stop, on a grid
// from the page's left edge. The tab starts at the indent, 1540 twips, so the first whole
// cell starts at 1600 twips.
let dots: Vec<i64> = find_all(&list, '.').iter().map(|g| g.1).collect();
let grid: Vec<i64> = (16..23).map(|k| 100 * k * 1270).collect();
assert_eq!(dots, grid);
}
#[test]
fn starts_the_border_of_a_hanging_paragraph_at_its_first_line() {
let cell = r#"<w:p><w:pPr><w:ind w:left="400" w:hanging="300"/><w:pBdr><w:top w:val="single" w:sz="4"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
let list = lay_out(&table("", &[3000], &[("", &[cell])]), NORMAL, None);
// The first line starts 100 twips into the cell's text column, which starts at 1440 twips
// and ends at 4224, and the line starts 6 device dots before it.
let border = rects(&list, 0)[0];
let (left, right) = (du(1540) - 6, du(4224) + 6);
assert_eq!((border.0, border.2), (left, right - left));
}
#[test]
fn indents_and_aligns_lines_in_cells() {
let cell = r#"<w:p><w:pPr><w:ind w:left="100"/><w:jc w:val="right"/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>"#;
let list = lay_out(&table("", &[3000], &[("", &[cell])]), NORMAL, None);
// The line ends at the right margin of the cell: 1332 + 3000 - 108 twips.
assert_eq!(at(&list, 'a').0, du(4224 - 200));
}
#[test]
fn lays_out_a_package_with_tables_in_the_body_and_the_header() {
let header = table("", &[2000], &[("", &[&p("h")])]);
let body = table("", &[2000], &[("", &[&p("b")])]);
let bytes = package(&body, &header, HEADER_REFERENCE);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let list = crate::layout(
&package,
(&Fake, &crate::ArtPictures::new()),
&crate::Options::base(),
)
.unwrap()
.value;
assert_eq!(list.pages().len(), 1);
assert_eq!(at(&list, 'h').1, base(720));
assert_eq!(at(&list, 'b').1, base(1440));
}
#[test]
fn moves_paths_with_the_rest_of_a_cell() {
let styles = Styles::default();
let settings = Settings::default();
let (theme, fonts) = (Theme::default(), FontTable::default());
let context = base_context(&styles, &settings);
let stories = context.for_stories();
let sections = Sections::one(SectionLayout::plain(&crate::body::Section::default(), 0));
let mut layout = Layout::new(
(&context, &stories),
§ions,
Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
);
let point = |y: i64| Point {
x: Length::ZERO,
y: Length::from_units(y),
};
let commands = vec![
PathCommand::MoveTo(point(1)),
PathCommand::LineTo(point(2)),
PathCommand::QuadTo(point(3), point(4)),
PathCommand::CubicTo(point(5), point(6), point(7)),
PathCommand::Close,
];
layout.items.push(Item::Path(PathItem {
commands,
color: Rgb::BLACK,
fill_rule: FillRule::default(),
}));
layout.shift(0..1, Length::from_units(10));
let items = layout.items.to_vec();
let Item::Path(path) = &items[0] else {
panic!("not a path");
};
let ys: Vec<i64> = path
.commands
.iter()
.flat_map(|c| match c {
PathCommand::MoveTo(a) | PathCommand::LineTo(a) => vec![a.y],
PathCommand::QuadTo(a, b) => vec![a.y, b.y],
PathCommand::CubicTo(a, b, c) => vec![a.y, b.y, c.y],
PathCommand::Close => Vec::new(),
})
.map(Length::units)
.collect();
assert_eq!(ys, (11..=17).collect::<Vec<_>>());
}
/// A table of two rows and two columns with 1 pt borders and the cell spacing `spacing` in
/// twips, or none.
fn spaced(spacing: Option<i64>) -> DisplayList {
let spacing = spacing.map_or(String::new(), |w| {
format!(r#"<w:tblCellSpacing w:w="{w}" w:type="dxa"/>"#)
});
let line = r#"w:val="single" w:sz="8""#;
let borders = format!(
"{spacing}<w:tblBorders><w:top {line}/><w:left {line}/><w:bottom {line}/><w:right {line}/><w:insideH {line}/><w:insideV {line}/></w:tblBorders>"
);
let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &p("b")]), ("", &[&p("c"), &p("d")])];
lay_out(&table(&borders, &[2000, 2000], rows), NORMAL, None)
}
#[test]
fn keeps_the_cells_of_a_table_with_cell_spacing_apart() {
let (plain, spaced) = (spaced(None), spaced(Some(40)));
// The first cell's box starts twice the spacing (80 twips) inside the grid line, the
// second one the spacing inside it, and the text starts half a line (10 twips) after the
// box's edge.
assert_eq!(at(&plain, 'a').0, du(1440));
assert_eq!(at(&spaced, 'a').0, du(1440 + 90));
assert_eq!(at(&spaced, 'b').0, du(3440 + 50));
// Below the table's 1 pt top line come twice the spacing and the cell's 1 pt top line.
assert_eq!(find(&spaced, 'a').2, base(1440 + 20 + 80 + 20));
// The first row holds its cells' bottom lines and the spacing below them, and the second
// row's boxes start the spacing below that.
assert_eq!(find(&spaced, 'c').2, base(1560 + 200 + 20 + 40 + 40 + 20));
}
#[test]
fn draws_a_box_for_each_cell_of_a_table_with_cell_spacing() {
let rects = rects(&spaced(Some(40)), 0);
// The table's own top line spans the table, the first cell's box lies inside it with its
// edges on the device grid toward the inside, and no line runs between the boxes.
assert!(
rects.contains(&(du(1332 - 10), 300, du(4020), 4)),
"{rects:?}"
);
assert!(rects.contains(&(295, 321, 685 - 295, 4)), "{rects:?}");
assert!(!rects.iter().any(|r| r.0 == du(3332 - 10)), "{rects:?}");
}
#[test]
fn takes_a_cell_spacing_below_zero_as_none() {
assert_eq!(spaced(Some(-20)), spaced(None));
}
#[test]
fn draws_the_lines_inside_a_table_from_the_column_edge_on_the_device_grid() {
// A left margin of 851 twips (42.55 pt) lies off the device grid of 0.24 pt. In mode 15,
// the left border's outer edge is at the margin, rounded to 42.48 pt (177 units). The
// lines inside take the grid lines from the margin rounded to the device grid: 42.48 pt
// plus the half border and 5,382 twips is 311.83 pt, which rounds to 1,299 units, and the
// 0.48 pt line starts one unit to its left. Taken from the exact margin, the grid line
// would round to 1,300 units.
let section = r#"<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="851" w:bottom="1440" w:left="851"/></w:sectPr>"#;
let borders = r#"<w:tblBorders><w:left w:val="single" w:sz="4"/><w:right w:val="single" w:sz="4"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>"#;
let body = table(borders, &[5382, 3398], &[("", &[&p("a"), &p("b")])]) + section;
let list = lay_out(&body, NORMAL, Some(15));
let mut starts: Vec<i64> = rects(&list, 0).iter().map(|r| r.0).collect();
starts.sort_unstable();
starts.dedup();
assert_eq!(starts, [177, 1298, 2006]);
}
/// The rectangles of the first page in dots of 1/600 inch: x, y, width and height.
fn rects_600(list: &DisplayList) -> Vec<(i64, i64, i64, i64)> {
let unit = DOT / 2;
list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) => Some([r.x, r.y, r.width, r.height].map(|v| {
assert_eq!(v.units() % unit, 0, "{r:?}");
v.units() / unit
})),
Item::Glyphs(_)
| Item::Path(_)
| Item::Gradient(_)
| Item::Image(_)
| Item::Group(_) => None,
})
.map(Into::into)
.collect()
}
#[test]
fn centers_vertical_lines_on_their_grid_lines_from_the_column_edge_a_half_down() {
// A left margin of 1134 twips is 472.5 dots of 1/600 inch, which the column's edge takes a
// half down, as 472. In mode 15 the grid lies half the 0.75 pt border, 7.5 twips, right of the margin;
// rounded up to 8 twips, the grid lines move 635 half-EMUs right. The 0.75 pt lines are
// 6.25 dots, so 6 dots wide, and each is centered on its grid line rounded: 475.33, 1308.67
// and 2558.67 dots, so they start at 472, 1306 and 2556.
let section = r#"<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1134" w:bottom="1440" w:left="1134"/></w:sectPr>"#;
let borders = r#"<w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/><w:insideV w:val="single" w:sz="6"/></w:tblBorders>"#;
let body = table(borders, &[2000, 3000], &[("", &[&p("a"), &p("b")])]) + section;
let list = lay_out_centered_lines(&body, NORMAL, Some(15));
let mut lines: Vec<(i64, i64)> = rects_600(&list).iter().map(|r| (r.0, r.2)).collect();
lines.sort_unstable();
lines.dedup();
assert_eq!(lines, [(472, 6), (1306, 6), (2556, 6)]);
}
/// The start and the width, in dots of 1/600 inch, of each vertical line of a table of mode 15
/// centered in a text column of 9,360 twips from a margin of 1,440, with a grid of `grid` twips
/// and lines of 0.75 pt, laid out on `device`.
fn centered_line_starts(
target: &(crate::grid::Device, crate::quirks::Quirks),
grid: [i64; 2],
) -> Vec<(i64, i64)> {
let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>"#;
let borders = r#"<w:jc w:val="center"/><w:tblLayout w:type="fixed"/><w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/><w:insideV w:val="single" w:sz="6"/></w:tblBorders>"#;
let body = table(borders, &grid, &[("", &[&p("a"), &p("b")])]) + section;
let list = pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
*target,
)
.list;
let mut lines: Vec<(i64, i64)> = rects_600(&list).iter().map(|r| (r.0, r.2)).collect();
lines.sort_unstable();
lines.dedup();
lines
}
#[test]
fn draws_a_centered_tables_lines_from_its_outer_edge_on_the_device_grid() {
// Centered in a text column of 9,360 twips from a margin of 1,440 (600 dots), with lines
// of 0.75 pt (6 dots, 7.5 twips for half of one), a table's lines are drawn from the outer
// edge of its left border rounded to the nearest dot, and the half border rounded up to 8
// twips. A grid of 2,002 and 3,000 twips leaves 4,358 twips: the outer edge lies at
// 1,504.79 dots, so 1,505, and the centers at 1,508.33, 2,342.5 and 3,592.5 dots, where
// the exact grid lines give 2,341.67 and 3,591.67 for the two on the right. A grid of
// 5,000 and 4,403 twips, wider than the column, puts the edge at 587.92 dots, so 588, and
// the centers at 591.33, 2,674.67 and 4,509.25, where the exact lines give 591.04, 2,674.38
// and 4,508.96. Grids of 2,012 and 3,001 twips and of 5,000 and 4,405 put the edge on
// exactly half a dot, 1,502.5 and 587.5, and the lines stay at their exact places.
let target = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::TableLines::RoundsCenters)
.with_variant(crate::quirks::CenteredTableLines::FromOuterEdge)
});
for (grid, starts) in [
([2002, 3000], [1505, 2340, 3590]),
([5000, 4403], [588, 2672, 4506]),
([2012, 3001], [1503, 2341, 3591]),
([5000, 4405], [588, 2671, 4506]),
] {
assert_eq!(
centered_line_starts(&target, grid),
starts.map(|x| (x, 6)),
"{grid:?}"
);
}
}
#[test]
fn draws_a_centered_tables_lines_from_its_outer_edge_in_fixed_point_on_a_half_dot() {
// The grids of 2,012 and 3,001 twips and of 5,000 and 4,405 of the test above put the
// outer edge on exactly half a dot, 1,502.5 and 587.5. In fixed-point points, the margin
// plus half of the column's width less the grid's width less the 0.75 pt border lies above
// the half for the first and on it for the second, so both edges take the dot above, 1,503
// and 588, and the centers lie 8 twips and the grid lines' distance right of it: 1,506.33,
// 2,344.67 and 3,595.08 dots, and 591.33, 2,674.67 and 4,510.08.
let target = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::TableLines::RoundsCenters)
.with_variant(crate::quirks::CenteredTableLines::FromOuterEdge)
.with_variant(crate::quirks::CenteredTablePlace::FixedPointHalf)
.with_variant(crate::quirks::LineStartHalves::FixedPoint)
});
for (grid, starts) in [
([2002, 3000], [1505, 2340, 3590]),
([2012, 3001], [1503, 2342, 3592]),
([5000, 4405], [588, 2672, 4507]),
] {
assert_eq!(
centered_line_starts(&target, grid),
starts.map(|x| (x, 6)),
"{grid:?}"
);
}
}
#[test]
fn draws_a_centered_tables_lines_from_the_column_edge_before_mode_15() {
// In mode 14, with a left margin of 1,443 twips (601.25 dots, so 601) and a text column of
// 9,357 twips, a centered table's lines of 0.75 pt (6 dots) are drawn from the margin's
// dot, each center at its grid line's distance from the margin, the half twip of an odd
// free width dropped. A grid of 2,001 and 3,000 twips leaves 4,356: the centers lie 2,178,
// 4,179 and 7,179 twips right of the margin, 907.5, 1,741.25 and 2,991.25 dots, so at
// 1,509, 2,342 and 3,592, where the exact grid lines give 2,342.5 and 3,592.5 for the two
// on the right. A grid of 5,000 and 4,368 twips leaves -11: the first center lies 6 twips,
// 2.5 dots, left of the margin's dot and takes the dot further left, 598, where the exact
// grid line gives 598.96. With a left margin of 1,446 twips, exactly 602.5 dots, the lines
// of a grid of 2,001 and 3,000 twips stay at their exact places: 1,509.38, 2,343.13 and
// 3,593.13, where the margin's dot above would give 1,510.
let (device, quirks) = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::TableLines::RoundsCenters)
.with_variant(crate::quirks::CenteredTableLinesBefore15::FromColumnEdge)
});
let borders = r#"<w:jc w:val="center"/><w:tblLayout w:type="fixed"/><w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/><w:insideV w:val="single" w:sz="6"/></w:tblBorders>"#;
for (margin, grid, starts) in [
(1443, [2001, 3000], [1506, 2339, 3589]),
(1443, [5000, 4368], [595, 2679, 4499]),
(1446, [2001, 3000], [1506, 2340, 3590]),
] {
let section = format!(
r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="{margin}"/></w:sectPr>"#
);
let body = table(borders, &grid, &[("", &[&p("a"), &p("b")])]) + §ion;
let target = (device, quirks);
let list = pass_with(
&body,
(NORMAL, Some(14)),
None,
Numbering::default(),
target,
)
.list;
let mut lines: Vec<(i64, i64)> = rects_600(&list).iter().map(|r| (r.0, r.2)).collect();
lines.sort_unstable();
lines.dedup();
assert_eq!(lines, starts.map(|x| (x, 6)), "{grid:?}");
}
}
#[test]
fn starts_a_centered_tables_text_on_a_whole_twip_before_mode_15() {
// A centered cell of 5,013 twips in a text column of 9,360 twips from a margin of 1,440
// leaves 4,347 twips: the table starts 2,173.5 twips right of the margin, and its text
// 108 twips further, at 3,721.5 twips or 1,550.63 dots, on the dot 1,551. Before mode 15,
// with the half twip dropped, the text starts at 3,721 twips, 1,550.42 dots, on the dot
// 1,550. Mode 15 keeps the exact place, and so does a table of an even free width.
let (device, quirks) = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::CenteredTableTextBefore15::WholeTwip)
});
let dot = 3048;
let start = |width: i64, mode: u32| {
let body = table(r#"<w:jc w:val="center"/>"#, &[width], &[("", &[&p("a")])]);
let target = (device, quirks);
let list = pass_with(
&body,
(NORMAL, Some(mode)),
None,
Numbering::default(),
target,
)
.list;
find(&list, 'a').1
};
assert_eq!(start(5013, 14), 1550 * dot);
assert_eq!(start(5013, 15), 1551 * dot);
// 4,346 twips leave the table at 2,173 twips, its text at 3,721 twips in both modes.
assert_eq!(start(5014, 14), 1550 * dot);
assert_eq!(start(5014, 15), 1550 * dot);
}
#[test]
fn starts_the_text_from_the_half_border_on_whole_twips_from_mode_15() {
// A left line of 6 eighths is 15 twips wide, and half of it is 7.5 twips. A centered cell
// of 5,000 twips in a text column of 9,360 twips from a margin of 1,440 starts 2,180 twips
// right of the margin, and its text 108 twips further, at 3,728 twips or 1,553.33 dots, on
// the dot 1,553. With half the border rounded up to 8 twips, the text starts at 3,728.5
// twips, 1,553.54 dots, on the dot 1,554. A left-aligned table indented 3 twips puts its
// text at 1,558.5 twips, 649.38 dots, or at 1,559 twips, 649.58 dots. Mode 14 keeps the
// exact place.
let (device, quirks) = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::EdgeTableText::WholeTwipBorder)
});
let dot = 3048;
let border = r#"<w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/></w:tblBorders>"#;
let start = |place: &str, mode: u32| {
let props = format!("{place}{border}");
let body = table(&props, &[5000], &[("", &[&p("a")])]);
let target = (device, quirks);
let list = pass_with(
&body,
(NORMAL, Some(mode)),
None,
Numbering::default(),
target,
)
.list;
find(&list, 'a').1
};
let center = r#"<w:jc w:val="center"/>"#;
let indent = r#"<w:tblInd w:w="3" w:type="dxa"/>"#;
assert_eq!(start(center, 15), 1554 * dot);
assert_eq!(start(center, 14), 1553 * dot);
assert_eq!(start(indent, 15), 650 * dot);
}
#[test]
fn keeps_the_exact_place_for_a_cell_margin_less_than_half_the_left_line() {
// The centered cell of the test above with a left margin of 0, less than half its left
// line of 15 twips: the text starts half the line, 7.5 twips, right of the exact grid line
// at 3,620 twips, at 3,627.5 twips or 1,511.46 dots, on the dot 1,511. From the grid line
// with half the border rounded up to 8 twips it would start at 3,628 twips, on the dot
// 1,512.
let (device, quirks) = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::EdgeTableText::WholeTwipBorder)
.with_variant(crate::quirks::CellTextRoom::CombinedBorderMinimum)
});
let props = concat!(
r#"<w:jc w:val="center"/><w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/></w:tblBorders>"#,
r#"<w:tblCellMar><w:left w:w="0" w:type="dxa"/></w:tblCellMar>"#
);
let body = table(props, &[5000], &[("", &[&p("a")])]);
let target = (device, quirks);
let list = pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
target,
)
.list;
assert_eq!(find(&list, 'a').1, 1511 * 3048);
}
#[test]
fn starts_a_spaced_cells_text_after_its_whole_left_line_under_inside_lines() {
// A table with a cell spacing of 40 twips and lines of 1.5 pt, 30 twips: the cell's box
// starts twice the spacing inside the grid line. Its text starts after half the box's left
// line under `LineMiddles` and after the whole line under `InsideLines`, 15 twips further
// right: 6.25 dots of 1/600 inch, which the text's place on the device takes as 6 dots.
let props = concat!(
r#"<w:tblCellSpacing w:w="40" w:type="dxa"/>"#,
r#"<w:tblBorders><w:left w:val="single" w:sz="12"/></w:tblBorders>"#
);
let body = table(props, &[5000], &[("", &[&p("a")])]);
let start = |text: crate::quirks::SpacedCellText| {
let target = on_base_with(|p| p.with_variant(text));
find(
&pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list,
'a',
)
.1
};
let middles = start(crate::quirks::SpacedCellText::LineMiddles);
let inside = start(crate::quirks::SpacedCellText::InsideLines);
assert_eq!(inside - middles, 6 * 3048);
}
#[test]
fn rounds_line_widths_down_and_centers_the_bottom_line_below_the_row() {
// A 1.5 pt line is 12.5 dots of 1/600 inch, drawn 12 dots wide. The top line starts
// at the row's top, 600 dots. The row's bottom is 404 twips lower, at 768.33 dots, and the
// bottom line is centered 0.75 pt, 6.25 dots, below it: at 774.58, rounded to 775, so it
// starts at 769, not at the bottom rounded, 768. The side lines end where it starts, and
// the corners fill it.
let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="12"/><w:left w:val="single" w:sz="12"/><w:bottom w:val="single" w:sz="12"/><w:right w:val="single" w:sz="12"/></w:tblBorders>"#;
let height = r#"<w:trHeight w:val="404" w:hRule="exact"/>"#;
let body = table(borders, &[2000], &[(height, &[&p("a")])]);
let list = lay_out_centered_lines(&body, NORMAL, Some(15));
let rects = rects_600(&list);
assert!(rects.iter().all(|r| r.2.min(r.3) == 12), "{rects:?}");
for line in [
(612, 600, 822, 12),
(612, 769, 822, 12),
(600, 612, 12, 157),
] {
assert!(rects.contains(&line), "{line:?} in {rects:?}");
}
assert!(rects.contains(&(600, 769, 12, 12)), "{rects:?}");
}
#[test]
fn fills_a_continued_merged_cell_under_the_text_of_the_region() {
// A gray cell merged over two rows with lines between the rows. The second row's cell
// continues the region: its fill starts at the top of its row, where no line is drawn,
// and it lies under the text of the region, which the first cell holds.
let gray = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
let borders = r#"<w:tblBorders><w:insideH w:val="single" w:sz="8"/></w:tblBorders>"#;
let first = format!(
r#"<w:tcPr><w:vMerge w:val="restart"/>{gray}</w:tcPr>{}"#,
p("a")
);
let next = format!("<w:tcPr><w:vMerge/>{gray}</w:tcPr><w:p/>");
let list = lay_out(
&table(borders, &[2000], &[("", &[&first]), ("", &[&next])]),
NORMAL,
None,
);
let items = list.pages()[0].items();
let gray_fills: Vec<(usize, i64, i64)> = items
.iter()
.enumerate()
.filter_map(|(index, item)| match item {
Item::Rect(r) if r.color.r == 0xD9 => Some((
index,
r.y.units() / DOT,
(r.y.units() + r.height.units()) / DOT,
)),
_ => None,
})
.collect();
assert_eq!(gray_fills.len(), 2, "{gray_fills:?}");
// The second fill starts where the first ends.
assert_eq!(gray_fills[1].1, gray_fills[0].2);
// Both fills come before the text.
let text = items
.iter()
.position(|item| matches!(item, Item::Glyphs(run) if run.text == "a"))
.unwrap();
assert!(gray_fills.iter().all(|(index, _, _)| *index < text));
}
/// The fills of the first page of `body` with the merged cells' fill `fill`, as their red
/// channel and their top and bottom in dots, from the top down; black lines left out.
fn merged_fills(body: &str, fill: crate::quirks::MergedCellFill) -> Vec<(u8, i64, i64)> {
let target = on_base_with(|p| p.with_variant(fill));
let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
let mut fills: Vec<(u8, i64, i64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) if r.color.r != 0 => Some((
r.color.r,
r.y.units() / DOT,
(r.y.units() + r.height.units()) / DOT,
)),
_ => None,
})
.collect();
fills.sort_by_key(|fill| fill.1);
fills
}
/// Spans across the page: each a left and a right x in layout units.
type Spans = Vec<(i64, i64)>;
/// The gray fills and the black vertical lines of the first page of `list`, each as its left and
/// right x in layout units, from left to right; a line drawn twice counts once.
fn fills_and_lines(list: &DisplayList) -> (Spans, Spans) {
let mut fills = Vec::new();
let mut lines = Vec::new();
for item in list.pages()[0].items() {
if let Item::Rect(r) = item {
let x = (r.x.units(), r.x.units() + r.width.units());
if r.color.r == 0xD9 {
fills.push(x);
} else if r.color.r == 0 && r.height > r.width {
lines.push(x);
}
}
}
fills.sort_unstable();
lines.sort_unstable();
lines.dedup();
(fills, lines)
}
/// The gray fills and the black vertical lines of the first page of `body` with the cells'
/// fill sides `sides`, each as its left and right x in layout units, from left to right.
fn fill_sides(body: &str, sides: crate::quirks::CellFillSides) -> (Spans, Spans) {
let target = on_base_with(|p| p.with_variant(sides));
let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
fills_and_lines(&list)
}
#[test]
fn fills_a_cell_from_grid_line_to_grid_line_under_half_of_each_line() {
// Two gray cells with 1 pt lines on every side and between them. With `GridLines`, each
// fill runs from grid line to grid line, under half of each line.
let body = own_lines_table(8, &[2000, 2000]);
let (grid, lines) = fill_sides(&body, crate::quirks::CellFillSides::GridLines);
let under = |x: i64, line: (i64, i64)| line.0 < x && x < line.1;
assert_eq!((grid.len(), lines.len()), (2, 3), "{grid:?} {lines:?}");
assert!(under(grid[0].0, lines[0]), "{grid:?} {lines:?}");
assert!(under(grid[0].1, lines[1]), "{grid:?} {lines:?}");
assert_eq!(grid[0].1, grid[1].0);
assert!(under(grid[1].1, lines[2]), "{grid:?} {lines:?}");
}
/// The gray fills and the black vertical lines of the first page of `body`, each as its left
/// and right x in layout units from left to right, on a Letter page with margins of 1 inch in
/// mode 15, on a device of 600 dots per inch whose table lines are centered on their places
/// (`TableLines::RoundsCenters`), with the cells' fills between their side lines
/// (`CellFillSides::InsideLines`).
fn dot_fill_sides(body: &str) -> (Spans, Spans) {
let (device, quirks) = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::TableLines::RoundsCenters)
.with_variant(crate::quirks::CellFillSides::InsideLines)
});
let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>"#;
let body = format!("{body}{section}");
let list = pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
(device, quirks),
)
.list;
fills_and_lines(&list)
}
/// Asserts that [`dot_fill_sides`] of `body` gives the black vertical lines `lines` and the gray
/// fills `fills`, each given in dots of 1/600 inch, half of [`DOT`].
fn assert_dot_spans(body: &str, lines: &[(i64, i64)], fills: &[(i64, i64)]) {
let dot = DOT / 2;
let in_dots = |spans: &[(i64, i64)]| -> Spans {
spans.iter().map(|&(a, b)| (a * dot, b * dot)).collect()
};
let (found_fills, found_lines) = dot_fill_sides(body);
assert_eq!(found_lines, in_dots(lines), "{found_lines:?}");
assert_eq!(found_fills, in_dots(fills), "{found_fills:?}");
}
/// A table of fixed layout with the columns `grid` in twips and one row of two gray cells,
/// with single lines of `eighths` on every side of the table and between the cells.
fn own_lines_table(eighths: u32, grid: &[i64]) -> String {
let gray = r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:tcPr>"#;
let line = format!(r#"w:val="single" w:sz="{eighths}""#);
let borders = format!(
"<w:tblLayout w:type=\"fixed\"/><w:tblBorders><w:top {line}/><w:left {line}/><w:bottom {line}/><w:right {line}/><w:insideV {line}/></w:tblBorders>"
);
let cell = format!("{gray}{}", p("a"));
table(&borders, grid, &[("", &[&cell, &cell])])
}
#[test]
fn fills_a_cell_on_whole_dots_half_its_own_line_inside_the_lines_place() {
// Lines of 1 pt (20 twips) on every side: the grid starts half the table's left line,
// 10 twips, right of the margin's 1,440 twips, so the lines' places are 1,450, 2,051 and
// 2,652 twips, 604.17, 854.58 and 1,105 dots, and the lines of 8 dots are drawn from 600,
// 851 and 1,101. Each fill lies 10 twips inside the places, rounded to the dot: from
// 1,460 (608.33, so 608) to 2,041 (850.42, so 850), one dot before the line between the
// cells, and from 2,061 (858.75, so 859) to 2,642 (1,100.83, so 1,101).
assert_dot_spans(
&own_lines_table(8, &[601, 601]),
&[(600, 608), (851, 859), (1101, 1109)],
&[(608, 850), (859, 1101)],
);
}
/// The top and bottom of each gray fill of the first page of `body`, in layout units, on a
/// device of 600 dots per inch in mode 15, with the cells' fill rows `rows`.
fn fill_rows(body: &str, rows: crate::quirks::CellFillRows) -> Vec<(i64, i64)> {
let target = crate::layout::testing::target_at(600, |p| p.with_variant(rows));
let list = pass_with(body, (NORMAL, Some(15)), None, Numbering::default(), target).list;
list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) if r.color.r == 0xD9 => Some((r.y.units(), (r.y + r.height).units())),
_ => None,
})
.collect()
}
/// The gray rectangles and the black ones of the first page of `body` in their order, as
/// (index, top, bottom, gray) in layout units, on a device of 600 dots per inch in mode 15,
/// with the cells' top bands `band` and lines whose width the device rounds down.
fn band_rects(body: &str, band: crate::quirks::CellTopBand) -> Vec<(usize, i64, i64, bool)> {
let target = crate::layout::testing::target_at(600, |p| {
p.with_variant(band)
.with_variant(crate::quirks::TableLines::RoundsCenters)
});
let list = pass_with(body, (NORMAL, Some(15)), None, Numbering::default(), target).list;
list.pages()[0]
.items()
.iter()
.enumerate()
.filter_map(|(i, item)| match item {
Item::Rect(r) if r.color.r == 0xD9 || r.color.r == 0 => {
Some((i, r.y.units(), (r.y + r.height).units(), r.color.r == 0xD9))
}
_ => None,
})
.collect()
}
#[test]
fn paints_the_dot_that_a_top_line_loses_in_the_fills_color_after_it_on_a_target_that_does() {
// Two gray cells without a top margin under a line of 1.5 pt, 12.5 dots of 1/600 inch,
// which the device draws 12 dots tall where it rounds a line's width down. With `FromLineEdge`, a gray band follows the line
// in the items, from the line's drawn lower edge down to its top plus 12.5 dots, a half up:
// one dot under each cell. With `BelowMargin`, a cell without a top margin has no band.
use crate::quirks::CellTopBand::{BelowMargin, FromLineEdge};
let body = own_lines_table(12, &[2000, 2000]);
let dot = DOT / 2;
let gray = |rects: &[(usize, i64, i64, bool)]| rects.iter().filter(|r| r.3).count();
let plain = band_rects(&body, BelowMargin);
assert_eq!(gray(&plain), 2, "{plain:?}");
let banded = band_rects(&body, FromLineEdge);
assert_eq!(gray(&banded), 4, "{banded:?}");
let top_line = banded.iter().filter(|r| !r.3).min_by_key(|r| r.1).copied();
let Some((line_at, line_top, line_end, _)) = top_line else {
panic!("no line: {banded:?}");
};
assert_eq!(line_end - line_top, 12 * dot, "{banded:?}");
let bands: Vec<_> = banded
.iter()
.filter(|r| r.3 && r.1 == line_end && r.2 - r.1 == dot)
.collect();
assert_eq!(bands.len(), 2, "{banded:?}");
assert!(bands.iter().all(|r| r.0 > line_at), "{banded:?}");
}
#[test]
fn puts_a_cells_fill_top_and_bottom_on_the_nearest_dots_on_a_target_that_does() {
// Two gray cells under a line of 0.5 pt: each fill starts 0.5 pt below the row's top,
// between two dots of 1/600 inch. With `WholeDots`, its top and bottom move to the nearest
// dots, each by half a dot or less; with `Exact`, its top lies between them.
use crate::quirks::CellFillRows::{Exact, WholeDots};
let body = own_lines_table(4, &[2000, 2000]);
let dot = DOT / 2;
let on_dot = |y: i64| y % dot == 0;
let (exact, dots) = (fill_rows(&body, Exact), fill_rows(&body, WholeDots));
assert_eq!((exact.len(), dots.len()), (2, 2), "{exact:?} {dots:?}");
assert!(exact.iter().all(|&(top, _)| !on_dot(top)), "{exact:?}");
assert!(
dots.iter()
.all(|&(top, bottom)| on_dot(top) && on_dot(bottom)),
"{dots:?}"
);
let near = |a: i64, b: i64| 2 * (a - b).abs() <= dot;
for (&(top, bottom), &(dot_top, dot_bottom)) in exact.iter().zip(&dots) {
assert!(
near(top, dot_top) && near(bottom, dot_bottom),
"{exact:?} {dots:?}"
);
}
}
#[test]
fn fills_a_cell_half_its_own_line_inside_in_whole_twips_rounded_down() {
// Lines of 0.25 pt (5 twips) on every side: the grid starts half the table's left line,
// 2.5 twips, rounded up to 3 twips right of the margin, so the line between the cells of
// 3,005 and 601 twips lies at 4,448 twips (1,853.33 dots) and is drawn from 1,852 to
// 1,854. Half the line is 2 twips in whole twips, rounded down: the left cell's fill ends
// at 4,446 twips, exactly 1,852.5 dots, so 1,853, one dot under the line, and the right
// cell's fill starts at 4,450 twips (1,854.17, so 1,854). The table's own lines at 1,443
// and 5,049 twips give the fill's outer ends: 1,445 (602.08, so 602) and 5,047 (2,102.92,
// so 2,103).
assert_dot_spans(
&own_lines_table(2, &[3005, 601]),
&[(600, 602), (1852, 1854), (2103, 2105)],
&[(602, 1853), (1854, 2103)],
);
}
#[test]
fn fills_a_cell_to_the_lines_place_on_a_side_without_its_own_line() {
// Two gray cells of 601 twips without table lines, and one line of 0.5 pt (10 twips)
// between them, the left cell's own right line; the right cell's own left border is nil.
// The line's place lies 2,041 twips from the page's edge, 850.42 dots, so the line of 4
// dots is drawn from 848. The left cell's fill ends half its own line inside the place,
// at 2,036 twips (848.33, so 848); the right cell's fill starts at the place itself, 850,
// under the line. The outer sides have no line: the fills end at the places, 600 and
// 1,101 (2,642 twips, 1,100.83 dots).
let line = r#"w:val="single" w:sz="4""#;
let shading = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
let left = format!(
"<w:tcPr><w:tcBorders><w:right {line}/></w:tcBorders>{shading}</w:tcPr>{}",
p("a")
);
let right = format!(
r#"<w:tcPr><w:tcBorders><w:left w:val="nil"/></w:tcBorders>{shading}</w:tcPr>{}"#,
p("b")
);
let props = r#"<w:tblLayout w:type="fixed"/>"#;
let body = table(props, &[601, 601], &[("", &[&left, &right])]);
assert_dot_spans(&body, &[(848, 852)], &[(600, 848), (850, 1101)]);
}
#[test]
fn fills_a_merged_cell_with_its_first_cells_shading_on_a_target_that_does() {
// A merged cell over three rows: an orange first cell, a blue second cell and a third cell
// without a shading. With `FirstCell`, each row of the merged cell is orange, from the
// first row's fill down without a gap; with `EachRow`, the first row is orange, the second
// blue and the third has no fill.
let orange = r#"<w:shd w:val="clear" w:color="auto" w:fill="FBE4D5"/>"#;
let blue = r#"<w:shd w:val="clear" w:color="auto" w:fill="D2EAF1"/>"#;
let borders = r#"<w:tblBorders><w:insideH w:val="single" w:sz="8"/></w:tblBorders>"#;
let first = format!(
r#"<w:tcPr><w:vMerge w:val="restart"/>{orange}</w:tcPr>{}"#,
p("a")
);
let second = format!("<w:tcPr><w:vMerge/>{blue}</w:tcPr><w:p/>");
let third = "<w:tcPr><w:vMerge/></w:tcPr><w:p/>";
let rows: [(&str, &[&str]); 3] = [("", &[&first]), ("", &[&second]), ("", &[third])];
let body = table(borders, &[2000], &rows);
let whole = merged_fills(&body, crate::quirks::MergedCellFill::FirstCell);
assert_eq!(whole.len(), 3, "{whole:?}");
assert!(whole.iter().all(|fill| fill.0 == 0xFB), "{whole:?}");
assert!(
whole.windows(2).all(|pair| pair[1].1 == pair[0].2),
"{whole:?}"
);
let each = merged_fills(&body, crate::quirks::MergedCellFill::EachRow);
let colors: Vec<u8> = each.iter().map(|fill| fill.0).collect();
assert_eq!(colors, [0xFB, 0xD2], "{each:?}");
}
#[test]
fn takes_back_the_fill_under_a_merged_cell_when_its_next_row_moves_on() {
// A centred merged cell, orange in its first row, whose second row does not fit on the
// small page and moves to the next page whole. The trial of the second row puts the first
// cell's fill under the merged cell's content in the first row; going back takes it out,
// so that the first page is the one of a merged cell without that fill: every item of the
// first row stays, and no fill reaches below it.
let orange = r#"<w:shd w:val="clear" w:color="auto" w:fill="FBE4D5"/>"#;
let section = r#"<w:sectPr><w:pgSz w:w="4000" w:h="2400"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr>"#;
let first = format!(
r#"<w:tcPr><w:vMerge w:val="restart"/>{orange}<w:vAlign w:val="center"/></w:tcPr>{}"#,
p("a")
);
let tall: String = ["b", "c", "d", "e"].into_iter().map(p).collect();
let rest = "<w:tcPr><w:vMerge/></w:tcPr><w:p/>";
let rows: [(&str, &[&str]); 2] = [("", &[&first, &p("x")]), ("<w:cantSplit/>", &[rest, &tall])];
let body = table("", &[1200, 1200], &rows) + section;
let first_page = |fill| {
let target = on_base_with(|p| p.with_variant(fill));
let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
assert!(list.pages().len() > 1, "the second row moves on");
list.pages()[0].items().to_vec()
};
assert_eq!(
first_page(crate::quirks::MergedCellFill::FirstCell),
first_page(crate::quirks::MergedCellFill::EachRow)
);
}
#[test]
fn paints_the_top_margin_of_a_filled_cell_again_after_the_lines() {
// A gray cell with a top margin of 72 twips (3.6 pt, 15 dots) below a 1 pt top line: after
// the line comes a gray band from the line's bottom down by the margin.
let gray = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="8"/></w:tblBorders>"#;
let margin = r#"<w:tcMar><w:top w:w="72" w:type="dxa"/></w:tcMar>"#;
let cell = format!("<w:tcPr>{margin}{gray}</w:tcPr>{}", p("a"));
let list = lay_out(&table(borders, &[2000], &[("", &[&cell])]), NORMAL, None);
let rects: Vec<(u8, i64, i64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) => Some((
r.color.r,
r.y.units() / DOT,
(r.y.units() + r.height.units()) / DOT,
)),
_ => None,
})
.collect();
// The fill, the line, then the band from the line's bottom.
assert_eq!(rects.len(), 3, "{rects:?}");
let (line, band) = (rects[1], rects[2]);
assert_eq!((rects[0].0, line.0, band.0), (0xD9, 0, 0xD9));
assert_eq!((band.1, band.2 - band.1), (line.2, 15));
}
#[test]
fn paints_a_white_band_and_then_the_right_line_beside_it() {
// A white cell with a top margin of 72 twips, a top line and a right line: its white fill
// under the lines, a white band after the top line, and the right line's piece beside the
// band after it.
let white = r#"<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/>"#;
let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="8"/><w:right w:val="single" w:sz="8"/></w:tblBorders>"#;
let margin = r#"<w:tcMar><w:top w:w="72" w:type="dxa"/></w:tcMar>"#;
let cell = format!("<w:tcPr>{margin}{white}</w:tcPr>{}", p("a"));
let list = lay_out(&table(borders, &[2000], &[("", &[&cell])]), NORMAL, None);
let rects: Vec<(u8, i64, i64, i64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) => Some((
r.color.r,
r.x.units(),
r.y.units(),
r.y.units() + r.height.units(),
)),
_ => None,
})
.collect();
let band = rects
.iter()
.rposition(|r| r.0 == 0xFF)
.expect("a white band");
let (_, band_x, top, bottom) = rects[band];
// The cell's fill is the first item, white, from inside the band down past its bottom.
let fill = rects[0];
assert!(
fill.0 == 0xFF && (top..bottom).contains(&fill.2) && fill.3 > bottom,
"{rects:?}"
);
let after: Vec<_> = rects.iter().skip(band + 1).collect();
// The right line's piece beside the band comes after it, and the rest of the line before.
assert_eq!(after.len(), 1, "{rects:?}");
assert!(
after[0].1 > band_x && (after[0].2, after[0].3) == (top, bottom),
"{rects:?}"
);
assert!(
rects
.iter()
.take(band)
.any(|r| r.1 == after[0].1 && r.2 == bottom),
"{rects:?}"
);
}
#[test]
fn draws_automatic_text_white_on_a_dark_fill() {
// Text of the automatic color is white on a dark cell fill and black on a light one, and a
// dark highlight does not change it.
let color = |fill: &str, run: &str| {
let cell = format!(
r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="{fill}"/></w:tcPr><w:p><w:r>{run}<w:t>a</w:t></w:r></w:p>"#
);
let list = lay_out(&table("", &[2000], &[("", &[&cell])]), NORMAL, None);
list.pages()[0]
.items()
.iter()
.find_map(|item| match item {
Item::Glyphs(run) => Some([run.color.r, run.color.g, run.color.b]),
_ => None,
})
.unwrap()
};
assert_eq!(color("002060", ""), [255, 255, 255]);
assert_eq!(color("D9D9D9", ""), [0, 0, 0]);
assert_eq!(color("C00000", ""), [255, 255, 255]);
assert_eq!(color("365F91", ""), [0, 0, 0]);
// A color of the run's own stays.
assert_eq!(
color("002060", r#"<w:rPr><w:color w:val="000000"/></w:rPr>"#),
[0, 0, 0]
);
// On a white cell, a dark highlight keeps the text black.
assert_eq!(
color(
"FFFFFF",
r#"<w:rPr><w:highlight w:val="darkBlue"/></w:rPr>"#
),
[0, 0, 0]
);
}
#[test]
fn draws_a_white_run_fill_over_a_dark_cell_with_black_text() {
// A run shaded white in a dark cell: the cell's fill, then the run's white fill over it,
// and text of the automatic color stays black on the run's own white.
let cell = r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="002060"/></w:tcPr><w:p><w:r><w:rPr><w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/></w:rPr><w:t>a</w:t></w:r></w:p>"#;
let list = lay_out(&table("", &[2000], &[("", &[cell])]), NORMAL, None);
let painted: Vec<[u8; 3]> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) => Some([r.color.r, r.color.g, r.color.b]),
Item::Glyphs(run) => Some([run.color.r, run.color.g, run.color.b]),
_ => None,
})
.collect();
assert_eq!(
painted,
[[0x00, 0x20, 0x60], [255, 255, 255], [0, 0, 0]],
"the cell's fill, the run's fill and the glyphs, in this order"
);
}
#[test]
fn keeps_the_cell_of_each_line_record() {
// Two tables with a paragraph between them. The second table's first cell holds two
// paragraphs and spans both grid columns of its row, and a nested table lies in its
// second row; the nested table takes the next number. The empty paragraph after the
// nested table ends the cell and has no line.
let nested = table("", &[1000], &[("", &[&p("n")])]);
let second_row = format!("{}{nested}<w:p/>", p("d"));
let span = format!(
r#"<w:tcPr><w:gridSpan w:val="2"/></w:tcPr>{}{}"#,
p("b"),
p("c")
);
let body = table("", &[2000, 2000], &[("", &[&p("a"), &p("x")])])
+ &p("o")
+ &table(
"",
&[2000, 2000],
&[("", &[&span]), ("", &[&second_row, &p("e")])],
);
let pass = pass_with_header(&body, NORMAL, None, None);
let cells: Vec<_> = pass
.lines
.iter()
.map(|line| {
let cell = line.cell.map(|c| (c.table, c.row, c.column));
(cell, line.index)
})
.collect();
assert_eq!(
cells,
[
(Some((1, 1, 1)), 0),
(Some((1, 1, 2)), 0),
(None, 0),
(Some((2, 1, 1)), 0),
(Some((2, 1, 1)), 0),
(Some((2, 2, 1)), 0),
(Some((3, 1, 1)), 0),
(Some((2, 2, 2)), 0),
],
"{cells:?}"
);
}
#[test]
fn numbers_the_lines_of_a_paragraph() {
// Ten "q" of 5 pt each and spaces do not fit in a cell 1000 twips (50 pt) wide less its
// margins, so the paragraph takes more than one line.
let text = ["q"; 10].join(" ");
let body = table("", &[1000], &[("", &[&p(&text)])]);
let pass = pass_with_header(&body, NORMAL, None, None);
let indexes: Vec<usize> = pass.lines.iter().map(|line| line.index).collect();
assert!(indexes.len() > 1, "{indexes:?}");
assert!(indexes.iter().copied().eq(0..indexes.len()), "{indexes:?}");
}
/// The cell floor gives the lowest bottom of the wrapping drawings, or of all drawings, with
/// `i64::MIN` for no drawing, on many orders of wrapping and other drawings.
#[test]
fn cell_floor_reaches_the_lowest_bottom_of_its_drawings() {
let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
let mut next = |range: u64| {
seed = seed
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) % range
};
for _ in 0..2_000 {
let mut floor = CellFloor::Clear;
let (mut wrapping, mut every) = (i64::MIN, i64::MIN);
for _ in 0..next(6) {
let bottom = i64::try_from(next(2_000)).unwrap() - 500;
let wraps = next(2) == 1;
floor = floor.lowered(Length::from_units(bottom), wraps);
if wraps {
wrapping = wrapping.max(bottom);
}
every = every.max(bottom);
}
let content = i64::try_from(next(2_000)).unwrap() - 500;
for (all, pair) in [(false, wrapping), (true, every)] {
let reached = floor
.reach(all)
.map_or(content, |floor| content.max(floor.units()));
assert_eq!(reached, content.max(pair), "{floor:?} {all}");
}
}
}
#[test]
fn wrap_none_in_centered_cell_aligns_without_growing_row_height() {
let drawing = |pos_pt: i64, h_pt: i64, wrap: &str| {
let pos = pos_pt * 12_700;
let cy = h_pt * 12_700;
format!(
r#"<w:r><w:drawing><wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" behindDoc="1" locked="0" layoutInCell="1" allowOverlap="1" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>{pos}</wp:posOffset></wp:positionV><wp:extent cx="635000" cy="{cy}"/><wp:effectExtent l="0" t="0" r="0" b="0"/>{wrap}<wp:docPr id="1" name="s"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="{cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
)
};
let cell = |va: &str, d: &str| {
format!(r#"<w:tcPr><w:vAlign w:val="{va}"/></w:tcPr><w:p>{d}<w:r><w:t>a</w:t></w:r></w:p>"#)
};
// Auto-height centered row: 100 pt wrapNone does not grow row height, while 100 pt wrapSquare
// does.
let auto_none = table(
"",
&[2000],
&[
("", &[&cell("center", &drawing(0, 100, "<wp:wrapNone/>"))]),
("", &[&p("b")]),
],
);
let auto_plain = table(
"",
&[2000],
&[("", &[&cell("center", "")]), ("", &[&p("b")])],
);
let auto_sq = table(
"",
&[2000],
&[
(
"",
&[&cell(
"center",
&drawing(0, 100, r#"<wp:wrapSquare wrapText="bothSides"/>"#),
)],
),
("", &[&p("b")]),
],
);
let none_list = lay_out(&auto_none, NORMAL, Some(15));
let plain_list = lay_out(&auto_plain, NORMAL, Some(15));
let sq_list = lay_out(&auto_sq, NORMAL, Some(15));
assert_eq!(at(&none_list, 'b').1, at(&plain_list, 'b').1);
assert!(at(&sq_list, 'b').1 > at(&none_list, 'b').1 + du(1500));
// Minimum-height 120 pt centered row: 60 pt wrapNone at +20 pt (bottom 80 pt < 120 pt) shifts
// "a" down by (120 - 80)/2 = 20 pt, less than the (120 - 10)/2 = 55 pt of text alone.
let min_tr = r#"<w:trHeight w:val="2400" w:hRule="atLeast"/>"#;
let min_none = table(
"",
&[2000],
&[
(
min_tr,
&[&cell("center", &drawing(20, 60, "<wp:wrapNone/>"))],
),
("", &[&p("b")]),
],
);
let min_plain = table(
"",
&[2000],
&[(min_tr, &[&cell("center", "")]), ("", &[&p("b")])],
);
let min_none_list = lay_out(&min_none, NORMAL, Some(15));
let min_plain_list = lay_out(&min_plain, NORMAL, Some(15));
assert_eq!(at(&min_none_list, 'b').1, at(&min_plain_list, 'b').1);
assert_eq!(at(&min_none_list, 'a').1 - base(1440), du(400));
assert!(at(&min_plain_list, 'a').1 > at(&min_none_list, 'a').1 + du(500));
}
#[test]
fn puts_the_row_end_s_rest_at_the_bottom_of_a_cell_aligned_to_the_bottom() {
// A row of at least 318 twips at the top margin of 1,440 twips ends 1,758 twips from the
// page's top, exactly on half a dot of 600 dots per inch (732.5 dots), and its height
// enters 0.4 of a 1/4,096 pt short. Its cell, aligned to the bottom, holds a single line
// of 222.2 twips, which is not whole twips, so its moved text top starts no rest. The
// line's box rounds up, so its bottom, at the row's end, places it. The cell takes the
// row end's rest there, and the line goes up the page; held exactly, the half goes down.
let body = aligned_row(318, "bottom", &p("b"));
assert_eq!(
held_one_dot_up_on(&Tall, None, &body),
Length::UNITS_PER_INCH / 600
);
}
#[test]
fn moves_a_centered_cell_by_half_of_the_rests_of_its_free_room() {
// A row of at least 289 twips at the top margin of 1,440 twips, whose height enters 0.2
// of a 1/4,096 pt short, holds a centered single line of 222.2 twips. Moved by half of the
// free room, the line's bottom lies exactly on half a dot (884.5 dots), and its moved
// text top, which is not whole twips, takes half of the row end's rest: 0.1 of a 1/4,096
// pt short, so the line goes up the page; held exactly, the half goes down.
let body = aligned_row(289, "center", &p("b"));
assert_eq!(
held_one_dot_up_on(&Tall, None, &body),
Length::UNITS_PER_INCH / 600
);
}
#[test]
fn starts_the_rest_of_a_moved_text_top_of_whole_twips_as_one_length() {
// A row of at least 276 twips at the top margin of 1,440 twips holds a centered exact line
// of 240 twips. Its free room of 36 twips moves the cell's text top to 1,458 twips from
// the page's top, whole twips, exactly on half a dot (607.5 dots). That top starts its
// rest as one length, 0.4 of a 1/4,096 pt short, so the line goes up the page. Half of the
// free room's rests would put it 0.1 past, and held exactly the half goes down.
let line = r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
let body = aligned_row(276, "center", line);
assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}
#[test]
fn gives_the_rests_of_a_cell_s_move_for_its_alignment() {
use super::rows::moved_rest;
let half_emu = Length::from_units(1);
assert_eq!(
moved_rest(Some(VerticalAlign::Bottom), -1270, half_emu),
Some(-1270)
);
assert_eq!(
moved_rest(Some(VerticalAlign::Center), -1270, Length::ZERO),
Some(-635)
);
assert_eq!(
moved_rest(Some(VerticalAlign::Center), 1270, half_emu),
Some(891)
);
assert_eq!(moved_rest(Some(VerticalAlign::Top), 1270, half_emu), None);
assert_eq!(moved_rest(None, 1270, half_emu), None);
}
#[test]
fn starts_the_twips_rest_at_the_top_of_a_split_cell_s_part() {
// On pages 3,000 twips high with a top margin of 1,134 twips and a bottom margin of 1,000
// twips, a cell's fourth exact line of 240 twips ends below the page's foot, so the row
// splits and that line goes on at the next page's top margin. The line ends 1,374 twips
// from that page's top, exactly on half a dot (114.5 dots). Its part's text top, 1,134
// twips, held as the nearest 1/4,096 pt, lies above its exact place, so the line goes up
// the page; held exactly, the half goes down.
let exact = |text| {
format!(
r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let cell = [exact("a"), exact("a"), exact("a"), exact("b")].concat();
let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="3000"/><w:pgMar w:top="1134" w:right="1440" w:bottom="1000" w:left="1440"/></w:sectPr>"#;
let body = table("", &[2000], &[("", &[&cell])]) + section;
assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}
/// The step from the text of the first to the text of the second of two cells of 2,000 twips on
/// a grid of the same widths, in a table with a cell spacing of 40 twips and the properties
/// `props`, under the quirk `columns`.
fn spaced_column_step(props: &str, columns: crate::quirks::SpacedColumns) -> i64 {
let props = format!(r#"<w:tblCellSpacing w:w="40" w:type="dxa"/>{props}"#);
let cell = |text: &str| {
format!(
r#"<w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>{}"#,
p(text)
)
};
let (a, b) = (cell("a"), cell("b"));
let body = table(&props, &[2000, 2000], &[("", &[&a, &b])]);
let target = on_base_with(|p| p.with_variant(columns));
let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
find(&list, 'b').1 - find(&list, 'a').1
}
#[test]
fn widens_a_spaced_column_to_its_cells_width_and_spacing_under_cell_widths() {
// Under `Grid` the second cell's text starts 2,000 twips less the spacing after the
// first's; under `CellWidths`, in a table of fixed layout, the first column is the cell's
// width plus three spacings, and the second text starts 120 twips, 50 dots, further right.
let fixed = r#"<w:tblLayout w:type="fixed"/>"#;
let grid = spaced_column_step(fixed, crate::quirks::SpacedColumns::Grid);
let widths = spaced_column_step(fixed, crate::quirks::SpacedColumns::CellWidths);
assert_eq!(widths - grid, 50 * 3048);
}
#[test]
fn keeps_the_grid_columns_of_a_spaced_table_of_automatic_layout_under_cell_widths() {
// Without a fixed layout the columns fit their content in Word, and `CellWidths` keeps the
// grid.
let grid = spaced_column_step("", crate::quirks::SpacedColumns::Grid);
let widths = spaced_column_step("", crate::quirks::SpacedColumns::CellWidths);
assert_eq!(widths, grid);
}
/// The step from the text of the first to the text of the second of two cells of 3,000 twips,
/// on the saved grid `grid`, in a table with the properties `props`, under the quirk `columns`.
fn autofit_column_step(props: &str, grid: &[i64], columns: crate::quirks::AutofitGrid) -> i64 {
autofit_step_after("a", props, grid, columns)
}
/// [`autofit_column_step`] with the first cell's text `first`, which starts with "a".
fn autofit_step_after(
first: &str,
props: &str,
grid: &[i64],
columns: crate::quirks::AutofitGrid,
) -> i64 {
let cell = |text: &str| {
format!(
r#"<w:tcPr><w:tcW w:w="3000" w:type="dxa"/></w:tcPr>{}"#,
p(text)
)
};
let (a, b) = (cell(first), cell("b"));
let body = table(props, grid, &[("", &[&a, &b])]);
let target = on_base_with(|p| p.with_variant(columns));
let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
find(&list, 'b').1 - find(&list, 'a').1
}
#[test]
fn takes_the_cells_widths_of_an_autofit_table_whose_grid_disagrees_under_fitting_cells() {
// The grid of 1,500 twips a column disagrees with the cells of 3,000, which fit the text
// column: under `FittingCells` the second text starts 1,500 twips, 625 dots, further right,
// within the one dot of the device grid.
use crate::quirks::AutofitGrid::{FittingCells, Saved};
let saved = autofit_column_step("", &[1500, 1500], Saved);
let cells = autofit_column_step("", &[1500, 1500], FittingCells);
assert!((cells - saved - 625 * 3048).abs() <= 3048);
}
#[test]
fn keeps_the_saved_grid_of_a_fixed_wide_or_unfitting_table_under_fitting_cells() {
// A fixed layout, a preferred width, and an indent that leaves the cells no room keep the
// grid.
use crate::quirks::AutofitGrid::{FittingCells, Saved};
let fixed = r#"<w:tblLayout w:type="fixed"/>"#;
let width = r#"<w:tblW w:w="5000" w:type="dxa"/>"#;
let indent = r#"<w:tblInd w:w="4000" w:type="dxa"/>"#;
for props in [fixed, width, indent] {
let saved = autofit_column_step(props, &[1500, 1500], Saved);
assert_eq!(
autofit_column_step(props, &[1500, 1500], FittingCells),
saved
);
}
}
#[test]
fn keeps_the_saved_grid_where_a_word_is_wider_than_its_cell_under_fitting_cells() {
// A word of 60 letters, wider than the first cell of 3,000 twips, is a least width that the
// cell does not hold: Word widened that column for it, so the saved grid stays.
use crate::quirks::AutofitGrid::{FittingCells, Saved};
let word = "a".repeat(60);
let saved = autofit_step_after(&word, "", &[1500, 1500], Saved);
assert_eq!(
autofit_step_after(&word, "", &[1500, 1500], FittingCells),
saved
);
}
#[test]
fn keeps_the_saved_grid_where_a_cell_over_both_columns_holds_a_wider_word_under_fitting_cells() {
// A word of 140 letters in a cell over both columns is wider than the two cells of 3,000
// twips together, so the saved grid stays; a short word there lets the cells' widths in.
use crate::quirks::AutofitGrid::{FittingCells, Saved};
let step = |letters: usize, columns| {
let cell = |text: &str| {
format!(
r#"<w:tcPr><w:tcW w:w="3000" w:type="dxa"/></w:tcPr>{}"#,
p(text)
)
};
let spanned = format!(
r#"<w:tcPr><w:tcW w:w="6000" w:type="dxa"/><w:gridSpan w:val="2"/></w:tcPr>{}"#,
p(&"x".repeat(letters))
);
let (a, b) = (cell("a"), cell("b"));
let body = table("", &[1500, 1500], &[("", &[&spanned]), ("", &[&a, &b])]);
let target = on_base_with(|p| p.with_variant(columns));
let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
find(&list, 'b').1 - find(&list, 'a').1
};
assert_eq!(step(140, FittingCells), step(140, Saved));
assert_ne!(step(4, FittingCells), step(4, Saved));
}
#[test]
fn starts_a_spaced_tables_text_at_its_indent_before_mode_15_under_spaced_text_start() {
// In mode 12, a table with a cell spacing of 45 twips, a left line of 30 twips, left cell
// margins of 100 twips and an indent of 300 twips. Under `ExplicitTextStart` the first grid
// line lies one margin left of the indent; under `SpacedTextStart` it lies the margin, twice
// the spacing and the whole line left of it, so that the text starts at the indent: 120
// twips, 50 dots, further left.
let props = concat!(
r#"<w:tblCellSpacing w:w="45" w:type="dxa"/><w:tblInd w:w="300" w:type="dxa"/>"#,
r#"<w:tblBorders><w:left w:val="single" w:sz="12"/></w:tblBorders>"#,
r#"<w:tblCellMar><w:left w:w="100" w:type="dxa"/></w:tblCellMar>"#
);
let body = table(props, &[3000], &[("", &[&p("a")])]);
let start = |indent: crate::quirks::TableIndent| {
let target = on_base_with(|p| {
p.with_variant(indent)
.with_variant(crate::quirks::SpacedCellText::InsideLines)
});
find(
&pass_with(
&body,
(NORMAL, Some(12)),
None,
Numbering::default(),
target,
)
.list,
'a',
)
.1
};
let margin = start(crate::quirks::TableIndent::ExplicitTextStart);
let text = start(crate::quirks::TableIndent::SpacedTextStart);
assert_eq!(margin - text, 50 * 3048);
}
#[test]
fn keeps_only_the_text_of_a_table_of_zero_cell_spacing_between_the_line_middles() {
// A cell spacing of zero, in mode 12, with an indent of 300 twips, left cell margins of 100
// twips, a left line of 6 pt (120 twips, 50 dots) and cells of 2,040 twips on a grid of
// 1,800. The text keeps the room of half the line, but the first grid line lies the margin
// and the whole line left of the indent, 120 twips further left than one margin, and the
// first column is the cell's width, 240 twips (100 dots) wider than the grid's.
let props = concat!(
r#"<w:tblCellSpacing w:w="0" w:type="dxa"/><w:tblInd w:w="300" w:type="dxa"/>"#,
r#"<w:tblBorders><w:left w:val="single" w:sz="48"/></w:tblBorders>"#,
r#"<w:tblLayout w:type="fixed"/>"#,
r#"<w:tblCellMar><w:left w:w="100" w:type="dxa"/></w:tblCellMar>"#
);
let a = format!(
r#"<w:tcPr><w:tcW w:w="2040" w:type="dxa"/></w:tcPr>{}"#,
p("a")
);
let b = format!(
r#"<w:tcPr><w:tcW w:w="2040" w:type="dxa"/></w:tcPr>{}"#,
p("b")
);
let body = table(props, &[1800, 1800], &[("", &[&a, &b])]);
let places = |rules: bool| {
let target = on_base_with(|p| {
if rules {
p.with_variant(crate::quirks::SpacedCellText::InsideLines)
.with_variant(crate::quirks::SpacedColumns::CellWidths)
.with_variant(crate::quirks::TableIndent::SpacedTextStart)
} else {
p.with_variant(crate::quirks::SpacedCellText::LineMiddles)
.with_variant(crate::quirks::SpacedColumns::Grid)
.with_variant(crate::quirks::TableIndent::ExplicitTextStart)
}
});
let list = pass_with(
&body,
(NORMAL, Some(12)),
None,
Numbering::default(),
target,
)
.list;
(find(&list, 'a').1, find(&list, 'b').1)
};
let (rules, earlier) = (places(true), places(false));
assert_eq!(earlier.0 - rules.0, 50 * 3048);
assert_eq!((rules.1 - rules.0) - (earlier.1 - earlier.0), 100 * 3048);
}
#[test]
fn excludes_whole_side_borders_from_text_width_when_cell_spacing_is_zero() {
// With w:tblCellSpacing w:w="0" and 6 pt (120 twips) left and right borders, `InsideLines`
// starts left-aligned text at half the left border (matching `LineMiddles`), while excluding
// both whole borders (240 twips vs 120 twips) from the cell's text width: so centered text
// shifts left by 60 twips (3 pt) and right-aligned text shifts left by 120 twips (6 pt).
let props = concat!(
r#"<w:tblCellSpacing w:w="0" w:type="dxa"/>"#,
r#"<w:tblBorders><w:left w:val="single" w:sz="48"/><w:right w:val="single" w:sz="48"/></w:tblBorders>"#,
r#"<w:tblCellMar><w:left w:w="60" w:type="dxa"/><w:right w:w="60" w:type="dxa"/></w:tblCellMar>"#,
);
let cell = |jc: &str, ch: char| {
format!(r#"<w:p><w:pPr><w:jc w:val="{jc}"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#)
};
let left_cell = cell("left", 'a');
let center_cell = cell("center", 'b');
let right_cell = cell("right", 'c');
let body = table(
props,
&[2000],
&[
("", &[left_cell.as_str()]),
("", &[center_cell.as_str()]),
("", &[right_cell.as_str()]),
],
);
let places = |variant: crate::quirks::SpacedCellText| {
let target = on_base_with(|p| p.with_variant(variant));
let list = pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
target,
)
.list;
(find(&list, 'a').1, find(&list, 'b').1, find(&list, 'c').1)
};
let inside = places(crate::quirks::SpacedCellText::InsideLines);
let middles = places(crate::quirks::SpacedCellText::LineMiddles);
assert_eq!(middles.0 - inside.0, 0);
// 60 twips = 76_200 half-EMUs (3 pt); 120 twips = 152_400 half-EMUs (6 pt).
assert_eq!(middles.1 - inside.1, 60 * 1270);
assert_eq!(middles.2 - inside.2, 120 * 1270);
}
/// The page and the baseline in dots of `x` and of `y` in a cell whose paragraph holds `x`, a
/// break of the kind `kind` and `y`, with the quirk `breaks`.
fn cell_break_places(kind: &str, breaks: crate::quirks::CellBreak) -> ((usize, i64), (usize, i64)) {
let cell = format!(r#"<w:p><w:r><w:t>x</w:t><w:br w:type="{kind}"/><w:t>y</w:t></w:r></w:p>"#);
let body = table("", &[4000], &[("", &[cell.as_str()])]);
let target = on_base_with(|p| p.with_variant(breaks));
let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
let (x_page, _, x) = find(&list, 'x');
let (y_page, _, y) = find(&list, 'y');
((x_page, x), (y_page, y))
}
#[test]
fn keeps_the_text_around_a_break_in_a_cell_on_one_line_on_a_target_that_ignores_it() {
use crate::quirks::CellBreak;
for kind in ["page", "column"] {
let (x, y) = cell_break_places(kind, CellBreak::Ignored);
assert_eq!(x, y, "{kind}");
let (x, y) = cell_break_places(kind, CellBreak::EndsLine);
assert_eq!(x.0, y.0, "{kind}");
assert!(y.1 > x.1, "{kind}");
}
}
#[test]
fn drops_space_before_on_leading_cell_break_in_mode_15_only() {
use crate::quirks::CellBreak;
let delta = |mode: u32, valign: &str, c1: &str, c2: &str| {
let va = if valign.is_empty() {
String::new()
} else {
format!(r#"<w:tcPr><w:vAlign w:val="{valign}"/></w:tcPr>"#)
};
let body = format!(
r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc>{va}{c1}</w:tc><w:tc>{va}{c2}</w:tc></w:tr></w:tbl>"#
);
let target = on_base_with(|p| p.with_variant(CellBreak::Ignored));
let list = pass_with(
&body,
(NORMAL, Some(mode)),
None,
Numbering::default(),
target,
)
.list;
find(&list, 'B').2 - find(&list, 'A').2
};
let p_ref = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#;
let p_lead_pg = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:br w:type="page"/><w:t>A</w:t></w:r></w:p>"#;
let p_lead_col = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:br w:type="column"/><w:t>A</w:t></w:r></w:p>"#;
let p_mid_pg = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:t>X</w:t><w:br w:type="page"/><w:t>A</w:t></w:r></w:p>"#;
let p2_c1 = format!(
r#"<w:p><w:pPr><w:spacing w:after="120"/></w:pPr><w:r><w:t>P</w:t></w:r></w:p>{p_lead_pg}"#
);
let p2_c2 = format!(
r#"<w:p><w:pPr><w:spacing w:after="120"/></w:pPr><w:r><w:t>Q</w:t></w:r></w:p>{p_ref}"#
);
let cases = [
(15, "", p_lead_pg, p_ref, du(240)),
(15, "center", p_lead_pg, p_ref, du(120)),
(15, "", p_lead_col, p_ref, du(240)),
(15, "", p2_c1.as_str(), p2_c2.as_str(), du(120)),
(15, "", p_mid_pg, p_ref, 0),
(14, "", p_lead_pg, p_ref, 0),
(12, "", p_lead_pg, p_ref, 0),
];
for (mode, valign, c1, c2, expected) in cases {
assert_eq!(delta(mode, valign, c1, c2), expected);
}
}
#[test]
fn shifts_aligned_inline_and_floating_tables_by_border_in_mode_15_and_margin_before() {
let dot = 3048;
let target = crate::layout::testing::target_at(600, |p| {
p.with_variant(crate::quirks::RightToLeftEdge::LeadingAndInside)
});
let pad = r#"<w:tblCellMar><w:left w:w="200" w:type="dxa"/><w:right w:w="200" w:type="dxa"/></w:tblCellMar>"#;
let x_of = |props: &str, mode: u32| {
let body = table(props, &[2000, 2000], &[("", &[&p("a"), &p("b")])]);
find(
&pass_with(
&body,
(NORMAL, Some(mode)),
None,
Numbering::default(),
target,
)
.list,
'a',
)
.1
};
let l12 = format!(r#"{pad}<w:tblBorders><w:left w:val="single" w:sz="96"/></w:tblBorders>"#);
let r12 = format!(r#"{pad}<w:tblBorders><w:right w:val="single" w:sz="96"/></w:tblBorders>"#);
let i12 = format!(r#"{pad}<w:tblBorders><w:insideV w:val="single" w:sz="96"/></w:tblBorders>"#);
let r_nil = format!(r#"{pad}<w:tblBorders><w:right w:val="nil"/></w:tblBorders>"#);
let ic = r#"<w:jc w:val="center"/>"#;
let ir = r#"<w:jc w:val="right"/>"#;
let fl = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="left" w:vertAnchor="margin" w:tblpY="200"/>"#;
let fc = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="center" w:vertAnchor="margin" w:tblpY="200"/>"#;
let fr = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="right" w:vertAnchor="margin" w:tblpY="200"/>"#;
let rtl = "<w:bidiVisual/>";
let rtl_cases = [
format!("{rtl}{ic}"),
format!("{rtl}{fl}"),
format!("{rtl}{fc}"),
format!("{rtl}{fr}"),
];
let mode_15_cases: [(&str, [i64; 3]); 9] = [
(ic, [25, -25, 0]),
(ir, [0, -50, 0]),
(fl, [50, 0, 0]),
(fc, [25, -25, 0]),
(fr, [0, -50, 0]),
(&rtl_cases[0], [-25, 0, -25]),
(&rtl_cases[1], [0, 0, -50]),
(&rtl_cases[2], [-25, 0, -50]),
(&rtl_cases[3], [-50, 0, -50]),
];
for (prefix, [dl, dr, di]) in mode_15_cases {
let base_nil = x_of(&format!("{prefix}{r_nil}"), 15);
let base_unset = x_of(&format!("{prefix}{pad}"), 15);
assert_eq!(x_of(&format!("{prefix}{l12}"), 15) - base_unset, dl * dot);
assert_eq!(x_of(&format!("{prefix}{r12}"), 15) - base_nil, dr * dot);
assert_eq!(x_of(&format!("{prefix}{i12}"), 15) - base_unset, di * dot);
}
let m0 = r#"<w:tblCellMar><w:left w:w="0" w:type="dxa"/><w:right w:w="0" w:type="dxa"/></w:tblCellMar>"#;
let m108 = r#"<w:tblCellMar><w:left w:w="108" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar>"#;
for (prefix, delta) in [(ir, 90), (fl, 0), (rtl_cases[3].as_str(), 90)] {
assert_eq!(
x_of(&format!("{prefix}{m108}"), 14) - x_of(&format!("{prefix}{m0}"), 14),
delta * dot
);
}
}
#[test]
fn reserves_fifteen_twips_right_edge_for_unbordered_aligned_floating_tables() {
let dot = Length::UNITS_PER_INCH / 600;
let target = crate::layout::testing::target_at(600, Clone::clone);
let pad = r#"<w:tblCellMar><w:left w:w="200" w:type="dxa"/><w:right w:w="200" w:type="dxa"/></w:tblCellMar>"#;
let r_nil = format!(r#"{pad}<w:tblBorders><w:right w:val="nil"/></w:tblBorders>"#);
let r_none = format!(r#"{pad}<w:tblBorders><w:right w:val="none"/></w:tblBorders>"#);
let x_of = |props: &str| {
let body = table(props, &[2000, 2000], &[("", &[&p("a"), &p("b")])]);
find(
&pass_with(
&body,
(NORMAL, Some(15)),
None,
Numbering::default(),
target,
)
.list,
'a',
)
.1
};
let fr = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="right" w:vertAnchor="margin" w:tblpY="200"/>"#;
let fc = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="center" w:vertAnchor="margin" w:tblpY="200"/>"#;
let ir = r#"<w:jc w:val="right"/>"#;
assert_eq!(
x_of(&format!("{fr}{pad}")) - x_of(&format!("{fr}{r_nil}")),
-7 * dot
);
assert_eq!(x_of(&format!("{fr}{r_none}")), x_of(&format!("{fr}{pad}")));
assert_eq!(
x_of(&format!("{fc}{pad}")) - x_of(&format!("{fc}{r_nil}")),
-3 * dot
);
assert_eq!(x_of(&format!("{ir}{pad}")), x_of(&format!("{ir}{r_nil}")));
}
#[test]
fn split_row_first_part_enforces_at_least_minimum_height_for_vertical_alignment() {
// On a 6,000-twip page with 720-twip top/bottom margins (4,560-twip body) and a 3,720-twip
// exact spacer, 840 twips remain on page 1. A row with trHeight="720" (36 pt atLeast)
// splits across pages 1 and 2 when cell 2's 720-twip second paragraph overflows page 1; cell 1
// (vAlign="center") centers inside the 720-twip minimum height rather than cell 2's shorter
// 240-twip page-1 paragraph alone.
let spacer = r#"<w:p><w:pPr><w:spacing w:after="0" w:line="3720" w:lineRule="exact"/></w:pPr><w:r><w:t>S</w:t></w:r></w:p>"#;
let c1 = r#"<w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:vAlign w:val="center"/></w:tcPr><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
let c2 = concat!(
r#"<w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>"#,
r#"<w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
r#"<w:p><w:pPr><w:spacing w:after="0" w:line="720" w:lineRule="exact"/></w:pPr><w:r><w:t>C</w:t></w:r></w:p>"#,
);
let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="6000"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr>"#;
let y_of = |row_props: &str| {
let body = format!(
"{spacer}{}{section}",
table("", &[2000, 2000], &[(row_props, &[c1, c2])])
);
let list = lay_out(&body, NORMAL, None);
assert_eq!(list.pages().len(), 2);
assert_eq!(find(&list, 'A').0, 0);
assert_eq!(find(&list, 'C').0, 1);
find(&list, 'A').2
};
let auto_y = y_of("");
let min_y = y_of(r#"<w:trHeight w:val="720"/>"#);
// Minimum 720 twips vs 240-twip page-1 content adds 480 twips free room -> +240 twips (+12 pt = +50 dots at 300 dpi) for center alignment.
assert_eq!(min_y - auto_y, 50);
}
#[test]
fn realigns_inline_table_across_mirrored_pages_and_columns() {
// 2-column section: page 12240, margins 1440, space 720 -> col 1 left=1440, col 2 left=6480
// (+5040 twips). A table with 4 tall rows overflows column 1 into column 2, shifting row 4
// right by 5040 twips.
let tall = r#"<w:trHeight w:val="4000" w:hRule="atLeast"/>"#;
let body_cols = format!(
r#"{}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/><w:cols w:num="2" w:space="720"/></w:sectPr>"#,
table(
"",
&[3600],
&[
(tall, &[&p("A")]),
(tall, &[&p("B")]),
(tall, &[&p("C")]),
(tall, &[&p("D")]),
]
)
);
let list_cols = lay_out(&body_cols, NORMAL, Some(15));
let (pa, xa, _) = find(&list_cols, 'A');
let (pd, xd, _) = find(&list_cols, 'D');
assert_eq!((pa, pd), (0, 0));
assert_eq!((xd - xa) / Length::UNITS_PER_TWIP, 5040);
// Mirrored margins: left=720, right=1440 (diff +720 twips on even page 2). Both a whole-row
// break and a split-row break shift page 2's cells right by 720 twips.
let settings = Settings {
side_margins: crate::styles::SideMargins::Mirrored,
..Settings::default()
};
let paras = |ch: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:after="0" w:line="4000" w:lineRule="exact"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#
)
};
let cell = format!("{}{}{}{}", paras("W"), paras("X"), paras("Y"), paras("Z"));
let body_mirror = format!(
r#"{}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="720"/></w:sectPr>"#,
table("", &[3600], &[("", &[cell.as_str()])])
);
let doc = crate::layout::testing::parse(&format!(
r#"<w:body xmlns:w="{}">{body_mirror}</w:body>"#,
crate::ns::W
));
let body = crate::body::Body::read(
&mut crate::reader::PartReader::new(&doc),
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base(),
settings.mode_rules,
),
);
let styles = Styles::default();
let (theme, fonts) = (Theme::default(), FontTable::default());
let context = base_context(&styles, &settings);
let stories = context.for_stories();
let sections = crate::layout::testing::sections_of(&body, &crate::layout::Stories::default());
let list_mirror = Layout::new(
(&context, &stories),
§ions,
Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
)
.run_with_wraps(&body)
.list;
let (pw, xw, _) = find(&list_mirror, 'W');
let (pz, xz, _) = find(&list_mirror, 'Z');
assert_eq!((pw, pz), (0, 1));
assert_eq!((xz - xw) / Length::UNITS_PER_TWIP, 720);
}