//! Paragraphs laid out with the fake fonts of the layout test harness: kerning, lists, line
//! heights, positional tabs, frames, text boxes, hidden marks, page breaks and the bars of
//! fractions.
use f_office_paint::{DisplayList, Painted};
use f_office_units::Length;
use crate::body::{Body, Sections};
use crate::grid::DOT;
use crate::layout::testing::{
self, AnchoredShape, DEEP, Fake, FakeMath, NORMAL, ShapeText, TALL, base, base_context, du,
find, find_all, lay_out, p, parse, table,
};
use crate::layout::{Context, Layout, SectionLayout};
use crate::ns::W;
use crate::numbering::Numbering;
use crate::quirks::{BodyFieldResults, ListLevelReading};
use crate::reader::PartReader;
use crate::styles::{FontTable, Settings, SideMargins, Styles, Theme};
use crate::text::{Shaper, ShaperSettings};
#[test]
fn draws_a_text_box_that_fits_its_text_as_tall_as_the_text() {
// A box that says it is 100 pt tall, with insets of 3.6 pt, holds one 10 pt line of the
// fake font and 10 pt of space after it.
let text_box = |fit: &str| {
let body = format!(
r#"<wps:bodyPr lIns="45720" tIns="45720" rIns="45720" bIns="45720">{fit}</wps:bodyPr>"#
);
let shape = AnchoredShape {
across: ("margin", 0),
down: ("margin", 0),
size: (2_540_000, 1_270_000),
wrap: "<wp:wrapNone/>",
outline: Some(12_700),
text: Some(ShapeText {
blocks: r#"<w:p><w:pPr><w:spacing w:after="200"/></w:pPr><w:r><w:t>Box</w:t></w:r></w:p>"#,
body: &body,
}),
};
format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing())
};
let outline_height = |list: &DisplayList| {
list.pages()[0]
.items()
.iter()
.find_map(|item| match item {
f_office_paint::Item::Path(path) => {
let ys: Vec<i64> = path
.commands
.iter()
.filter_map(|c| match c {
f_office_paint::PathCommand::MoveTo(p)
| f_office_paint::PathCommand::LineTo(p) => Some(p.y.units()),
_ => None,
})
.collect();
Some(ys.iter().max()? - ys.iter().min()?)
}
_ => None,
})
.unwrap()
};
let point = Length::from_points(1).unwrap().units();
// The outline runs 0.5 pt outside the box on each side.
let fixed = outline_height(&lay_out(&text_box(""), "", None));
assert_eq!(fixed, 101 * point);
// Fitting: 3.6 pt, the 12 pt line of the fake font at 10 pt, 10 pt of space after, 3.6 pt.
let fitted = outline_height(&lay_out(&text_box("<a:spAutoFit/>"), "", None));
assert!(fitted < 40 * point, "{fitted}");
assert!(fitted > 25 * point, "{fitted}");
}
#[test]
fn draws_a_text_box_whose_body_does_not_wrap_as_wide_as_its_widest_line() {
// A box of 100 pt with insets of 7.2 pt and an outline of 1 pt holds a centered line of
// `letters` letters of 5 pt and a centered "B".
let text_box = |wrap: &str, letters: usize| {
let body = format!(
r#"<wps:bodyPr wrap="{wrap}" lIns="91440" tIns="45720" rIns="91440" bIns="45720"/>"#
);
let blocks = format!(
r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>{}</w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
"A".repeat(letters)
);
let shape = AnchoredShape {
across: ("margin", 0),
down: ("margin", 0),
size: (1_270_000, 1_270_000),
wrap: "<wp:wrapNone/>",
outline: Some(12_700),
text: Some(ShapeText {
blocks: &blocks,
body: &body,
}),
};
lay_out(
&format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing()),
"",
None,
)
};
let outline_width = |list: &DisplayList| {
list.pages()[0]
.items()
.iter()
.find_map(|item| match item {
f_office_paint::Item::Path(path) => {
let xs: Vec<i64> = path
.commands
.iter()
.filter_map(|c| match c {
f_office_paint::PathCommand::MoveTo(p)
| f_office_paint::PathCommand::LineTo(p) => Some(p.x.units()),
_ => None,
})
.collect();
Some(xs.iter().max()? - xs.iter().min()?)
}
_ => None,
})
.unwrap()
};
let point = Length::UNITS_PER_POINT;
let rows = |list: &DisplayList| {
let mut ys: Vec<i64> = find_all(list, 'A').iter().map(|&(_, _, y)| y).collect();
ys.dedup();
ys.len()
};
// A box that wraps keeps its width and breaks its 200 pt of letters into lines.
let square = text_box("square", 40);
assert_eq!(outline_width(&square), 101 * point);
assert!(rows(&square) > 1);
// A box that does not wrap keeps them on one line and grows by their width: 20 more
// letters make it 100 pt wider.
let unbroken = text_box("none", 40);
assert_eq!(rows(&unbroken), 1);
assert_eq!(
outline_width(&unbroken) - outline_width(&text_box("none", 20)),
100 * point
);
// The "B" centers on the widest line, 97.5 pt after the line's start.
let start = find(&unbroken, 'A').1;
let shift = find(&unbroken, 'B').1 - start;
assert!((shift - 195 * point / 2).abs() <= DOT, "{shift}");
}
/// The place and turn of the glyph "A" in a text box of the preset `preset`, 100 by 200 pt at
/// the margin's corner, without an outline, with the insets 3, 6, 12 and 24 pt on its left, top,
/// right and bottom sides, the attributes `xfrm` on its `a:xfrm` and the body's `vert`.
fn boxed_glyph(preset: &str, xfrm: &str, vert: &str) -> (i64, i64, Option<f_office_paint::Turn>) {
boxed_glyphs((preset, xfrm, vert), "A")
.into_iter()
.find(|glyph| glyph.0 == 'A')
.map(|(_, x, y, turn)| (x, y, turn))
.unwrap()
}
/// The first character, origin and run turn of each glyph of `text`, in a text box of the
/// preset, transform and body `vert` of [`boxed_glyph`].
fn boxed_glyphs(
(preset, xfrm, vert): (&str, &str, &str),
text: &str,
) -> Vec<(char, i64, i64, Option<f_office_paint::Turn>)> {
use crate::ns::{A, WP, WPS};
let shape = format!(
r#"<w:drawing><wp:anchor xmlns:wp="{WP}" behindDoc="0" distL="0" distR="0" distT="0" distB="0"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="2540000"/><wp:wrapNone/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:xfrm {xfrm}/><a:prstGeom prst="{preset}"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr vert="{vert}" lIns="38100" tIns="76200" rIns="152400" bIns="304800"/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
);
let list = lay_out(&format!("<w:p><w:r>{shape}</w:r></w:p>"), "", None);
list.pages()[0]
.painted()
.iter()
.flat_map(|item| match item {
Painted::Glyphs(run) => run
.glyphs
.iter()
.filter_map(|glyph| {
let ch = run.glyph_text(glyph)?.chars().next()?;
Some((ch, glyph.x.units(), glyph.y.units(), run.turn))
})
.collect(),
_ => Vec::new(),
})
.collect()
}
#[test]
fn stands_the_east_asian_glyphs_of_an_east_asian_vertical_text_box_upright() {
use crate::layout::table::DOWN;
let upright = f_office_paint::Turn {
xx: f_office_paint::Turn::SCALE,
yx: 0,
xy: 0,
yy: f_office_paint::Turn::SCALE,
};
let glyphs = |vert: &str| boxed_glyphs(("rect", "", vert), "A\u{65E5}B");
let turns = |vert: &str| glyphs(vert).iter().map(|g| (g.0, g.3)).collect::<Vec<_>>();
// In `vert` every glyph turns with the line; in `eaVert` the ideograph stands upright.
assert_eq!(
turns("vert"),
[
('A', Some(DOWN)),
('\u{65E5}', Some(DOWN)),
('B', Some(DOWN))
]
);
assert_eq!(
turns("eaVert"),
[
('A', Some(DOWN)),
('\u{65E5}', Some(upright)),
('B', Some(DOWN))
]
);
// The Latin glyphs lie where `vert` puts them; the ideograph's origin moves left of the
// baseline, by half an em less the line's axis, and down from its pen by its face's top.
let (turned, stood) = (glyphs("vert"), glyphs("eaVert"));
assert_eq!((turned[0], turned[2]), (stood[0], stood[2]));
let (pen, upright) = (turned[1], stood[1]);
assert!(upright.1 < pen.1, "{pen:?} {upright:?}");
assert!(upright.2 > pen.2, "{pen:?} {upright:?}");
}
#[test]
fn turns_the_text_of_a_text_box_whose_body_or_shape_turns_it() {
use crate::layout::table::{DOWN, UP};
let text_box = |xfrm: &str, vert: &str| boxed_glyph("rect", xfrm, vert);
let point = Length::UNITS_PER_POINT;
let near = |value: i64, want: i64| (value - want).abs() <= 2 * DOT;
let (left, _, upright) = text_box("", "horz");
let (down_x, down_y, down) = text_box("", "vert");
let (up_x, up_y, up) = text_box("", "vert270");
let (shape_x, shape_y, with_shape) = text_box(r#"rot="5400000""#, "horz");
assert_eq!(
(upright, down, up, with_shape),
(None, Some(DOWN), Some(UP), Some(DOWN))
);
// Text that runs down starts below the top inset, and text that runs up above the bottom
// inset, 200 - 6 - 24 pt further down.
assert!(near(up_y - down_y, 170 * point), "{down_y} {up_y}");
// The first line of text that runs down lies inside the right inset, and of text that
// runs up inside the left inset, an ascent from each: their sum across is the box's left
// side twice, its width, less the right inset and plus the left one.
let side = left - 3 * point;
assert!(
near(down_x + up_x - 2 * side, 91 * point),
"{down_x} {up_x} {side}"
);
// A shape turned a quarter turn about its centre shows its box 200 pt wide and 100 pt high,
// from 50 pt left of its left side and 50 pt down. Its text turns with it: it starts 3 pt
// below the box's top, the left inset turned, and its first line lies inside the top inset,
// 6 pt from the box's right side, 150 pt right of the left side.
assert!(near(shape_y - down_y, 47 * point), "{shape_y} {down_y}");
assert!(near(shape_x - down_x, 56 * point), "{shape_x} {down_x}");
}
#[test]
fn lays_out_the_text_of_a_mirrored_shape_in_its_mirrored_text_rectangle_and_turns_it_down() {
let text_box = |preset: &str, xfrm: &str| boxed_glyph(preset, xfrm, "horz");
let point = Length::UNITS_PER_POINT;
let near = |value: i64, want: i64| (value - want).abs() <= 2 * DOT;
let (plain_x, plain_y, plain) = text_box("homePlate", "");
let (across_x, across_y, across) = text_box("homePlate", r#"flipH="1""#);
let (left, _, _) = text_box("rect", "");
let (down_x, _, down) = text_box("rect", r#"flipV="1""#);
assert_eq!(
(plain, across, down),
(None, None, crate::picture::turn(2, [false, false]))
);
// The text rectangle of a home plate 100 pt wide ends half its height's point short of
// its right side, 25 pt; mirrored across, it starts 25 pt from the left side.
assert!(near(across_x - plain_x, 25 * point), "{plain_x} {across_x}");
assert_eq!(across_y, plain_y);
// Turned by a half turn about the box's centre, the glyph starts 3 pt left of the box's
// right side: its places across sum to the box's left side twice and its width.
let side = left - 3 * point;
assert!(
near(down_x + left, 2 * side + 100 * point),
"{left} {down_x} {side}"
);
}
/// A text box at the margin's corner for the tests of its text anchor: `height` pt high, with
/// insets of `inset` EMU above and below and an outline of `outline` EMU, holding a line of
/// exactly 12 pt for each letter, the last with `after` twips after it.
#[derive(Clone, Copy)]
struct AnchoredBox<'a> {
height: i64,
inset: i64,
outline: i64,
after: i64,
fit: &'a str,
letters: &'a str,
/// Blocks after the letters' paragraphs.
after_letters: &'a str,
}
impl AnchoredBox<'_> {
/// A box of 100 pt with insets of 3.6 pt, an outline of 1 pt and two lines.
const PLAIN: Self = AnchoredBox {
height: 100,
inset: 45_720,
outline: 12_700,
after: 0,
fit: "",
letters: "AB",
after_letters: "",
};
fn xml(self, anchor: &str) -> String {
use std::fmt::Write as _;
let last = self.letters.chars().count() - 1;
let mut lines = String::new();
for (i, c) in self.letters.chars().enumerate() {
let after = if i == last { self.after } else { 0 };
let _ = write!(
lines,
r#"<w:p><w:pPr><w:spacing w:after="{after}" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>{c}</w:t></w:r></w:p>"#
);
}
lines.push_str(self.after_letters);
let (inset, fit) = (self.inset, self.fit);
let body = format!(
r#"<wps:bodyPr lIns="91440" tIns="{inset}" rIns="91440" bIns="{inset}" anchor="{anchor}">{fit}</wps:bodyPr>"#
);
let shape = AnchoredShape {
across: ("margin", 0),
down: ("margin", 0),
size: (2_540_000, self.height * 12_700),
wrap: "<wp:wrapNone/>",
outline: (self.outline != 0).then_some(self.outline),
text: Some(ShapeText {
blocks: &lines,
body: &body,
}),
};
format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing())
}
/// How far down the text lies with `anchor`, in device dots, from where the same box puts
/// it at the top.
fn shift(self, anchor: &str) -> i64 {
let baseline = |anchor| find(&lay_out(&self.xml(anchor), "", None), 'A').2;
baseline(anchor) - baseline("t")
}
}
/// Whether a shift in device dots lies within a dot of a length in units.
fn near(shift: i64, units: i64) -> bool {
(shift - f_office_units::div_round(units, DOT)).abs() <= 1
}
#[test]
fn moves_the_text_of_a_text_box_down_by_the_room_that_its_anchor_names() {
let plain = AnchoredBox::PLAIN;
let point = Length::UNITS_PER_POINT;
let inset = plain.inset * Length::UNITS_PER_EMU;
// The room lies inside the insets and half the outline's width at the top and at the
// bottom: 100 − 7.2 − 1 pt, less two lines of 12 pt.
let room = 100 * point - 2 * inset - point - 24 * point;
assert!(near(plain.shift("b"), room));
assert!(near(plain.shift("ctr"), room / 2));
// Without insets the room grows by both insets, and without an outline by its width.
assert!(near(
AnchoredBox { inset: 0, ..plain }.shift("b"),
room + 2 * inset
));
assert!(near(
AnchoredBox {
outline: 0,
..plain
}
.shift("b"),
room + point
));
// The space after the last paragraph counts as text: 10 pt after leaves 10 pt less room.
let after = AnchoredBox {
after: 200,
..plain
};
assert!(near(after.shift("b"), room - 10 * point));
}
#[test]
fn keeps_the_text_of_a_text_box_at_the_top_when_the_box_has_no_room_below_it() {
// Text taller than its box stays at the top, and a box that fits its text has no room.
let tall = AnchoredBox {
height: 60,
letters: "ABCDEFGH",
..AnchoredBox::PLAIN
};
assert_eq!(tall.shift("b"), 0);
assert_eq!(tall.shift("ctr"), 0);
let fitted = AnchoredBox {
fit: "<a:spAutoFit/>",
..AnchoredBox::PLAIN
};
assert_eq!(fitted.shift("b"), 0);
}
/// The layout, on a target with the text box clip `clip`, of a box 30 pt high with insets of
/// 3.6 pt and an outline of 1 pt: its text area is 21.8 pt high, so the first 12 pt line fits,
/// the second crosses the area's bottom and the third lies below it. A last paragraph holds an
/// inline shape with an outline.
/// A paragraph holding one inline ellipse drawing.
fn inline_ellipse() -> String {
use crate::ns::{A, WP, WPS};
format!(
r#"<w:p><w:r><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="127000"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="ellipse"/><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
)
}
fn cut_box(clip: crate::quirks::TextBoxClip) -> DisplayList {
let shape = inline_ellipse();
let xml = AnchoredBox {
height: 30,
letters: "ABC",
after_letters: &shape,
..AnchoredBox::PLAIN
}
.xml("t");
let target = testing::on_base_with(|p| p.with_variant(clip));
testing::pass_with(&xml, ("", None), None, Numbering::default(), target).list
}
/// The groups among the items of the first page of `list`.
fn page_groups(list: &DisplayList) -> Vec<f_office_paint::Group> {
list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
f_office_paint::Item::Group(group) => Some(group.clone()),
_ => None,
})
.collect()
}
/// The text of the glyph runs among `items`.
fn letters_of(items: &[f_office_paint::Item]) -> String {
items
.iter()
.filter_map(|item| match item {
f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
_ => None,
})
.collect()
}
/// The paths among `items`.
fn paths_of(items: &[f_office_paint::Item]) -> Vec<f_office_paint::Item> {
items
.iter()
.filter(|item| matches!(item, f_office_paint::Item::Path(_)))
.cloned()
.collect()
}
/// The top left and the bottom right corner of the box around the points of `commands`.
fn corners_of(
commands: &[f_office_paint::PathCommand],
) -> (f_office_paint::Point, f_office_paint::Point) {
use f_office_paint::{PathCommand, Point};
let points: Vec<Point> = commands.iter().flat_map(PathCommand::points).collect();
let x = points.iter().map(|p| p.x);
let y = points.iter().map(|p| p.y);
let (left, right) = (x.clone().min().unwrap(), x.max().unwrap());
let (top, bottom) = (y.clone().min().unwrap(), y.max().unwrap());
(
Point { x: left, y: top },
Point {
x: right,
y: bottom,
},
)
}
#[test]
fn cuts_the_text_of_a_text_box_at_its_text_area_on_a_target_that_cuts_it() {
use crate::quirks::TextBoxClip;
use f_office_paint::GroupPlaces;
let overflow = cut_box(TextBoxClip::Overflow);
assert_eq!(page_groups(&overflow), []);
let cut = cut_box(TextBoxClip::InsideOutline);
let [group] = page_groups(&cut).try_into().unwrap();
// The letters of every line lie in the group, which holds the page's items: the writer
// places them as the page's.
assert_eq!(letters_of(&group.items), "ABC");
assert_eq!(letters_of(cut.pages()[0].items()), "");
assert_eq!(group.places, GroupPlaces::Page);
// The paths of the box and of the inline shape stay outside the group, uncut, as they are
// on a target that does not cut the text.
assert_eq!(paths_of(&group.items), []);
let uncut = paths_of(overflow.pages()[0].items());
assert_eq!(uncut.len(), 2);
assert_eq!(paths_of(cut.pages()[0].items()), uncut);
}
#[test]
fn cuts_the_cells_of_a_table_in_a_text_box_also_at_the_text_box_s_clip() {
use crate::quirks::{CellClip, TextBoxClip};
use f_office_paint::Item;
let table = testing::table("", &[1000], &[("", &[&p("D")])]);
let xml = AnchoredBox {
height: 30,
letters: "A",
after_letters: &table,
..AnchoredBox::PLAIN
}
.xml("t");
let target = testing::on_base_with(|p| {
p.with_variant(TextBoxClip::InsideOutline)
.with_variant(CellClip::InsideLines)
});
let list = testing::pass_with(&xml, ("", None), None, Numbering::default(), target).list;
// The cell's group lies in the text box's group, so that both clips cut the cell's text.
let [group] = page_groups(&list).try_into().unwrap();
assert_eq!(letters_of(&group.items), "A");
let cells: Vec<_> = group
.items
.iter()
.filter_map(|item| match item {
Item::Group(cell) => Some(letters_of(&cell.items)),
_ => None,
})
.collect();
assert_eq!(cells, ["D"]);
}
#[test]
fn puts_the_clip_of_a_text_box_inside_its_outline_and_its_insets() {
use crate::quirks::TextBoxClip;
use f_office_paint::Item;
// The clip lies half the outline inside the box across and the insets and half the
// outline inside it down; the outline's path runs half its width outside the box.
let cut = cut_box(TextBoxClip::InsideOutline);
let [group] = page_groups(&cut).try_into().unwrap();
let outline = cut.pages()[0]
.items()
.iter()
.find_map(|item| match item {
Item::Path(path) => Some(corners_of(&path.commands)),
_ => None,
})
.unwrap();
let twips = |twips: i64| Length::from_twips(twips).unwrap();
let clip = corners_of(&group.clip.unwrap().commands);
assert_eq!(clip.0.x - outline.0.x, twips(20));
assert_eq!(clip.0.y - outline.0.y, twips(92));
assert_eq!(outline.1.x - clip.1.x, twips(20));
assert_eq!(outline.1.y - clip.1.y, twips(92));
}
#[test]
fn keeps_uncut_items_in_paint_order_inside_a_clipped_text_box() {
use crate::quirks::TextBoxClip;
use f_office_paint::Item;
let middle = format!("{}<w:p><w:r><w:t>Z</w:t></w:r></w:p>", inline_ellipse());
let xml = AnchoredBox {
height: 60,
letters: "A",
after_letters: &middle,
..AnchoredBox::PLAIN
}
.xml("t");
let target = testing::on_base_with(|p| p.with_variant(TextBoxClip::InsideOutline));
let list = testing::pass_with(&xml, ("", None), None, Numbering::default(), target).list;
let items = list.pages()[0].items();
let a_at = items
.iter()
.position(|item| matches!(item, Item::Group(group) if letters_of(&group.items) == "A"))
.expect("first clipped group");
let z_at = items
.iter()
.position(|item| matches!(item, Item::Group(group) if letters_of(&group.items) == "Z"))
.expect("second clipped group");
let shape_at = items[a_at..z_at]
.iter()
.position(|item| matches!(item, Item::Path(_)));
assert!(
shape_at.is_some(),
"uncut item between A and Z must stay between their clipped groups"
);
}
#[test]
fn leaves_out_the_lines_and_cells_outside_the_page_on_targets_that_leave_them_out() {
// A text box at (x, y) pt from the page's corner, 72 pt wide and `height` pt high, with no
// insets but `inset` pt at the bottom, with the blocks `lines`, or one paragraph for each
// letter.
let boxed = |(x, y): (i64, i64), (height, inset): (i64, i64), lines: &str| {
let emu = |points: i64| points * 12_700;
let (x, y, height, inset) = (emu(x), emu(y), emu(height), emu(inset));
let body = format!(r#"<wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="{inset}"/>"#);
let shape = AnchoredShape {
across: ("page", x),
down: ("page", y),
size: (emu(72), height),
wrap: "<wp:wrapNone/>",
outline: None,
text: Some(ShapeText {
blocks: lines,
body: &body,
}),
};
format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing())
};
let text_box = |(x, y): (i64, i64), (height, inset): (i64, i64), letters: &str| {
let lines: String = letters.chars().map(|c| p(&c.to_string())).collect();
boxed((x, y), (height, inset), &lines)
};
// Lines of 10 or 12 pt from 25 pt above the page: `A` and `B` lie wholly above it, `C`
// crosses its top and `D` lies inside. `E` and `I` lie wholly above the page in boxes that
// reach 6 pt into it; the text area of `E` ends 2 pt above the page, and that of `I` 6 pt
// into it. From 775 pt, `F` lies inside, `G` crosses the bottom and `H` lies below it. `R`
// lies wholly right of the page; `S` lies right of it in a box that reaches 6 pt into it;
// `M` lies inside.
let mut body = text_box((200, -25), (50, 0), "ABCD");
body += &text_box((100, -30), (36, 8), "E");
body += &text_box((400, -30), (36, 0), "I");
body += &text_box((300, 775), (50, 0), "FGH");
body += &text_box((620, 100), (36, 0), "R");
body += &text_box((606, 160), (36, 0), "S");
body += &text_box((250, 400), (36, 0), "M");
// The same from 775 pt in the rows of a table, one letter in each, which a target that
// cuts table cells puts into the groups of the cells' clips:
// `J` lies inside, `K` crosses the bottom and
// `L` lies below it.
let (j, k, l) = (p("J"), p("K"), p("L"));
let rows = [
("", &[j.as_str()][..]),
("", &[k.as_str()]),
("", &[l.as_str()]),
];
body += &boxed((450, 775), (50, 0), &table("", &[1440], &rows));
// A table indented 3 inches left of the margin of 1 inch: the cell of `X` lies wholly left
// of the page, the cell of `Y` reaches into it, and the cell of `Z` lies inside.
body += &table(
r#"<w:tblInd w:w="-4320" w:type="dxa"/><w:tblLayout w:type="fixed"/>"#,
&[2000, 2000, 2000],
&[("", &[&p("X"), &p("Y"), &p("Z")])],
);
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let mut seen = Vec::new();
for target in crate::Target::all() {
let quirk = crate::profile::Profile::of(target)
.unwrap()
.quirks()
.off_page_objects;
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let drawn: String = "ABCDEFGHIRSMXYZJKL"
.chars()
.filter(|&c| !find_all(&list, c).is_empty())
.collect();
let expected = match quirk {
crate::quirks::OffPageObjects::Drawn => "ABCDEFGHIRSMXYZJKL",
crate::quirks::OffPageObjects::LeftOut => "ABCDFGISMYZJK",
};
assert_eq!(drawn, expected, "{target}");
seen.push(quirk);
}
assert!(seen.contains(&crate::quirks::OffPageObjects::Drawn));
assert!(seen.contains(&crate::quirks::OffPageObjects::LeftOut));
}
#[test]
fn keeps_the_records_of_a_text_box_in_a_row_whose_cells_get_fills() {
// A text box anchored in the second cell of a row whose first cell is shaded. The row
// inserts the fill of the first cell under its content after the cells' lines are placed,
// and the text box's lines join the page as a whole, so no move of the page's items
// applies to their records.
let text_box = AnchoredBox::PLAIN.xml("t");
let shaded = format!(
r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="FFFF00"/></w:tcPr>{}"#,
p("Shaded")
);
let body = table(
"",
&[3000, 3000],
&[("", &[shaded.as_str(), text_box.as_str()])],
);
let pass = testing::pass_with_header(&body, NORMAL, None, None);
let boxed: Vec<_> = pass
.lines
.iter()
.filter(|line| line.story == crate::layout::LineStory::TextBox)
.collect();
assert_eq!(boxed.len(), 2);
assert!(
boxed
.iter()
.all(|line| line.item == crate::layout::FirstItem::Carried)
);
}
#[test]
fn records_the_lines_of_frames_as_lines_of_the_story_that_holds_them() {
use crate::layout::LineStory;
use crate::lines::Step;
let framed = r#"<w:p><w:pPr><w:framePr w:w="2000" w:hAnchor="page" w:x="8000" w:yAlign="bottom"/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>"#;
let pass = testing::pass_with_header(&format!("{framed}{}", p("c")), "", None, Some(framed));
let steps = |story: LineStory| -> Vec<Vec<Step>> {
pass.lines
.iter()
.filter(|line| line.story == story)
.map(|line| line.steps.clone())
.collect()
};
let frame = vec![Step::Start, Step::Glyph];
assert_eq!(steps(LineStory::Header), vec![frame.clone()]);
assert_eq!(steps(LineStory::Body), vec![frame, vec![Step::Start]]);
assert!(
pass.lines
.iter()
.filter(|line| line.steps.len() == 2)
.all(|line| line.item == crate::layout::FirstItem::Carried)
);
}
#[test]
fn records_what_lies_before_each_drawn_glyph() {
use crate::lines::Step;
let body = r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">ab c</w:t><w:tab/><w:t>d</w:t></w:r></w:p>"#;
let pass = testing::pass_with_header(body, "", None, None);
let line = &pass.lines[0];
assert_eq!(line.alignment, crate::props::Alignment::Center);
assert_eq!(
line.steps,
vec![Step::Start, Step::Glyph, Step::Space, Step::Tab]
);
}
#[test]
fn names_aligned_tabs_and_a_tab_that_starts_the_line() {
use crate::lines::Step;
// A center stop at 1 inch and a right stop at 4 inches; the third tab goes to a default
// stop past them. The second line starts with a tab to a default stop.
let body = concat!(
r#"<w:p><w:pPr><w:tabs><w:tab w:val="center" w:pos="1440"/><w:tab w:val="right" w:pos="5760"/></w:tabs></w:pPr>"#,
r#"<w:r><w:tab/><w:t>a</w:t><w:tab/><w:t>b</w:t><w:tab/><w:t>c</w:t></w:r></w:p>"#,
r#"<w:p><w:r><w:tab/><w:t>d</w:t></w:r></w:p>"#,
);
let pass = testing::pass_with_header(body, "", None, None);
assert_eq!(
pass.lines[0].steps,
vec![Step::AlignedTab, Step::AlignedTab, Step::Tab]
);
assert_eq!(pass.lines[1].steps, vec![Step::Tab]);
}
#[test]
fn kerns_a_pair_across_two_runs_of_the_same_font_and_size() {
// A run of "V" and a run of "A". At 10 pt, -100 of 1000 units is -1 pt.
let x_of_a = |second: &str| {
let body = format!(
r#"<w:p><w:r><w:rPr><w:kern w:val="2"/></w:rPr><w:t>V</w:t></w:r><w:r><w:rPr>{second}</w:rPr><w:t>A</w:t></w:r></w:p>"#
);
find(&lay_out(&body, "", None), 'A').1
};
let plain = x_of_a("");
let kerned = x_of_a(r#"<w:kern w:val="2"/>"#);
assert_eq!(plain - kerned, Length::from_points(1).unwrap().units());
// Another size or a tab in between keeps the pair apart.
assert_eq!(x_of_a(r#"<w:kern w:val="2"/><w:sz w:val="24"/>"#), plain);
let body = r#"<w:p><w:r><w:rPr><w:kern w:val="2"/></w:rPr><w:t>V</w:t><w:tab/><w:t>A</w:t></w:r></w:p>"#;
let with_tab = lay_out(body, "", None);
let body = r"<w:p><w:r><w:t>V</w:t><w:tab/><w:t>A</w:t></w:r></w:p>";
assert_eq!(find(&with_tab, 'A'), find(&lay_out(body, "", None), 'A'));
}
/// Lays out the paragraphs of `body` with a numbering whose list 2 has a decimal level with a
/// left indent of 720 and a hanging indent of 360 twips, and the run properties `label_run`.
fn lay_out_numbered(body: &str, label_run: &str, settings: &Settings) -> DisplayList {
lay_out_numbered_with(body, "", label_run, settings)
}
/// Lays out paragraphs as `lay_out_numbered` does, with more elements `level` in the level.
fn lay_out_numbered_with(
body: &str,
level: &str,
label_run: &str,
settings: &Settings,
) -> DisplayList {
lay_out_numbered_styled(
body,
level,
label_run,
settings,
("", ListLevelReading::AsWritten),
)
}
/// Lays out paragraphs as `lay_out_numbered_with` does, with the styles `styles`, whose list
/// levels and those of the body read as `reading` says.
fn lay_out_numbered_styled(
body: &str,
level: &str,
label_run: &str,
settings: &Settings,
(styles, reading): (&str, ListLevelReading),
) -> DisplayList {
let numbering = parse(&format!(
r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/>{level}<w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:rPr>{label_run}</w:rPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
));
let body_doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
let body = Body::read(
&mut PartReader::new(&body_doc)
.with_list_levels(crate::reader::settings::ListLevels::with_reading(reading)),
body_doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
settings.mode_rules,
),
);
let styles_doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault/><w:pPrDefault/></w:docDefaults>{styles}</w:styles>"#
));
let styles = Styles::read(
&mut PartReader::new(&styles_doc)
.with_list_levels(crate::reader::settings::ListLevels::with_reading(reading)),
styles_doc.root().unwrap(),
);
let (theme, fonts) = (Theme::default(), FontTable::default());
let context = Context {
numbering: Numbering::read(
&mut PartReader::new(&numbering),
numbering.root().unwrap(),
crate::reader::settings::ReaderSettings::with_built_in_list(
crate::quirks::BuiltInList::WithoutPart,
),
),
..base_context(&styles, settings)
};
let stories = context.for_stories();
let section = &body.sections.last().section;
let sections = Sections::one(SectionLayout::plain(section, body.blocks.len()));
Layout::new(
(&context, &stories),
§ions,
Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
)
.run_with_wraps(&body)
.list
}
/// A numbered paragraph of the text "X".
const NUMBERED_X: &str = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>X</w:t></w:r></w:p>"#;
#[test]
fn starts_page_numbers_with_the_number_of_the_last_chapter_heading() {
// "heading 1" is numbered with list 2, so the second heading is chapter 2.
let heading = r#"<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:style>"#;
let titled = |text: &str| {
format!(
r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let field = r#"<w:p><w:fldSimple w:instr="PAGE"><w:r><w:t>9</w:t></w:r></w:fldSimple></w:p>"#;
// The text of the PAGE field, the last run of the page.
let page = |numbers: &str, styles: &str| {
let body = format!(
"{}{}{field}<w:sectPr><w:pgNumType {numbers}/></w:sectPr>",
titled("A"),
titled("B")
);
let list = lay_out_numbered_styled(
&body,
"",
"",
&Settings::default(),
(styles, ListLevelReading::AsWritten),
);
list.pages()[0]
.items()
.iter()
.rev()
.find_map(|item| match item {
f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
_ => None,
})
.unwrap_or_default()
};
assert_eq!(page(r#"w:chapStyle="1" w:chapSep="colon""#, heading), "2:1");
assert_eq!(page(r#"w:chapStyle="1""#, heading), "2-1");
// Without a numbered heading of that style, and without w:chapStyle, the page number
// stands alone.
assert_eq!(page(r#"w:chapStyle="1""#, ""), "1");
assert_eq!(page(r#"w:start="1""#, heading), "1");
}
#[test]
fn numbers_body_lines_in_the_left_margin() {
let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
let suppressed = r"<w:p><w:pPr><w:suppressLineNumbers/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>";
let cell = format!(
"<w:tbl><w:tblGrid><w:gridCol w:w=\"2000\"/></w:tblGrid><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>",
p("C")
);
// Lines 1 to 4 are "A", the empty paragraph, "D" and "E", and every second one shows.
let body = format!(
"{}<w:p/>{suppressed}{cell}{}{}<w:sectPr><w:lnNumType w:countBy=\"2\" w:distance=\"200\"/></w:sectPr>",
p("A"),
p("D"),
p("E")
);
let list = lay_out(&body, NORMAL, None);
let twips = |n: i64| n * Length::UNITS_PER_TWIP;
// A digit is 100 twips wide, so it starts 300 twips left of the 1440 twip margin.
let two = find_all(&list, '2');
assert_eq!(two.len(), 1);
assert_eq!(two[0].1, twips(1140));
let four = find(&list, '4');
assert_eq!((four.1, four.2), (twips(1140), find(&list, 'E').2));
assert!(find_all(&list, '1').is_empty() && find_all(&list, '3').is_empty());
// By default the count starts again on each page.
let body = format!(
"{}<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>B</w:t></w:r></w:p><w:sectPr><w:lnNumType w:countBy=\"1\"/></w:sectPr>",
p("A")
);
let pages: Vec<usize> = find_all(&lay_out(&body, NORMAL, None), '1')
.iter()
.map(|found| found.0)
.collect();
assert_eq!(pages, [0, 1]);
}
#[test]
fn numbers_a_line_after_the_largest_start_with_the_largest_number() {
let body = r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:sectPr><w:lnNumType w:countBy="1" w:start="9223372036854775807"/></w:sectPr>"#;
let list = lay_out(body, NORMAL, None);
let texts: Vec<String> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
_ => None,
})
.collect();
assert!(texts.contains(&i64::MAX.to_string()), "{texts:?}");
}
#[test]
fn the_empty_paragraph_that_ends_a_section_has_no_line_number_and_no_count() {
let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
let end = |runs: &str| {
format!(
r#"<w:p><w:pPr><w:sectPr><w:lnNumType w:countBy="1" w:restart="continuous"/></w:sectPr></w:pPr>{runs}</w:p>"#
)
};
let last = r#"<w:sectPr><w:lnNumType w:countBy="1" w:restart="continuous"/></w:sectPr>"#;
let count = |body: &str, digit: char| find_all(&lay_out(body, NORMAL, None), digit).len();
// "A" is line 1, the empty paragraph at the section's end is no line, and "B" in the
// next section is line 2.
let body = format!("{}{}{}{last}", p("A"), end(""), p("B"));
assert_eq!((count(&body, '2'), count(&body, '3')), (1, 0));
// With text, the paragraph that ends the section is line 2, and "B" is line 3.
let body = format!(
"{}{}{}{last}",
p("A"),
end("<w:r><w:t>C</w:t></w:r>"),
p("B")
);
assert_eq!((count(&body, '2'), count(&body, '3')), (1, 1));
// So it is with one space.
let space = r#"<w:r><w:t xml:space="preserve"> </w:t></w:r>"#;
let body = format!("{}{}{}{last}", p("A"), end(space), p("B"));
assert_eq!((count(&body, '2'), count(&body, '3')), (1, 1));
}
/// The step from "L" to "N", in dots, on the base with the variant `ends` of the quirk
/// `ContinuousSectionEnd`, with `before` and the paragraph "L" before the empty paragraph that
/// ends a section of one column before a continuous section, or with no paragraph between "L"
/// and "N" when `end` is none. `end` gives the empty paragraph's space after, its properties
/// and its content, and `numbering` the lists of a numbering part.
fn section_end_step(
(ends, mode): (crate::quirks::ContinuousSectionEnd, Option<u32>),
(before, line_after): (&str, u32),
end: Option<(u32, &str, &str)>,
(next_before, numbering): (u32, &str),
) -> i64 {
let spaced = |before: u32, after: u32, text: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:before="{before}" w:after="{after}"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let end = end.map_or(String::new(), |(after, props, content)| {
format!(
r#"<w:p><w:pPr>{props}<w:spacing w:before="360" w:after="{after}"/><w:sectPr/></w:pPr>{content}</w:p>"#
)
});
let body = format!(
r#"{}{before}{end}{}<w:sectPr><w:type w:val="continuous"/></w:sectPr>"#,
spaced(0, line_after, "L"),
spaced(next_before, 0, "N")
);
let doc = parse(&format!(
r#"<w:numbering xmlns:w="{W}">{numbering}</w:numbering>"#
));
let numbering = Numbering::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::ReaderSettings::with_built_in_list(
crate::quirks::BuiltInList::WithoutPart,
),
);
let target = testing::on_base_with(|p| p.with_variant(ends));
let list = testing::pass_with(&body, (NORMAL, mode), None, numbering, target).list;
find(&list, 'N').2 - find(&list, 'L').2
}
/// Lays out a section of two columns that ends at a continuous section break, on a page
/// 20,000 pt high: "A", "B" and "C", each one exact line of `points` points, then "D", one exact
/// line of 1 pt, so that the limit of balanced columns grows by 1 pt. Gives whether each
/// paragraph is in the first column, and the counts of the warnings of the trial limit.
fn balanced_columns(points: i64) -> ([bool; 4], u32) {
let line = |text: char, twips: i64, section: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{twips}" w:lineRule="exact"/>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let page = r#"<w:pgSz w:w="12240" w:h="400000"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
let columns = format!(r#"<w:sectPr>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#);
let body = format!(
r#"{}{}{}{}<w:sectPr><w:type w:val="continuous"/>{page}</w:sectPr>"#,
line('A', points * 20, ""),
line('B', points * 20, ""),
line('C', points * 20, ""),
line('D', 20, &columns),
);
let pass = testing::pass_with(
&body,
(NORMAL, None),
None,
Numbering::default(),
testing::on_base(),
);
let first = find(&pass.list, 'A').1;
let in_first = ['A', 'B', 'C', 'D'].map(|ch| find(&pass.list, ch).1 == first);
let trials = pass
.warnings
.iter()
.filter(|(warning, _)| {
matches!(
warning,
crate::Warning::LimitReached {
limit: crate::warnings::Limit::BalanceTrials,
..
}
)
})
.map(|(_, count)| count)
.sum();
(in_first, trials)
}
#[test]
fn balances_columns_within_the_trial_limit_and_keeps_them_as_they_fill_past_it() {
// Lines of 2,000 pt fit when the limit has grown from the mean of 3,000 pt to 4,000 pt,
// after about 1,000 trials: "A" and "B" in the first column, "C" and "D" in the second.
assert_eq!(balanced_columns(2_000), ([true, true, false, false], 0));
// Lines of 5,000 pt would need about 2,500 trials, more than the limit: the columns stay
// as they fill, all four paragraphs in the first column, with the warning.
let (in_first, trials) = balanced_columns(5_000);
assert_eq!(in_first, [true; 4]);
assert!(trials > 0);
}
#[test]
fn balances_the_last_page_of_columns_that_start_on_an_earlier_page_where_the_target_does() {
use crate::quirks::LastPageBalance::{LastPage, OnePage};
// Columns of three exact lines of 100 pt on each page: "A" to "F" fill the first page,
// "G" and "H" go on to the second, and a continuous section with "N" follows. Gives the
// page and the x of "G" and "H" and the baseline of "N".
let layout = |balance| {
let line = |text: char, section: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="2000" w:lineRule="exact"/>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let page = r#"<w:pgSz w:w="12240" w:h="8880"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
let columns = format!(r#"<w:sectPr>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#);
let lines: String = "ABCDEFG".chars().map(|ch| line(ch, "")).collect();
let body = format!(
r#"{lines}{}{}<w:sectPr><w:type w:val="continuous"/>{page}</w:sectPr>"#,
line('H', &columns),
line('N', ""),
);
let target = testing::on_base_with(|p| p.with_variant(balance));
let list =
testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
let (g, h, n) = (find(&list, 'G'), find(&list, 'H'), find(&list, 'N'));
((g.0, g.1), (h.0, h.1), n.2)
};
let (g, h, n) = layout(LastPage);
let (plain_g, plain_h, plain_n) = layout(OnePage);
// Both stay on the second page; balanced, "H" goes to the second column, and "N" starts
// one line higher, below "G".
assert_eq!((g.0, h.0, plain_g.0, plain_h.0), (1, 1, 1, 1));
assert_eq!(plain_g.1, plain_h.1);
assert!(h.1 > g.1);
assert_eq!(g, plain_g);
assert!(n < plain_n);
}
/// Columns that fill the page, of exact lines of 100 pt: three fill the first column, or two
/// below "T" of a section of one column when `title` holds, and "D", with 20 pt before, starts
/// the second. Gives the page, x and baseline of "A" and "D".
fn column_top(
space: crate::quirks::ColumnTopSpace,
title: bool,
) -> ((usize, i64, i64), (usize, i64, i64)) {
let line = |text: char, before: u32, section: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:before="{before}" w:after="0" w:line="2000" w:lineRule="exact"/>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let page = r#"<w:pgSz w:w="12240" w:h="8880"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
let (start, lines) = if title {
(line('T', 0, &format!("<w:sectPr>{page}</w:sectPr>")), "AB")
} else {
(String::new(), "ABC")
};
let lines: String = lines.chars().map(|ch| line(ch, 0, "")).collect();
let body = format!(
r#"{start}{lines}{}<w:sectPr><w:type w:val="continuous"/>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#,
line('D', 400, ""),
);
let target = testing::on_base_with(|p| p.with_variant(space));
let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
(find(&list, 'A'), find(&list, 'D'))
}
#[test]
fn leaves_out_the_space_before_at_the_top_of_a_column_at_the_page_top_where_the_target_does() {
use crate::quirks::ColumnTopSpace::{GoesAtPageTop, Stays};
let (a, d) = column_top(GoesAtPageTop, false);
let (kept_a, kept_d) = column_top(Stays, false);
let (below_a, below_d) = column_top(GoesAtPageTop, true);
// At the page top, "D" starts the second column level with "A" where the space goes, and
// below it where it stays.
assert_eq!((a.0, d.0, d.2, kept_a), (0, 0, a.2, a));
assert!(d.1 > a.1 && kept_d.2 > a.2);
// Below "T", the second column's top is not the page's, and "D" keeps the space.
assert!(below_d.1 > below_a.1 && below_d.2 > below_a.2);
assert_eq!(column_top(Stays, true), (below_a, below_d));
}
/// The page and the baseline in dots of "A", which has 12 pt before it, after a table whose
/// rows all went, in a document of the mode `mode` on a target with the variant `top`. The
/// table stands at a section's top after "T" (`start` "section"), after a page break ("break"),
/// at the document's top ("body") or below the line "T" ("middle").
fn deleted_table_top(top: crate::quirks::DeletedTableTop, mode: u32, start: &str) -> (usize, i64) {
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
let first = match start {
"section" => {
format!("<w:p><w:pPr><w:sectPr>{page}</w:sectPr></w:pPr><w:r><w:t>T</w:t></w:r></w:p>")
}
"break" => r#"<w:p><w:r><w:t>T</w:t><w:br w:type="page"/></w:r></w:p>"#.to_owned(),
"middle" => "<w:p><w:r><w:t>T</w:t></w:r></w:p>".to_owned(),
_ => String::new(),
};
let body = format!(
r#"{first}<w:tbl><w:tblPr/><w:tblGrid/></w:tbl><w:p><w:pPr><w:spacing w:before="240" w:after="0"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p><w:sectPr>{page}</w:sectPr>"#
);
let target = testing::on_base_with(|p| p.with_variant(top));
let list = testing::pass_with(
&body,
(NORMAL, Some(mode)),
None,
Numbering::default(),
target,
)
.list;
let (page, _, y) = find(&list, 'A');
(page, y)
}
#[test]
fn a_table_whose_rows_all_went_at_the_page_top_leaves_the_space_before_by_the_mode() {
use crate::quirks::DeletedTableTop::{AsTable, ByMode};
let kept = deleted_table_top(AsTable, 15, "section");
let gone = deleted_table_top(ByMode, 14, "section");
// Before mode 15, "A" has no space before at a section's top; from mode 15 it keeps it.
assert_eq!((gone.0, kept.0), (1, 1));
assert!(gone.1 < kept.1);
assert_eq!(deleted_table_top(ByMode, 15, "section"), kept);
// At the document's top likewise, and after a page break the space goes in both modes.
let body = (
deleted_table_top(ByMode, 14, "body").1,
deleted_table_top(ByMode, 15, "body").1,
);
assert_eq!(body, (gone.1, kept.1));
assert_eq!(deleted_table_top(ByMode, 15, "break"), gone);
assert_eq!(deleted_table_top(AsTable, 15, "break"), kept);
// Below a line, the table keeps its place in every mode.
assert_eq!(
deleted_table_top(ByMode, 14, "middle"),
deleted_table_top(AsTable, 14, "middle")
);
}
/// The page of the line "B" of exactly 15 pt with a bottom border of 5 pt of space and 1.5 pt of
/// width below a line "S" of exactly `spacer` twips at the top of a page 648 pt high, on a target
/// with the variant `room`.
fn foot_border_page(room: crate::quirks::FootBorderRoom, spacer: u32) -> usize {
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
let body = format!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{spacer}" w:lineRule="exact"/></w:pPr><w:r><w:t>S</w:t></w:r></w:p><w:p><w:pPr><w:widowControl w:val="0"/><w:pBdr><w:bottom w:val="single" w:sz="12" w:space="5" w:color="000000"/></w:pBdr><w:spacing w:before="0" w:after="0" w:line="300" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p><w:sectPr>{page}</w:sectPr>"#
);
let target = testing::on_base_with(|p| p.with_variant(room));
let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
find(&list, 'B').0
}
#[test]
fn a_last_line_at_the_foot_needs_room_for_its_bottom_border_where_the_target_does() {
use crate::quirks::FootBorderRoom::{Fits, Hangs};
// 632 pt above "B" leave 1 pt below its box: the border's 6.5 pt do not fit.
assert_eq!(foot_border_page(Hangs, 12_640), 0);
assert_eq!(foot_border_page(Fits, 12_640), 1);
// 626 pt leave 7 pt, and the border fits on the page in both.
assert_eq!(foot_border_page(Fits, 12_520), 0);
assert_eq!(foot_border_page(Hangs, 12_520), 0);
}
#[test]
fn the_empty_paragraph_that_ends_a_section_takes_part_in_the_spacing_without_a_line() {
use crate::quirks::ContinuousSectionEnd::{KeepsSpacesWithoutLine, OnlyBlockKeepsLine};
let step = |ends, line_after, end: Option<(u32, &str)>, next_before| {
let end = end.map(|(after, content)| (after, "", content));
section_end_step((ends, None), ("", line_after), end, (next_before, ""))
};
let dots = |twips: i64| twips * 50 / 240;
// The space after of "L" stays, and "N" has its whole space before beyond the empty
// paragraph's space after of 0; the empty paragraph's space before does nothing.
let joins = KeepsSpacesWithoutLine;
assert_eq!(
step(joins, 240, Some((0, "")), 240) - step(joins, 240, None, 240),
dots(240)
);
// With 18 pt after the empty paragraph, the 12 pt before "N" lie within it.
assert_eq!(
step(joins, 120, Some((360, "")), 240) - step(joins, 120, None, 240),
-dots(120)
);
// A paragraph of a bookmark takes no line either.
let bookmark = r#"<w:bookmarkStart w:id="0" w:name="m"/><w:bookmarkEnd w:id="0"/>"#;
assert_eq!(
step(joins, 0, Some((0, bookmark)), 0),
step(joins, 0, None, 0)
);
// With the other variant, the empty paragraph has no part in the spacing, and a paragraph
// of a bookmark keeps its line.
let base = OnlyBlockKeepsLine;
assert_eq!(
step(base, 240, Some((0, "")), 240),
step(base, 240, None, 240)
);
assert!(step(base, 0, Some((0, bookmark)), 0) > step(base, 0, None, 0));
}
#[test]
fn a_continuous_section_end_shows_nothing_with_a_label_or_a_border() {
// quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
let joins = (KeepsSpacesWithoutLine, Some(15));
let numbering = r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>"#;
let label = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>"#;
let border =
r#"<w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="000000"/></w:pBdr>"#;
let none = r#"<w:pBdr><w:bottom w:val="none" w:sz="0" w:space="0" w:color="auto"/></w:pBdr>"#;
let with = |before: &str, props: &str| {
section_end_step(joins, (before, 0), Some((0, props, "")), (0, numbering))
};
let without = |before: &str| section_end_step(joins, (before, 0), None, (0, numbering));
// After a paragraph, the empty paragraph has no line, with a list label or a border too.
assert_eq!(with("", ""), without(""));
assert_eq!(with("", none), without(""));
assert_eq!(with("", label), without(""));
assert_eq!(with("", border), without(""));
// It is in no group of borders: a paragraph before it with the same border draws its
// bottom line below itself, as without the empty paragraph.
let bordered = format!("<w:p><w:pPr>{border}</w:pPr><w:r><w:t>B</w:t></w:r></w:p>");
assert_eq!(with(&bordered, border), without(&bordered));
assert!(without(&bordered) > without(""));
}
#[test]
fn a_continuous_section_end_after_a_table_keeps_its_line_in_mode_15_only() {
// quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
let cell = table(
"",
&[2000],
&[("", &["<w:p><w:r><w:t>T</w:t></w:r></w:p>"])],
);
let step =
|mode, end| section_end_step((KeepsSpacesWithoutLine, mode), (&cell, 0), end, (0, ""));
let end = Some((0, "", ""));
assert!(step(Some(15), end) > step(Some(15), None));
assert_eq!(step(Some(14), end), step(Some(14), None));
assert_eq!(step(None, end), step(None, None));
}
#[test]
fn after_a_continuous_section_end_the_rest_of_the_space_before_starts_the_next_page() {
// quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
use crate::quirks::ContinuousSectionEnd::{KeepsSpacesWithoutLine, OnlyBlockKeepsLine};
// 64 lines fill the first page, so "N" starts page 2 with the 48 twips of its space before
// beyond the empty paragraph's 240 after: 10 dots below the top margin.
let body = format!(
r#"{}<w:p><w:pPr><w:spacing w:after="240"/><w:sectPr/></w:pPr></w:p><w:p><w:pPr><w:spacing w:before="288"/></w:pPr><w:r><w:t>N</w:t></w:r></w:p><w:sectPr><w:type w:val="continuous"/></w:sectPr>"#,
testing::filler(64)
);
let place = |ends| {
let target = testing::on_base_with(|p| p.with_variant(ends));
let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
find(&list.list, 'N')
};
assert_eq!(
place(KeepsSpacesWithoutLine),
(1, 1440 * 1270, base(1440) + 10)
);
// With the other variant, the empty paragraph takes no room and "N" has no space there.
assert_eq!(place(OnlyBlockKeepsLine), (1, 1440 * 1270, base(1440)));
}
#[test]
fn after_a_continuous_section_end_a_kept_paragraph_keeps_the_rest_of_its_space_on_the_next_page() {
// quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
// "N" fits below 60 lines, but "M", which it is kept with, does not when it has 200 pt
// before; then the chain starts page 2, and "N" keeps there the 48 twips of its space
// before beyond the empty paragraph's 240 after: 10 dots below the top margin.
let body = |keep: &str, m_before: u32| {
format!(
r#"{}<w:p><w:pPr><w:spacing w:after="240"/><w:sectPr/></w:pPr></w:p><w:p><w:pPr>{keep}<w:spacing w:before="288"/></w:pPr><w:r><w:t>N</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:before="{m_before}"/></w:pPr><w:r><w:t>M</w:t></w:r></w:p><w:sectPr><w:type w:val="continuous"/></w:sectPr>"#,
testing::filler(60)
)
};
let place = |body: &str| {
let target = testing::on_base_with(|p| p.with_variant(KeepsSpacesWithoutLine));
let list = testing::pass_with(body, (NORMAL, None), None, Numbering::default(), target);
find(&list.list, 'N')
};
assert_eq!(place(&body("", 4000)).0, 0);
assert_eq!(
place(&body("<w:keepNext/>", 4000)),
(1, 1440 * 1270, base(1440) + 10)
);
// The room test of the chain gives "N" the same rest of 48 twips above it as its layout,
// not the whole 288: then "M" with 300 twips before fits below "N", and the chain stays
// where it stands without the keep.
assert_eq!(place(&body("<w:keepNext/>", 300)), place(&body("", 300)));
}
#[test]
fn continuous_section_end_drops_trailing_break_line_and_after_before_mode_15() {
// quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
let dots = |twips: i64| twips * 50 / 240;
let gap = |mode: Option<u32>, tail: &str, next: &str| {
let body = format!(
r#"<w:p><w:pPr><w:spacing w:after="240" w:line="240" w:lineRule="exact"/><w:sectPr/></w:pPr><w:r><w:t>A</w:t></w:r>{tail}</w:p>{next}<w:sectPr><w:type w:val="continuous"/></w:sectPr>"#
);
let target = testing::on_base_with(|p| p.with_variant(KeepsSpacesWithoutLine));
let list = testing::pass_with(&body, (NORMAL, mode), None, Numbering::default(), target);
find(&list.list, 'B').2 - find(&list.list, 'A').2
};
let next_p = |before: u32| {
format!(
r#"<w:p><w:pPr><w:spacing w:before="{before}" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#
)
};
let next_tbl = table(
"",
&[2000],
&[(
"",
&[
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 br = "<w:r><w:br/></w:r>";
let br2 = format!("{br}{br}");
let br_sp = format!(r#"{br}<w:r><w:t xml:space="preserve"> </w:t></w:r>"#);
let one_line = dots(240);
let p0 = next_p(0);
let p120 = next_p(120);
let p288 = next_p(288);
let cases = [
(Some(14), "", p0.as_str(), one_line + dots(240)),
// In mode 14, trailing `<w:br/>` drops the empty line and `after` before a paragraph or table.
(Some(14), br, p0.as_str(), one_line),
(Some(14), br, next_tbl.as_str(), one_line),
// The next paragraph keeps only the excess of its `before` beyond the dropped `after`.
(Some(14), br, p120.as_str(), one_line),
(Some(14), br, p288.as_str(), one_line + dots(48)),
// Double `<w:br/>` drops only the final empty line (idempotent).
(Some(14), br2.as_str(), p0.as_str(), one_line * 2),
// A trailing space after `<w:br/>` keeps the final line and `after`.
(
Some(14),
br_sp.as_str(),
p0.as_str(),
one_line * 2 + dots(240),
),
// In mode 15, both the trailing empty line and `after` stay.
(Some(15), br, p0.as_str(), one_line * 2 + dots(240)),
(Some(15), br, next_tbl.as_str(), one_line * 2 + dots(240)),
];
for (mode, tail, next, expected) in cases {
assert_eq!(gap(mode, tail, next), expected);
}
}
/// The counts of the warnings of picture bullets of a body of two paragraphs of a bullet list
/// whose level asks for the picture bullet `picture`, of which the numbering part has the
/// picture bullet 0.
fn picture_bullet_warnings(picture: &str) -> u32 {
let numbering = format!(
r#"<w:numbering xmlns:w="{W}"><w:numPicBullet w:numPicBulletId="0"><w:pict/></w:numPicBullet><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="{picture}"/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
);
let doc = parse(&numbering);
let numbering = Numbering::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::ReaderSettings::with_built_in_list(
crate::quirks::BuiltInList::WithoutPart,
),
);
let item = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
let body = format!("{item}{item}<w:sectPr/>");
let pass = testing::pass_with(&body, (NORMAL, None), None, numbering, testing::on_base());
pass.warnings
.iter()
.filter(|(warning, _)| {
matches!(
warning,
crate::Warning::FeatureNotSupported {
feature: crate::Feature::PictureBullet,
..
}
)
})
.map(|(_, count)| count)
.sum()
}
#[test]
fn warns_of_a_picture_bullet_once_for_each_paragraph_that_shows_it() {
assert_eq!(picture_bullet_warnings("0"), 2);
// A level whose picture bullet the part does not have shows its text.
assert_eq!(picture_bullet_warnings("5"), 0);
}
#[test]
fn draws_a_picture_bullet_scaled_from_label_font_size_without_warning() {
use f_office_paint::Item;
// Minimal 1x1 valid GIF header (64x32 aspect in logical screen descriptor).
let gif_2x1: Vec<u8> = b"GIF89a\x40\x00\x20\x00\x00\x00\x00;".to_vec();
let numbering = format!(
r#"<w:numbering xmlns:w="{W}" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:numPicBullet w:numPicBulletId="0"><w:pict><v:shape style="width:24pt;height:12pt"><v:imagedata r:id="rId1"/></v:shape></w:pict></w:numPicBullet><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="0"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
);
let doc = parse(&numbering);
let mut numbering = Numbering::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::ReaderSettings::with_built_in_list(
crate::quirks::BuiltInList::WithoutPart,
),
);
numbering.attach_images(&mut |_| Some(f_office_paint::Image::new(gif_2x1.clone())));
let body = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr><w:rPr><w:sz w:val="24"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="24"/></w:rPr><w:t>A</w:t></w:r></w:p><w:sectPr/>"#;
let pass = testing::pass_with(body, (NORMAL, None), None, numbering, testing::on_base());
let bullet_warns: u32 = pass
.warnings
.iter()
.filter(|(w, _)| {
matches!(
w,
crate::Warning::FeatureNotSupported {
feature: crate::Feature::PictureBullet,
..
}
)
})
.map(|(_, c)| c)
.sum();
assert_eq!(bullet_warns, 0);
let image = pass.list.pages()[0]
.items()
.iter()
.find_map(|item| match item {
Item::Image(img) => Some(img),
_ => None,
})
.expect("expected picture bullet image item");
// At 12 pt (sz=24), target height is 12/2 - 1 = 5 pt -> ~5.04 pt; 2:1 aspect -> ~9.96 pt.
assert!(
(image.height.units() - Length::from_points(5).unwrap().units()).abs()
<= Length::UNITS_PER_DOT
);
assert!(
(image.width.units() - Length::from_points(10).unwrap().units()).abs()
<= Length::UNITS_PER_DOT
);
}
#[test]
fn a_numbered_paragraph_that_ends_a_section_counts_once_in_its_list() {
let numbered = |text: &str, section: &str| {
format!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let final_section = r#"<w:sectPr><w:type w:val="continuous"/></w:sectPr>"#;
let numbering = format!(
r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
);
// "A" is 1, "C", which ends a section of one or of two columns before a continuous
// section, is 2, and "B" is 3.
for columns in ["", r#"<w:cols w:num="2"/>"#] {
let body = format!(
"{}{}{}{final_section}",
numbered("A", ""),
numbered("C", &format!("<w:sectPr>{columns}</w:sectPr>")),
numbered("B", "")
);
let list = testing::lay_out_with_numbering(&body, &numbering);
assert_eq!(
(find_all(&list, '3').len(), find_all(&list, '4').len()),
(1, 0)
);
}
}
#[test]
fn a_section_starts_on_the_page_of_a_break_that_holds_only_line_numbers() {
let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
// "A" is line 1 and the line of the page break line 2. The empty paragraph that ends the
// numbered section comes after the break, and its number would be the only thing on the
// new page. The next section starts on that page, and the number 3 is not drawn.
let body = format!(
"{}<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p><w:p><w:pPr><w:sectPr><w:lnNumType w:countBy=\"1\"/></w:sectPr></w:pPr></w:p>{}<w:sectPr/>",
p("A"),
p("B")
);
let list = lay_out(&body, NORMAL, None);
assert_eq!(list.pages().len(), 2);
assert_eq!(find(&list, 'B').0, 1);
let pages = |digit: char| -> Vec<usize> {
find_all(&list, digit).iter().map(|found| found.0).collect()
};
assert_eq!(
(pages('1'), pages('2'), pages('3')),
(vec![0], vec![0], vec![])
);
}
#[test]
fn a_section_starts_on_the_page_of_a_break_that_holds_only_an_empty_shaded_paragraph() {
// The empty paragraph that ends the section after the page break is shaded white or gray.
// Its fill keeps the next section off the new page no more than its line number would:
// the next section starts on that page, and the fill is not drawn.
for fill in ["FFFFFF", "D9D9D9"] {
let body = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:br w:type="page"/></w:r></w:p><w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="{fill}"/><w:sectPr/></w:pPr></w:p><w:p><w:r><w:t>B</w:t></w:r></w:p><w:sectPr/>"#
);
let list = lay_out(&body, NORMAL, None);
assert_eq!(list.pages().len(), 2, "{fill}");
assert_eq!(find(&list, 'B').0, 1, "{fill}");
}
}
#[test]
fn the_fill_of_a_paragraph_in_a_cell_lies_above_a_drawing_behind_the_text_that_it_anchors() {
// The page's items in the order of painting, with the items of each group in its place.
fn painted(items: &[f_office_paint::Item], out: &mut Vec<char>) {
for item in items {
match item {
f_office_paint::Item::Group(group) => painted(&group.items, out),
f_office_paint::Item::Path(_) => out.push('d'),
f_office_paint::Item::Rect(rect)
if rect.color
== (f_office_paint::Rgb {
r: 0xD9,
g: 0xD9,
b: 0xD9,
}) =>
{
out.push('f');
}
_ => {}
}
}
}
// In a table cell, a gray paragraph anchors an outlined drawing behind the text, and a
// plain paragraph after it anchors another. The fill comes after the first drawing and
// before the second, which no fill of its own paragraph covers.
let behind = AnchoredShape {
across: ("column", 0),
down: ("paragraph", 0),
size: (635_000, 254_000),
wrap: "<wp:wrapNone/>",
outline: Some(12_700),
text: None,
}
.drawing()
.replace(r#"behindDoc="0""#, r#"behindDoc="1""#);
let cell = format!(
r#"<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:pPr><w:r>{behind}</w:r><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r>{behind}</w:r><w:r><w:t>B</w:t></w:r></w:p>"#
);
let body = format!(
"{}<w:p/><w:sectPr/>",
table("", &[3000], &[("", &[cell.as_str()])])
);
let list = lay_out(&body, NORMAL, None);
let mut order = Vec::new();
painted(list.pages()[0].items(), &mut order);
assert_eq!(order.into_iter().collect::<String>(), "dfd");
}
#[test]
fn a_level_that_reads_as_none_by_its_octet_shows_no_number_at_the_margin() {
// The list defines level 0 only, with a left indent of 720 twips. Read as written, 9 falls
// to level 0; read by its octet, 9 has no number and no indent, and 265 reads as 9 does.
let x = |value: &str, reading| {
let body = format!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="{value}"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>X</w:t></w:r></w:p>"#
);
let list = lay_out_numbered_styled(&body, "", "", &Settings::default(), ("", reading));
(find_all(&list, '1').len(), find(&list, 'X').1)
};
let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
assert_eq!(x("9", ListLevelReading::AsWritten), (1, twips(720)));
for value in ["9", "265", "-245"] {
assert_eq!(
x(value, ListLevelReading::ByOctet),
(0, twips(0)),
"{value}"
);
}
// 256 and 15 read as level 0 by their octets, as 0 does.
for value in ["0", "256", "15"] {
assert_eq!(
x(value, ListLevelReading::ByOctet),
(1, twips(720)),
"{value}"
);
}
}
#[test]
fn removing_a_style_list_drops_the_style_indents() {
// "Bullet" puts its paragraphs in list 2 with a hanging indent of its own, "Plain" has the
// same indent and no list, and "Cleared*" styles cancel numbering inside the style chain.
let styles = concat!(
r#"<w:style w:type="paragraph" w:styleId="Bullet"><w:pPr><w:numPr><w:numId w:val="2"/></w:numPr><w:ind w:left="357" w:right="500" w:hanging="357"/></w:pPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="Plain"><w:pPr><w:ind w:left="357" w:right="500" w:hanging="357"/></w:pPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="ClearedBullet"><w:basedOn w:val="Bullet"/><w:pPr><w:numPr><w:numId w:val="0"/></w:numPr></w:pPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="ClearedPlain"><w:basedOn w:val="Plain"/><w:pPr><w:numPr><w:numId w:val="0"/></w:numPr></w:pPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="ClearedWithOwn"><w:basedOn w:val="Bullet"/><w:pPr><w:numPr><w:numId w:val="0"/></w:numPr><w:ind w:left="720"/></w:pPr></w:style>"#,
);
let x = |style: &str, direct_num: &str, ind: &str| {
let body = format!(
r#"<w:p><w:pPr><w:pStyle w:val="{style}"/>{direct_num}{ind}</w:pPr><w:r><w:t>X</w:t></w:r></w:p>"#
);
let list = lay_out_numbered_styled(
&body,
"",
"",
&Settings::default(),
(styles, ListLevelReading::AsWritten),
);
find(&list, 'X').1
};
let zero = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="0"/></w:numPr>"#;
let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
// Direct and style-level `w:numId="0"` reset inherited left and first-line indents whether or
// not any ancestor names a list, keeping only `w:ind` set at that layer.
for (style, direct_num, ind, want) in [
("Bullet", zero, r#"<w:ind w:left="357"/>"#, 357),
("Bullet", zero, "", 0),
("Plain", zero, r#"<w:ind w:left="357"/>"#, 357),
("Plain", zero, "", 0),
("ClearedBullet", "", "", 0),
("ClearedPlain", "", "", 0),
("ClearedWithOwn", "", "", 720),
] {
assert_eq!(x(style, direct_num, ind), twips(want), "{style}");
}
// Inherited right indent is preserved when `w:numId="0"` clears left and first-line indents.
assert_eq!(
x("ClearedPlain", "", r#"<w:jc w:val="right"/>"#),
x("Plain", "", r#"<w:jc w:val="right"/>"#),
);
}
#[test]
fn ends_or_centers_a_label_at_the_start_of_the_first_line() {
// The label "1." is 200 twips wide and the first line starts at 360 twips, so the label
// starts at 360, at 260 when centered there and at 160 when it ends there. The text
// after the tab starts at the left indent of 720 twips in each case.
let at = |level: &str| {
let list = lay_out_numbered_with(NUMBERED_X, level, "", &Settings::default());
(find(&list, '1').1, find(&list, 'X').1)
};
let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
assert_eq!(at(""), (twips(360), twips(720)));
assert_eq!(at(r#"<w:lvlJc w:val="center"/>"#), (twips(260), twips(720)));
assert_eq!(at(r#"<w:lvlJc w:val="right"/>"#), (twips(160), twips(720)));
}
#[test]
fn starts_the_text_of_a_legacy_level_at_its_indent_from_the_label() {
// The label "1." starts at 360 twips and is 200 twips wide. The text starts the legacy
// indent after the label's start, or the legacy space after its end, without a tab.
let text_at = |legacy: &str| {
let list = lay_out_numbered_with(NUMBERED_X, legacy, "", &Settings::default());
find(&list, 'X').1
};
let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
let indent = r#"<w:legacy w:legacy="1" w:legacySpace="0" w:legacyIndent="400"/>"#;
assert_eq!(text_at(indent), twips(760));
let space = r#"<w:legacy w:legacy="1" w:legacySpace="50" w:legacyIndent="100"/>"#;
assert_eq!(text_at(space), twips(610));
}
#[test]
fn leaves_out_automatic_space_only_above_the_first_paragraph_even_when_it_is_empty() {
let auto = r#"<w:pPr><w:spacing w:beforeAutospacing="1" w:afterAutospacing="1"/></w:pPr>"#;
// Each paragraph's automatic space after follows its line, so the baseline sits the fake
// font's ascent of 8 pt, 33.33 device dots rounded to 33, below the line's top.
let spaced = |top: i64| top * Length::UNITS_PER_TWIP / DOT + 33;
let first = format!("<w:p>{auto}<w:r><w:t>A</w:t></w:r></w:p>");
assert_eq!(find(&lay_out(&first, "", None), 'A').2, spaced(1440));
// The empty first paragraph is 200 twips tall, and 14 pt (280 twips) of automatic space
// come before the second one.
let after_empty = format!("<w:p>{auto}</w:p><w:p>{auto}<w:r><w:t>X</w:t></w:r></w:p>");
assert_eq!(
find(&lay_out(&after_empty, "", None), 'X').2,
spaced(1440 + 200 + 280)
);
}
#[test]
fn a_last_line_whose_space_after_the_next_paragraph_removes_takes_the_single_rules() {
// Two paragraphs of one style with 10 pt after. Where the space after follows the first
// line, its baseline sits the rounded ascent of 33 device dots below its top at 1440
// twips. Where contextual spacing removes the space, the line takes the single rules: the
// descent, rounded to 8 dots, above the exact bottom 41.67 dots below the top.
let spaced = |top: i64| du(top) + 33;
let pair = |mark: &str| {
let props = format!(r#"<w:pPr><w:spacing w:after="200"/>{mark}</w:pPr>"#);
format!(
"<w:p>{props}<w:r><w:t>A</w:t></w:r></w:p><w:p>{props}<w:r><w:t>B</w:t></w:r></w:p>"
)
};
let kept = lay_out(&pair(""), "", None);
assert_eq!(find(&kept, 'A').2, spaced(1440));
assert_eq!(find(&kept, 'B').2, spaced(1440 + 200 + 200));
let removed = lay_out(&pair("<w:contextualSpacing/>"), "", None);
assert_eq!(find(&removed, 'A').2, base(1440));
assert_eq!(base(1440), spaced(1440) + 1);
// The last paragraph, which no paragraph follows, keeps its space after.
assert_eq!(find(&removed, 'B').2, spaced(1440 + 200));
}
#[test]
fn an_empty_line_takes_its_height_from_the_line_break_that_ends_it() {
// "A" is 10 pt, and a 20 pt run has two breaks before "B". The first line keeps its
// 10 pt, the empty line is 20 pt tall, and "B" rises 16 pt above its baseline.
let body = r#"<w:p><w:r><w:t>A</w:t></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:br/><w:br/><w:t>B</w:t></w:r></w:p>"#;
let list = lay_out(body, "", None);
let gap = find(&list, 'B').2 - find(&list, 'A').2;
let points = |n: i64| f_office_units::div_round(n * Length::UNITS_PER_POINT, DOT);
assert!((gap - points(2 + 20 + 16)).abs() <= 1, "{gap}");
}
#[test]
fn a_comment_reference_mark_sizes_its_line_and_draws_nothing() {
// "A" is 10 pt, and a 20 pt run holds only the reference mark of a comment. The line is
// 20 pt tall, so "B" starts 400 twips down, and the mark draws no glyph.
let body = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:annotationRef/></w:r></w:p>{}"#,
p("B")
);
let list = lay_out(&body, "", None);
assert_eq!(find(&list, 'B').2, base(1440 + 400));
assert_eq!(find_all(&list, 'A').len(), 1);
}
#[test]
fn a_list_label_sizes_the_ascent_of_its_line_but_not_its_descent() {
// The label is 20 pt and the text 10 pt, so the line rises 16 pt above its baseline and
// goes 2 pt below it, and the next 10 pt line has its baseline 8 pt lower again.
let body = format!("{NUMBERED_X}{}", p("Y"));
let list = lay_out_numbered(&body, r#"<w:sz w:val="40"/>"#, &Settings::default());
// Baselines are in device dots, and 10 pt are 41.67 of them.
let ten_points = |gap: i64| (gap * DOT - 10 * Length::UNITS_PER_POINT).abs() <= DOT;
let (x, y) = (find(&list, 'X').2, find(&list, 'Y').2);
assert!(ten_points(y - x), "{}", y - x);
assert_eq!(x, find(&list, '1').2);
// A line that holds only the label takes its descent from the paragraph mark.
let empty =
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:p>"#;
let list = lay_out_numbered(
&format!("{empty}{}", p("Y")),
r#"<w:sz w:val="40"/>"#,
&Settings::default(),
);
let gap = find(&list, 'Y').2 - find(&list, '1').2;
assert!(ten_points(gap), "{gap}");
}
#[test]
fn an_empty_list_item_takes_its_ascent_from_the_taller_of_its_label_and_mark() {
// A 20 pt paragraph mark with a 10 pt list label on an empty list item rises by the 20 pt
// mark's ascent (16 pt) rather than the smaller 10 pt label's ascent (8 pt), so its baseline
// lies 16 pt below the line above's bottom (18 pt below an earlier 10 pt baseline).
let empty = concat!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>"#,
r#"<w:rPr><w:sz w:val="40"/></w:rPr></w:pPr></w:p>"#,
);
let body = format!("{}{empty}{}", p("A"), p("B"));
let list = lay_out_numbered(&body, r#"<w:sz w:val="20"/>"#, &Settings::default());
let (a, label, b) = (find(&list, 'A').2, find(&list, '1').2, find(&list, 'B').2);
// A is 10 pt (2 pt descent), empty item has 20 pt mark (16 pt ascent + 4 pt descent), B has
// 8 pt ascent: A -> label is 18 pt, label -> B is 12 pt.
let near = |gap: i64, pts: i64| (gap * DOT - pts * Length::UNITS_PER_POINT).abs() <= DOT;
assert!(near(label - a, 18), "A->label gap: {}", label - a);
assert!(near(b - label, 12), "label->B gap: {}", b - label);
}
#[test]
fn a_list_label_descent_sizes_its_line_where_the_target_counts_it() {
use crate::quirks::ListLabelDescent;
// The label is 20 pt and the text 10 pt: where the label's descent counts, the line goes
// its 4 pt below the baseline, not the text's 2 pt, and the next line comes 2 pt lower,
// also below a line that holds only the label.
let numbering = format!(
r#"<w:numbering xmlns:w="{W}">{}</w:numbering>"#,
testing::LARGE_LABELS
);
let empty =
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:p>"#;
let gap = |body: &str, from: char, variant| {
let list = testing::lay_out_with_numbering_as(body, &numbering, variant);
find(&list, 'Y').2 - find(&list, from).2
};
let two_points = |more: i64| (more * DOT - 2 * Length::UNITS_PER_POINT).abs() <= DOT;
for (body, from) in [
(format!("{NUMBERED_X}{}", p("Y")), 'X'),
(format!("{empty}{}", p("Y")), '1'),
] {
let left = gap(&body, from, ListLabelDescent::LeftOutOfLine);
let counted = gap(&body, from, ListLabelDescent::Counted);
assert!(two_points(counted - left), "{from}: {left} {counted}");
}
}
#[test]
fn a_list_label_alone_rises_with_the_spacing_where_the_target_scales_it() {
use crate::quirks::LabelAloneRise;
// The label is 20 pt, 16 pt of it above the baseline, and the mark 10 pt, 8 pt: where the
// spacing scales the label's rise on a line that holds only the label, 1.5 lines put half
// of its 8 pt more between the plain lines around it, and single spacing puts nothing.
let numbering = format!(
r#"<w:numbering xmlns:w="{W}">{}</w:numbering>"#,
testing::LARGE_LABELS
);
let step = |line: u32, variant| {
let empty = format!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr></w:p>"#
);
let body = format!("{}{empty}{}", p("X"), p("Y"));
let list = testing::lay_out_with_numbering_as(&body, &numbering, variant);
find(&list, 'Y').2 - find(&list, 'X').2
};
for (line, more) in [(360, 4), (240, 0)] {
let unscaled = step(line, LabelAloneRise::Unscaled);
let scaled = step(line, LabelAloneRise::Scaled);
let wanted = more * Length::UNITS_PER_POINT;
assert!(
((scaled - unscaled) * DOT - wanted).abs() <= DOT,
"{line}: {unscaled} {scaled}"
);
}
}
/// The x in units of the text after the label of a numbered paragraph with a left indent of
/// 720 and a hanging indent of 360 twips, with default tab stops every 708 twips.
fn text_after_label(indent_is_numbering_tab_stop: bool) -> i64 {
let settings = Settings {
default_tab_stop: Length::from_twips(708).unwrap(),
indent_is_numbering_tab_stop,
..Settings::default()
};
let list = lay_out_numbered(NUMBERED_X, "", &settings);
find(&list, 'X').1 - find(&list, '1').1
}
#[test]
fn a_list_label_tab_skips_the_indent_when_the_document_turns_that_off() {
// The label starts at 360 twips and ends before 708, so the tab goes to the indent at 720,
// or without it to the default stop at 708: 360 and 348 twips after the label's start.
assert_eq!(text_after_label(true), 360 * Length::UNITS_PER_TWIP);
assert_eq!(text_after_label(false), 348 * Length::UNITS_PER_TWIP);
}
/// The x in twips of the first glyph of "a", "b" and "c" on three pages, with a left margin of
/// 1440 twips, a gutter of 432 and a right margin of 2304, and the first page numbered
/// `first`.
fn page_lefts(side_margins: SideMargins, first: u32) -> Vec<i64> {
let settings = Settings {
side_margins,
..Settings::default()
};
let next = |text: &str| {
format!("<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
};
let body = format!(
r#"{}{}{}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="2304" w:bottom="1440" w:left="1440" w:gutter="432"/><w:pgNumType w:start="{first}"/></w:sectPr>"#,
p("a"),
next("b"),
next("c")
);
let list = lay_out_numbered(&body, "", &settings);
['a', 'b', 'c']
.iter()
.enumerate()
.map(|(page, ch)| {
let (on, x, _) = find(&list, *ch);
assert_eq!(on, page);
x / Length::UNITS_PER_TWIP
})
.collect()
}
#[test]
fn mirrors_the_side_margins_of_pages_with_even_numbers() {
// Odd pages start at the left margin and the gutter, 1872 twips; even pages at the right
// margin, 2304 twips.
assert_eq!(page_lefts(SideMargins::Mirrored, 1), [1872, 2304, 1872]);
assert_eq!(page_lefts(SideMargins::Mirrored, 2), [2304, 1872, 2304]);
assert_eq!(page_lefts(SideMargins::Section, 2), [1872, 1872, 1872]);
// Portrait book-fold omits the gutter without swapping side margins.
assert_eq!(page_lefts(SideMargins::BookFold, 1), [1440, 1440, 1440]);
}
#[test]
fn swaps_landscape_side_margins_and_places_gutter_on_inside_under_book_fold() {
let lefts = |side_margins: SideMargins| {
let settings = Settings {
side_margins,
..Settings::default()
};
let next = |text: &str| {
format!("<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
};
let body = format!(
r#"{}{}{}<w:sectPr><w:pgSz w:w="8419" w:h="11906" w:orient="landscape"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="720" w:gutter="360"/></w:sectPr>"#,
p("a"),
next("b"),
next("c")
);
let list = lay_out_numbered(&body, "", &settings);
['a', 'b', 'c']
.iter()
.enumerate()
.map(|(page, ch)| {
let (on, x, _) = find(&list, *ch);
assert_eq!(on, page);
x / Length::UNITS_PER_TWIP
})
.collect::<Vec<_>>()
};
// BookFold: inside (right + gutter = 1800) on left of odd pages, outside (720) on even.
assert_eq!(lefts(SideMargins::BookFold), [1800, 720, 1800]);
// BookFoldReverse: outside (720) on left of odd pages, inside (1800) on even.
assert_eq!(lefts(SideMargins::BookFoldReverse), [720, 1800, 720]);
// Plain landscape section: left + gutter (1080) on every page.
assert_eq!(lefts(SideMargins::Section), [1080, 1080, 1080]);
}
#[test]
fn flips_inside_and_outside_horizontal_frame_alignment_on_even_pages() {
let frame = |align: &str, ch: &str| {
format!(
r#"<w:p><w:pPr><w:framePr w:w="1440" w:wrap="around" w:vAnchor="text" w:hAnchor="margin" w:xAlign="{align}" w:y="1"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#
)
};
let page_two = "<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>2</w:t></w:r></w:p>";
let body = format!(
"{}{}{}{}{}{}",
p("1"),
frame("outside", "A"),
frame("inside", "B"),
page_two,
frame("outside", "C"),
frame("inside", "D"),
);
// Letter page (12240 twips) with 1440-twip margins: left edge = 1440, right frame start = 9360.
let list = lay_out(&body, NORMAL, None);
let at = |ch: char| {
let (page, x, _) = find(&list, ch);
(page, x / Length::UNITS_PER_TWIP)
};
assert_eq!(at('A'), (0, 9360));
assert_eq!(at('B'), (0, 1440));
assert_eq!(at('C'), (1, 1440));
assert_eq!(at('D'), (1, 9360));
}
#[test]
fn sizes_an_empty_paragraph_by_the_character_style_of_its_mark() {
let styles = r#"<w:style w:type="character" w:styleId="Big"><w:rPr><w:sz w:val="40"/></w:rPr></w:style>"#;
let body = format!(
r#"<w:p><w:pPr><w:rPr><w:rStyle w:val="Big"/></w:rPr></w:pPr></w:p>{}"#,
p("B")
);
// The empty line is 20 pt (400 twips) tall, so "B" starts 400 twips down.
assert_eq!(find(&lay_out(&body, styles, None), 'B').2, base(1440 + 400));
}
#[test]
fn lines_text_up_at_positional_tabs_on_the_margins() {
let ptab = |alignment: &str| {
format!(r#"<w:ptab w:relativeTo="margin" w:alignment="{alignment}" w:leader="none"/>"#)
};
let body = format!(
"<w:p><w:r><w:t>a</w:t>{}<w:t>c</w:t>{}<w:t>b</w:t></w:r></w:p>",
ptab("center"),
ptab("right")
);
let list = lay_out(&body, NORMAL, None);
// The text column runs from 1440 to 10800 twips, and glyphs are 100 twips wide: "c" is
// centered at 6120, and "b" ends at the right margin.
assert_eq!(find(&list, 'c').1, 6070 * Length::UNITS_PER_TWIP);
assert_eq!(find(&list, 'b').1, 10_700 * Length::UNITS_PER_TWIP);
}
#[test]
fn stacks_paragraphs_in_frames_that_lie_in_place() {
let framed = |text: &str| {
format!(
r#"<w:p><w:pPr><w:framePr w:wrap="auto" w:vAnchor="margin" w:hAnchor="text" w:xAlign="left" w:yAlign="inline"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let list = lay_out(&format!("{}{}", framed("a"), framed("b")), NORMAL, None);
// Lines of 200 twips from the top margin at 1440 twips, one below the other.
assert_eq!(find(&list, 'a').2, base(1440));
assert_eq!(find(&list, 'b').2, base(1640));
}
#[test]
fn stacks_neighbor_paragraphs_with_equal_frames_in_one_frame() {
let framed = |text: &str| {
format!(
r#"<w:p><w:pPr><w:framePr w:w="2000" w:hAnchor="page" w:x="8000" w:yAlign="bottom"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
)
};
let list = lay_out(&format!("{}{}", framed("a"), framed("b")), NORMAL, None);
// One frame of two 200 twip lines, which ends at the bottom margin at 14400 twips, 8000
// twips from the page's left edge on the device grid.
let (page, x, y) = find(&list, 'a');
assert_eq!((page, y), (0, base(14_000)));
assert!((x - 8000 * Length::UNITS_PER_TWIP).abs() < DOT, "{x}");
assert_eq!(find(&list, 'b').2, base(14_200));
}
#[test]
fn flows_text_beside_a_frame_that_it_wraps_around() {
// A frame 2000 twips wide at the left margin and 1440 twips from the top of the page,
// as its `w:y` says without `w:vAnchor`, with text wrapping around it.
let frame = r#"<w:p><w:pPr><w:framePr w:w="2000" w:wrap="around" w:hAnchor="page" w:x="1440" w:y="1440"/></w:pPr><w:r><w:t>f</w:t></w:r></w:p>"#;
let list = lay_out(&format!("{frame}{}", p("q")), NORMAL, None);
assert_eq!(find(&list, 'f').2, base(1440));
// The line beside the frame starts at its right edge.
let (_, x, y) = find(&list, 'q');
assert_eq!(y, base(1440));
assert!((x - 3440 * Length::UNITS_PER_TWIP).abs() < DOT, "{x}");
}
/// A paragraph of 80 words that anchors at its top a box 2 inches wide and half an inch high,
/// from 234 pt across the page, at the middle of the column, with the given wrap and no
/// distances.
fn beside_a_middle_box(wrap: &str) -> DisplayList {
let words = vec!["zz"; 80].join(" ");
let shape = AnchoredShape {
across: ("page", 2_971_800),
down: ("paragraph", 0),
size: (1_828_800, 457_200),
wrap,
outline: None,
text: None,
};
let body = format!(
"<w:p><w:r>{}<w:t>{words}</w:t></w:r></w:p>",
shape.drawing()
);
lay_out(&body, NORMAL, None)
}
/// The x of each glyph of the first line, left and right of the box of [`beside_a_middle_box`]:
/// how many lie left of it, how many right of it, and how many on it.
fn sides_of_the_first_line(list: &DisplayList) -> (usize, usize, usize) {
let glyphs = find_all(list, 'z');
let first = glyphs.iter().map(|g| g.2).min().unwrap();
let point = Length::from_points(1).unwrap().units();
let (left, right) = (234 * point, 378 * point);
let line: Vec<i64> = glyphs
.iter()
.filter(|g| g.2 == first)
.map(|g| g.1)
.collect();
(
line.iter().filter(|&&x| x < left).count(),
line.iter().filter(|&&x| x >= right).count(),
line.iter().filter(|&&x| (left..right).contains(&x)).count(),
)
}
#[test]
fn flows_a_line_on_the_sides_that_a_square_wrap_names() {
let square = |sides: &str| {
sides_of_the_first_line(&beside_a_middle_box(&format!(
r#"<wp:wrapSquare wrapText="{sides}"/>"#
)))
};
// Both sides: the line fills the piece left of the box, then goes on right of it.
let (left, right, on) = square("bothSides");
assert!(left > 0 && right > 0 && on == 0, "{left} {right} {on}");
// The wider piece, of two equal ones the left one, and the named sides.
assert!(matches!(square("largest"), (1.., 0, 0)));
assert!(matches!(square("left"), (1.., 0, 0)));
assert!(matches!(square("right"), (0, 1.., 0)));
}
#[test]
fn keeps_a_line_to_the_widest_piece_beside_a_polygon_that_is_not_its_bounds() {
let tight = |points: &str| {
sides_of_the_first_line(&beside_a_middle_box(&format!(
r#"<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0">{points}</wp:wrapPolygon></wp:wrapTight>"#
)))
};
// A rectangle on the box's edges lets the line flow on both sides.
let rectangle = r#"<wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/>"#;
let (left, right, on) = tight(rectangle);
assert!(left > 0 && right > 0 && on == 0, "{left} {right} {on}");
// Beside a triangle with the same bounds, the line takes the right one of the two equal
// pieces.
let triangle = r#"<wp:start x="10800" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="10800" y="0"/>"#;
assert!(matches!(tight(triangle), (0, 1.., 0)));
}
#[test]
fn flows_a_line_on_both_sides_of_a_centered_frame_or_floating_table() {
// An object 2000 twips wide at the middle of the page, from about 5120 to 7120 twips, and
// a paragraph that flows around it: its first line holds words on both sides and none on
// it.
let words = p(&vec!["qq"; 60].join(" "));
let frame = r#"<w:p><w:pPr><w:framePr w:w="2000" w:wrap="around" w:hAnchor="page" w:x="5120" w:y="1440"/></w:pPr><w:r><w:t>f</w:t></w:r></w:p>"#;
let floating = table(
r#"<w:tblpPr w:horzAnchor="page" w:tblpX="5120" w:vertAnchor="page" w:tblpY="1440"/><w:tblW w:w="2000" w:type="dxa"/>"#,
&[2000],
&[("", &[&p("f")])],
);
for object in [frame.to_owned(), floating] {
let list = lay_out(&format!("{object}{words}"), NORMAL, None);
let glyphs = find_all(&list, 'q');
let first = glyphs.iter().map(|g| g.2).min().unwrap();
let line: Vec<i64> = glyphs
.iter()
.filter(|g| g.2 == first)
.map(|g| g.1)
.collect();
let twips = |t: i64| t * Length::UNITS_PER_TWIP;
// The table's cell margins move its edges by a tenth of an inch at most.
assert!(line.iter().any(|&x| x < twips(5000)), "{object}");
assert!(line.iter().any(|&x| x > twips(7000)), "{object}");
assert!(
!line
.iter()
.any(|&x| (twips(5200)..twips(6900)).contains(&x)),
"{object}"
);
}
}
#[test]
fn an_empty_paragraph_with_a_hidden_mark_takes_no_room() {
let styles =
r#"<w:style w:type="character" w:styleId="Hidden"><w:rPr><w:vanish/></w:rPr></w:style>"#;
let empty = |mark: &str| format!("<w:p><w:pPr><w:rPr>{mark}</w:rPr></w:pPr></w:p>");
// Hidden by the mark's character style and by the mark itself; the third mark turns its
// style's hiding off again, so that paragraph keeps its line.
let body = [
p("A"),
empty(r#"<w:rStyle w:val="Hidden"/>"#),
empty("<w:vanish/>"),
empty(r#"<w:rStyle w:val="Hidden"/><w:vanish w:val="0"/>"#),
p("B"),
]
.concat();
let shown = [p("A"), empty(""), p("B")].concat();
let b = |body: &str| find(&lay_out(body, styles, None), 'B');
assert_eq!(b(&body), b(&shown));
// In a table cell, the last paragraph ends the cell and keeps its line.
let cell = |last: &str| table("", &[2000], &[("", &[&format!("{}{last}", p("A"))])]);
let after = |last: &str| {
find(
&lay_out(&format!("{}{}", cell(last), p("B")), styles, None),
'B',
)
};
assert_eq!(after(&empty("<w:vanish/>")), after(&empty("")));
}
#[test]
fn an_empty_paragraph_after_a_hidden_mark_joins_the_paragraph_before_it() {
// "A" has a hidden mark and 400 twips of space after it; the paragraph after it holds only
// a space and has 100 twips after it. Joined, they take one line, which the second one's
// space after follows, as after a paragraph "A" with 100 twips after it.
let hidden = r#"<w:p><w:pPr><w:spacing w:after="400"/><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
let blank = r#"<w:p><w:pPr><w:spacing w:after="100"/></w:pPr><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>"#;
let shown = r#"<w:p><w:pPr><w:spacing w:after="100"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
let b = |body: &str| find(&lay_out(body, NORMAL, None), 'B');
assert_eq!(
b(&[hidden, blank, &p("B")].concat()),
b(&[shown, &p("B")].concat())
);
// Without the hidden mark, the paragraph of a space keeps its own line.
let visible = hidden.replace("<w:vanish/>", "");
assert!(b(&[&visible, blank, &p("B")].concat()).2 > b(&[shown, &p("B")].concat()).2);
}
#[test]
fn a_header_whose_last_paragraph_hides_its_mark_ends_without_its_space_after_on_a_target_that_asks()
{
use crate::quirks::HiddenHeaderFooterEnd;
// A header of four lines of 200 twips from the 720 twip header distance ends at 1520
// twips, below the 1440 twip top margin, and its 400 twips of space after take the body
// down to 1920. A target that drops the space after of a last paragraph with a hidden
// mark starts the body at 1520; a mark that shows keeps it on every target.
let header = |mark: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:after="400"/><w:rPr>{mark}</w:rPr></w:pPr><w:r><w:t>h</w:t><w:br/><w:t>i</w:t><w:br/><w:t>j</w:t><w:br/><w:t>k</w:t></w:r></w:p>"#
)
};
for (end, hidden) in [
(HiddenHeaderFooterEnd::KeepsSpaceAfter, 1920),
(HiddenHeaderFooterEnd::DropsSpaceAfter, 1520),
] {
let target = testing::on_base_with(|p| p.with_variant(end));
let body_top = |mark: &str| {
let header = header(mark);
let pass = testing::pass_with(
&p("b"),
(NORMAL, None),
Some(&header),
Numbering::default(),
target,
);
find(&pass.list, 'b').2
};
assert_eq!(body_top("<w:vanish/>"), base(hidden), "{end:?}");
assert_eq!(body_top(""), base(1920), "{end:?}");
}
}
#[test]
fn a_page_break_at_the_end_of_the_document_starts_no_page() {
let last = r#"<w:p><w:r><w:t>a</w:t><w:br w:type="page"/></w:r></w:p>"#;
assert_eq!(lay_out(last, NORMAL, None).pages().len(), 1);
// An empty paragraph after the break goes onto the next page, which then stays.
let then_empty = format!("{last}<w:p/>");
assert_eq!(lay_out(&then_empty, NORMAL, None).pages().len(), 2);
}
#[test]
fn draws_a_check_box_field_as_a_square_as_wide_as_its_line() {
let check_box = |check_box: &str| {
format!(
r#"<w:p><w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:checkBox>{check_box}</w:checkBox></w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>Y</w:t></w:r></w:p>"#
)
};
let bars = |list: &DisplayList| {
let mut sizes: Vec<(i64, i64)> = testing::rects(list, 0)
.into_iter()
.map(|(_, _, width, height)| (width, height))
.collect();
sizes.sort_unstable();
sizes
};
let point = Length::from_points(1).unwrap().units();
let plain = lay_out(&p("Y"), "", None);
let auto = lay_out(&check_box("<w:sizeAuto/>"), "", None);
// The fake font's single line at 10 pt is 10 pt, which is the box's advance.
assert_eq!(find(&auto, 'Y').1 - find(&plain, 'Y').1, 10 * point);
// The line rounds to 42 device dots, so the side between the middles of the strokes of
// 3 units is 33 units: bars of 36 by 3 units across and 3 by 30 units down.
assert_eq!(bars(&auto), [(3, 30), (3, 30), (36, 3), (36, 3)]);
// A box of its own size takes the line of that size: 20 pt, 83 device dots.
let sized = lay_out(&check_box(r#"<w:size w:val="40"/>"#), "", None);
assert_eq!(find(&sized, 'Y').1 - find(&plain, 'Y').1, 20 * point);
assert_eq!(bars(&sized), [(3, 71), (3, 71), (77, 3), (77, 3)]);
}
/// The widths and heights of the rectangles of a list's first page, in units, in order.
fn rect_sizes(list: &DisplayList) -> Vec<(i64, i64)> {
let mut sizes: Vec<(i64, i64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
f_office_paint::Item::Rect(r) => Some((r.width.units(), r.height.units())),
f_office_paint::Item::Glyphs(_)
| f_office_paint::Item::Path(_)
| f_office_paint::Item::Gradient(_)
| f_office_paint::Item::Image(_)
| f_office_paint::Item::Group(_) => None,
})
.collect();
sizes.sort_unstable();
sizes
}
/// The widths and heights of the four bars of a check box square on a target's `device` with
/// its `quirks`, in units, in order, for a field that starts in a run of 10 pt and whose code
/// run sets 20 pt, in the fake font, whose single line is its size.
fn check_box_bars(device: &crate::grid::Device, quirks: &crate::quirks::Quirks) -> [(i64, i64); 4] {
use crate::quirks::{CheckBoxSide, ComputedFieldFormat};
let point = Length::from_points(1).unwrap();
let cell = device.snap(match quirks.computed_field_format {
ComputedFieldFormat::CodeRun => point * 20,
ComputedFieldFormat::ResultRun => point * 10,
});
// Strokes of 0.72 pt to the nearest dot, and the side between their middles.
let stroke = device.snap(Length::from_units(point.units() * 72 / 100));
let side = match quirks.check_box_side {
CheckBoxSide::ThreeStrokes => cell - stroke * 3,
CheckBoxSide::ThreeStrokesAndDot => cell - stroke * 3 - device.dots(1),
};
let (across, down) = ((side + stroke).units(), (side - stroke).units());
let stroke = stroke.units();
[
(stroke, down),
(stroke, down),
(across, stroke),
(across, stroke),
]
}
#[test]
fn draws_a_check_box_with_the_stroke_side_and_sizing_run_of_each_target() {
use crate::quirks::{CheckBoxSide, ComputedFieldFormat};
// The field starts in a run of 10 pt, and the run of its code sets 20 pt.
let body = concat!(
r#"<w:p><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:fldChar w:fldCharType="begin"><w:ffData><w:checkBox><w:sizeAuto/></w:checkBox></w:ffData></w:fldChar></w:r>"#,
r#"<w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>Y</w:t></w:r></w:p>"#
);
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
let bytes = crate::tests::package(body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let (mut sides, mut formats) = (Vec::new(), Vec::new());
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let expected = check_box_bars(&profile.device(), &profile.quirks());
assert_eq!(rect_sizes(&list), expected, "{target}");
sides.push(profile.quirks().check_box_side);
formats.push(profile.quirks().computed_field_format);
}
assert!(sides.contains(&CheckBoxSide::ThreeStrokes));
assert!(sides.contains(&CheckBoxSide::ThreeStrokesAndDot));
assert!(formats.contains(&ComputedFieldFormat::CodeRun));
assert!(formats.contains(&ComputedFieldFormat::ResultRun));
}
#[test]
fn ends_the_underline_of_a_run_at_a_tab_of_another_run() {
let underlined = r#"<w:rPr><w:u w:val="single"/></w:rPr>"#;
let body = format!(
r"<w:p><w:r>{underlined}<w:t>ab</w:t></w:r><w:r><w:tab/></w:r><w:r>{underlined}<w:t>cd</w:t></w:r></w:p>"
);
let lines = |body: &str| {
let list = lay_out(body, "", None);
let mut widths: Vec<i64> = testing::rects(&list, 0)
.into_iter()
.map(|(_, _, width, _)| width)
.collect();
widths.sort_unstable();
widths
};
// Two lines, one under each text, and none under the tab between them.
let split = lines(&body);
assert_eq!(split.len(), 2, "{split:?}");
// An underlined tab draws its own line, which joins the two.
let joined = lines(&body.replace(
"<w:r><w:tab/></w:r>",
&format!("<w:r>{underlined}<w:tab/></w:r>"),
));
assert_eq!(joined.len(), 3, "{joined:?}");
assert!(joined.iter().sum::<i64>() > split.iter().sum::<i64>());
}
#[test]
fn draws_a_list_label_without_the_underline_of_its_paragraph_mark() {
use crate::ns::W;
// An underlined mark underlines the text after the label but not the label, and a level
// whose own run properties underline it does underline the label.
let numbering = |level_rpr: &str| {
format!(
r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:suff w:val="space"/>{level_rpr}</w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#
)
};
let body = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr><w:rPr><w:u w:val="single"/></w:rPr></w:pPr><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>Name</w:t></w:r></w:p>"#;
// Where the underline starts, and the device dot nearest to where the text starts.
let starts = |level_rpr: &str| {
let list = testing::lay_out_with_numbering(body, &numbering(level_rpr));
let line = testing::rects(&list, 0).iter().map(|r| r.0).min().unwrap();
(line, f_office_units::div_round(find(&list, 'N').1, DOT))
};
let (line, text) = starts("");
assert_eq!(line, text);
let (line, text) = starts(r#"<w:rPr><w:u w:val="single"/></w:rPr>"#);
assert!(line < text, "{line} {text}");
}
#[test]
fn fills_a_shaded_paragraph_out_to_its_side_borders() {
let shaded = |borders: &str| {
format!(
r#"<w:p><w:pPr>{borders}<w:shd w:val="clear" w:color="auto" w:fill="306785"/></w:pPr><w:r><w:t>Name</w:t></w:r></w:p>"#
)
};
// The fill is the widest rectangle of the page, in device dots.
let fill_width = |body: &str| {
let list = lay_out(body, "", None);
testing::rects(&list, 0).iter().map(|r| r.2).max().unwrap()
};
let plain = fill_width(&shaded(""));
let side = r#"w:val="single" w:sz="4" w:space="6" w:color="000000""#;
let boxed = fill_width(&shaded(&format!(
r"<w:pBdr><w:left {side}/><w:right {side}/></w:pBdr>"
)));
// 6 pt of space at each side is 25 device dots.
assert!(boxed >= plain + 2 * 25, "{plain} {boxed}");
}
#[test]
fn a_shaded_body_paragraph_fills_out_to_the_reach_of_its_border_lines() {
let shaded = r#"<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="306785"/><w:ind w:left="723" w:right="1442"/></w:pPr><w:r><w:t>Name</w:t></w:r></w:p>"#;
// The fill's left end and the first glyph's dot, in device dots.
let ends = |body: &str| {
let list = lay_out(body, "", None);
let fill = testing::rects(&list, 0)
.into_iter()
.max_by_key(|r| r.2)
.unwrap();
(fill.0, f_office_units::div_round(find(&list, 'N').1, DOT))
};
// 1.5 pt, rounded down to whole device dots of 0.24 pt, is 6 units.
let (fill, text) = ends(shaded);
assert_eq!(fill, text - 6);
// In a table cell, the fill keeps to the indent.
let cell = format!(
r#"<w:tbl><w:tblPr><w:tblW w:w="6000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="6000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="6000" w:type="dxa"/></w:tcPr>{shaded}</w:tc></w:tr></w:tbl><w:p/>"#
);
let (fill, text) = ends(&cell);
assert!((fill - text).abs() <= 1, "{fill} {text}");
}
#[test]
fn a_right_to_left_paragraph_counts_its_fill_ends_from_the_column_right_edge() {
// A left-to-right paragraph indented 723 and 1,442 twips, a right-to-left one with the
// same indents on the same sides of the page (in it, `w:left` indents the right side), and
// a right-to-left one without indents.
let shaded = |bidi: &str, ind: &str| {
format!(
r#"<w:p><w:pPr>{bidi}<w:shd w:val="clear" w:color="auto" w:fill="306785"/><w:ind {ind}/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>"#
)
};
let body = shaded("", r#"w:left="723" w:right="1442""#)
+ &shaded("<w:bidi/>", r#"w:left="1442" w:right="723""#)
+ &shaded("<w:bidi/>", r#"w:left="0""#);
// The fills' left and right ends in the order of the paragraphs, on a page of `width`
// twips with a left margin of `left`, for each target, with its device, the dot by which
// a right-to-left line's glyphs lie right of their steps (one where the glyphs take the
// edge steps) and the column's right edge in half-EMUs.
let fills = |width: i64, left: i64| {
let page = format!(
r#"<w:pgSz w:w="{width}" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="{left}" w:header="720" w:footer="720" w:gutter="0"/>"#
);
let bytes = crate::tests::package(&body, "", &page);
let package =
f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
crate::Target::all()
.map(|target| {
let device = crate::profile::Profile::of(target).unwrap().device();
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let ends: Vec<(i64, i64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
f_office_paint::Item::Rect(r) => {
Some((r.x.units(), r.x.units() + r.width.units()))
}
f_office_paint::Item::Glyphs(_)
| f_office_paint::Item::Path(_)
| f_office_paint::Item::Gradient(_)
| f_office_paint::Item::Image(_)
| f_office_paint::Item::Group(_) => None,
})
.collect();
assert_eq!(ends.len(), 3, "{target} {ends:?}");
let steps = matches!(device.advances(), crate::grid::Advances::RightEdge { .. });
let dot = if steps { device.dots(1).units() } else { 0 };
let edge = Length::from_twips(width - 1440).unwrap().units();
(target, device, dot, edge, ends)
})
.collect::<Vec<_>>()
};
// On a page of 8.5 inches with margins of one inch, both edges of the column lie on dots
// of every device. There the right-to-left ends mirror the left-to-right ones, and lie one
// dot further right where the glyphs take the edge steps, as the glyphs of a right-to-left
// line do. The paragraph without indents gives the reach past the right edge.
let (mut reaches, mut stepped) = (Vec::new(), false);
for (target, _, dot, edge, ends) in fills(12240, 1440) {
let (ltr, rtl) = (ends[0], ends[1]);
assert_eq!((rtl.0 - ltr.0, rtl.1 - ltr.1), (dot, dot), "{target}");
reaches.push(ends[2].1 - edge - dot);
stepped |= dot > 0;
}
assert!(stepped);
assert!(reaches.iter().all(|&reach| reach > 0), "{reaches:?}");
// With a page of 11,906 twips and a left margin of 1,417, the right edge, 10,466 twips,
// lies between dots on every device, and counted from the left edge it would land on
// another dot on the device of 600 dots per inch. The right end of the paragraph without
// indents lies on
// the dot of the right edge, the glyphs' dot further right, and out by the same reach.
for ((target, device, dot, edge, ends), reach) in fills(11906, 1417).into_iter().zip(reaches) {
let right = device.snap(Length::from_units(edge)).units();
assert_eq!(ends[2].1, right + dot + reach, "{target} {ends:?}");
}
}
/// The fake fonts as the target's own faces, whose instructions give each glyph the device
/// width of its advance with the fraction of a dot taken off.
struct OwnFaces;
impl crate::Fonts for OwnFaces {
fn face(
&self,
family: &f_office_fonts::FamilyName,
bold: bool,
italic: bool,
) -> Option<crate::ChosenFace> {
Fake.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Fake.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Fake.advance(font, glyph)
}
fn target_face(&self, _font: f_office_fonts::FontId) -> Option<(String, String)> {
Some(("Fake".to_owned(), "1".to_owned()))
}
fn device_width(&self, font: f_office_fonts::FontId, glyph: u32, ppem: u16) -> Option<i32> {
let units = i32::from(Fake.advance(font, glyph)?);
Some(units * i32::from(ppem) / 1000)
}
}
#[test]
fn steps_the_glyphs_of_right_to_left_text_as_the_quirk_says() {
// The same bold glyph twelve times at 11.5 pt, in a left-to-right paragraph and in a
// right-to-left one. Its advance, 600 of 1,000 units, is 6.9 pt, which the device widths
// take down to whole dots where a dot is not a tenth of a point. Under
// `RightToLeftSteps::DeviceWidths` the right-to-left glyphs step as the left-to-right
// ones; under `RightToLeftSteps::Nearest` they step by their advance at the nearest dot,
// which no device width enters.
let run = |rtl: &str, ch: char| {
let text: String = std::iter::repeat_n(ch, 12).collect();
format!(
r#"<w:r><w:rPr>{rtl}<w:b/><w:bCs/><w:sz w:val="23"/><w:szCs w:val="23"/></w:rPr><w:t>{text}</w:t></w:r>"#
)
};
let body = format!(
"<w:p>{}</w:p><w:p><w:pPr><w:bidi/></w:pPr>{}</w:p>",
run("", 'a'),
run("<w:rtl/>", '\u{5d0}')
);
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
// The steps from each glyph to the next in reading order, in units: from left to right
// for 'a', from right to left for the Hebrew letter.
let steps = |list: &DisplayList, ch: char| -> Vec<i64> {
let mut xs: Vec<i64> = find_all(list, ch).iter().map(|&(_, x, _)| x).collect();
xs.sort_unstable();
let mut steps: Vec<i64> = xs.windows(2).map(|pair| pair[1] - pair[0]).collect();
if ch != 'a' {
steps.reverse();
}
steps
};
let mut stepped = Vec::new();
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
let device = profile.device();
if !matches!(device.advances(), crate::grid::Advances::RightEdge { .. }) {
continue;
}
let quirk = profile.quirks().right_to_left_steps;
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let with = |fonts: &dyn crate::Fonts| {
crate::layout(&package, (fonts, &crate::ArtPictures::new()), &options).unwrap()
};
let (own, fake) = (with(&OwnFaces).value, with(&Fake).value);
// The device widths change the left-to-right steps. The right-to-left glyphs, which all
// have one width, step as the left-to-right ones do, or the same with either faces'
// device widths, within the half-EMU of rounding each place once from the writer's
// exact sum.
assert_ne!(steps(&own, 'a'), steps(&fake, 'a'), "{target}");
let hebrew = '\u{5d0}';
assert!(
right_to_left_steps_hold(
quirk,
(&steps(&own, hebrew), &steps(&fake, hebrew)),
&steps(&own, 'a')
),
"{target}"
);
stepped.push(quirk);
}
assert!(stepped.contains(&crate::quirks::RightToLeftSteps::Nearest));
}
/// Whether the right-to-left steps with the target's own faces and with the fake faces
/// (`own`, `fake`) are those that `quirk` says beside the left-to-right steps `ltr` with the
/// own faces: the left-to-right steps, or, by the advance at the nearest dot, the same with
/// either faces and not the left-to-right steps.
fn right_to_left_steps_hold(
quirk: crate::quirks::RightToLeftSteps,
(own, fake): (&[i64], &[i64]),
ltr: &[i64],
) -> bool {
match quirk {
crate::quirks::RightToLeftSteps::DeviceWidths => within_one(own, ltr),
crate::quirks::RightToLeftSteps::Nearest => within_one(own, fake) && !within_one(own, ltr),
}
}
/// The targets whose right-to-left lines start on whole dots, each with its device's dot.
fn right_to_left_whole_dots_targets() -> Vec<(crate::Target, i64)> {
crate::Target::all()
.filter_map(|target| {
let profile = crate::profile::Profile::of(target).unwrap();
let quirks = profile.quirks();
(quirks.right_to_left_line_start == crate::quirks::RightToLeftLineStart::WholeDots
&& quirks.aligned_ends == crate::quirks::AlignedEnds::OnDots)
.then(|| (target, profile.device().dots(1).units()))
})
.collect()
}
/// The places of the glyphs of `letters` in the layout of `package` for `target`, by line from
/// the top, and in each line from the left.
fn letter_lines(
package: &f_office_opc::Package,
target: crate::Target,
letters: &[char],
) -> Vec<Vec<i64>> {
letter_lines_in(
package,
target,
crate::profile::Overrides::default(),
letters,
)
}
/// The places of the glyphs of `letters` in the layout of `package` for `target` with the
/// development override `overrides`, by line from the top, and in each line from the left.
fn letter_lines_in(
package: &f_office_opc::Package,
target: crate::Target,
overrides: crate::profile::Overrides,
letters: &[char],
) -> Vec<Vec<i64>> {
let options = crate::Options {
configuration: crate::Configuration::of(target),
overrides,
..crate::Options::default()
};
let list = crate::layout(package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let mut lines: std::collections::BTreeMap<i64, Vec<i64>> = std::collections::BTreeMap::new();
for &ch in letters {
for (_, x, y) in find_all(&list, ch) {
lines.entry(y).or_default().push(x);
}
}
lines
.into_values()
.map(|mut xs| {
xs.sort_unstable();
xs
})
.collect()
}
/// The three Hebrew letters of the right-to-left tests.
const HEBREW: [char; 3] = ['\u{5d0}', '\u{5d1}', '\u{5d2}'];
/// A package of `body` on a Letter page with margins of 1 inch.
fn letter_page(body: &str) -> f_office_opc::Package {
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(body, "", page);
f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap()
}
#[test]
fn a_start_aligned_right_to_left_line_keeps_the_places_of_its_end_aligned_twin() {
// Two right-to-left paragraphs with one text of two lines at 9.5 pt, whose advances are
// not whole dots: start-aligned, at the right margin, and then end-aligned, at the left one.
// A start at the line's exact place would move the steps of the first line too.
let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(27);
let paragraph = |jc: &str| {
format!(
r#"<w:p><w:pPr><w:bidi/>{jc}</w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
)
};
let package = letter_page(&(paragraph("") + ¶graph(r#"<w:jc w:val="end"/>"#)));
let targets = right_to_left_whole_dots_targets();
assert_ne!(targets, []);
for (target, dot) in targets {
let lines = letter_lines(&package, target, &HEBREW);
assert_eq!(lines.len(), 4, "{target}");
// The start-aligned first line, which does not end its paragraph, takes the places of
// its end-aligned twin, moved right by whole dots.
let (start, end) = (&lines[0], &lines[2]);
assert_eq!(start.len(), end.len(), "{target}");
let moves: Vec<i64> = start.iter().zip(end).map(|(s, e)| s - e).collect();
assert!(moves.iter().all(|&m| m == moves[0]), "{target} {moves:?}");
assert!(moves[0] > 0 && moves[0] % dot == 0, "{target} {moves:?}");
}
}
#[test]
fn a_centered_right_to_left_paragraph_puts_only_its_last_line_on_dots() {
// A centered right-to-left paragraph of two lines at 9.5 pt, whose advances are not whole
// dots, with an end indent of 2 twips. With `RightToLeftCenteredLine::OnDots` its last line
// moves as a whole by whole dots from where it lies with `Exact`. Its first line, which
// does not end the paragraph, keeps its places, where the rule of the last line would move
// it.
let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(29);
let package = letter_page(&format!(
r#"<w:p><w:pPr><w:bidi/><w:ind w:right="2"/><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
));
let targets: Vec<(crate::Target, i64)> = right_to_left_whole_dots_targets()
.into_iter()
.filter(|&(target, _)| {
crate::profile::Profile::of(target)
.unwrap()
.quirks()
.right_to_left_centered_line
== crate::quirks::RightToLeftCenteredLine::OnDots
})
.collect();
assert_ne!(targets, []);
for (target, dot) in targets {
let on_dots = letter_lines(&package, target, &HEBREW);
let exact =
crate::profile::Overrides::default().with_quirk("RightToLeftCenteredLine", "Exact");
let exact = letter_lines_in(&package, target, exact, &HEBREW);
assert_eq!(on_dots.len(), 2, "{target}");
assert_eq!(on_dots[0], exact[0], "{target}");
let (last, before) = (&on_dots[1], &exact[1]);
assert_eq!(last.len(), before.len(), "{target}");
let moves: Vec<i64> = last.iter().zip(before).map(|(a, b)| a - b).collect();
assert!(moves.iter().all(|&m| m == moves[0]), "{target} {moves:?}");
assert!(moves[0] != 0 && moves[0] % dot == 0, "{target} {moves:?}");
}
}
#[test]
fn the_spaces_that_start_a_start_aligned_right_to_left_line_keep_their_room() {
// A start-aligned right-to-left paragraph of two lines at 9.5 pt that starts with two
// spaces. They lie at the right end of its first line, which moves by the free whole dots
// after its written text, the spaces included.
let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(27);
let package = letter_page(&format!(
r#"<w:p><w:pPr><w:bidi/></w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve"> {text}</w:t></w:r></w:p>"#
));
// The column's right edge, and the width of a glyph of the fake font at 9.5 pt.
let (edge, glyph) = (
540 * Length::UNITS_PER_POINT,
Length::UNITS_PER_POINT * 95 / 20,
);
let targets = right_to_left_whole_dots_targets();
assert_ne!(targets, []);
for (target, dot) in targets {
let lines = letter_lines(&package, target, &HEBREW);
let right = lines[0].last().unwrap() + glyph;
// The two spaces keep their room at the right end: the letters end at least their
// width, less two dots, left of the edge. The device's steps of the line take the rest,
// which is less than a third glyph.
assert!(
right <= edge - 2 * glyph + 2 * dot,
"{target} {}",
edge - right
);
assert!(right > edge - 3 * glyph, "{target} {}", edge - right);
}
}
#[test]
fn a_start_indent_that_keeps_the_dot_of_its_right_edge_keeps_a_right_to_left_line_in_place() {
// Two start-aligned right-to-left paragraphs with one text of two lines on an A4 page,
// whose column's right edge lies 0.83 dot past a dot at 600 dots per inch. Their start
// indents of 720 and 721 twips are 300 and 300.42 dots, which both go to the dot 300, so
// the column's right edge less that dot gives one edge. The column's width less each indent
// goes to two dots, 3,461 and 3,460, which would move the second line a dot left.
let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(27);
let paragraph = |start: u32| {
format!(
r#"<w:p><w:pPr><w:bidi/><w:ind w:left="{start}"/></w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
)
};
let page = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(&(paragraph(720) + ¶graph(721)), "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let targets: Vec<crate::Target> = right_to_left_whole_dots_targets()
.into_iter()
.map(|(target, _)| target)
.filter(|&target| {
crate::profile::Profile::of(target)
.unwrap()
.quirks()
.right_to_left_line_edge
== crate::quirks::RightToLeftLineEdge::FromColumnRight
})
.collect();
assert_ne!(targets, []);
for target in targets {
let lines = letter_lines(&package, target, &HEBREW);
assert_eq!(lines.len(), 4, "{target}");
// The first lines, which do not end their paragraphs, take the same places.
assert_eq!(lines[0], lines[2], "{target}");
}
}
#[test]
fn a_justified_right_to_left_line_moves_up_to_the_dot_of_its_right_edge() {
// A justified right-to-left paragraph at 12 pt on an A4 page, and the same text
// start-aligned. The page's column and the start indent of 613 twips end off the dots of
// 600 dots per inch. Placed from its exact edges, the stretched first line would fill its
// space from the dot of the space's left edge, 600, with its glyphs a dot right of it. Drawn
// from that dot, its device steps end one dot past the dot of its right edge, so the line
// moves one dot left, and its glyphs lie from the dot 600 on.
let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(40);
let paragraph = |jc: &str| {
format!(
r#"<w:p><w:pPr><w:bidi/><w:ind w:left="613"/>{jc}</w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
)
};
let page = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
let body = paragraph(r#"<w:jc w:val="both"/>"#) + ¶graph("");
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let targets: Vec<(crate::Target, i64)> = right_to_left_whole_dots_targets()
.into_iter()
.filter(|&(target, _)| {
crate::profile::Profile::of(target)
.unwrap()
.quirks()
.right_to_left_justified_line
== crate::quirks::RightToLeftJustifiedLine::EndsAtEdge
})
.collect();
assert_ne!(targets, []);
for (target, dot) in targets {
let lines = letter_lines(&package, target, &HEBREW);
assert_eq!(lines.len() % 2, 0, "{target}");
let (justified, twin) = (&lines[0], &lines[lines.len() / 2]);
// The glyphs of the fake font lie a fixed part of a dot past their steps, which the
// twin's places, whole dots from the dot of its start, show.
let past = twin[0].rem_euclid(dot);
assert_eq!(
justified[0] - past,
600 * dot,
"{target} {}",
justified[0] - past
);
}
}
#[test]
fn a_justified_right_to_left_line_before_a_soft_break_moves_up_to_its_right_edge_with_its_stretch()
{
// A justified right-to-left paragraph whose first line, of three words of the fake font at
// 12 pt, ends in a soft line break with no space before it, and a justified paragraph of
// 40 such words whose first line ends in a space. Both first lines stretch their spaces to
// fill the column, so where a line moves from the dot where its steps end to the dot of
// its right edge, both start at the same dot: the steps of the short line end with the
// stretch of its spaces, though no trailing space gives their end.
let word = "\u{5d0}\u{5d1}\u{5d2}";
let run = |text: &str| {
format!(
r#"<w:r><w:rPr><w:rtl/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r>"#
)
};
let paragraph =
|runs: String| format!(r#"<w:p><w:pPr><w:bidi/><w:jc w:val="both"/></w:pPr>{runs}</w:p>"#);
let broken = run(&[word; 3].join(" ")) + "<w:r><w:br/></w:r>" + &run(word);
let body = paragraph(broken) + ¶graph(run(&[word; 40].join(" ")));
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let targets: Vec<crate::Target> = crate::Target::all()
.filter(|&target| {
crate::profile::Profile::of(target)
.unwrap()
.quirks()
.right_to_left_justified_line
== crate::quirks::RightToLeftJustifiedLine::EndsAtEdge
})
.collect();
assert_ne!(targets, []);
for target in targets {
let dot = crate::profile::Profile::of(target)
.unwrap()
.device()
.dots(1)
.units();
let lines = letter_lines(&package, target, &HEBREW);
assert_eq!(lines[0].len(), 9, "{target}");
let moved = lines[0][0] - lines[2][0];
assert!(moved.abs() <= dot, "{target} {moved}");
}
}
#[test]
fn swaps_the_indents_of_a_right_to_left_paragraph() {
let x = |bidi: &str, ind: &str| {
let body =
format!(r"<w:p><w:pPr>{bidi}<w:ind {ind}/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>");
find(&lay_out(&body, NORMAL, Some(15)), 'a').1
};
let twips = |t: i64| t * Length::UNITS_PER_TWIP;
let rtl = |ind: &str| x("<w:bidi/>", ind);
let start = rtl(r#"w:left="0""#);
// The short line starts at the right. `w:left` indents that side, and `w:right` the left
// side, which the line does not reach.
assert_eq!(rtl(r#"w:left="1440""#), start - twips(1440));
assert_eq!(rtl(r#"w:right="1440""#), start);
// The first line's indent lies at the right too, and a hanging one reaches out there.
assert_eq!(rtl(r#"w:firstLine="720""#), start - twips(720));
assert_eq!(rtl(r#"w:left="720" w:hanging="360""#), start - twips(360));
// A left-to-right paragraph keeps `w:left` at the left.
let ltr = x("", r#"w:left="0""#);
assert_eq!(x("", r#"w:left="1440""#), ltr + twips(1440));
}
/// Twelve right-aligned lines with the right indent 721 twips and the left indents 720 to 731
/// twips, each a twelfth of a dot further right.
fn twelve_right_aligned_lines() -> String {
(720..732)
.map(|left| {
format!(
r#"<w:p><w:pPr><w:ind w:left="{left}" w:right="721"/><w:jc w:val="right"/></w:pPr><w:r><w:t>AB</w:t></w:r></w:p>"#
)
})
.collect::<Vec<_>>()
.concat()
}
/// Lays out `body` on an A4 page with side margins of 851 twips, 354.58 dots at 600 dots per
/// inch, for each target whose aligned lines start on whole dots and take the right edge of
/// their space from the column's edge, and checks that the twelve lines of
/// [`twelve_right_aligned_lines`] in it start on one dot.
fn assert_the_twelve_lines_start_on_one_dot(body: &str) {
let page = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="851" w:bottom="1440" w:left="851" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
let quirks = profile.quirks();
if quirks.aligned_ends != crate::quirks::AlignedEnds::OnDots
|| quirks.aligned_line_edge != crate::quirks::AlignedLineEdge::FromColumnEdge
{
continue;
}
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let unit = profile.device().dots(1).units();
// A glyph's place is its dot plus the writer's offset, which is under a dot.
let starts: Vec<i64> = find_all(&list, 'A').iter().map(|a| a.1 / unit).collect();
assert_eq!(starts.len(), 12, "{target:?}");
assert!(
starts.iter().all(|&s| s == starts[0]),
"{target:?} {starts:?}"
);
}
}
#[test]
fn a_right_aligned_line_ends_on_an_edge_that_its_left_indent_does_not_move() {
assert_the_twelve_lines_start_on_one_dot(&twelve_right_aligned_lines());
}
#[test]
fn a_right_aligned_line_of_a_table_cell_ends_on_an_edge_that_its_left_indent_does_not_move() {
// The same lines in the one cell of a table without lines, whose text edge lies at no
// whole dot either: the page's margin of 851 twips and the cell's left margin of 113 twips.
let body = format!(
r#"<w:tbl><w:tblPr><w:tblW w:w="9000" w:type="dxa"/><w:tblLayout w:type="fixed"/><w:tblCellMar><w:left w:w="113" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="9000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="9000" w:type="dxa"/></w:tcPr>{}</w:tc></w:tr></w:tbl><w:p/>"#,
twelve_right_aligned_lines()
);
assert_the_twelve_lines_start_on_one_dot(&body);
}
#[test]
fn a_right_aligned_and_a_centered_line_keep_the_glyph_places_of_the_left_aligned_line() {
let aligned = |jc: &str, text: &str| {
format!(
r#"<w:p><w:pPr><w:jc w:val="{jc}"/></w:pPr><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
)
};
let body = p("ABCABCABC")
+ &aligned("right", "ABCABCABC")
+ &aligned("center", "ABCABCABC")
+ &aligned("right", "XY ");
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1417" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let (a, c) = (find_all(&list, 'A'), find_all(&list, 'C'));
assert_eq!((a.len(), c.len()), (9, 9));
if profile.quirks().aligned_ends != crate::quirks::AlignedEnds::OnDots {
continue;
}
let unit = profile.device().dots(1).units();
// The lines of the three alignments start at the glyphs 0, 3 and 6. A glyph's place
// is its dot plus the writer's offset, which is under a dot.
let (left, right, center) = (a[0].1 / unit, a[3].1 / unit, a[6].1 / unit);
let offsets = |from: usize| -> Vec<i64> {
(0..3)
.flat_map(|k| [a[from + k].1 - a[from].1, c[from + k].1 - a[from].1])
.collect()
};
// Each place is the half-EMU nearest the writer's exact place, so an offset from the
// line's start may differ by one half-EMU.
assert!(within_one(&offsets(3), &offsets(0)));
assert!(within_one(&offsets(6), &offsets(0)));
assert_eq!(center - left, (right - left) / 2);
// A shorter line with trailing spaces starts further right.
assert!(find_all(&list, 'X')[0].1 / unit > right);
}
}
#[test]
fn starts_the_text_after_a_right_or_a_center_stop_as_an_aligned_line() {
// The left margin and the stop lie on dots of each device (1,440 and 4,320 twips), and
// the fake glyphs of 10 pt are 5 pt wide, which is not a whole number of dots at 600 dots
// per inch. Paragraph 1: a right stop, then "KL" and two spaces. Paragraph 2: "MN" and
// two spaces, right-aligned in a space that ends at the stop. Paragraph 3: a center stop,
// then "PQ". Paragraph 4: a right stop, then "RS". Paragraph 5: a center stop, then the
// reference mark of a comment, a piece without a glyph or a width, and "UV". Paragraphs 6
// and 7: a right stop, then "YZ" and a no-break space, and "GHJ".
let tabbed = |kind: &str, text: &str| {
format!(
r#"<w:p><w:pPr><w:tabs><w:tab w:val="{kind}" w:pos="4320"/></w:tabs></w:pPr><w:r><w:tab/><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
)
};
let body = tabbed("right", "KL ")
+ r#"<w:p><w:pPr><w:ind w:right="5040"/><w:jc w:val="right"/></w:pPr><w:r><w:t xml:space="preserve">MN </w:t></w:r></w:p>"#
+ &tabbed("center", "PQ")
+ &tabbed("right", "RS")
+ r#"<w:p><w:pPr><w:tabs><w:tab w:val="center" w:pos="4320"/></w:tabs></w:pPr><w:r><w:tab/><w:annotationRef/><w:t>UV</w:t></w:r></w:p>"#
+ &tabbed("right", "YZ ")
+ &tabbed("right", "GHJ");
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
if profile.quirks().aligned_ends != crate::quirks::AlignedEnds::OnDots {
continue;
}
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let unit = profile.device().dots(1).units();
// A glyph's place is its dot plus the writer's offset, which is under a dot.
let dot = |ch: char| find(&list, ch).1 / unit;
let stop = (1440 + 4320) * Length::UNITS_PER_TWIP / unit;
// The text after the right stop ends on the stop's dot, where the right-aligned line
// ends: at its first trailing space, which the steps put a dot past the exact end.
assert_eq!(dot('K'), dot('M'), "{target:?}");
// The text after the center stop starts half of its written width, rounded down, left
// of the stop's dot. The written width of "PQ" is that of "RS" after the right stop.
let width = stop - dot('R');
assert_eq!(dot('P'), stop - width / 2, "{target:?} {width}");
// The text whose width a stop takes ends at the first piece that is not a glyph. After
// the mark, no text is left to center, and "UV" starts on the stop.
assert_eq!(dot('U'), stop, "{target:?}");
// Only the space U+0020 trails: a no-break space at the end is written text, as wide
// as a letter of the fake font.
assert_eq!(dot('Y'), dot('G'), "{target:?}");
}
}
#[test]
fn ends_an_aligned_line_of_only_a_label_and_its_tab_at_the_dot_after_the_tab() {
// Empty list paragraphs, whose line is the label "AB1" of three fake glyphs of 10 pt and
// the tab after it, which ends at the default stop of 36 pt: centered, then right-aligned,
// with right indents of 0 to 11 twips, which move the space's right edge across dots. The
// margin of 1,440 twips lies on dot 600 at 600 dots per inch.
let numbering = parse(&format!(
r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="AB%1"/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
));
let label = |jc: &str, right: u32| {
format!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr><w:ind w:left="0" w:right="{right}" w:firstLine="0"/><w:jc w:val="{jc}"/></w:pPr></w:p>"#
)
};
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
if profile.quirks().aligned_tab_end != crate::quirks::AlignedTabEnd::StopDot {
continue;
}
let unit = profile.device().dots(1).units();
let start = 1440 * Length::UNITS_PER_TWIP / unit;
let places = |right: u32, variant| {
let body = label("center", right) + &label("right", right);
let aligned = profile.with_variant(variant);
let (device, quirks) = (aligned.device(), aligned.quirks());
let lists = Numbering::read(
&mut PartReader::new(&numbering),
numbering.root().unwrap(),
crate::reader::settings::ReaderSettings::with_built_in_list(
crate::quirks::BuiltInList::WithoutPart,
),
);
let list = testing::pass_with(&body, ("", None), None, lists, (device, quirks)).list;
match find_all(&list, 'A')[..] {
[centered, right_aligned] => (centered.1 / unit, right_aligned.1 / unit),
_ => panic!("{target:?}: two labels"),
}
};
for right in 0..12 {
// The right-aligned line moves by the free whole dots between the dot after its
// tab and the space's right edge, and the centered one by half of them, rounded
// down.
let (centered, right_aligned) = places(right, crate::quirks::AlignedTabEnd::StopDot);
assert_eq!(
centered - start,
(right_aligned - start) / 2,
"{target:?} {right}"
);
}
// Without the end, the centered line keeps its exact start, 1,799.58 dots right of
// the margin with a right indent of 2 twips, on the dot above.
let stopped = places(2, crate::quirks::AlignedTabEnd::StopDot).0;
let unended = places(2, crate::quirks::AlignedTabEnd::Unended).0;
assert_eq!(
(stopped - start, unended - start),
(1799, 1800),
"{target:?}"
);
}
}
#[test]
fn lands_the_text_after_a_tab_in_a_centered_line_where_a_start_aligned_line_lands_it() {
// The left margin of 1,701 twips lies three quarters of a dot past a dot at 600 dots per
// inch, and the left stop at 851 twips a third of a dot past one. Both paragraphs have a
// first-line indent of 567 twips and hold two fake glyphs of 5 pt, a tab and two more;
// the first is centered, the second start-aligned.
let paragraph = |jc: &str, text: (&str, &str)| {
format!(
r#"<w:p><w:pPr><w:tabs><w:tab w:val="left" w:pos="851"/></w:tabs><w:ind w:firstLine="567"/>{jc}</w:pPr><w:r><w:t>{}</w:t><w:tab/><w:t>{}</w:t></w:r></w:p>"#,
text.0, text.1
)
};
let body = paragraph(r#"<w:jc w:val="center"/>"#, ("AB", "CD")) + ¶graph("", ("EF", "GH"));
let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1701" w:bottom="1440" w:left="1701" w:header="720" w:footer="720" w:gutter="0"/>"#;
let bytes = crate::tests::package(&body, "", page);
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
for target in crate::Target::all() {
let profile = crate::profile::Profile::of(target).unwrap();
if profile.quirks().aligned_line_segments
!= crate::quirks::AlignedLineSegments::FromExactStart
{
continue;
}
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let unit = profile.device().dots(1).units();
// A glyph's place is its dot plus the writer's offset, which is under a dot.
let dot = |ch: char| find(&list, ch).1 / unit;
// The start-aligned line lands the text after the tab on the dot of the stop's exact
// place, the dot of the margin plus the stop's distance from it, and the centered line
// lands it as far from its first glyph.
assert_eq!(dot('C') - dot('A'), dot('G') - dot('E'), "{target:?}");
assert!(dot('A') > dot('E'), "{target:?}");
}
}
#[test]
fn draws_the_bar_of_a_fraction_in_a_part_at_the_axis_above_that_part() {
// At 10 pt, the inline fraction x over (y, then a over b). Each bar's middle lies on the
// axis, 585/2048 of its fraction's size, above its fraction's own baseline: the line's
// for the outer bar at 10 pt, and the denominator's for the inner bar at the
// denominator's 7 pt. The bar's top and bottom lie on dots, so its middle lies within a
// dot of the axis.
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let r = |text: &str| format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{text}</m:t></m:r>");
let f = |num: &str, den: &str| format!("<m:f><m:num>{num}</m:num><m:den>{den}</m:den></m:f>");
let denominator = r("y") + &f(&r("a"), &r("b"));
let body = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{}</m:oMath></w:p>"#,
f(&r("x"), &denominator)
);
let list = lay_out(&body, "", None);
let mut bars = testing::rects(&list, 0);
bars.sort_by_key(|&(_, _, width, _)| std::cmp::Reverse(width));
let [
(_, outer_top, _, outer_height),
(_, inner_top, _, inner_height),
] = bars[..]
else {
panic!("{bars:?}");
};
// In half dots, so that a bar's middle is whole.
let axis = |half_points: i64| {
let size = Length::from_half_points(half_points).unwrap().units();
f_office_units::div_round(2 * f_office_units::div_round(size * 585, 2048), DOT)
};
let (line, part) = (2 * find(&list, 'A').2, 2 * find(&list, 'y').2);
let outer = 2 * outer_top + outer_height;
let inner = 2 * inner_top + inner_height;
assert!((line - axis(20) - outer).abs() <= 2, "{line} {outer}");
assert!((part - axis(14) - inner).abs() <= 2, "{part} {inner}");
// The denominator lies below the line, so its bar lies below the outer bar's.
assert!(part > line && inner > outer, "{outer} {inner}");
}
#[test]
fn draws_the_bar_of_a_fraction_whose_edges_round_to_one_dot_one_dot_thick() {
// The bar takes the size of the fraction's control properties. At 1 pt it is 133/2048 pt
// thick, about a quarter of a dot, and its top and its bottom round to the same dot; it is
// drawn one dot thick, as every line of the text layout whose thickness comes from a font
// is (`Device::line_thickness`). At 10 pt it is 0.65 pt, from 2.53 to 3.18 pt above the
// baseline, and its edges round to 11 and 13 dots.
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
for (half_points, dots) in [(2, 1), (20, 2)] {
let size = format!(r#"<w:rPr><w:sz w:val="{half_points}"/></w:rPr>"#);
let r = |text: &str| format!("<m:r><m:rPr><m:nor/></m:rPr>{size}<m:t>{text}</m:t></m:r>");
let body = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}"><m:f><m:fPr><m:ctrlPr>{size}</m:ctrlPr></m:fPr><m:num>{}</m:num><m:den>{}</m:den></m:f></m:oMath></w:p>"#,
r("x"),
r("y")
);
let list = lay_out(&body, "", None);
let [(_, _, _, height)] = testing::rects(&list, 0)[..] else {
panic!("{:?}", testing::rects(&list, 0));
};
assert_eq!(height, dots, "{half_points}");
}
}
#[test]
fn moves_a_part_whose_ink_comes_closer_to_the_bar_than_the_gap_minimum() {
// At 10 pt, a fraction whose numerator, x and a glyph that reaches far down, and whose
// denominator, y and a glyph that reaches far up, both cross the bar at the shifts. Each
// part moves away from the bar until its ink keeps the gap minimum from the bar's edge,
// to the nearest dot: 133/2048 of 10 pt in a line, where the parts are at 7 pt, and
// 260/2048 of 10 pt in a display, where they keep 10 pt.
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let r = |text: String| format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{text}</m:t></m:r>");
let fraction = format!(
"<m:f><m:num>{}</m:num><m:den>{}</m:den></m:f>",
r(format!("x{DEEP}")),
r(format!("y{TALL}"))
);
let line = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{fraction}</m:oMath></w:p>"#
);
let display = format!(
r#"<w:p><m:oMathPara xmlns:m="{math}"><m:oMath>{fraction}</m:oMath></m:oMathPara></w:p>"#
);
let pt = |points: i64| points * Length::UNITS_PER_POINT;
for (body, part, gap) in [(line, pt(7), 133), (display, pt(10), 260)] {
let list = lay_out(&body, "", None);
let [(_, top, _, height)] = testing::rects(&list, 0)[..] else {
panic!("{:?}", testing::rects(&list, 0));
};
let minimum = f_office_units::div_round(pt(10) * gap, 2048 * DOT);
let reach = |units: i64| f_office_units::div_round(part * units, 1000 * DOT);
// Down the page: the numerator's ink ends DEEP's depth below its baseline, and the
// denominator's starts TALL's height above its own.
let numerator = find(&list, 'x').2 + reach(900);
let denominator = find(&list, 'y').2 - reach(1900);
assert!(
(top - numerator - minimum).abs() <= 1,
"{top} {numerator} {minimum}"
);
assert!(
(denominator - (top + height) - minimum).abs() <= 1,
"{top} {height} {denominator} {minimum}"
);
}
}
#[test]
fn moves_the_scripts_of_one_base_apart_by_halves_of_the_shortfall_of_their_gap() {
// At 10 pt, a base with a subscript that reaches far up and a superscript that reaches far
// down, both at 7 pt: at their shifts the inks cross. The subscript drops and the
// superscript rises by half of the shortfall each, so that the inks keep 300/2048 of 10 pt
// between them, to the nearest dot.
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let r = |text: String| format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{text}</m:t></m:r>");
let pair = format!(
"<m:sSubSup><m:e>{}</m:e><m:sub>{}</m:sub><m:sup>{}</m:sup></m:sSubSup>",
r("b".to_owned()),
r(format!("{TALL}")),
r(format!("{DEEP}"))
);
let body =
format!(r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{pair}</m:oMath></w:p>"#);
let list = lay_out(&body, "", None);
let pt = |points: i64| points * Length::UNITS_PER_POINT;
let dots = |size: i64, units: i64, em: i64| f_office_units::div_round(size * units, em * DOT);
let (base, sub, sup) = (find(&list, 'b').2, find(&list, TALL).2, find(&list, DEEP).2);
// Down the page: the subscript's ink starts TALL's height above its baseline, and the
// superscript's ends DEEP's depth below its own.
let gap = (sub - dots(pt(7), 1900, 1000)) - (sup + dots(pt(7), 900, 1000));
let minimum = dots(pt(10), 300, 2048);
assert!((gap - minimum).abs() <= 2, "{gap} {minimum}");
let drop = sub - base - dots(pt(10), 418, 2048);
let rise = base - sup - dots(pt(10), 750, 2048);
assert!(drop > 0 && (drop - rise).abs() <= 2, "{drop} {rise}");
}
#[test]
fn gives_a_line_the_room_of_the_ink_of_its_inline_scripts_on_a_target_that_asks() {
use crate::quirks::ScriptRoom;
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let r = |text: &str| format!("<m:r><m:t>{text}</m:t></m:r>");
// The distances in dots from the baseline of a plain line to that of a line of text with
// the equation `equation`, and from that line to the plain line after it, with the fake
// fonts that have a `MATH` table, on a target with the quirk variant `variant`.
let distances = |equation: &str, variant: ScriptRoom| {
let body = format!(
r#"{}<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{equation}</m:oMath></w:p>{}"#,
p("Top"),
p("End")
);
let (device, quirks) = testing::on_base_with(|p| p.with_variant(variant));
let shaper = ShaperSettings::base_with(|p| p.with_variant(variant));
let target = (device, quirks, crate::layout::EarlierPass::default());
let fonts = (&FakeMath as &dyn crate::Fonts, shaper);
let pass = testing::pass_on(
&body,
("", None),
None,
Numbering::default(),
target,
&fonts,
);
let line = find(&pass.list, 'A').2;
(
line - find(&pass.list, 'T').2,
find(&pass.list, 'E').2 - line,
)
};
let plain = distances(&r("x"), ScriptRoom::Ink);
let superscript = format!(
"<m:sSup><m:e>{}</m:e><m:sup>{}</m:sup></m:sSup>",
r("x"),
r("x")
);
let subscript = format!(
"<m:sSub><m:e>{}</m:e><m:sub>{}</m:sub></m:sSub>",
r("x"),
r("(")
);
// The other variant gives the scripts no room of their own.
assert_eq!(distances(&superscript, ScriptRoom::FontLines), plain);
assert_eq!(distances(&subscript, ScriptRoom::FontLines), plain);
// At 10 pt, the scripts are at 7 pt. The superscript rises 750/2048 of 10 pt, to the
// nearest dot, and its ink reaches 700/1000 of 7 pt above its baseline, with MathLeading,
// 150/1000 of 10 pt, over it: beyond the line's ascent of 8 pt. The subscript drops
// 418/2048 of 10 pt, and its parenthesis reaches 250/1000 of 7 pt below its baseline:
// beyond the line's descent of 2 pt. Each other side keeps the room of the font's lines.
// The baselines lie on whole dots, so each distance is within a dot of its room.
let pt = |points: i64| points * Length::UNITS_PER_POINT;
let dots = |units: i64| f_office_units::div_round(units, DOT);
let rise = dots(f_office_units::div_round(pt(10) * 750, 2048)) * DOT;
let above = rise + pt(7) * 7 / 10 + pt(10) * 15 / 100 - pt(8);
let drop = dots(f_office_units::div_round(pt(10) * 418, 2048)) * DOT;
let below = drop + pt(7) / 4 - pt(2);
let (up, down) = distances(&superscript, ScriptRoom::Ink);
assert!(
(up - plain.0 - dots(above)).abs() <= 1,
"{up} {plain:?} {above}"
);
assert!((down - plain.1).abs() <= 1, "{down} {plain:?}");
let (up, down) = distances(&subscript, ScriptRoom::Ink);
assert!((up - plain.0).abs() <= 1, "{up} {plain:?}");
assert!(
(down - plain.1 - dots(below)).abs() <= 1,
"{down} {plain:?} {below}"
);
}
#[test]
fn an_inline_object_moves_with_its_raised_or_lowered_run_and_its_line_holds_it() {
use crate::ns::{A, WP, WPS};
// A shape 30 pt tall in a run raised by `half_points`, beside a letter of the fake font at
// 10 pt (8 pt above the baseline and 2 pt below it), above a paragraph of another letter:
// the baselines of both letters in device dots, and the top of the shape in units.
let laid = |half_points: i64| {
let body = format!(
r#"<w:p><w:r><w:rPr><w:position w:val="{half_points}"/></w:rPr><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="381000"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r><w:r><w:t>a</w:t></w:r></w:p>{}"#,
p("b")
);
let list = lay_out(&body, "", None);
(
find(&list, 'a').2,
find(&list, 'b').2,
testing::shape_top(&list),
)
};
// The test device has dots of 0.24 pt.
let six_points = 25;
let (a, b, top) = laid(0);
// Lowered by 6 pt, the shape reaches 24 pt above the baseline and 6 pt below it: the
// baseline rises by 6 pt, and the line ends at the shape's bottom, 2 pt above the plain
// line's end below the letter's descent. The shape stays where it was.
let (lowered_a, lowered_b, lowered_top) = laid(-12);
assert_eq!(lowered_a, a - six_points);
assert_eq!(lowered_b, b - 8);
assert_eq!(lowered_top, top);
// Lowered by 12 pt, the baseline rises by 12 pt, and the line still ends at the shape's
// bottom.
let (deeper_a, deeper_b, _) = laid(-24);
assert_eq!((deeper_a, deeper_b), (a - 2 * six_points, lowered_b));
// Raised by 6 pt, it reaches 36 pt above the baseline: the baseline and the next line go
// down by 6 pt, and the shape stays at the line's top.
let (raised_a, raised_b, raised_top) = laid(12);
assert_eq!(raised_a, a + six_points);
assert_eq!(raised_b, b + six_points);
assert_eq!(raised_top, top);
}
#[test]
fn a_lowered_object_in_multiple_spacing_keeps_the_extra_space_below_its_depth() {
use crate::ns::{A, WP, WPS};
// A shape 8 pt tall in a run lowered by `half_points`, beside a letter of the fake font at
// 10 pt (8 pt above the baseline and 2 pt below it), in a paragraph of spacing 1.5, above a
// paragraph of another letter: the baselines of both letters in device dots.
let laid = |half_points: i64| {
let body = format!(
r#"<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:position w:val="{half_points}"/></w:rPr><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="101600"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r><w:r><w:t>a</w:t></w:r></w:p>{}"#,
p("b")
);
let list = lay_out(&body, "", None);
(find(&list, 'a').2, find(&list, 'b').2)
};
// The test device has dots of 0.24 pt.
let six_points = 25;
let (a, b) = laid(0);
// Lowered by 8 pt, the shape reaches 6 pt below the letter's descent: the baseline stays,
// and the next line goes down by those 6 pt, as the half line of spacing 1.5 stays below
// the shape.
let (lowered_a, lowered_b) = laid(-16);
assert_eq!(lowered_a, a);
assert!((lowered_b - b - six_points).abs() <= 1, "{b} {lowered_b}");
}
/// A paragraph of automatic spacing `line` that holds an inline shape 10 pt wide and `height`
/// EMU tall, in a run lowered by `lowered` half-points where given, then the letter `letter` in a
/// run of its own where given.
fn shape_paragraph(line: u32, lowered: Option<i32>, height: i64, letter: Option<char>) -> String {
use crate::ns::{A, WP, WPS};
let run = lowered.map_or_else(String::new, |half_points| {
format!(r#"<w:rPr><w:position w:val="-{half_points}"/></w:rPr>"#)
});
let after = letter.map_or_else(String::new, |c| format!("<w:r><w:t>{c}</w:t></w:r>"));
format!(
r#"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr><w:r>{run}<w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="{height}"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>{after}</w:p>"#
)
}
/// The baselines of the letters `a` and `b` of `body` in device dots, laid out with the variant
/// `rule` of `ObjectAscent`, and with the part of a multiple spacing above single spacing below
/// the line's descent.
fn ascent_baselines(body: &str, rule: crate::quirks::ObjectAscent) -> (i64, i64) {
use crate::quirks::MultipleBaseline;
let target = testing::on_base_with(|p| {
p.with_variant(rule)
.with_variant(MultipleBaseline::DescentAboveExtra)
});
let list = testing::pass_with(body, (NORMAL, None), None, Numbering::default(), target);
(find(&list.list, 'a').2, find(&list.list, 'b').2)
}
#[test]
fn a_lowered_object_above_the_ascent_moves_the_baseline_where_the_target_counts_the_ascent() {
use crate::quirks::ObjectAscent::{Ascent, SingleLine};
// A shape 11.5 pt tall in a run lowered by 2 pt, beside a letter of the fake font at 10 pt
// (8 pt above the baseline and 2 pt below it), in a paragraph of automatic spacing `line`,
// above a paragraph of another letter: its part above the baseline, 9.5 pt, is taller than
// the letter's ascent and shorter than its single line of 10 pt.
let laid = |rule, line: u32| {
let body = format!(
"{}{}",
shape_paragraph(line, Some(4), 146_050, Some('a')),
p("b")
);
ascent_baselines(&body, rule)
};
// Counted against the ascent, the part puts the baseline 1.5 pt (6.25 dots of the test
// device) lower, and the next line goes 1.5 pt down too: in single spacing, and unscaled in
// spacing above it.
for line in [240, 276, 480] {
let (a, b) = laid(SingleLine, line);
let (counted_a, counted_b) = laid(Ascent, line);
assert!((counted_a - a - 6).abs() <= 1, "{line}: {a} {counted_a}");
assert!((counted_b - b - 6).abs() <= 1, "{line}: {b} {counted_b}");
}
}
#[test]
fn an_object_not_lowered_above_the_ascent_moves_the_baseline_where_the_target_counts_the_ascent() {
use crate::quirks::ObjectAscent::{Ascent, SingleLine};
// A shape 9.5 pt tall in a run that is not lowered, beside a letter of the fake font at
// 10 pt, in a paragraph of automatic spacing `line`, above a paragraph of another letter:
// the shape is taller than the letter's ascent and shorter than its single line.
let laid = |rule, line: u32| {
let body = format!(
"{}{}",
shape_paragraph(line, None, 120_650, Some('a')),
p("b")
);
ascent_baselines(&body, rule)
};
// Counted against the ascent, the shape moves both baselines 1.5 pt down, unscaled.
for line in [240, 276, 480] {
let (a, b) = laid(SingleLine, line);
let (counted_a, counted_b) = laid(Ascent, line);
assert!((counted_a - a - 6).abs() <= 1, "{line}: {a} {counted_a}");
assert!((counted_b - b - 6).abs() <= 1, "{line}: {b} {counted_b}");
}
}
#[test]
fn an_object_not_lowered_alone_on_its_line_keeps_the_single_line_where_the_target_counts_the_ascent()
{
use crate::quirks::ObjectAscent::{Ascent, SingleLine};
// The same shape alone in its paragraph, whose mark takes the fake font at 10 pt, between
// two paragraphs of a letter: the line of the shape does not grow on either variant.
for line in [240, 360, 480] {
let body = format!(
"{}{}{}",
p("a"),
shape_paragraph(line, None, 120_650, None),
p("b")
);
assert_eq!(
ascent_baselines(&body, SingleLine),
ascent_baselines(&body, Ascent),
"{line}"
);
}
}
#[test]
fn object_run_face_sizes_short_inline_objects_in_mode_15_only() {
use crate::ns::{A, WP, WPS};
use crate::quirks::ObjectLineMultiple::{Mark, ObjectRun};
let rect = |cy: i64| {
format!(
r#"<w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="{cy}"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing>"#
)
};
let layout_baselines =
|body: &str, variant: crate::quirks::ObjectLineMultiple, mode: Option<u32>| {
let target = testing::on_base_with(|p| p.with_variant(variant));
let pass = testing::pass_with(body, (NORMAL, mode), None, Numbering::default(), target);
(find(&pass.list, 'a').2, find(&pass.list, 'b').2)
};
// The fake font has single line equal to font size (ascent 80%, descent 20%).
// 1. Short object (4 pt = 50_800 EMU) alone in a 10 pt run under a 20 pt mark:
// mode 15 ObjectRun uses 10 pt; mode 14 and Mark use 20 pt.
let short_alone = format!(
r#"{}<w:p><w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr>{}</w:r></w:p>{}"#,
p("a"),
rect(50_800),
p("b")
);
let (a15, b15) = layout_baselines(&short_alone, ObjectRun, Some(15));
let (a14, b14) = layout_baselines(&short_alone, ObjectRun, Some(14));
let (amk, bmk) = layout_baselines(&short_alone, Mark, Some(15));
assert_eq!((a14, b14), (amk, bmk));
// 10 pt shorter on the 300 dpi (0.24 pt/dot) test device is ~41-42 dots.
assert!((b14 - b15 - 42).abs() <= 1, "{a15} {b15} vs {a14} {b14}");
// 2. Medium object (16 pt = 203_200 EMU) alone in a 10 pt run under a 20 pt mark:
// mode 15 ObjectRun uses 16 pt (4 pt shorter than 20 pt mark = ~16-17 dots).
let med_alone = format!(
r#"{}<w:p><w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr>{}</w:r></w:p>{}"#,
p("a"),
rect(203_200),
p("b")
);
let (_, b15_m) = layout_baselines(&med_alone, ObjectRun, Some(15));
let (_, b14_m) = layout_baselines(&med_alone, ObjectRun, Some(14));
assert!((b14_m - b15_m - 17).abs() <= 1, "{b15_m} vs {b14_m}");
// 3. Short object (4 pt) in a 20 pt run beside 10 pt text at 1.5x spacing:
// mode 15 ObjectRun expands the single line to 20 pt (30 pt at 1.5x) while keeping the
// 10 pt text descent (baseline 18 pt below top = 10 pt lower than mode 14's 8 pt).
let beside_text = format!(
r#"<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:t>a</w:t></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr>{}</w:r></w:p>{}"#,
rect(50_800),
p("b")
);
let (first_15, next_15) = layout_baselines(&beside_text, ObjectRun, Some(15));
let (first_14, next_14) = layout_baselines(&beside_text, ObjectRun, Some(14));
// Baseline moves down 10 pt (~42 dots); next line moves down 15 pt (30 - 15 = 15 pt ~ 62-63 dots).
assert!(
(first_15 - first_14 - 42).abs() <= 1,
"{first_15} vs {first_14}"
);
assert!(
(next_15 - next_14 - 63).abs() <= 1,
"{next_15} vs {next_14}"
);
}
#[test]
fn a_shifted_run_adds_its_shift_once_in_multiple_spacing_where_the_target_counts_it_once() {
use crate::quirks::RaisedRunSpacing::{Once, Scaled};
// A letter of the fake font at 10 pt (8 pt above the baseline and 2 pt below it) and one in
// a run raised or lowered by `half_points`, in a paragraph of spacing `line`, above a
// paragraph of another letter: the baselines of both letters in device dots.
let laid = |rule, line: u32, half_points: i32| {
let body = format!(
r#"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr><w:r><w:t>a</w:t></w:r><w:r><w:rPr><w:position w:val="{half_points}"/></w:rPr><w:t>c</w:t></w:r></w:p>{}"#,
p("b")
);
let target = testing::on_base_with(|p| p.with_variant(rule));
let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
(find(&list.list, 'a').2, find(&list.list, 'b').2)
};
// The test device has dots of 0.24 pt, so 3 pt are 12.5 dots.
for half_points in [6, -6] {
// In single spacing the variants agree.
assert_eq!(laid(Scaled, 240, half_points), laid(Once, 240, half_points));
// In double spacing, a raising or lowering of 3 pt comes twice when the spacing scales
// it and once when it does not: the first letter stays, and the next paragraph comes
// 3 pt higher.
let (a, b) = laid(Scaled, 480, half_points);
let (once_a, once_b) = laid(Once, 480, half_points);
assert_eq!(once_a, a, "{half_points}");
assert!((b - once_b - 12).abs() <= 1, "{half_points}: {b} {once_b}");
}
// A paragraph whose text is all lowered alike has no shift room: the variants agree.
let alike = |rule| {
let body = format!(
r#"<w:p><w:pPr><w:spacing w:line="480" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:position w:val="-6"/></w:rPr><w:t>ac</w:t></w:r></w:p>{}"#,
p("b")
);
let target = testing::on_base_with(|p| p.with_variant(rule));
let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
(find(&list.list, 'a').2, find(&list.list, 'b').2)
};
assert_eq!(alike(Scaled), alike(Once));
}
/// [`Fake`] fonts in which the family `Fake Deep` ascends 600 of the em's 1000 units and
/// descends 400: its single line is as tall as the others', and lies lower.
struct FakeDeep;
impl crate::Fonts for FakeDeep {
fn face(
&self,
family: &f_office_fonts::FamilyName,
bold: bool,
italic: bool,
) -> Option<crate::ChosenFace> {
let mut face = Fake.face(family, bold, italic)?;
if family.is("Fake Deep") {
face.font = f_office_fonts::FontId::from_index(face.font.index() + 4);
let metrics = &mut face.metrics;
(metrics.hhea_ascender, metrics.hhea_descender) = (600, -400);
(metrics.line_top, metrics.script_top, metrics.descent) = (600, 600, 400);
}
Some(face)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Fake.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Fake.advance(font, glyph)
}
}
#[test]
fn a_line_of_two_fonts_adds_its_face_room_once_in_multiple_spacing_where_the_target_counts_it_once()
{
use crate::quirks::FaceRoomSpacing::{Once, Scaled};
// A letter of the fake font at 10 pt (8 pt above the baseline and 2 pt below it) and one of
// `second` at 10 pt, in a paragraph of spacing `line`, above a paragraph of another letter:
// the baselines of both letters in device dots.
let laid = |rule, line: u32, second: &str| {
let body = format!(
r#"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr><w:r><w:t>a</w:t></w:r><w:r><w:rPr><w:rFonts w:ascii="{second}" w:hAnsi="{second}"/></w:rPr><w:t>c</w:t></w:r></w:p>{}"#,
p("b")
);
let (device, quirks) = testing::on_base_with(|p| p.with_variant(rule));
let target = (device, quirks, crate::layout::EarlierPass::default());
let fonts = (&FakeDeep as &dyn crate::Fonts, ShaperSettings::base());
let list = testing::pass_on(
&body,
(NORMAL, None),
None,
Numbering::default(),
target,
&fonts,
);
(find(&list.list, 'a').2, find(&list.list, 'b').2)
};
// The box of the two faces is 12 pt, 8 pt above the baseline and 4 pt below it, and the
// single line of each is 10 pt, so the face room is 2 pt. The test device has dots of
// 0.24 pt, so 2 pt are 8.33 dots.
// In single spacing the variants agree.
assert_eq!(laid(Scaled, 240, "Fake Deep"), laid(Once, 240, "Fake Deep"));
// In double spacing, the room comes twice when the spacing scales it and once when it does
// not: the first letter stays, and the next paragraph comes 2 pt higher.
let (a, b) = laid(Scaled, 480, "Fake Deep");
let (once_a, once_b) = laid(Once, 480, "Fake Deep");
assert_eq!(once_a, a);
assert!((b - once_b - 8).abs() <= 1, "{b} {once_b}");
// Two faces of one shape have no face room: the variants agree.
assert_eq!(laid(Scaled, 480, "Other"), laid(Once, 480, "Other"));
}
const MATH: &str = "http://schemas.openxmlformats.org/officeDocument/2006/math";
/// A math run of `text`.
fn math_run(text: &str) -> String {
format!("<m:r><m:t>{text}</m:t></m:r>")
}
/// The display list of a 10 pt line of text with the equation `equation`, with the fonts
/// `fonts`.
fn equation_list(equation: &str, fonts: &dyn crate::Fonts) -> DisplayList {
let body = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{MATH}">{equation}</m:oMath></w:p>"#
);
let (device, quirks) = testing::on_base();
let target = (device, quirks, crate::layout::EarlierPass::default());
let fonts = (fonts, ShaperSettings::base());
testing::pass_on(
&body,
("", None),
None,
Numbering::default(),
target,
&fonts,
)
.list
}
/// The glyph ID of the first root sign of a display list.
fn root_sign_glyph(list: &DisplayList) -> Option<u32> {
list.pages()[0]
.painted()
.into_iter()
.find_map(|item| match item {
f_office_paint::Painted::Glyphs(run) => run
.glyphs
.iter()
.find(|g| run.glyph_text(g).unwrap().starts_with('\u{221A}'))
.map(|g| g.id),
_ => None,
})
}
/// A length in whole points, in units.
fn points(points: i64) -> i64 {
points * Length::UNITS_PER_POINT
}
/// A length in units, to the nearest device dot.
fn nearest_dots(units: i64) -> i64 {
f_office_units::div_round(units, DOT)
}
#[test]
fn draws_a_root_sign_with_a_bar_over_its_element() {
let root = format!("<m:rad><m:e>{}</m:e></m:rad>", math_run("x"));
let list = equation_list(&root, &FakeMath);
// x's ink, from 0 to 7 pt, with the gap of 1 pt and the bar of 0.5 pt, needs 8.5 pt: the
// root sign's own glyph, 10 pt tall, draws.
assert_eq!(root_sign_glyph(&list), Some(0x221A));
// The bar runs from the end of the sign over x's advance, 5 pt, 0.5 pt thick, with its top
// at the top of the sign's ink, 7.5 pt above the sign's baseline. The rectangles' edges are
// in whole dots, down.
let (_, sign_x, sign_line) = find(&list, '\u{221A}');
let (_, x_at, _) = find(&list, '\u{1D465}');
assert_eq!(x_at, sign_x + points(5));
let [(left, top, width, height)] = testing::rects(&list, 0)[..] else {
panic!("not one bar");
};
assert_eq!((left, width), (x_at / DOT, points(5) / DOT));
assert_eq!(height, nearest_dots(points(1) / 2));
let bar_top = sign_line - nearest_dots(points(15) / 2);
assert!((top - bar_top).abs() <= 1, "{top} {bar_top}");
// The middle of the sign's ink, 2.5 pt above its baseline, lies the bar's thickness above
// the middle of the element's height, from 0 to 7 pt: the sign rises 1.5 pt.
let rise = find(&list, 'A').2 - sign_line;
assert!((rise - nearest_dots(points(3) / 2)).abs() <= 1, "{rise}");
}
#[test]
fn draws_a_taller_root_sign_over_a_fraction_and_raises_a_degree() {
let x = math_run("x");
let fraction = format!("<m:f><m:num>{x}</m:num><m:den>{x}</m:den></m:f>");
let over = equation_list(&format!("<m:rad><m:e>{fraction}</m:e></m:rad>"), &FakeMath);
assert!(matches!(root_sign_glyph(&over), Some(8000 | 8001)));
// A degree at 6 pt, 3 pt wide, rises to 60 % of the sign's ink height above its bottom,
// and the sign starts 3 pt left of the degree's end, at the degree's start.
let three = math_run("3");
let cube = format!("<m:rad><m:deg>{three}</m:deg><m:e>{x}</m:e></m:rad>");
let list = equation_list(&cube, &FakeMath);
let (_, three_x, three_line) = find(&list, '3');
let (_, sign_x, sign_line) = find(&list, '\u{221A}');
assert_eq!(sign_x, three_x);
let low = sign_line + nearest_dots(points(10) / 4);
let high = sign_line - nearest_dots(points(15) / 2);
let degree_line = low - (low - high) * 60 / 100;
assert!(
(three_line - degree_line).abs() <= 1,
"{three_line} {degree_line}"
);
}
#[test]
fn keeps_the_root_sign_in_a_font_without_the_radical_constants() {
let root = format!("<m:rad><m:e>{}</m:e></m:rad>", math_run("x"));
let plain = equation_list(&root, &testing::Fake);
assert_eq!(root_sign_glyph(&plain), Some(0x221A));
assert_eq!(testing::rects(&plain, 0), []);
}
#[test]
fn starts_scripts_by_the_corners_of_their_base_and_leaves_a_space_after_them() {
use testing::{FakeScripts, MATH_X};
let (x, two) = (math_run("x"), math_run("2"));
let plus = math_run("+");
let place = |structure: &str, fonts: &dyn crate::Fonts| {
let script = structure[1..].to_lowercase();
let equation = format!(
"<m:{structure}><m:e>{x}</m:e><m:{script}>{two}</m:{script}></m:{structure}>{plus}"
);
let list = equation_list(&equation, fonts);
let base = find(&list, MATH_X).1;
(find(&list, '2').1 - base, find(&list, '+').1 - base)
};
// How far the script and the plus sign after it move from their places in a font without
// the script values of a `MATH` table.
let moves = |structure: &str| {
let (start, after) = place(structure, &FakeScripts);
let (plain_start, plain_after) = place(structure, &FakeMath);
(start - plain_start, after - plain_after)
};
let near =
|found: i64, expected: i64| assert!((found - expected).abs() <= DOT, "{found} {expected}");
// At 10 pt, a superscript starts after x's italic correction, 1 pt, and its top right
// kern, 0.5 pt; a subscript starts x's bottom right kern at the subscript's ink top, 1 pt,
// to the left, the larger of that and the 3 pt at x's ink bottom. The space after the
// script, 2 pt, comes before the plus sign.
let (start, after) = moves("sSup");
near(start, points(3) / 2);
near(after, points(3) / 2 + points(2));
let (start, after) = moves("sSub");
near(start, -points(1));
near(after, -points(1) + points(2));
}
#[test]
fn ends_a_script_after_the_italic_correction_of_its_last_glyph() {
use testing::{FakeScripts, MATH_X};
// x to the power of x, and x to the power of 2, each followed by a plus sign: the glyphs
// of x and 2 have the same advance, and only x has an italic correction, 100 units.
// The step from the script's start to the plus sign, and the script's size.
let step = |script: &str, glyph: char| {
let equation = format!(
"<m:sSup><m:e>{}</m:e><m:sup>{}</m:sup></m:sSup>{}",
math_run("x"),
math_run(script),
math_run("+")
);
let list = equation_list(&equation, &FakeScripts);
let start = find_all(&list, glyph).last().unwrap().1;
let size = list.pages()[0]
.painted()
.iter()
.rev()
.find_map(|item| match item {
Painted::Glyphs(run) if run.text.starts_with(glyph) => Some(run.size),
_ => None,
})
.unwrap();
(find(&list, '+').1 - start, size)
};
let ((slanted, size), (upright, _)) = (step("x", MATH_X), step("2", '2'));
let italic = size.units() / 10;
assert!(
(slanted - upright - italic).abs() <= DOT,
"{slanted} {upright} {italic}"
);
}
#[test]
fn ends_a_bar_and_a_root_past_the_italic_correction_that_a_subscript_on_an_overbar_gives_back() {
use testing::{FakeScripts, MATH_X};
let x = math_run("x");
let bar = format!("<m:bar><m:barPr><m:pos m:val=\"top\"/></m:barPr><m:e>{x}</m:e></m:bar>");
let root =
format!("<m:rad><m:radPr><m:degHide m:val=\"1\"/></m:radPr><m:deg/><m:e>{x}</m:e></m:rad>");
// The step from the first x to the first glyph `ch` after it.
let step = |equation: &str, ch: char| {
let list = equation_list(equation, &FakeScripts);
let from = find_all(&list, MATH_X)[0].1;
let to = find_all(&list, ch)
.into_iter()
.map(|(_, x, _)| x)
.find(|&at| at > from)
.unwrap();
to - from
};
// x's italic correction, a tenth of its size: an x after a plain x stands at its advance,
// and one after a bar or a root over x at the bar's end, past the correction.
let size = equation_list(&x, &FakeScripts).pages()[0]
.painted()
.iter()
.find_map(|item| match item {
Painted::Glyphs(run) => Some(run.size),
_ => None,
})
.unwrap();
let italic = size.units() / 10;
let plain = step(&format!("{x}{x}"), MATH_X);
for structure in [&bar, &root] {
let after = step(&format!("{structure}{x}"), MATH_X);
assert!(
(after - plain - italic).abs() <= DOT,
"{after} {plain} {italic}"
);
}
// A subscript on a bar over x starts at x's advance, a superscript at the bar's end; on a
// root both start at the bar's end.
let script = |base: &str, kind: &str, side: &str| {
step(
&format!(
"<m:{kind}><m:e>{base}</m:e><m:{side}>{}</m:{side}></m:{kind}>",
math_run("2")
),
'2',
)
};
let (sub, sup) = (script(&bar, "sSub", "sub"), script(&bar, "sSup", "sup"));
assert!((sup - sub - italic).abs() <= DOT, "{sup} {sub} {italic}");
let (sub, sup) = (script(&root, "sSub", "sub"), script(&root, "sSup", "sup"));
assert!((sup - sub).abs() <= DOT, "{sup} {sub}");
// Scripts on an underbar under x start where they start on x alone, by x's corners.
let under = bar.replace("top", "bot");
for (kind, side) in [("sSub", "sub"), ("sSup", "sup")] {
let (on_bar, alone) = (script(&under, kind, side), script(&x, kind, side));
assert!((on_bar - alone).abs() <= DOT, "{kind} {on_bar} {alone}");
}
}
#[test]
fn keeps_the_italic_correction_before_a_digit_that_starts_the_next_math_run() {
use testing::{FakeScripts, MATH_X};
let step = |equation: &str| {
let list = equation_list(equation, &FakeScripts);
find_all(&list, '2')[0].1 - find_all(&list, MATH_X)[0].1
};
let plain = step(&math_run("x2"));
// Two runs of the same properties, measured as one text, keep x's correction between them.
let joined = step(&format!("{}{}", math_run("x"), math_run("2")));
assert!(joined - plain > DOT, "{joined} {plain}");
}
#[test]
fn a_later_column_on_half_a_dot_takes_the_dot_of_its_parts_before_mode_15() {
// quirk: ColumnEdgeHalves::ColumnParts (src/quirks.rs)
use crate::quirks::ColumnEdgeHalves::{self, ColumnParts, WholeEdge};
use crate::quirks::{ColumnWidths, LineStartHalves};
// Two columns of 4,104 twips, 1,027 apart, from a left margin of 1,127 twips: the second
// column's edge, 6,258 twips, is 2,607.5 dots. Its parts, the margin and the first
// column's width with its space (5,131 twips), each round up in 1/65536 pt, so their sum
// takes dot 2,608; the whole edge rounds down and takes dot 2,607.
let body = r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:br w:type="column"/><w:t>B</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1878" w:bottom="1440" w:left="1127" w:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="2" w:space="1027"/></w:sectPr>"#;
let dots = |edge: ColumnEdgeHalves, mode, ch| {
let target = crate::layout::testing::target_at(600, |p| {
p.with_variant(LineStartHalves::FixedPoint)
.with_variant(ColumnWidths::WholeTwips)
.with_variant(edge)
});
let device = target.0;
let pass = testing::pass_with(body, ("", Some(mode)), None, Numbering::default(), target);
let (page, x, _) = find(&pass.list, ch);
(page, x / device.dots(1).units(), x % device.dots(1).units())
};
for mode in [11, 12, 14] {
assert_eq!(dots(ColumnParts, mode, 'B'), (0, 2_608, 0));
}
assert_eq!(dots(ColumnParts, 15, 'B'), (0, 2_607, 0));
assert_eq!(dots(WholeEdge, 14, 'B'), (0, 2_607, 0));
// The first column's edge, the margin alone, takes the same dot under both variants.
assert_eq!(dots(ColumnParts, 14, 'A'), dots(WholeEdge, 14, 'A'));
}
#[test]
fn lays_out_a_text_box_s_text_in_one_column_whatever_the_section_s_columns() {
// quirk: TextBoxColumns::OneColumn (src/quirks.rs)
use crate::quirks::TextBoxColumns::{self, OneColumn, SectionColumns};
// A box 200 pt wide at the margin's corner with a right-aligned letter: in one column the
// letter ends at the right of the box's text area; in the first of the section's columns
// it ends further left.
let shape = AnchoredShape {
across: ("margin", 0),
down: ("margin", 0),
size: (2_540_000, 1_270_000),
wrap: "<wp:wrapNone/>",
outline: None,
text: Some(ShapeText {
blocks: r#"<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>R</w:t></w:r></w:p>"#,
body: "<wps:bodyPr/>",
}),
};
let x = |variant: TextBoxColumns, columns: u32| {
let body = format!(
r#"<w:p><w:r>{}</w:r></w:p><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:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="{columns}" w:space="720"/></w:sectPr>"#,
shape.drawing()
);
let target = testing::on_base_with(|p| p.with_variant(variant));
let pass = testing::pass_with(&body, ("", None), None, Numbering::default(), target);
find(&pass.list, 'R').1
};
assert_eq!(x(OneColumn, 2), x(OneColumn, 1));
assert_eq!(x(OneColumn, 3), x(OneColumn, 1));
assert!(x(SectionColumns, 2) < x(SectionColumns, 1));
assert_eq!(x(SectionColumns, 1), x(OneColumn, 1));
}
#[test]
fn lays_the_columns_of_a_right_to_left_section_out_from_the_right_margin() {
// quirk: RightToLeftSectionColumns::FromRight (src/quirks.rs)
use crate::quirks::RightToLeftSectionColumns::{self, FromLeft, FromRight};
// Two equal columns of 4,320 twips with 720 between them on a text area from 1,440 to
// 10,800 twips: the letter A of the first column, then B after a column break.
let x = |variant: RightToLeftSectionColumns, bidi: &str, letter: char| {
let body = format!(
r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:br w:type="column"/><w:t>B</w:t></w:r></w:p><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:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="2" w:space="720"/>{bidi}</w:sectPr>"#
);
let target = testing::on_base_with(|p| p.with_variant(variant));
let pass = testing::pass_with(&body, ("", None), None, Numbering::default(), target);
find(&pass.list, letter).1
};
let twips = |t: i64| t * Length::UNITS_PER_TWIP;
let near = |a: i64, b: i64| (a - b).abs() <= Length::UNITS_PER_POINT;
assert!(near(x(FromRight, "<w:bidi/>", 'A'), twips(6_480)));
assert!(near(x(FromRight, "<w:bidi/>", 'B'), twips(1_440)));
assert_eq!(x(FromLeft, "<w:bidi/>", 'A'), x(FromRight, "", 'A'));
assert!(near(x(FromRight, "", 'B'), twips(6_480)));
}
#[test]
fn gives_a_hidden_paragraphs_border_to_the_shaded_paragraph_after_it_from_mode_15() {
// quirk: HiddenMarkBorders::ByMode (src/quirks.rs)
use crate::quirks::HiddenMarkBorders::{self, ByMode, Dropped};
use f_office_paint::{Item, Rgb};
// A paragraph of hidden text with a hidden mark and a bottom border of 0.75 pt with 1 pt of
// space, before a paragraph that shows text, shaded or plain.
let hidden = r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="000000"/></w:pBdr><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 black_lines = |variant: HiddenMarkBorders, mode: u32, shaded: bool| {
let shading = if shaded {
r#"<w:pPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:pPr>"#
} else {
""
};
let body = format!(
"<w:p><w:r><w:t>A</w:t></w:r></w:p>{hidden}<w:p>{shading}<w:r><w:t>B</w:t></w:r></w:p><w:p><w:r><w:t>C</w:t></w:r></w:p>"
);
let target = testing::target_at(600, |p| p.with_variant(variant));
let pass = testing::pass_with(&body, ("", Some(mode)), None, Numbering::default(), target);
pass.list.pages()[0]
.items()
.iter()
.filter(|item| matches!(item, Item::Rect(r) if r.color == Rgb::BLACK))
.count()
};
assert_eq!(black_lines(ByMode, 15, true), 1);
// Before mode 15, before a plain paragraph and where the target drops the borders: none.
assert_eq!(black_lines(ByMode, 14, true), 0);
assert_eq!(black_lines(ByMode, 15, false), 0);
assert_eq!(black_lines(Dropped, 15, true), 0);
}
#[test]
fn draws_the_line_between_two_columns_that_hold_text_where_the_target_draws_it() {
// quirk: ColumnSeparator::SpaceMiddle (src/quirks.rs)
use crate::quirks::ColumnSeparator::{self, NotDrawn, SpaceMiddle};
use f_office_paint::Item;
// Two equal columns of 4,320 twips with 720 between them on a text area from 1,440 to
// 10,800 twips: the space's middle lies at 6,120 twips, dot 2,550 at 600 dots per inch.
// The first column holds two lines of exactly 14 pt and the second, after a column break
// at the end of the second line, one; without the break, the first column holds all three.
let exact =
r#"<w:pPr><w:spacing w:before="0" w:after="0" w:line="280" w:lineRule="exact"/></w:pPr>"#;
let rects = |variant: ColumnSeparator, sep: &str, broken: bool| {
let column_break = if broken {
r#"<w:br w:type="column"/>"#
} else {
""
};
let body = format!(
r#"<w:p>{exact}<w:r><w:t>A</w:t></w:r></w:p><w:p>{exact}<w:r><w:t>A</w:t>{column_break}</w:r></w:p><w:p>{exact}<w:r><w:t>B</w:t></w:r></w:p><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:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="2" w:space="720"{sep}/></w:sectPr>"#
);
let target = testing::target_at(600, |p| p.with_variant(variant));
let dot = target.0.dots(1).units();
let pass = testing::pass_with(&body, ("", Some(15)), None, Numbering::default(), target);
pass.list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Rect(r) => Some([r.x, r.y, r.width, r.height].map(|v| v.units() / dot)),
Item::Glyphs(_)
| Item::Path(_)
| Item::Gradient(_)
| Item::Image(_)
| Item::Group(_) => None,
})
.collect::<Vec<_>>()
};
let sep = r#" w:sep="1""#;
// Six dots wide from three dots left of the middle, from the top margin, dot 600, to the
// dot nearest to the bottom of the first column's second line, 100 pt.
assert_eq!(rects(SpaceMiddle, sep, true), [[2_547, 600, 6, 233]]);
let none: [[i64; 4]; 0] = [];
assert_eq!(rects(NotDrawn, sep, true), none);
assert_eq!(rects(SpaceMiddle, "", true), none);
// The second column holds no text: no line.
assert_eq!(rects(SpaceMiddle, sep, false), none);
}
#[test]
fn a_line_at_a_wrap_edge_takes_the_dot_of_the_edge_on_a_target_that_counts_from_it() {
// quirk: WrapEdgeDot::WrapEdge (src/quirks.rs)
use crate::quirks::WrapEdgeDot::{self, ColumnAndDistance, WrapEdge};
// A left margin of 1,208 twips, 503.33 dots, and a box with square wrap from it, 692 twips
// wide, so its wrap edge lies at 1,900 twips, 791.67 dots: the line beside it takes dot 792
// from the edge as one length, and dot 503 plus dot 288 from the column's edge and the
// distance. The line below the box starts at the margin's dot under both.
let shape = AnchoredShape {
across: ("margin", 0),
down: ("margin", 0),
size: (439_420, 457_200),
wrap: testing::SQUARE_WRAP,
outline: None,
text: None,
};
let body = format!(
r#"<w:p><w:r>{}</w:r><w:r><w:t>W</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:before="1440"/></w:pPr><w:r><w:t>K</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1208" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#,
shape.drawing()
);
let dots = |variant: WrapEdgeDot, ch| {
let target = crate::layout::testing::target_at(600, |p| p.with_variant(variant));
let device = target.0;
let pass = testing::pass_with(&body, ("", Some(15)), None, Numbering::default(), target);
let (page, x, _) = find(&pass.list, ch);
(page, x / device.dots(1).units())
};
assert_eq!(dots(WrapEdge, 'W'), (0, 792));
assert_eq!(dots(ColumnAndDistance, 'W'), (0, 791));
assert_eq!(dots(WrapEdge, 'K'), (0, 503));
assert_eq!(dots(ColumnAndDistance, 'K'), (0, 503));
}
#[test]
fn a_line_beside_a_drawing_on_its_left_keeps_only_a_first_line_indent_past_the_wrap_edge() {
// Two paragraphs with a left indent of 720 twips, each anchoring at its top a box with
// square wrap from the margin (1,440 twips), 1,440 twips wide, so the wrap edge lies at
// 2,880 twips, dot 1,200: the first with a first-line indent of 360 twips, the second, on
// the next page, with a hanging indent of 360 twips, each with a line break. The first line
// of the first starts at the wrap edge plus its first-line indent, dot 1,350; every other
// line beside a box starts at the wrap edge. With the indents counted past the wrap edge,
// they would start at dots 1,650, 1,500, 1,350 and 1,500.
let shape = AnchoredShape {
across: ("margin", 0),
down: ("paragraph", 0),
size: (914_400, 457_200),
wrap: testing::SQUARE_WRAP,
outline: None,
text: None,
};
let drawing = shape.drawing();
let body = format!(
r#"<w:p><w:pPr><w:ind w:left="720" w:firstLine="360"/></w:pPr><w:r>{drawing}</w:r><w:r><w:t>W</w:t><w:br/><w:t>K</w:t></w:r></w:p><w:p><w:pPr><w:pageBreakBefore/><w:ind w:left="720" w:hanging="360"/></w:pPr><w:r>{drawing}</w:r><w:r><w:t>V</w:t><w:br/><w:t>Z</w:t></w:r></w:p><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:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#
);
assert_eq!(
dots_at_600(&body, &['W', 'K', 'V', 'Z']),
[(0, 1_350), (0, 1_200), (1, 1_200), (1, 1_200)]
);
}
#[test]
fn a_line_beside_a_frame_on_its_left_keeps_its_whole_start_past_the_wrap_edge() {
// A frame of 2,880 twips from the page's left edge, with text around it, and a paragraph
// beside it with a left indent of 720 twips, a first-line indent of 360 twips and a line
// break: the frame's wrap edge lies at 2,880 twips, dot 1,200, and each line keeps its whole
// start past it, the first line dot 1,650 and the second dot 1,500, unlike a line beside a
// drawing.
let body = r#"<w:p><w:pPr><w:framePr w:w="2880" w:h="1440" w:hRule="exact" w:wrap="around" w:vAnchor="text" w:hAnchor="page" w:x="0" w:y="0"/></w:pPr><w:r><w:t>F</w:t></w:r></w:p><w:p><w:pPr><w:ind w:left="720" w:firstLine="360"/></w:pPr><w:r><w:t>W</w:t><w:br/><w:t>K</w:t></w:r></w:p><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:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#;
assert_eq!(dots_at_600(body, &['W', 'K']), [(0, 1_650), (0, 1_500)]);
}
/// The page and the dot from the page's left edge of the first glyph of each of `chars` in
/// `body`, laid out for the target's profile at 600 dots an inch.
fn dots_at_600(body: &str, chars: &[char]) -> Vec<(usize, i64)> {
let target = testing::target_at(600, crate::profile::Profile::clone);
let dot = target.0.dots(1).units();
let pass = testing::pass_with(body, ("", Some(15)), None, Numbering::default(), target);
chars
.iter()
.map(|&ch| {
let (page, x, _) = find(&pass.list, ch);
(page, x / dot)
})
.collect()
}
/// The top and the height of a box in the middle of a Letter page, beside lines 15 to 32, in
/// points from the page's top edge.
const MIDDLE_BOX: (i64, i64) = (246, 200);
/// The top and the height of a box whose bottom lies between the tops of the last two lines
/// of a Letter page, so that only the page's last line has the column's whole width below it.
const FOOT_BOX: (i64, i64) = (450, 252);
/// The lines on each page of one paragraph of `words` words "x" on lines of exactly 12 pt,
/// beside a box with a square wrap at `place` (its top and height in points) on a Letter page,
/// half the column wide, under the widow forecast `variant`.
fn lines_beside_a_box(
variant: crate::quirks::WidowForecast,
place: (i64, i64),
words: usize,
) -> Vec<usize> {
const EMU_PER_PT: i64 = 12_700;
let (top, height) = place;
let shape = AnchoredShape {
across: ("page", 300 * EMU_PER_PT),
down: ("page", top * EMU_PER_PT),
size: (300 * EMU_PER_PT, height * EMU_PER_PT),
wrap: testing::SQUARE_WRAP,
outline: None,
text: None,
};
let body = format!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r>{}</w:r><w:r><w:t xml:space="preserve">{}</w:t></w:r></w:p><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:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#,
shape.drawing(),
"x ".repeat(words)
);
let target = testing::target_at(600, |p| p.with_variant(variant));
let pass = testing::pass_with(&body, ("", Some(15)), None, Numbering::default(), target);
let lines: std::collections::BTreeSet<(usize, i64)> = find_all(&pass.list, 'x')
.into_iter()
.map(|(page, _, y)| (page, y))
.collect();
let mut pages = Vec::new();
for (page, _) in lines {
pages.resize(pages.len().max(page + 1), 0);
if let Some(count) = pages.get_mut(page) {
*count += 1;
}
}
pages
}
/// The most words of [`lines_beside_a_box`] that fit on page 1 beside the box at `place` under
/// the forecast at the column's whole width, and one more.
fn words_at_the_page_end(place: (i64, i64)) -> (usize, usize) {
use crate::quirks::WidowForecast::WholeWidth;
let (mut fits, mut over) = (1, 6_000);
assert_eq!(lines_beside_a_box(WholeWidth, place, fits).len(), 1);
assert!(lines_beside_a_box(WholeWidth, place, over).len() > 1);
while over - fits > 1 {
let words = usize::midpoint(fits, over);
if lines_beside_a_box(WholeWidth, place, words).len() == 1 {
fits = words;
} else {
over = words;
}
}
(fits, over)
}
#[test]
fn moves_the_line_before_a_last_line_that_a_wrap_pushes_alone_to_the_next_page_where_the_target_counts_wrapped_lines()
{
// quirk: WidowForecast::AsWrapped (src/quirks.rs)
use crate::quirks::WidowForecast::{AsWrapped, WholeWidth};
// The fewest words that reach page 2 beside the box: at the column's whole width they
// would fit on page 1, so the forecast of the paragraph's start finds no widow break.
let (fits, over) = words_at_the_page_end(MIDDLE_BOX);
let whole = lines_beside_a_box(WholeWidth, MIDDLE_BOX, over);
let wrapped = lines_beside_a_box(AsWrapped, MIDDLE_BOX, over);
// The last line goes alone to page 2 under the forecast at the whole width; counted as the
// box breaks the lines, the line before it goes with it.
assert_eq!(whole.get(1), Some(&1));
assert_eq!(
wrapped,
vec![whole.first().copied().unwrap_or_default() - 1, 2]
);
// One word fewer fits on page 1 under both.
assert_eq!(lines_beside_a_box(AsWrapped, MIDDLE_BOX, fits).len(), 1);
}
#[test]
fn keeps_on_the_page_a_paragraph_whose_forecast_line_breaks_again_below_the_box_where_the_target_counts_wrapped_lines()
{
// quirk: WidowForecast::AsWrapped (src/quirks.rs)
use crate::quirks::WidowForecast::AsWrapped;
// Beside the box, the paragraph's narrow lines would put its last line alone on page 2,
// but the line before it stands below the box and breaks again at the column's whole
// width, where the paragraph fits on page 1: every paragraph that fits there under the
// forecast at the whole width fits there as the box breaks its lines too.
let (fits, _) = words_at_the_page_end(FOOT_BOX);
for words in fits.saturating_sub(60)..=fits {
assert_eq!(
lines_beside_a_box(AsWrapped, FOOT_BOX, words).len(),
1,
"{words} words"
);
}
}
/// Whether `a` and `b` have one length and their numbers differ by at most one each.
fn within_one(a: &[i64], b: &[i64]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1)
}
fn narrow_wrap_anchor(x_pt: i64, width_pt: i64) -> String {
const EMU_PER_PT: i64 = 12_700;
let shape = AnchoredShape {
across: ("column", x_pt * EMU_PER_PT),
down: ("paragraph", 0),
size: (width_pt * EMU_PER_PT, 48 * EMU_PER_PT),
wrap: testing::SQUARE_WRAP,
outline: None,
text: None,
};
format!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="20" w:lineRule="exact"/></w:pPr><w:r>{}</w:r></w:p>"#,
shape.drawing()
)
}
fn read_test_numbering(inner: &str) -> Numbering {
let xml = format!(r#"<w:numbering xmlns:w="{W}">{inner}</w:numbering>"#);
let doc = parse(&xml);
Numbering::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::ReaderSettings::base(),
)
}
const LETTER_ONE_INCH_SECT: &str = 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:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#;
#[test]
fn list_label_beside_narrow_wrap_moves_below_unless_empty() {
let numbering = read_test_numbering(
r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum>
<w:abstractNum w:abstractNumId="2"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:suff w:val="space"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>
<w:num w:numId="2"><w:abstractNumId w:val="2"/></w:num>"#,
);
let anchor = narrow_wrap_anchor(0, 444);
for num_id in [1, 2] {
let body = format!(
r#"{anchor}<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="{num_id}"/></w:numPr></w:pPr><w:r><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
);
let pass = testing::pass_with(
&body,
("", Some(15)),
None,
numbering.clone(),
testing::on_base(),
);
let (_, lx, ly) = find(&pass.list, '1');
let (_, bx, by) = find(&pass.list, 'S');
assert_eq!(ly, by, "num_id={num_id}: label and body share one baseline");
assert!(lx < bx && lx < Length::from_points(120).unwrap().units());
}
let empty = format!(
r#"{anchor}<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr></w:p>{LETTER_ONE_INCH_SECT}"#
);
let pass = testing::pass_with(&empty, ("", Some(15)), None, numbering, testing::on_base());
assert!(find(&pass.list, '1').1 > Length::from_points(500).unwrap().units());
}
#[test]
fn leading_tab_and_middle_wrap_list_label_do_not_orphan_prefix() {
let anchor = narrow_wrap_anchor(0, 444);
let tabbed = format!(
"{anchor}<w:p><w:r><w:tab/><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"
);
let pass = testing::pass_with(
&tabbed,
("", Some(15)),
None,
Numbering::default(),
testing::on_base(),
);
let (_, sx, sy) = find(&pass.list, 'S');
assert!(sy * DOT > Length::from_points(120).unwrap().units());
assert!(
sx >= Length::from_points(107).unwrap().units()
&& sx <= Length::from_points(109).unwrap().units()
);
let mid_numbering = read_test_numbering(
r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="0" w:hanging="0"/></w:pPr></w:lvl></w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>"#,
);
let mid_body = format!(
r#"{}<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#,
narrow_wrap_anchor(24, 180)
);
let pass = testing::pass_with(
&mid_body,
("", Some(15)),
None,
mid_numbering,
testing::on_base(),
);
let (_, lx, ly) = find(&pass.list, '1');
let (_, bx, by) = find(&pass.list, 'S');
assert_eq!(ly, by);
assert!(ly * DOT < Length::from_points(110).unwrap().units());
assert!(lx > Length::from_points(270).unwrap().units() && bx > lx);
}
#[test]
fn leading_spaces_and_first_of_two_tabs_stay_beside_narrow_wrap() {
let anchor = narrow_wrap_anchor(0, 444);
let spaced = format!(
r#"{anchor}<w:p><w:r><w:t xml:space="preserve"> Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
);
let pass = testing::pass_with(
&spaced,
("", Some(15)),
None,
Numbering::default(),
testing::on_base(),
);
let (_, sx, sy) = find(&pass.list, 'S');
assert!(sy * DOT > Length::from_points(120).unwrap().units());
assert!(
sx >= Length::from_points(71).unwrap().units()
&& sx <= Length::from_points(73).unwrap().units()
);
let two_tabs = format!(
"{anchor}<w:p><w:r><w:tab/><w:tab/><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"
);
let pass = testing::pass_with(
&two_tabs,
("", Some(15)),
None,
Numbering::default(),
testing::on_base(),
);
let (_, tx, ty) = find(&pass.list, 'S');
assert!(ty * DOT > Length::from_points(120).unwrap().units());
assert!(
tx >= Length::from_points(107).unwrap().units()
&& tx <= Length::from_points(109).unwrap().units()
);
}