//! Tests of the line, paragraph and measuring rules of the layout.
use super::line::draw::{Drawn, drawn_x};
use super::line::height::{
BoxTop, FromBottom, LineBox, SpaceBefore, Ties, below_text, boxed_baseline,
holds_glyph_besides_white_space, line_box, placed_baseline, placed_baseline_and_form,
text_baseline, text_below_object, text_end, twips_rest,
};
use super::line::shift::{
MarkSides, Shift, SpaceShares, aligned_as_last, compressed_marks, inner_mark_shrink_before,
shift, spread_over_gaps,
};
use super::measure::{
JUSTIFIED_SHRINK, WORD_PERFECT_SHRINK, place_in_paragraph, shrink, spaces_beside_east_asian,
};
use super::paragraph::{Previous, gap, holds_glyph_besides_ascii_space};
use super::testing::plain_line_box;
use crate::grid::{DOT, base_device};
use crate::lines::{Line, Piece, Placed, Shrink};
use crate::mode::{CompatibilityMode, ModeRules};
use crate::props::{Alignment, LineSpacing, ListRef, ParaProps};
use crate::styles::Justification;
use crate::text::{FaceIndex, Glyph};
use f_office_units::Length;
#[test]
fn leaves_out_automatic_space_between_paragraphs_of_one_list() {
let pt = |n: i64| Length::from_units(n * 25_400);
// 5 pt written, 14 pt automatic, in list `list`.
let auto = |list: Option<u32>| ParaProps {
before: Some(pt(5)),
after: Some(pt(5)),
before_auto: Some(true),
after_auto: Some(true),
numbering: list.map(ListRef::of),
..ParaProps::default()
};
let gap_between = |a: Option<u32>, b: Option<u32>| {
gap(Some(&Previous::of(&auto(a))), &auto(b)).units() / 25_400
};
assert_eq!(gap_between(Some(1), Some(1)), 0);
assert_eq!(gap_between(Some(1), Some(2)), 14);
assert_eq!(gap_between(None, Some(1)), 14);
assert_eq!(gap_between(Some(1), None), 14);
assert_eq!(gap_between(Some(0), Some(0)), 14);
// Written space stays between items of one list.
let written = ParaProps {
after: Some(pt(5)),
numbering: Some(ListRef::of(1)),
..ParaProps::default()
};
assert_eq!(
gap(Some(&Previous::of(&written)), &written).units() / 25_400,
5
);
}
#[test]
fn adds_and_keeps_every_space_in_the_fixed_reading() {
use crate::props::HtmlAutoSpacing;
let pt = |n: i64| Length::from_units(n * 25_400);
let fixed = |props: ParaProps| ParaProps {
html_auto_spacing: Some(HtmlAutoSpacing::Fixed),
..props
};
let auto = |list: Option<u32>| {
fixed(ParaProps {
before_auto: Some(true),
after_auto: Some(true),
numbering: list.map(ListRef::of),
..ParaProps::default()
})
};
let between = |a: &ParaProps, b: &ParaProps| gap(Some(&Previous::of(a)), b).units() / 25_400;
// 5 pt after and 5 pt before add, also between two paragraphs of one list.
assert_eq!(between(&auto(Some(1)), &auto(Some(1))), 10);
assert_eq!(between(&auto(None), &auto(None)), 10);
let none = fixed(ParaProps::default());
assert_eq!(between(&auto(None), &none), 5);
// Written and automatic spaces add too.
let written = |before: i64, after: i64| {
fixed(ParaProps {
before: Some(pt(before)),
after: Some(pt(after)),
..ParaProps::default()
})
};
assert_eq!(between(&auto(None), &written(12, 0)), 17);
assert_eq!(between(&written(0, 6), &written(6, 0)), 12);
}
#[test]
fn keeps_a_space_after_at_a_cell_end_where_the_paragraph_or_the_reading_says_so() {
use crate::props::HtmlAutoSpacing;
use crate::quirks::CellEndListSpace::{Dropped, Kept};
let auto = |list: Option<u32>, reading: HtmlAutoSpacing| {
Previous::of(&ParaProps {
after_auto: Some(true),
numbering: list.map(ListRef::of),
html_auto_spacing: Some(reading),
..ParaProps::default()
})
};
let quirks =
|list_space| crate::layout::testing::on_base_with(|p| p.with_variant(list_space)).1;
let (kept, dropped) = (&quirks(Kept), &quirks(Dropped));
let item = auto(Some(1), HtmlAutoSpacing::Html);
assert!(item.keeps_after_at_cell_end(kept));
assert!(!item.keeps_after_at_cell_end(dropped));
assert!(!auto(None, HtmlAutoSpacing::Html).keeps_after_at_cell_end(kept));
assert!(auto(None, HtmlAutoSpacing::Fixed).keeps_after_at_cell_end(dropped));
let written = Previous::of(&ParaProps {
after: Length::from_twips(100),
..ParaProps::default()
});
assert!(written.keeps_after_at_cell_end(dropped));
}
#[test]
fn line_boxes() {
// Whole device dots, so that the rounding of the text baseline changes nothing.
let u = |n: i64| Length::from_units(n * DOT);
let exact = |h: i64| LineSpacing::Exact(u(h));
let at_least = |h: i64| LineSpacing::AtLeast(u(h));
// An excess of 200 is an object 300 tall on a text line of 100: the spacing scales
// only the text, and with automatic spacing, or a smaller minimum, the object's top is at
// the line top and its bottom on the baseline. A larger minimum keeps the baseline one
// descent above the bottom. An exact height puts the baseline four fifths of the way
// down, whatever the font.
// Below single spacing, the line loses height above and below the text in the ratio of
// its ascent and descent.
let cases = [
(LineSpacing::Auto(240), 0, (100, 80)),
(LineSpacing::Auto(360), 0, (150, 80)),
(LineSpacing::Auto(180), 0, (75, 60)),
(exact(60), 0, (60, 48)),
(exact(150), 0, (150, 120)),
(at_least(60), 0, (100, 80)),
(at_least(130), 0, (130, 110)),
(LineSpacing::Auto(240), 200, (300, 300)),
(LineSpacing::Auto(360), 200, (350, 300)),
(exact(60), 200, (60, 48)),
(at_least(130), 200, (300, 300)),
(at_least(400), 200, (400, 380)),
];
for (rule, excess, (height, baseline)) in cases {
assert_eq!(
line_box(
&base_device(),
(u(80), u(20), Length::ZERO),
rule,
(u(excess), false)
),
(u(height), u(baseline)),
"{rule:?} {excess}"
);
}
}
#[test]
fn space_after_puts_a_single_line_s_baseline_at_its_rounded_ascent() {
// Times New Roman 12 pt: the cut descent gives 46 units, and on the last line of a
// paragraph with space after, the rounded ascent of 46.68 units gives 47. The height
// stays the single line, and an at-least minimum below it does the same.
let at_12_pt = |units: i64| Length::from_units(units * 304_800 / 2048);
let dots = |n: i64| Length::from_units(n * DOT);
let metrics = (at_12_pt(1912), at_12_pt(443), Length::ZERO);
let single = LineSpacing::Auto(240);
let low = LineSpacing::AtLeast(Length::from_units(330_200));
let line = |rule, spaced| line_box(&base_device(), metrics, rule, (Length::ZERO, spaced));
assert_eq!(line(single, false).1, dots(46));
assert_eq!(line(single, true).1, dots(47));
assert_eq!(line(low, true).1, dots(47));
assert_eq!(line(single, true).0, line(single, false).0);
// A line that rounds up takes the rounded ascent too: 43.0 units, not 52.7 less the
// rounded descent of 10.
let tenths = |t: i64| Length::from_units(t * DOT / 10);
assert_eq!(
text_baseline(&base_device(), (tenths(430), tenths(97)), 240, true),
tenths(430)
);
}
#[test]
fn multiple_spacing_leaves_the_rise_of_a_list_label_unscaled() {
let u = |n: i64| Length::from_units(n * DOT);
// Text of 80 + 20 with a label that rises 10 above it.
let metrics = (u(90), u(20), u(10));
let line = |metrics, rule| line_box(&base_device(), metrics, rule, (Length::ZERO, false));
// 1.5 times the text's 100, and the 10 on top. The baseline is the label's ascent.
assert_eq!(line(metrics, LineSpacing::Auto(360)), (u(160), u(90)));
// Half of the text's 100 and the 10 on top: the baseline is the 10 and half the text's 80.
assert_eq!(line(metrics, LineSpacing::Auto(120)), (u(60), u(50)));
// With single spacing, the line is as tall as the label's ascent and the descent.
assert_eq!(
line(metrics, LineSpacing::Auto(240)).0,
line((u(90), u(20), Length::ZERO), LineSpacing::Auto(240)).0
);
}
#[test]
fn a_list_label_keeps_its_size_under_a_mark_with_rtl() {
use super::testing::{LARGE_LABELS, find, lay_out_with_numbering, marked};
let list = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>"#;
let item = |mark: &str| marked(&format!("{list}<w:rPr>{mark}</w:rPr>"), "X");
let numbering = format!(
r#"<w:numbering xmlns:w="{}">{LARGE_LABELS}</w:numbering>"#,
crate::ns::W
);
let at = |mark| {
let list = lay_out_with_numbering(&item(mark), &numbering);
(find(&list, '1'), find(&list, 'X'))
};
// The 20 pt label of the level, not the 10 pt complex script size of the mark, sets the
// line's height.
assert_eq!(at("<w:rtl/>"), at(""));
}
#[test]
fn the_list_label_of_a_right_to_left_paragraph_takes_the_complex_script_size() {
use super::testing::{find, lay_out_with_numbering, marked};
let abstract_num = |id: u32, half_points: u32| {
format!(
r#"<w:abstractNum w:abstractNumId="{id}"><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:rPr><w:sz w:val="20"/><w:szCs w:val="{half_points}"/></w:rPr></w:lvl></w:abstractNum>"#
)
};
let num = |id: u32| format!(r#"<w:num w:numId="{id}"><w:abstractNumId w:val="{id}"/></w:num>"#);
let numbering = format!(
r#"<w:numbering xmlns:w="{}">{}{}{}{}</w:numbering>"#,
crate::ns::W,
abstract_num(1, 40),
abstract_num(2, 20),
num(1),
num(2),
);
let baseline = |list: u32, direction: &str| {
let item = marked(
&format!(
r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="{list}"/></w:numPr>{direction}"#
),
"X",
);
find(&lay_out_with_numbering(&item, &numbering), 'X').2
};
// The label of 10 pt, and 20 pt for complex script text, raises the line only in a
// paragraph that is right to left.
assert!(baseline(1, "<w:bidi/>") > baseline(1, ""));
assert_eq!(baseline(1, ""), baseline(2, ""));
assert_eq!(baseline(2, "<w:bidi/>"), baseline(2, ""));
}
#[test]
fn multiple_spacing_puts_the_baseline_the_rounded_descent_above_the_rounded_extra() {
use crate::quirks::MultipleBaseline;
let rounded_ascent = crate::grid::Device::per_inch(288).unwrap();
let above_extra = crate::layout::testing::device_at(288, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
});
let quarter = rounded_ascent.dots(1);
let baseline = |device, metrics, n| {
line_box(device, metrics, LineSpacing::Auto(n), (Length::ZERO, false)).1
};
// Arial at 11 pt, with a single line of 2,355 of 2,048 units and a descent of 434:
// 10.318 pt above the baseline and 2.331 pt below it.
let arial = (
Length::from_units(262_074),
Length::from_units(59_209),
Length::ZERO,
);
// At 1.5 lines, the line of 18.973 pt rounds to 19 pt and its extra of 6.324 pt to
// 6.25 pt, and the baseline sits the descent's 2.25 pt above them, at 10.5 pt, not at
// the rounded ascent of 10.25 pt.
assert_eq!(baseline(&above_extra, arial, 360), quarter * 42);
assert_eq!(baseline(&rounded_ascent, arial, 360), quarter * 41);
// At 1.15 lines, the extra of 1.897 pt rounds up to 2 pt, so the baseline stays at 10.25
// pt.
assert_eq!(baseline(&above_extra, arial, 276), quarter * 41);
// The baseline sits no higher than the rounded ascent: 10.2 pt and 2.2 pt at 1.5 lines
// give 18.5 pt less 6.25 pt and 2.25 pt, which is 10 pt, above the ascent's 10.25 pt.
let pt = |hundredths: i64| Length::from_units(hundredths * 254);
let low = (pt(1020), pt(220), Length::ZERO);
assert_eq!(baseline(&above_extra, low, 360), quarter * 41);
// Single spacing and spacing below it keep their rules.
for n in [120, 240] {
assert_eq!(
baseline(&above_extra, arial, n),
baseline(&rounded_ascent, arial, n),
"{n}"
);
}
}
#[test]
fn rounds_drawn_advances_to_a_ten_thousandth_of_an_em() {
// Arial's "H" advances 1479/2048 em, 220,117 units at 12 pt. Word's PDF draws the next
// glyph 0.7222 em on, at 220,127 units.
let pt12 = Length::from_half_points(24).unwrap();
let u = Length::from_units;
let h = Drawn {
exact: Length::ZERO,
at: Length::ZERO,
advance: u(220_117),
spacing: None,
};
let drawn_x = |previous, x, size| {
drawn_x(
&base_device(),
previous,
(u(x), Length::ZERO),
(size, 2_048),
)
.at
.units()
};
assert_eq!(drawn_x(Some(h), 220_117, pt12), 220_127);
// Kerning moves the next glyph as it is.
assert_eq!(drawn_x(Some(h), 219_117, pt12), 219_127);
// The rounding adds up along a run: "e" advances 1139/2048 em, 169,515 units, and is
// drawn 0.5562 em on, 169,530 units.
let e = Drawn {
exact: u(220_117),
at: u(220_127),
advance: u(169_515),
spacing: None,
};
assert_eq!(drawn_x(Some(e), 389_632, pt12), 389_657);
// The first glyph of a run keeps its exact place.
assert_eq!(drawn_x(None, 5, pt12), 5);
}
#[test]
fn draws_a_size_off_the_grid_with_character_spacing_and_whole_corrections() {
// Times New Roman Bold at 14 pt, drawn at 58 dots (13.92 pt), in one text object: "P"
// (1251 of 2048 units) gives the object 3.4 thousandths of character spacing,
// since 614.35 - 611 rounds to 3.4. "o" (1024 units, width 500) is 502.874 thousandths of
// the drawn em, 502.9 rounded, so its correction is 3.4 - 2.9 = 0.5, rounded to 1: the
// writer draws it 502.4 thousandths on, 0.0066 pt short of its exact advance.
let pt14 = Length::from_half_points(28).unwrap();
let device = base_device();
let (u, zero) = (Length::from_units, Length::ZERO);
let p_advance = (pt14 * 1_251).div_round(2_048);
let first = drawn_x(&device, None, (zero, p_advance), (pt14, 2_048));
assert_eq!((first.at, first.spacing), (zero, None));
let second = drawn_x(&device, Some(first), (p_advance, zero), (pt14, 2_048));
assert_eq!(second.spacing, Some(34));
let o_advance = (pt14 * 1_024).div_toward_zero(2_048);
let o = Drawn {
exact: u(1_000_000),
at: u(1_000_000),
advance: o_advance,
spacing: Some(34),
};
let next = drawn_x(
&device,
Some(o),
(u(1_000_000) + o_advance, zero),
(pt14, 2_048),
);
// 502.4 thousandths of 13.92 pt.
assert_eq!(next.at - u(1_000_000), u(177_633));
assert_eq!(next.spacing, Some(34));
// Times New Roman's "s" at 11 pt, drawn at 46 dots (11.04 pt): 797 units are 387.75016
// thousandths of the drawn em, which round to 387.8, so the spacing is -1.2 thousandths,
// as Word writes it. The advance rounded to a unit of length, 108,731, would give -1.3.
let pt11 = Length::from_half_points(22).unwrap();
let s_advance = (pt11 * 797).div_round(2_048);
let s = drawn_x(&device, None, (zero, s_advance), (pt11, 2_048));
let t = drawn_x(&device, Some(s), (s_advance, zero), (pt11, 2_048));
assert_eq!(t.spacing, Some(-12));
// Kerning after the first glyph counts in its step and so in the object's spacing: with 40
// units more, the step is 407.21 thousandths of the drawn em, 407.2 rounded, 18.2 more than
// the width.
let kern = (pt11 * 40).div_round(2_048);
let kerned = drawn_x(&device, Some(s), (s_advance + kern, zero), (pt11, 2_048));
assert_eq!(kerned.spacing, Some(182));
}
#[test]
fn text_baselines() {
// Tenths of a device dot.
let tenths = |t: i64| Length::from_units(t * DOT / 10);
let text_baseline = |ascent, descent, lines, spaced| {
text_baseline(&base_device(), (ascent, descent), lines, spaced)
};
// A single line of 52.7 units rounds up, so the baseline sits the descent of 9.7
// units, rounded to 10, above the exact bottom.
assert_eq!(
text_baseline(tenths(430), tenths(97), 240, false),
tenths(427)
);
// A single line of 57.4 units rounds down to 57, and the descent of 10.8 units is cut
// to 51 twips (10.63 units), which round to 11. The rounded ascent would give 47.
assert_eq!(
text_baseline(tenths(466), tenths(108), 240, false),
tenths(460)
);
// With other spacing, the ascent rounds, here from 43.0 and from 46.6 units.
assert_eq!(
text_baseline(tenths(430), tenths(97), 276, false),
tenths(430)
);
assert_eq!(
text_baseline(tenths(466), tenths(108), 360, false),
tenths(470)
);
// A rounded-up ascent: 44.5 units go to 45.
assert_eq!(
text_baseline(tenths(445), tenths(80), 480, false),
tenths(450)
);
// A single line of exactly 57 units does not round up. Its descent of 10.5 units is
// cut to 50 twips (10.42 units), which round to 10, so the baseline sits at 47.
assert_eq!(
text_baseline(tenths(465), tenths(105), 240, false),
tenths(470)
);
}
#[test]
fn a_first_line_s_box_holds_its_space_before() {
// Times New Roman 12 pt below 8 pt of space before (16.67 device dots), whose box
// starts at 300.6 units. The box of 74.16 units rounds down to 74, so the baseline is
// the box's rounded top of 301 plus 74 less the descent of 11: 364. The line alone
// rounds its top of 317.27 to 317 and gives 317 + 57 - 11 = 363.
let at_12_pt = |units: i64| Length::from_units(units * 304_800 / 2048);
let dots = |n: i64| Length::from_units(n * DOT);
let (ascent, descent) = (at_12_pt(1912), at_12_pt(443));
let before = Length::from_units(101_600);
let top = Length::from_units(1_832_458) + before;
let boxed = |before| {
boxed_baseline(
&base_device(),
(top, SpaceBefore::of(Length::ZERO, before)),
(ascent, descent),
Ties::AwayFromTop,
)
};
assert_eq!(boxed(before), dots(364));
assert_eq!(boxed(Length::ZERO), dots(363));
// A line of single spacing takes the box, also in a table cell.
let size = LineBox {
single: true,
..plain_line_box((ascent, descent), ascent + descent, dots(363) - top)
};
assert_eq!(
placed_baseline(
&base_device(),
(top, SpaceBefore::of(Length::ZERO, before)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None)
),
dots(364)
);
// A box that rounds up keeps the exact bottom: with 3 pt (12.5 units) of space before,
// the box is 69.99 units, and the baseline is the exact top plus 57.495 less 11 units.
let three = Length::from_units(76_200);
assert_eq!(
boxed(three),
base_device().snap(top + ascent + descent - dots(11))
);
}
#[test]
fn names_the_form_that_placed_a_baseline() {
use crate::layout::BaselineForm;
// Times New Roman 12 pt, as in the tests of single and multiple spacing above.
let at_12_pt = |units: i64| Length::from_units(units * 304_800 / 2048);
let (ascent, descent) = (at_12_pt(1912), at_12_pt(443));
let rounded_ascent = base_device().snap(ascent);
let top = Length::from_units(1_832_458);
let form = |space: SpaceBefore, size: &LineBox| {
let rounding = (Ties::AwayFromTop, BoxTop::Lower);
placed_baseline_and_form(&base_device(), (top, space), size, rounding, (0, None)).1
};
let single = LineBox {
single: true,
..plain_line_box((ascent, descent), ascent + descent, ascent)
};
// A single box of 3 pt of space before rounds up, one of 8 pt rounds down.
let space = |units: i64| SpaceBefore::of(Length::ZERO, Length::from_units(units));
assert_eq!(form(space(76_200), &single), BaselineForm::SingleBottom);
assert_eq!(form(space(101_600), &single), BaselineForm::SingleTop);
let multiple = |baseline: Length| LineBox {
multiple: true,
..plain_line_box(
(ascent, descent),
((ascent + descent) * 276).div_toward_zero(240),
baseline,
)
};
// Below space before, the top, the space and the ascent round each; without it, a
// baseline whole dots below the top rounds with the top, and another one rounds once.
let whole = multiple(rounded_ascent);
assert_eq!(form(space(254_000), &whole), BaselineForm::SpaceAndAscent);
assert_eq!(
form(SpaceBefore::Absent, &whole),
BaselineForm::WholeDotsBelowTop
);
let exact = multiple(ascent);
assert_eq!(form(SpaceBefore::Absent, &exact), BaselineForm::Baseline);
}
#[test]
fn a_line_below_single_spacing_rounds_its_top_or_its_bottom_by_its_height() {
use crate::layout::BaselineForm;
use crate::quirks::LowMultipleBaseline;
let device = |variant| crate::layout::testing::device_at(600, |p| p.with_variant(variant));
// A dot of 600 per inch is 3,048 half-EMUs.
let dot = device(LowMultipleBaseline::RoundedOnce).dots(1).units();
let dots = |n: i64, units: i64| Length::from_units(n * dot + units);
let place = |variant, top: Length, (height, baseline): (Length, Length)| {
let size = LineBox {
multiple: true,
..plain_line_box((dots(70, 0), dots(20, 0)), height, baseline)
};
let rounding = (Ties::AwayFromTop, BoxTop::Lower);
let rests = (0, None);
placed_baseline_and_form(
&device(variant),
(top, SpaceBefore::Absent),
&size,
rounding,
rests,
)
};
// A height 80.25 dots and a baseline 65.6 dots below a top at 100.3: the top rounds to 100,
// and 65.6 less half of 0.25 rounds to 65. Rounded once, 165.9 gives 166.
let low = (dots(80, 762), dots(65, 1829));
let top = dots(100, 914);
assert_eq!(
place(LowMultipleBaseline::HeightFraction, top, low),
(dots(165, 0), BaselineForm::HeightFraction)
);
assert_eq!(
place(LowMultipleBaseline::RoundedOnce, top, low),
(dots(166, 0), BaselineForm::Baseline)
);
// A height 80.7 dots and a baseline 65.3 dots below a top at 100.1: the bottom at 180.8
// rounds to 181, and the baseline sits 15.4, rounded to 15, above it. Rounded once, 165.4
// gives 165.
let high = (dots(80, 2134), dots(65, 914));
let top = dots(100, 305);
assert_eq!(
place(LowMultipleBaseline::HeightFraction, top, high).0,
dots(166, 0)
);
assert_eq!(
place(LowMultipleBaseline::RoundedOnce, top, high).0,
dots(165, 0)
);
}
#[test]
fn a_first_line_of_multiple_spacing_rounds_its_space_before_on_its_own() {
// Times New Roman 12 pt at 1.15 lines below 10 pt of space before (41.67 device dots),
// whose box starts at 300.6 units. The box's top rounds to 301 and the space to 42, so the
// baseline lies the rounded ascent below 343. The exact top of 342.27 rounds to 342.
let at_12_pt = |units: i64| Length::from_units(units * 304_800 / 2048);
let dots = |n: i64| Length::from_units(n * DOT);
let (ascent, descent) = (at_12_pt(1912), at_12_pt(443));
let rounded_ascent = base_device().snap(ascent);
let before = Length::from_units(254_000);
let top = Length::from_units(1_832_458) + before;
let size = |multiple| LineBox {
multiple,
..plain_line_box(
(ascent, descent),
((ascent + descent) * 276).div_toward_zero(240),
rounded_ascent,
)
};
let placed = |multiple| {
placed_baseline(
&base_device(),
(top, SpaceBefore::of(Length::ZERO, before)),
&size(multiple),
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// Outside tables and in a table cell alike.
assert_eq!(placed(true), dots(343) + rounded_ascent);
// Without space before, the exact top rounds as a whole.
assert_eq!(placed(false), dots(342) + rounded_ascent);
assert_eq!(
placed_baseline(
&base_device(),
(top, SpaceBefore::Absent),
&size(true),
(Ties::AwayFromTop, BoxTop::Lower),
(0, None)
),
dots(342) + rounded_ascent
);
}
#[test]
fn a_first_line_whose_descent_goes_above_the_extra_holds_its_space_before_in_its_box() {
use crate::quirks::MultipleBaseline;
let device = crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
});
let dot = device.dots(1);
// A line of 93.36 dots above and 21.63 below the baseline at 1.15 lines (132.24 dots),
// below 4 pt (33.33 dots) of space before, whose box starts at 3,558.59 dots.
let (ascent, descent) = (Length::from_units(284_561), Length::from_units(65_928));
let height = Length::from_units(403_062);
let before = Length::from_units(101_600);
let top = Length::from_units(10_948_182);
let size = LineBox {
multiple: true,
..plain_line_box((ascent, descent), height, dot * 93)
};
// The box's top rounds to 3,559 dots. Its ascent of 126.69 dots rounds to 127, and so does
// its height of 165.57 dots less the extra of 17.25 and the descent of 21.63, each rounded:
// 166 - 17 - 22. The space rounded on its own (33) and the line's offset (93) give 126.
let placed = |device| {
placed_baseline(
device,
(top, SpaceBefore::of(Length::ZERO, before)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
assert_eq!(placed(&device), dot * (3559 + 127));
let ascent_rule =
crate::layout::testing::device_at(600, |p| p.with_variant(MultipleBaseline::RoundedAscent));
assert_eq!(placed(&ascent_rule), dot * (3559 + 33 + 93));
// Without space before, the line's own offset stays.
assert_eq!(
placed_baseline(
&device,
(top - before, SpaceBefore::Absent),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None)
),
dot * (3559 + 93)
);
}
#[test]
fn rounds_the_space_before_and_the_ascent_of_a_boxed_first_line_as_the_device_says() {
use crate::quirks::{MultipleBaseline, SpaceBeforeAscent};
let device = crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
});
let dot = device.dots(1);
// A single line of 93.36 dots above and 21.63 below the baseline, whose box holds 33.30
// dots of space before and 10 dots of space after, and starts at 1,000 dots.
let (ascent, descent) = (Length::from_units(284_561), Length::from_units(65_928));
let before = Length::from_units(101_498);
let size = LineBox {
after: dot * 10,
..plain_line_box((ascent, descent), ascent + descent, dot * 93)
};
let placed = |variant| {
placed_baseline(
&crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
.with_variant(variant)
}),
(dot * 1000 + before, SpaceBefore::of(Length::ZERO, before)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// The descent part: the box of 158.29 dots rounds to 158, less the space after (10) and
// the descent (22), 126. The space and the ascent rounded together give 127 (126.66), and
// each rounded on its own 33 + 93 = 126.
assert_eq!(placed(SpaceBeforeAscent::RoundedTogether), dot * 1127);
assert_eq!(placed(SpaceBeforeAscent::RoundedApart), dot * 1126);
}
#[test]
fn the_top_of_a_box_that_holds_its_space_before_carries_the_twips_rest_above_that_space() {
use crate::quirks::{MultipleBaseline, TwipLengthUnit};
let device = crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
.with_variant(TwipLengthUnit::Nearest4096ths)
});
let dot = device.dots(1);
// The box's top lies at 1,710 twips, 712.5 dots, a length of whole 4096ths of a point. The
// space before of 98 twips rounds down in those parts, so the line's top below it has a
// rest that would take the box's top on half a dot up the page.
let twips = |twips| Length::from_twips(twips).unwrap();
let before = twips(98);
let top = twips(1710) + before;
let rest = twips_rest(&device, top).unwrap();
assert!(rest < 0);
let (ascent, descent) = (Length::from_units(284_561), Length::from_units(65_928));
let size = LineBox {
after: dot * 10,
..plain_line_box((ascent, descent), ascent + descent, dot * 93)
};
let placed = |twips| {
placed_baseline(
&device,
(top, SpaceBefore::of(Length::ZERO, before)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, twips),
)
};
// The box's top takes the dot below the half, as it does without any rest.
assert_eq!(placed(Some(rest)), placed(None));
}
#[test]
fn a_last_line_s_box_holds_its_space_after_at_and_above_single_spacing() {
use crate::quirks::MultipleBaseline;
let device = crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
});
let dot = device.dots(1);
// Arial 11 pt: an ascent of 85.98 dots and a descent of 19.43. At 1.15 lines, a line of
// 121.22 dots and an extra of 15.81: its rounded height of 121 less 16 and 19 gives 86,
// the rounded ascent.
let at_11_pt = |units: i64| Length::from_units(units * 279_400 / 2048);
let (ascent, descent) = (at_11_pt(1921), at_11_pt(434));
let size = |height: Length, after| LineBox {
multiple: height > ascent + descent,
after,
..plain_line_box((ascent, descent), height, dot * 86)
};
let multiple = ((ascent + descent) * 276).div_round(240);
let top = dot * 1000;
let placed = |device, height, after| {
placed_baseline(
device,
(top, SpaceBefore::Absent),
&size(height, after),
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
let ten_pt = Length::from_units(254_000);
// With 10 pt (83.33 dots) of space after in the box, the box of 204.55 dots rounds to 205
// and its extra of 99.14 dots to 99, so the baseline lies 205 - 99 - 19 = 87 dots below
// the top.
assert_eq!(placed(&device, multiple, ten_pt), dot * (1000 + 87));
// Without a space after in the box, the line's own offset stays.
assert_eq!(placed(&device, multiple, Length::ZERO), dot * (1000 + 86));
// At single spacing, the box of 188.74 dots rounds to 189, less 83 and 19.
let single = ascent + descent;
assert_eq!(placed(&device, single, ten_pt), dot * (1000 + 87));
// Under the rounded ascent, the box does not hold the space after.
let ascent_rule =
crate::layout::testing::device_at(600, |p| p.with_variant(MultipleBaseline::RoundedAscent));
assert_eq!(placed(&ascent_rule, single, ten_pt), dot * (1000 + 86));
}
#[test]
fn a_box_that_holds_space_rounds_its_top_at_the_body_s_top_as_a_box_of_multiple_spacing() {
use crate::quirks::{MultipleBaseline, TopHalves};
let device = crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
.with_variant(TopHalves::FixedPoint)
});
let dot = device.dots(1);
// Arial 11 pt, single spacing, whose box holds 1.5 pt (12.5 dots) of space after: its
// ascent part (86) and its descent part (118 - 13 - 19) are both 86 dots.
let at_11_pt = |units: i64| Length::from_units(units * 279_400 / 2048);
let (ascent, descent) = (at_11_pt(1921), at_11_pt(434));
let size = LineBox {
after: Length::from_units(38_100),
..plain_line_box((ascent, descent), ascent + descent, dot * 86)
};
// The box starts at a top margin of 1,134 twips, 472.5 dots, which the fixed-point step
// takes to dot 472.
let top = Length::from_units(1134 * Length::UNITS_PER_TWIP);
let placed = |box_top| {
placed_baseline(
&device,
(top, SpaceBefore::Absent),
&size,
(Ties::AwayFromTop, box_top),
(0, None),
)
};
assert_eq!(placed(BoxTop::PageTop), dot * (472 + 86));
// Below the body's top, the half goes down the page.
assert_eq!(placed(BoxTop::Lower), dot * (473 + 86));
}
#[test]
fn the_fifth_of_an_exact_line_on_half_a_dot_rounds_as_a_top_on_half_a_dot() {
use crate::quirks::TopHalves;
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let device = crate::grid::Device::per_inch(600).unwrap();
let dot = device.dots(1);
// An exact line of 19.5 pt (390 twips, 162.5 dots) whose baseline lies four fifths down:
// its part below the baseline is 78 twips, 32.5 dots, 18 twips in 60.
let size = LineBox {
from_bottom: FromBottom::Exact,
..plain_line_box((dot * 130, dot * 33), twips(390), twips(312))
};
// Its top at 1,834 twips puts its exact bottom at 926.67 dots, which rounds to 927.
let placed = |top_halves| {
placed_baseline(
&crate::layout::testing::device_at(600, |p| p.with_variant(top_halves)),
(twips(1834), SpaceBefore::Absent),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// The half of the fifth up, 33 dots above the bottom.
assert_eq!(placed(TopHalves::AwayFromTop), dot * (927 - 33));
// The fixed-point dot of 78 twips, 32 dots above the bottom.
assert_eq!(placed(TopHalves::FixedPoint), dot * (927 - 32));
}
#[test]
fn a_spaced_exact_line_rounds_its_top_and_its_height_on_their_own() {
use crate::layout::BaselineForm;
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let device = crate::grid::Device::per_inch(600).unwrap();
let dot = device.dots(1);
// An exact line of 14 pt (280 twips, 116.67 dots) whose baseline lies four fifths down: its
// part below the baseline is 56 twips, 23.33 dots, which rounds to 23.
let size = |from_bottom| LineBox {
from_bottom,
..plain_line_box((dot * 90, dot * 23), twips(280), twips(224))
};
// Its top at 100.6 dots puts its exact bottom at 217.27 dots, which rounds to 217; the top
// rounds to 101 and the height to 117, whose sum is 218.
let top = Length::from_units(dot.units() * 100 + 1829);
let placed = |from_bottom| {
placed_baseline_and_form(
&device,
(top, SpaceBefore::Absent),
&size(from_bottom),
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
assert_eq!(
placed(FromBottom::Exact),
(dot * (217 - 23), BaselineForm::Bottom)
);
assert_eq!(
placed(FromBottom::ExactSpaced),
(dot * (218 - 23), BaselineForm::SpacedBottom)
);
}
#[test]
fn an_at_least_line_whose_box_rounds_down_takes_its_rounded_top_and_height() {
// Arial 10 pt (descent 17.66 dots of 1/600 inch, which rounds to 18) at a minimum of 281
// twips (117.08 dots), whose exact top lies at 1,000.45 dots.
let device = crate::grid::Device::per_inch(600).unwrap();
let dot = device.dots(1);
let at_10_pt = |units: i64| Length::from_units(units * 254_000 / 2048);
let (ascent, descent) = (at_10_pt(1921), at_10_pt(434));
let size = |height: Length, least: bool| LineBox {
from_bottom: if least {
FromBottom::AtLeast
} else {
FromBottom::Exact
},
..plain_line_box((ascent, descent), height, height - descent)
};
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let top = Length::from_units(3_049_372);
let placed = |(top, before): (Length, Length), size: &LineBox| {
placed_baseline(
&device,
(top + before, SpaceBefore::of(Length::ZERO, before)),
size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// The height rounds down to 117, so the bottom is the rounded top of 1,000 plus 117, and
// the baseline lies 18 dots above it. The exact bottom of 1,117.53 would round to 1,118.
assert_eq!(
placed((top, Length::ZERO), &size(twips(281), true)),
dot * (1000 + 117 - 18)
);
// A line of exact height keeps its exact bottom rounded.
assert_eq!(
placed((top, Length::ZERO), &size(twips(281), false)),
dot * (1118 - 18)
);
// Below 53 twips (22.08 dots) of space before, the box of 139.17 dots rounds down: its
// top of 1,000.45 dots rounds to 1,000, and 139 more less 18 give the baseline.
assert_eq!(
placed((top, twips(53)), &size(twips(281), true)),
dot * (1000 + 139 - 18)
);
// A minimum of 283 twips (117.92 dots) rounds up, and the exact bottom rounded stays: from
// a top at 1,000.55 dots, 1,118.47 rounds to 1,118, where the rounded top plus the rounded
// height would give 1,119.
assert_eq!(
placed(
(Length::from_units(3_049_676), Length::ZERO),
&size(twips(283), true)
),
dot * (1118 - 18)
);
}
#[test]
fn a_header_line_halfway_between_two_device_dots_rounds_up_the_page() {
// A header distance of 708 twips puts the header's first line at 147.5 device dots. A
// line of multiple spacing has its baseline the rounded ascent below that top. In the body
// the half rounds down the page, to 148 units; in a header up the page, to 147.
let at_12_pt = |units: i64| Length::from_units(units * 304_800 / 2048);
let dots = |n: i64| Length::from_units(n * DOT);
let (ascent, descent) = (at_12_pt(1912), at_12_pt(443));
let rounded_ascent = base_device().snap(ascent);
let top = Length::from_units(708 * Length::UNITS_PER_TWIP);
let size = LineBox {
multiple: true,
..plain_line_box(
(ascent, descent),
((ascent + descent) * 276).div_toward_zero(240),
rounded_ascent,
)
};
let placed = |ties| {
placed_baseline(
&base_device(),
(top, SpaceBefore::Absent),
&size,
(ties, BoxTop::Lower),
(0, None),
)
};
assert_eq!(placed(Ties::AwayFromTop), dots(148) + rounded_ascent);
assert_eq!(placed(Ties::TowardTop), dots(147) + rounded_ascent);
// A single line whose height rounds down rounds its top: 147.5 to 147, plus 57 units of
// height, less the 11 units of its descent.
let single = |ties| {
boxed_baseline(
&base_device(),
(top, SpaceBefore::Absent),
(ascent, descent),
ties,
)
};
assert_eq!(single(Ties::TowardTop), dots(147 + 57 - 11));
assert_eq!(single(Ties::AwayFromTop), dots(148 + 57 - 11));
// A position off the half rounds the same way in both.
let off = |ties| {
let at = (top + Length::from_units(100), SpaceBefore::Absent);
placed_baseline(&base_device(), at, &size, (ties, BoxTop::Lower), (0, None))
};
assert_eq!(off(Ties::TowardTop), off(Ties::AwayFromTop));
}
#[test]
fn single_baselines_of_fonts_at_12_pt() {
// The `hhea` ascender plus line gap and the win descent, in 2048 units per em, at 12 pt.
let at_12_pt = |units: i64| Length::from_units(units * 304_800 / 2048);
let baseline = |ascent: i64, descent: i64| {
text_baseline(
&base_device(),
(at_12_pt(ascent), at_12_pt(descent)),
240,
false,
)
.units()
/ DOT
};
// Times New Roman and Arial both have a line of 57.495 device dots, which rounds down.
// Times New Roman's descent of 51.91 twips is cut to 51, 10.63 units, and rounds to 11.
assert_eq!(baseline(1825 + 87, 443), 46);
// Arial's descent of 50.86 twips is cut to 50, 10.42 units, and rounds to 10.
assert_eq!(baseline(1854 + 67, 434), 47);
// Calibri's line of 61.035 units rounds down too, and its descent goes to 13 units.
assert_eq!(baseline(1950, 550), 48);
}
#[test]
fn centered_single_lines_sit_in_the_middle_of_their_rounded_height() {
use crate::quirks::SingleBaseline;
let device =
crate::layout::testing::device_at(288, |p| p.with_variant(SingleBaseline::Centered));
// The `hhea` ascender plus line gap and the win descent, in 2048 units per em, at `hp`
// half-points, and the baseline in dots of 0.25 pt.
let baseline = |hp: i64, ascent: i64, descent: i64| {
let at = |units: i64| Length::from_units(units * hp * 12_700 / 2048);
text_baseline(&device, (at(ascent), at(descent)), 240, false).units()
/ device.dots(1).units()
};
// Arial 9 pt: a line of 41.40 dots rounds to 41 and loses 0.40, and the ascent of 33.77
// dots less 0.20 rounds to 34, one dot below the rounded height less the rounded descent.
assert_eq!(baseline(18, 1854 + 67, 434), 34);
// Times New Roman 9 pt has the same line, but an ascent of 33.61 dots: 33.41 rounds to 33.
assert_eq!(baseline(18, 1825 + 87, 443), 33);
// Calibri 8 pt: 39.06 dots round to 39, and the ascent of 30.47 less 0.03 rounds to 30,
// where the descent of 8.59 dots, cut to whole twips (8.4 dots), would leave 31.
assert_eq!(baseline(16, 1950, 550), 30);
}
#[test]
fn a_rounded_descent_puts_a_line_below_space_the_exact_descent_rounded_above_its_rounded_bottom() {
use crate::quirks::SingleBaseline;
let device = |variant| crate::layout::testing::device_at(600, |p| p.with_variant(variant));
let dot = device(SingleBaseline::RoundedDescentBelowSpace).dots(1);
// A line of 93.36 dots above and 21.63 below the baseline below 4 pt (33.33 dots) of space
// before, whose box starts at 3,558.59 dots: the box of 148.32 dots rounds down to 148.
let (ascent, descent) = (Length::from_units(284_561), Length::from_units(65_928));
let before = Length::from_units(101_600);
let top = Length::from_units(10_846_582) + before;
let placed = |variant| {
boxed_baseline(
&device(variant),
(top, SpaceBefore::of(Length::ZERO, before)),
(ascent, descent),
Ties::AwayFromTop,
)
};
// The box's top rounds to 3,559 dots. The exact descent rounds to 22, so the baseline sits
// 148 - 22 dots below it; the descent cut to 51 twips (21.25 dots) rounds to 21.
assert_eq!(
placed(SingleBaseline::RoundedDescentBelowSpace),
dot * (3559 + 126)
);
assert_eq!(placed(SingleBaseline::CutDescent), dot * (3559 + 127));
// The middle of the box, 126.69 dots less half of the 0.32 that it loses, rounds to 127.
assert_eq!(placed(SingleBaseline::Centered), dot * (3559 + 127));
}
#[test]
fn a_rounded_descent_below_space_holds_where_a_new_page_left_the_space_out() {
use crate::quirks::SingleBaseline;
let device = crate::layout::testing::device_at(600, |p| {
p.with_variant(SingleBaseline::RoundedDescentBelowSpace)
});
let dot = device.dots(1);
// A line of 93.60 dots above and 21.55 below the baseline: its height of 115.15 dots rounds
// down to 115, its exact descent rounds to 22, and its middle, 93.60 less half of the 0.15
// that the height loses, rounds to 94.
let (ascent, descent) = (Length::from_units(285_293), Length::from_units(65_684));
let top = dot * 1000;
let placed =
|top, space| boxed_baseline(&device, (top, space), (ascent, descent), Ties::AwayFromTop);
// The first line of a paragraph whose space before a new page left out: 115 - 22.
let dropped = SpaceBefore::of(dot * 50, Length::ZERO);
assert_eq!(dropped, SpaceBefore::Dropped(dot * 50));
assert_eq!(placed(top, dropped), dot * (1000 + 93));
// A later line, or a line of a paragraph without space before, takes the centered form.
let absent = SpaceBefore::of(Length::ZERO, Length::ZERO);
assert_eq!(absent, SpaceBefore::Absent);
assert_eq!(placed(top, absent), dot * (1000 + 94));
// Below 6 pt (50 dots) of space before, the box of 165.15 dots rounds down to 165.
let before = dot * 50;
assert_eq!(SpaceBefore::of(before, before), SpaceBefore::Held(before));
assert_eq!(
placed(top + before, SpaceBefore::Held(before)),
dot * (1000 + 165 - 22)
);
}
#[test]
fn an_exact_line_whose_box_rounds_down_takes_the_forms_of_a_single_line_under_box_forms() {
use crate::quirks::{ExactBaseline, SingleBaseline};
let device = |variant| {
crate::layout::testing::device_at(600, |p| {
p.with_variant(SingleBaseline::RoundedDescentBelowSpace)
.with_variant(variant)
})
};
let dot = device(ExactBaseline::BoxForms).dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let exact = |height: Length| {
let baseline = (height * 4).div_round(5);
LineBox {
from_bottom: FromBottom::Exact,
..plain_line_box((baseline, height - baseline), height, baseline)
}
};
let placed = |variant, top, space, height| {
placed_baseline(
&device(variant),
(top, space),
&exact(height),
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// A later line of 301 twips (125.42 dots) whose exact top lies 0.125 dots below dot 1,000.
// Its baseline lies 100.33 dots down and 25.08 dots above the bottom. The rounded exact
// bottom of 1,125.54 dots gives 1,126 - 25. The box rounds down to 125 dots, and the
// centered form gives 100.33 less half of 0.42, rounded: 100 below dot 1,000.
let top = dot * 1000 + Length::from_units(381);
let later = |variant| placed(variant, top, SpaceBefore::Absent, twips(301));
assert_eq!(later(ExactBaseline::RoundedBottom), dot * 1101);
assert_eq!(later(ExactBaseline::BoxForms), dot * 1100);
// A first line of 259 twips below 80 twips of space before, a box of 339 twips (141.25
// dots) whose top lies 0.375 dots below dot 1,000. The descent of 21.58 dots rounds to 22,
// and the rounded descent gives 141 - 22, where the rounded exact bottom gives 120 and the
// centered form 120 as well.
let before = twips(80);
let first = |variant| {
placed(
variant,
dot * 1000 + Length::from_units(1143) + before,
SpaceBefore::of(before, before),
twips(259),
)
};
assert_eq!(first(ExactBaseline::RoundedBottom), dot * 1120);
assert_eq!(first(ExactBaseline::BoxForms), dot * 1119);
// A box that rounds up keeps the rounded exact bottom: 302 twips are 125.83 dots.
let up = |variant| placed(variant, top, SpaceBefore::Absent, twips(302));
assert_eq!(
up(ExactBaseline::BoxForms),
up(ExactBaseline::RoundedBottom)
);
// A box on exactly half a dot keeps it too: 306 twips are 127.5 dots. Below a top 0.6 dot
// past a whole dot, the centered form would put the baseline one dot lower.
let half = |variant| {
placed(
variant,
dot * 1000 + Length::from_units(1829),
SpaceBefore::Absent,
twips(306),
)
};
assert_eq!(half(ExactBaseline::RoundedBottom), dot * 1102);
assert_eq!(half(ExactBaseline::BoxForms), dot * 1102);
}
#[test]
fn an_exact_line_between_two_border_rooms_sits_in_the_middle_of_the_room_between_their_dots() {
let device = crate::layout::testing::device_at(600, Clone::clone);
let dot = device.dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// Rooms of 5 and 30 twips (2 1/12 and 12 1/2 dots) round to 2 and 13 dots, and the box of
// 365 twips (152 1/12 dots) to 152, so the line of 330 twips (137 1/2 dots) keeps 137 dots.
// Its baseline 110 dots down moves up a quarter dot and rounds up to 110, below the 2 dots
// of the top room.
let offset = device.centred_room_baseline((twips(5), twips(30)), (twips(330), twips(264)));
assert_eq!(offset, dot * 112);
}
#[test]
fn an_at_least_line_below_a_border_room_takes_the_room_as_its_rounded_bottom_less_the_line() {
use crate::quirks::SpaceBeforeAscent;
let device =
crate::layout::testing::device_at(600, |p| p.with_variant(SpaceBeforeAscent::RoundedApart));
let dot = device.dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let (ascent, descent, height) = (twips(214), twips(52), twips(280));
let (before, after) = (twips(30), twips(5));
let size = LineBox {
from_bottom: FromBottom::AtLeast,
after,
top_room: before,
..plain_line_box((ascent, descent), height, height - descent)
};
let baseline = |size: &LineBox| {
placed_baseline(
&device,
(dot * 1000 + before, SpaceBefore::of(before, before)),
size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// The top room of 12 1/2 dots and the line of 116 2/3 round together to 129, less the line's
// 117: 12 dots, above the extra of 5 5/6 dots and the ascent of 89 1/6, rounded to 6 and 89.
// The descent side, 131 less the bottom room's 2 and the descent's 22, is 107 too.
assert_eq!(baseline(&size), dot * (1000 + 12 + 6 + 89));
// A space before of the same length, without a border's room, rounds on its own to 13.
let spaced = LineBox {
top_room: Length::ZERO,
..size
};
assert_eq!(baseline(&spaced), dot * (1000 + 13 + 6 + 89));
}
#[test]
fn a_low_line_between_border_rooms_takes_the_lower_of_its_rounded_top_and_bottom_sides() {
let device = crate::layout::testing::device_at(600, crate::profile::Profile::clone);
let dot = device.dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let (ascent, descent, height, offset) = (twips(224), twips(52), twips(248), twips(202));
let room = twips(25);
let size = LineBox {
multiple: true,
after: room,
top_room: room,
..plain_line_box((ascent, descent), height, offset)
};
let baseline = placed_baseline(
&device,
(dot * 1000 + room, SpaceBefore::of(room, room)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
);
// Rooms of 10 5/12 dots round to 10 each, the line of 103 1/3 dots and its offset of 84 1/6
// to 103 and 84. Below the top: 10 and 84, 94 dots. Above the box's bottom of 124 1/6 dots,
// rounded to 124: the bottom room's 10 and the 19 of the line below the baseline, 95 dots.
assert_eq!(baseline, dot * (1000 + 95));
}
#[test]
fn a_low_line_below_a_top_border_room_alone_takes_the_higher_of_its_two_rounded_bottoms() {
let device = crate::layout::testing::device_at(600, crate::profile::Profile::clone);
let dot = device.dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
let (ascent, descent, height, offset) = (twips(224), twips(52), twips(248), twips(202));
let room = twips(12);
let size = LineBox {
multiple: true,
top_room: room,
..plain_line_box((ascent, descent), height, offset)
};
let baseline = placed_baseline(
&device,
(dot * 1000 + twips(1) + room, SpaceBefore::of(room, room)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
);
// The box's top of 1000 5/12 dots, its room of 5 and its line of 103 1/3 end at 1108 3/4,
// rounded to 1109; its top rounded to 1000 and its room and line rounded to 108 end at 1108,
// the higher one. The 19 1/6 dots of the line below the baseline round to 19.
assert_eq!(baseline, dot * (1108 - 19));
}
#[test]
fn an_exact_box_that_rounds_down_on_entered_lengths_takes_its_shorter_dot_and_the_entered_fifth() {
use crate::quirks::{
ExactBaseline, ExactBoxLength, ExactFifthHalves, SingleBaseline, TwipLengthUnit,
};
let device = |length| {
crate::layout::testing::device_at(600, |p| {
p.with_variant(SingleBaseline::RoundedDescentBelowSpace)
.with_variant(ExactBaseline::BoxForms)
.with_variant(TwipLengthUnit::Nearest4096ths)
.with_variant(ExactFifthHalves::Entered)
.with_variant(length)
})
};
let dot = device(ExactBoxLength::Exact).dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// The first line of a paragraph below `before` twips of space before, of an exact height
// of `height` twips, whose box's top lies on dot 1,000.
let placed = |length, before: i64, height: i64| {
let device = device(length);
let (before, height) = (twips(before), twips(height));
let baseline = (height * 4).div_round(5);
let size = LineBox {
from_bottom: FromBottom::Exact,
twips: twips_rest(&device, height),
..plain_line_box((baseline, height - baseline), height, baseline)
};
placed_baseline(
&device,
(dot * 1000 + before, SpaceBefore::of(before, before)),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// 30 twips above 204: a box of 234 twips, 97.5 dots, whose entries sum 0.2 part below it,
// so it rounds down to 97 dots. The fifth of 40.8 twips is 17 dots. On the exact length the
// box rounds up, and its bottom of 1,097.5 dots goes to 1,098.
assert_eq!(
placed(ExactBoxLength::Entered, 30, 204),
dot * (1000 + 97 - 17)
);
assert_eq!(placed(ExactBoxLength::Exact, 30, 204), dot * (1098 - 17));
// 24 twips above 150: a box of 174 twips, 72.5 dots, whose space before enters 0.2 part
// below it. The fifth of 30 twips, 12.5 dots, is 6,144 whole parts, exactly on the half, so
// it takes the longer dot, 13, above the shorter box.
assert_eq!(
placed(ExactBoxLength::Entered, 24, 150),
dot * (1000 + 72 - 13)
);
assert_eq!(placed(ExactBoxLength::Exact, 24, 150), dot * (1073 - 13));
// 7 twips above 210: a box of 217 twips, 90.42 dots, rounds down by its exact length. The
// fifth of 42 twips is 17.5 dots, and 8,601 whole parts of the entered height, below the
// half, so under entered lengths it takes the shorter dot, 17, where the box forms of a
// single line take the longer one, 18.
assert_eq!(
placed(ExactBoxLength::Entered, 7, 210),
dot * (1000 + 90 - 17)
);
assert_eq!(
placed(ExactBoxLength::Exact, 7, 210),
dot * (1000 + 90 - 18)
);
}
#[test]
fn the_fifth_of_an_exact_line_on_half_a_dot_takes_the_dot_of_its_entered_parts_under_entered() {
use crate::quirks::{ExactBoxLength, ExactFifthHalves, TopHalves, TwipLengthUnit};
let device = |halves| {
crate::layout::testing::device_at(600, |p| {
p.with_variant(TopHalves::FixedPoint)
.with_variant(TwipLengthUnit::Nearest4096ths)
.with_variant(ExactBoxLength::Entered)
.with_variant(halves)
})
};
let dot = device(ExactFifthHalves::AsTops).dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// A later line of an exact height of `height` twips whose top lies on dot 1,000.
let placed = |halves, height: i64| {
let device = device(halves);
let height = twips(height);
let baseline = (height * 4).div_round(5);
let size = LineBox {
from_bottom: FromBottom::Exact,
twips: twips_rest(&device, height),
..plain_line_box((baseline, height - baseline), height, baseline)
};
placed_baseline(
&device,
(dot * 1000, SpaceBefore::Absent),
&size,
(Ties::AwayFromTop, BoxTop::Lower),
(0, None),
)
};
// 10.5 pt, 210 twips, 87.5 dots: the bottom of 1,087.5 dots goes to 1,088. The fifth of 42
// twips, 17.5 dots, is 8,601.6 parts, and its 8,601 whole parts lie below the half, so it
// takes 17 dots, where its fixed-point value takes 18.
assert_eq!(placed(ExactFifthHalves::Entered, 210), dot * (1088 - 17));
assert_eq!(placed(ExactFifthHalves::AsTops, 210), dot * (1088 - 18));
// 7.5 pt, 150 twips, 62.5 dots: the fifth of 30 twips, 12.5 dots, is 6,144 whole parts,
// exactly on the half, so it takes the longer dot, 13, under both.
assert_eq!(placed(ExactFifthHalves::Entered, 150), dot * (1063 - 13));
assert_eq!(placed(ExactFifthHalves::AsTops, 150), dot * (1063 - 13));
}
#[test]
fn a_single_line_top_on_half_a_dot_takes_the_dot_of_its_top_halves() {
use crate::quirks::{SingleBaseline, TopHalves};
let device = |variant| {
crate::layout::testing::device_at(600, |p| {
p.with_variant(SingleBaseline::RoundedDescentBelowSpace)
.with_variant(variant)
})
};
let dot = device(TopHalves::AwayFromTop).dots(1);
// The line of 93.36 dots above and 21.63 below the baseline below 4 pt of space before,
// whose box of 148.32 dots rounds down, with the box's top at a top margin of 2 cm: 1,134
// twips, 472.5 dots, 54 in 60 twips.
let (ascent, descent) = (Length::from_units(284_561), Length::from_units(65_928));
let before = Length::from_units(101_600);
let top = Length::from_units(1_134 * Length::UNITS_PER_TWIP) + before;
let placed = |variant, ties| {
boxed_baseline(
&device(variant),
(top, SpaceBefore::of(Length::ZERO, before)),
(ascent, descent),
ties,
)
};
// In the body the fixed-point step sends the half up the page, to dot 472; the plain half
// up gives 473. The baseline sits 148 - 22 dots below.
assert_eq!(
placed(TopHalves::FixedPoint, Ties::AwayFromTop),
dot * (472 + 126)
);
assert_eq!(
placed(TopHalves::AwayFromTop, Ties::AwayFromTop),
dot * (473 + 126)
);
// A turned cell's frame takes no rule of whole twips: the half goes down the frame.
assert_eq!(
placed(TopHalves::FixedPoint, Ties::TurnedFrame),
dot * (473 + 126)
);
// A header keeps its own rule, a half up the page, with either variant.
assert_eq!(
placed(TopHalves::FixedPoint, Ties::TowardTop),
dot * (472 + 126)
);
assert_eq!(
placed(TopHalves::AwayFromTop, Ties::TowardTop),
dot * (472 + 126)
);
// A box whose height rounds up keeps its rule: without the space before, the line of
// 114.99 dots rounds up, and its baseline sits the rounded descent above its exact bottom.
let bare = |variant| {
boxed_baseline(
&device(variant),
(top - before, SpaceBefore::Absent),
(ascent, descent),
Ties::AwayFromTop,
)
};
assert_eq!(bare(TopHalves::FixedPoint), bare(TopHalves::AwayFromTop));
}
#[test]
fn a_single_line_top_in_a_cell_takes_the_dot_of_its_place_and_not_of_the_twips_rest() {
use crate::quirks::TopHalves;
let device = crate::layout::testing::device_at(600, |p| p.with_variant(TopHalves::FixedPoint));
let dot = device.dots(1);
// A single line whose box of 115.01 dots rounds down, at 2,478 twips, exactly on half a
// dot (1,032.5 dots). As one length in 1/65,536 pt, the place lies short of the half and
// takes dot 1,032; a twips rest of entered lengths above it that lies past it sends the
// body's line to dot 1,033.
let (ascent, descent) = (Length::from_units(284_561), Length::from_units(66_000));
let size = LineBox {
single: true,
..plain_line_box((ascent, descent), ascent + descent, ascent)
};
let top = Length::from_units(2_478 * Length::UNITS_PER_TWIP);
let placed = |ties| {
let at = (top, SpaceBefore::Absent);
placed_baseline_and_form(&device, at, &size, (ties, BoxTop::Lower), (0, Some(1_905)))
};
let (body, form) = placed(Ties::AwayFromTop);
let (cell, _) = placed(Ties::Cell);
assert_eq!(form, crate::layout::BaselineForm::SingleTop);
assert_eq!(body - cell, dot);
// A height rest still decides the half in a cell.
let rested = placed_baseline_and_form(
&device,
(top, SpaceBefore::Absent),
&size,
(Ties::Cell, BoxTop::Lower),
(1, Some(-1_270)),
);
assert_eq!(rested.0, body);
}
/// The baseline of a line of multiple spacing whose box has the top `at`, with the baseline
/// `baseline` below its top, on a device of 600 dots per inch with the line top's half
/// `variant`, in the body.
fn multiple_at(
variant: crate::quirks::TopHalves,
at: (Length, SpaceBefore),
baseline: Length,
box_top: BoxTop,
) -> Length {
let device = crate::layout::testing::device_at(600, |p| p.with_variant(variant));
let dot = device.dots(1);
let line = LineBox {
multiple: true,
..plain_line_box((dot * 14, dot * 4), dot * 21, baseline)
};
placed_baseline(&device, at, &line, (Ties::AwayFromTop, box_top), (0, None))
}
#[test]
fn a_multiple_line_at_the_page_top_on_half_a_dot_takes_the_dot_of_its_top_halves() {
use crate::quirks::TopHalves;
let dot = crate::grid::Device::per_inch(600).unwrap().dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// A top margin of 2 cm, 1,134 twips, 472.5 dots, 54 in 60 twips: at the body's top on a
// page the fixed-point step sends the half up the page, to dot 472; below it, and with the
// plain half up, the top goes to dot 473. The baseline lies 15 dots below the top.
let margin = (twips(1_134), SpaceBefore::Absent);
let at = |variant, box_top| multiple_at(variant, margin, dot * 15, box_top);
assert_eq!(at(TopHalves::FixedPoint, BoxTop::PageTop), dot * (472 + 15));
assert_eq!(at(TopHalves::FixedPoint, BoxTop::Lower), dot * (473 + 15));
assert_eq!(
at(TopHalves::AwayFromTop, BoxTop::PageTop),
dot * (473 + 15)
);
// The box's top below 6 pt (50 dots) of space before that a page break kept.
let before = twips(120);
let spaced = (twips(1_134) + before, SpaceBefore::of(before, before));
let below = |box_top| multiple_at(TopHalves::FixedPoint, spaced, dot * 15, box_top);
assert_eq!(below(BoxTop::PageTop), dot * (472 + 50 + 15));
assert_eq!(below(BoxTop::Lower), dot * (473 + 50 + 15));
}
#[test]
fn a_multiple_line_at_the_page_top_keeps_the_half_up_off_the_fixed_point_halves() {
use crate::quirks::TopHalves::FixedPoint;
let dot = crate::grid::Device::per_inch(600).unwrap().dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// A top margin of 1,170 twips, 30 in 60, lies on the fixed-point grid: the higher dot.
let thirty = (twips(1_170), SpaceBefore::Absent);
assert_eq!(
multiple_at(FixedPoint, thirty, dot * 15, BoxTop::PageTop),
dot * (488 + 15)
);
// A baseline off the dot grid, as below single spacing, rounds with the top as before.
let margin = (twips(1_134), SpaceBefore::Absent);
let off = dot * 15 + Length::from_units(1_000);
assert_eq!(
multiple_at(FixedPoint, margin, off, BoxTop::PageTop),
multiple_at(FixedPoint, margin, off, BoxTop::Lower)
);
}
#[test]
fn a_box_that_holds_its_space_after_at_the_page_top_on_half_a_dot_takes_the_fixed_point_dot() {
use crate::quirks::{MultipleBaseline, TopHalves};
let device = |variant| {
crate::layout::testing::device_at(600, |p| {
p.with_variant(MultipleBaseline::DescentAboveExtra)
.with_variant(variant)
})
};
let dot = device(TopHalves::AwayFromTop).dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// Arial 11 pt at single spacing with 10 pt of space after in its box lies 87 dots below
// the box's top (`a_last_line_s_box_holds_its_space_after_at_and_above_single_spacing`).
// At a top margin of 1,134 twips, 472.5 dots, the box's top at the body's top on a page
// takes the fixed-point dot 472, as the other boxes there do; below it, and with the plain
// half up, 473.
let at_11_pt = |units: i64| Length::from_units(units * 279_400 / 2048);
let (ascent, descent) = (at_11_pt(1921), at_11_pt(434));
let line = LineBox {
after: Length::from_units(254_000),
..plain_line_box((ascent, descent), ascent + descent, dot * 86)
};
let placed = |variant, box_top| {
placed_baseline(
&device(variant),
(twips(1_134), SpaceBefore::Absent),
&line,
(Ties::AwayFromTop, box_top),
(0, None),
)
};
assert_eq!(
placed(TopHalves::FixedPoint, BoxTop::PageTop),
dot * (472 + 87)
);
assert_eq!(
placed(TopHalves::FixedPoint, BoxTop::Lower),
dot * (473 + 87)
);
assert_eq!(
placed(TopHalves::AwayFromTop, BoxTop::PageTop),
dot * (473 + 87)
);
}
#[test]
fn a_space_before_that_a_natural_break_dropped_stays_in_the_box_above_the_page_top() {
use crate::quirks::{DroppedSpaceBox, SingleBaseline};
let device = |variant| {
crate::layout::testing::device_at(600, |p| {
p.with_variant(SingleBaseline::RoundedDescentBelowSpace)
.with_variant(variant)
})
};
let dot = device(DroppedSpaceBox::LeftOut).dots(1);
// A line of single spacing of 95.8 dots, 18 of them below its baseline, whose paragraph's
// 2 pt (16.67 dots) of space before a natural break dropped, at the body's top of 990 dots.
// Its height rounds up, so without the space its baseline is the rounded descent above its
// exact bottom: 990 + 95.8 - 18 = 1,067.8, dot 1,068. With the space above the page's top,
// the box of 112.47 dots rounds down below its top at 973.33, dot 973: 973 + 112 - 18 =
// 1,067, Word's dot.
let (ascent, descent) = (Length::from_units(237_134), dot * 18);
let line = LineBox {
single: true,
..plain_line_box((ascent, descent), ascent + descent, ascent)
};
let dropped = SpaceBefore::of(Length::from_units(50_800), Length::ZERO);
let placed = |variant, box_top| {
placed_baseline(
&device(variant),
(dot * 990, dropped),
&line,
(Ties::AwayFromTop, box_top),
(0, None),
)
};
assert_eq!(
placed(DroppedSpaceBox::HeldAbove, BoxTop::PageTop),
dot * 1067
);
assert_eq!(
placed(DroppedSpaceBox::LeftOut, BoxTop::PageTop),
dot * 1068
);
// Below the body's top, the space stays out of the box.
assert_eq!(
placed(DroppedSpaceBox::HeldAbove, BoxTop::Lower),
dot * 1068
);
}
#[test]
fn a_baseline_whole_dots_below_the_top_rounds_with_the_top_at_the_page_top() {
use crate::quirks::TopHalves;
let device = |variant| crate::layout::testing::device_at(600, |p| p.with_variant(variant));
let dot = device(TopHalves::AwayFromTop).dots(1);
let twips = |n: i64| Length::from_units(n * Length::UNITS_PER_TWIP);
// A line that neither single nor multiple spacing places, such as one beside a taller
// object, with its baseline 300 whole dots below its top: at a top margin of 1,134 twips,
// 472.5 dots, it takes the fixed-point dot of its top at the body's top on a page, and the
// half up below it.
let placed = |variant, baseline, box_top| {
let line = plain_line_box((dot * 80, dot * 20), dot * 400, baseline);
placed_baseline(
&device(variant),
(twips(1_134), SpaceBefore::Absent),
&line,
(Ties::AwayFromTop, box_top),
(0, None),
)
};
let whole = dot * 300;
assert_eq!(
placed(TopHalves::FixedPoint, whole, BoxTop::PageTop),
dot * (472 + 300)
);
assert_eq!(
placed(TopHalves::FixedPoint, whole, BoxTop::Lower),
dot * (473 + 300)
);
assert_eq!(
placed(TopHalves::AwayFromTop, whole, BoxTop::PageTop),
dot * (473 + 300)
);
// A baseline off the dot grid rounds with the top as one length, at the page's top too.
let off = whole + Length::from_units(1_000);
assert_eq!(
placed(TopHalves::FixedPoint, off, BoxTop::PageTop),
placed(TopHalves::FixedPoint, off, BoxTop::Lower)
);
}
#[test]
fn text_beside_a_taller_object_keeps_its_descent_and_the_extra_of_multiple_spacing() {
let u = Length::from_units;
// A text line of 80 above and 20 below the baseline, beside an object 300 tall that puts
// the baseline 300 below the line top.
assert_eq!(text_below_object(240, (u(80), u(20)), u(300)), u(320));
// Spacing of 1.08 lines adds 8 of the text's single line of 100 below the descent.
assert_eq!(text_below_object(259, (u(80), u(20)), u(300)), u(328));
assert_eq!(text_below_object(360, (u(80), u(20)), u(300)), u(370));
}
#[test]
fn text_ends() {
let u = Length::from_units;
let none = Length::ZERO;
// With automatic spacing the text is the single line, wherever the baseline is.
assert_eq!(
text_end(u(80), u(20), LineSpacing::Auto(276), none, u(81), false),
u(100)
);
// Under a taller object with text, the text ends a descent below the baseline.
assert_eq!(
text_end(u(80), u(20), LineSpacing::Auto(240), u(200), u(300), false),
u(320)
);
// A line of exact height needs its whole height: also when the font reaches below the
// line, and also when its text ends above the line's bottom.
let exact = LineSpacing::Exact(u(60));
assert_eq!(text_end(u(80), u(20), exact, none, u(40), false), u(60));
assert_eq!(text_end(u(40), u(30), exact, none, u(48), false), u(60));
assert_eq!(text_end(u(40), u(8), exact, none, u(48), false), u(60));
// A minimum below the single line leaves a single line, and one above it puts the extra
// space above the text.
let at_least = |h: i64| LineSpacing::AtLeast(u(h));
assert_eq!(
text_end(u(80), u(20), at_least(60), none, u(81), false),
u(100)
);
assert_eq!(
text_end(u(80), u(20), at_least(130), none, u(110), false),
u(130)
);
}
#[test]
fn text_ends_for_object_alone() {
let u = Length::from_units;
// A tall inline object standing alone without text or underline ends at the baseline without
// font descent, under both automatic spacing and a smaller at-least minimum; a minimum
// larger than the object keeps its full minimum height.
assert_eq!(
text_end(u(80), u(20), LineSpacing::Auto(240), u(200), u(300), true),
u(300)
);
assert_eq!(
text_end(u(80), u(20), LineSpacing::Auto(360), u(200), u(300), true),
u(300)
);
assert_eq!(
text_end(
u(80),
u(20),
LineSpacing::AtLeast(u(150)),
u(200),
u(300),
true
),
u(300)
);
assert_eq!(
text_end(
u(80),
u(20),
LineSpacing::AtLeast(u(350)),
u(200),
u(330),
true
),
u(350)
);
}
#[test]
fn alignment_shifts() {
let u = Length::from_units;
let offset = |a, last| shift(a, u(100), last).offset;
assert_eq!(offset(Alignment::Start, false), Length::ZERO);
assert_eq!(offset(Alignment::Center, false), u(50));
assert_eq!(offset(Alignment::End, false), u(100));
assert_eq!(shift(Alignment::Center, u(-30), false).offset, Length::ZERO);
assert_eq!(shift(Alignment::End, u(-5), false).offset, Length::ZERO);
}
#[test]
fn only_justified_lines_in_mode_15_shrink() {
let rules = |value| ModeRules::of(CompatibilityMode::read(value));
let both = Some(Alignment::Both);
assert_eq!(
shrink(both, rules(Some(15)), Justification::Word),
JUSTIFIED_SHRINK
);
assert_eq!(
shrink(both, rules(Some(16)), Justification::Word),
JUSTIFIED_SHRINK
);
assert_eq!(
shrink(both, rules(Some(14)), Justification::Word),
Shrink::default()
);
assert_eq!(
shrink(both, rules(None), Justification::Word),
Shrink::default()
);
assert_eq!(
shrink(Some(Alignment::Start), rules(Some(15)), Justification::Word),
Shrink::default()
);
assert_eq!(
shrink(both, rules(None), Justification::WordPerfect),
WORD_PERFECT_SHRINK
);
assert_eq!(
shrink(both, rules(Some(15)), Justification::WordPerfect),
JUSTIFIED_SHRINK
);
}
#[test]
fn the_justification_of_wordperfect_holds_below_mode_15_on_a_target_that_follows_it() {
use crate::quirks::WordPerfectJustification;
use crate::styles::Settings;
let take = |variant, mode, asked| {
let quirks = crate::layout::testing::on_base_with(|p| p.with_variant(variant)).1;
let settings = Settings {
mode_rules: ModeRules::of(CompatibilityMode::read(mode)),
justification: asked,
..Settings::default()
};
super::decisions::justification(&quirks, &settings)
};
let (shrinks, ignored) = (
WordPerfectJustification::ShrinksLine,
WordPerfectJustification::Ignored,
);
let (word, perfect) = (Justification::Word, Justification::WordPerfect);
assert_eq!(take(shrinks, None, perfect), perfect);
assert_eq!(take(shrinks, Some(14), perfect), perfect);
assert_eq!(take(shrinks, Some(15), perfect), word);
assert_eq!(take(shrinks, None, word), word);
assert_eq!(take(ignored, None, perfect), word);
}
#[test]
fn a_tab_to_a_left_stop_past_the_line_end_takes_the_target_s_choice_from_mode_15_only() {
use crate::quirks::LeftStopPastEnd;
let to_line_end = |target, value| {
let quirks = crate::layout::testing::on_base_with(|p| p.with_variant(target)).1;
let rules = ModeRules::of(CompatibilityMode::read(value));
super::decisions::line_breaking(&quirks, rules).left_stops_to_line_end
};
for value in [Some(15), Some(16)] {
assert!(to_line_end(LeftStopPastEnd::ToLineEnd, value));
}
for value in [Some(14), Some(12), None] {
assert!(!to_line_end(LeftStopPastEnd::ToLineEnd, value));
}
assert!(!to_line_end(LeftStopPastEnd::ToStop, Some(15)));
}
#[test]
fn justification_spreads_or_shrinks() {
let u = Length::from_units;
assert_eq!(shift(Alignment::Both, u(100), false).spread, u(100));
assert_eq!(shift(Alignment::Both, u(100), true).spread, Length::ZERO);
assert_eq!(shift(Alignment::Both, u(-30), false).spread, u(-30));
assert_eq!(shift(Alignment::Both, u(-30), true).spread, u(-30));
}
#[test]
fn a_soft_break_line_is_aligned_as_the_last_where_the_option_and_the_target_say_so() {
use crate::lines::LineEnd;
use crate::quirks::SoftBreakLine;
use crate::styles::{Settings, SoftBreakLines};
let ending = |end| Line {
end,
..Line::default()
};
let broken = ending(LineEnd::Break(None));
let set = Settings {
soft_break_lines: SoftBreakLines::AsLastLine,
..Settings::default()
};
let unset = Settings::default();
let followed =
super::testing::on_base_with(|p| p.with_variant(SoftBreakLine::OptionFollowed)).1;
let ignored = super::testing::on_base_with(|p| p.with_variant(SoftBreakLine::Justified)).1;
assert!(aligned_as_last(&broken, false, &set, &followed));
for other in [LineEnd::Wrap, LineEnd::PageBreak, LineEnd::ColumnBreak] {
assert!(!aligned_as_last(&ending(other), false, &set, &followed));
}
assert!(!aligned_as_last(&broken, false, &unset, &followed));
assert!(!aligned_as_last(&broken, false, &set, &ignored));
assert!(aligned_as_last(
&ending(LineEnd::Wrap),
true,
&unset,
&ignored
));
}
#[test]
fn the_room_below_a_fraction_comes_once() {
// Double spacing does not double the room below a denominator, and an exact height or a
// taller object keeps none.
let u = Length::from_units;
let none = Length::ZERO;
assert_eq!(below_text(LineSpacing::Auto(480), none, u(30)), u(30));
assert_eq!(below_text(LineSpacing::Auto(240), none, u(30)), u(30));
assert_eq!(below_text(LineSpacing::Exact(u(1)), none, u(30)), none);
assert_eq!(below_text(LineSpacing::Auto(240), u(5), u(30)), none);
}
#[test]
fn stacks_the_parts_of_a_fraction_over_the_wider_part() {
use super::measure::stack;
use crate::body::{GapMinimum, StackMark};
let glyph = |ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(1), ch));
let shift = |units| Piece::Shift(Length::from_units(units));
let bar = |units| Piece::Bar {
face: FaceIndex::nth(0),
width: Length::from_units(units),
};
let (mut open, mut pieces) = (Vec::new(), Vec::new());
let mut mark = |mark, pieces: &mut Vec<Piece>| {
stack(
&mut open,
pieces,
mark,
(Some(FaceIndex::nth(0)), Length::ZERO, &|_: &[Piece]| {
Length::ZERO
}),
);
};
let start = |bar: bool| StackMark::Start {
bar: bar.then_some(GapMinimum::Line),
centered: true,
};
// A numerator of 20 units over a denominator of 10: the bar is 20 units wide, the
// denominator starts 5 units in, and the fraction takes 20 units.
mark(start(true), &mut pieces);
pieces.extend([glyph('a'), glyph('b')]);
mark(StackMark::Middle, &mut pieces);
pieces.push(glyph('c'));
mark(StackMark::End, &mut pieces);
let fraction = vec![
bar(20),
shift(0),
glyph('a'),
glyph('b'),
shift(-15),
glyph('c'),
shift(5),
];
assert_eq!(pieces, fraction);
assert_eq!(
pieces.iter().map(crate::lines::advance).sum::<Length>(),
Length::from_units(20)
);
// A fraction without a bar puts down none, and a fraction in its numerator stacks first.
let mut pieces = Vec::new();
mark(start(false), &mut pieces);
mark(start(true), &mut pieces);
pieces.extend([glyph('a'), glyph('b')]);
mark(StackMark::Middle, &mut pieces);
pieces.push(glyph('c'));
mark(StackMark::End, &mut pieces);
mark(StackMark::Middle, &mut pieces);
pieces.extend([glyph('d'), glyph('e'), glyph('f')]);
mark(StackMark::End, &mut pieces);
let mut nested = vec![shift(5)];
nested.extend(fraction);
nested.extend([shift(-25), glyph('d'), glyph('e'), glyph('f'), shift(0)]);
assert_eq!(pieces, nested);
// The scripts of a sub-superscript both start at the stack's start, without a bar, and
// the stack takes the room of the wider one.
let mut pieces = Vec::new();
let scripts = StackMark::Start {
bar: None,
centered: false,
};
mark(scripts, &mut pieces);
pieces.push(glyph('i'));
mark(StackMark::Middle, &mut pieces);
pieces.extend([glyph('n'), glyph('m')]);
mark(StackMark::End, &mut pieces);
let stacked = vec![
shift(0),
glyph('i'),
shift(-10),
glyph('n'),
glyph('m'),
shift(0),
];
assert_eq!(pieces, stacked);
assert_eq!(
pieces.iter().map(crate::lines::advance).sum::<Length>(),
Length::from_units(20)
);
}
#[test]
fn starts_the_lower_limit_beside_a_large_operator_left_of_the_upper_one() {
use super::measure::stack;
use crate::body::StackMark;
let glyph = |ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(1), ch));
let shift = |units| Piece::Shift(Length::from_units(units));
let beside = |lower: &[char], upper: &[char]| {
let (mut open, mut pieces) = (Vec::new(), Vec::new());
let none = |_: &[Piece]| Length::ZERO;
let lead = (
Some(FaceIndex::nth(0)),
Length::from_units(4),
&none as &dyn Fn(&[Piece]) -> Length,
);
for (mark, part) in [
(StackMark::StartBeside('\u{222B}'), lower),
(StackMark::Middle, upper),
] {
stack(&mut open, &mut pieces, mark, lead);
pieces.extend(part.iter().map(|&ch| glyph(ch)));
}
stack(&mut open, &mut pieces, StackMark::End, lead);
pieces
};
// The lower limit starts 4 units left of the upper one, and the stack ends where the
// upper limit, which ends later, ends.
let both = beside(&['i'], &['n', 'm']);
let expected = vec![
shift(-4),
glyph('i'),
shift(-6),
glyph('n'),
glyph('m'),
shift(0),
];
assert_eq!(both, expected);
assert_eq!(
both.iter().map(crate::lines::advance).sum::<Length>(),
Length::from_units(20)
);
// A lower limit alone ends 4 units before its own width.
let lower = beside(&['i'], &[]);
assert_eq!(lower, vec![shift(-4), glyph('i'), shift(-6), shift(6)]);
assert_eq!(
lower.iter().map(crate::lines::advance).sum::<Length>(),
Length::from_units(6)
);
}
#[test]
fn a_word_perfect_line_narrows_its_spaces_by_a_quarter_then_its_pieces_in_whole_dots() {
use super::line::shift::Narrowing;
let u = Length::from_units;
let line = |text: &str, advance: &dyn Fn(char) -> i64| {
let mut x = 0;
Line {
placed: text
.chars()
.map(|ch| {
let placed = Placed {
piece: Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)),
x: u(x),
advance: u(advance(ch)),
leader: None,
tab: None,
};
x += advance(ch);
placed
})
.collect(),
..Line::default()
}
};
let at = |narrowing: Narrowing| (0..6).map(|i| narrowing.at(i).units()).collect::<Vec<_>>();
// A space of 8 gives up a quarter, 2, of an overrun of 5; the 3 dots left go to the last
// three pieces.
let proportional = line("aa bb", &|ch| if ch == ' ' { 8 } else { 20 });
let (taken, narrowing) = Narrowing::of(&proportional, u(5), u(1)).unwrap();
assert_eq!(taken, u(2));
assert_eq!(at(narrowing), vec![0, 0, -1, -1, -1, 0]);
// Where every piece has one advance, the spaces give up nothing: 7 is 4 dots of 2, to the
// nearest, one each for the last four pieces; 24 is 12 dots, 2 each and one more for the
// last two.
let fixed = line("aa aa", &|_| 10);
let (taken, narrowing) = Narrowing::of(&fixed, u(7), u(2)).unwrap();
assert_eq!(taken, Length::ZERO);
assert_eq!(at(narrowing), vec![0, -2, -2, -2, -2, 0]);
let (_, narrowing) = Narrowing::of(&fixed, u(24), u(2)).unwrap();
assert_eq!(at(narrowing), vec![-4, -4, -4, -6, -6, 0]);
assert!(Narrowing::of(&fixed, Length::ZERO, u(2)).is_none());
}
#[test]
fn justification_spreads_over_inner_spaces() {
let piece = |ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch));
let line = Line {
placed: "a b c "
.chars()
.enumerate()
.map(|(i, ch)| Placed {
piece: piece(ch),
x: Length::from_units(i64::try_from(i).unwrap() * 10),
advance: Length::from_units(10),
leader: None,
tab: None,
})
.collect(),
..Line::default()
};
let shares = |line: &Line, mark_shrink| {
Shift {
offset: Length::ZERO,
spread: Length::from_units(31),
}
.space_shares(line, mark_shrink)
};
assert_eq!(
shares(&line, Length::ZERO),
SpaceShares {
per_space: Length::from_units(15),
rest: Length::from_units(1),
}
);
assert_eq!(
shares(&Line::default(), Length::ZERO),
SpaceShares::default()
);
assert_eq!(
shares(&line, Length::from_units(-2)),
SpaceShares::default()
);
}
#[test]
fn places_glyphs_in_their_paragraph_in_utf16_code_units() {
let glyph = |ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch));
// A tab counts as one character, and a character beyond the BMP as two.
let mut pieces = vec![glyph('a'), Piece::Tab(None), glyph('😀'), glyph('b')];
place_in_paragraph(&mut pieces);
let places: Vec<u32> = pieces
.iter()
.filter_map(|p| match p {
Piece::Glyph(g) => Some(g.place.in_paragraph),
_ => None,
})
.collect();
assert_eq!(places, [0, 2, 4]);
}
/// The indexes of the spaces of `text` that stand beside East Asian text, with a tab piece for
/// each tab and a glyph piece for each other character.
fn spaces_beside_east_asian_in(text: &str) -> Vec<usize> {
let pieces: Vec<Piece> = text
.chars()
.map(|ch| {
if ch == '\t' {
return Piece::Tab(None);
}
Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch))
})
.collect();
spaces_beside_east_asian(&pieces)
}
#[test]
fn finds_the_spaces_next_to_east_asian_text_and_among_them() {
let found = spaces_beside_east_asian_in;
assert_eq!(found("AB CD EF 文字"), [8]);
assert_eq!(found("文字 AB CD EF"), [2]);
assert_eq!(found(" 文字"), [0, 1, 2]);
assert_eq!(found("( 年度)"), [1, 2]);
assert_eq!(found("2024 年 11 月"), [4, 6, 9]);
}
#[test]
fn keeps_latin_spaces_and_spaces_beyond_a_tab() {
let found = spaces_beside_east_asian_in;
assert_eq!(found("AB CD EF"), Vec::<usize>::new());
assert_eq!(found("AB \t文字"), Vec::<usize>::new());
// A no-break space is not one of the spaces.
assert_eq!(found("文\u{00A0}字"), Vec::<usize>::new());
}
/// A line of `text` whose characters are 10 wide.
fn line_of(text: &str) -> Line {
Line {
placed: text
.chars()
.enumerate()
.map(|(i, ch)| Placed {
piece: Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)),
x: Length::from_units(i64::try_from(i).unwrap() * 10),
advance: Length::from_units(10),
leader: None,
tab: None,
})
.collect(),
..Line::default()
}
}
#[test]
fn tells_the_lines_that_hold_a_glyph_besides_white_space_or_besides_the_ascii_space() {
// (text, a glyph besides white space, a glyph besides the ASCII space): they differ on a
// line of only no-break, ideographic or other Unicode spaces.
let cases = [
("", false, false),
(" ", false, false),
("\u{00A0}\u{00A0}", false, true),
("\u{3000}", false, true),
(" \u{2003} ", false, true),
(" a ", true, true),
("\u{00A0}a", true, true),
];
for (text, besides_white_space, besides_ascii_space) in cases {
let line = line_of(text);
assert_eq!(
(
holds_glyph_besides_white_space(&line),
holds_glyph_besides_ascii_space(&line)
),
(besides_white_space, besides_ascii_space),
"{text:?}"
);
}
}
#[test]
fn inner_blank_halves_give_up_the_overrun_and_a_last_closing_mark_keeps_its_half() {
let line = line_of;
let u = Length::from_units;
// Two inner halves, after the first two marks; the last mark ends the line.
assert_eq!(
compressed_marks(&line("永、永、永、"), u(-20), MarkSides::BlankHalf),
Some(u(-10))
);
// The shares round toward the larger shrink, so that the line fits.
assert_eq!(
compressed_marks(&line("永、永、永、"), u(-21), MarkSides::BlankHalf),
Some(u(-11))
);
// An opening mark's blank half lies before it.
assert_eq!(
compressed_marks(&line("永「永、永"), u(-20), MarkSides::BlankHalf),
Some(u(-10))
);
assert_eq!(
compressed_marks(&line("永、永、永、"), u(5), MarkSides::BlankHalf),
None
);
assert_eq!(
compressed_marks(&line("永永永"), u(-20), MarkSides::BlankHalf),
None
);
}
#[test]
fn japanese_middle_dot_counts_and_splits_shrink_only_for_japanese() {
let u = Length::from_units;
let jp_dot = line_of("所属・役職");
assert_eq!(
compressed_marks(&jp_dot, u(-20), MarkSides::Japanese),
Some(u(-20))
);
assert_eq!(
compressed_marks(&jp_dot, u(-20), MarkSides::BlankHalf),
None
);
assert_eq!(compressed_marks(&jp_dot, u(-20), MarkSides::Centered), None);
assert_eq!(
(0..jp_dot.placed.len())
.map(|index| inner_mark_shrink_before(&jp_dot, index, u(-10), MarkSides::Japanese))
.collect::<Vec<_>>(),
[u(0), u(0), u(-5), u(-5), u(0)]
);
let jp_comma = line_of("所属、役職");
assert_eq!(
(0..jp_comma.placed.len())
.map(|index| inner_mark_shrink_before(&jp_comma, index, u(-10), MarkSides::Japanese))
.collect::<Vec<_>>(),
[u(0), u(0), u(0), u(-10), u(0)]
);
}
#[test]
fn a_centered_mark_gives_up_half_its_share_on_each_side_and_the_line_total_stays() {
let u = Length::from_units;
let line = line_of("永,永)永,");
let shrinks = |sides| {
(0..line.placed.len())
.map(|index| inner_mark_shrink_before(&line, index, u(-10), sides))
.collect::<Vec<_>>()
};
// The inner comma moves by half the share and the ideograph after it by the whole share;
// the closing bracket keeps its place and the comma at the end keeps its blank half.
assert_eq!(
shrinks(MarkSides::Centered),
[u(0), u(-5), u(-5), u(0), u(-10), u(0)]
);
assert_eq!(
shrinks(MarkSides::BlankHalf),
[u(0), u(0), u(-10), u(0), u(-10), u(0)]
);
}
#[test]
fn tells_the_marks_that_stand_in_the_middle_of_their_em() {
for ch in [',', '、', '。', ';', ':'] {
assert!(crate::lines::centered_mark(ch), "{ch}");
}
for ch in [')', '「', '」', '永', ','] {
assert!(!crate::lines::centered_mark(ch), "{ch}");
}
}
#[test]
fn room_left_spreads_over_the_gaps_of_a_line_without_spaces() {
let u = Length::from_units;
assert_eq!(spread_over_gaps(&line_of("永、永、永、"), u(10)), u(2));
assert_eq!(spread_over_gaps(&line_of("永 永"), u(10)), Length::ZERO);
assert_eq!(spread_over_gaps(&line_of("永、永"), u(-10)), Length::ZERO);
// Only the gaps that touch a full-width character take a share.
assert_eq!(spread_over_gaps(&line_of("永abc永"), u(10)), u(5));
assert_eq!(spread_over_gaps(&line_of("www.abc"), u(10)), Length::ZERO);
}
#[test]
fn gives_equal_columns_their_exact_width_or_its_whole_twips() {
use crate::quirks::ColumnWidths;
// 3,892.5 twips: the exact rule keeps the half, the whole-twip rule drops it.
let exact = Length::from_units(3_892 * Length::UNITS_PER_TWIP + Length::UNITS_PER_TWIP / 2);
let width = |rule| {
let quirks = crate::layout::testing::on_base_with(|p| p.with_variant(rule)).1;
super::decisions::equal_column_width(&quirks, exact)
};
assert_eq!(width(ColumnWidths::Exact), exact);
assert_eq!(
width(ColumnWidths::WholeTwips),
Length::from_units(3_892 * Length::UNITS_PER_TWIP)
);
}
#[test]
fn a_setup_that_chooses_the_targets_own_variants_gives_the_same_pages() {
use crate::testing::WordParts as _;
let bytes = crate::testing::docx(
"<w:p><w:r><w:t>Two words</w:t></w:r></w:p>\
<w:p><w:pPr><w:jc w:val=\"both\"/></w:pPr><w:r><w:t>a b c d e f g h</w:t></w:r></w:p>",
)
.plain_styles()
.zip()
.unwrap();
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
for target in crate::Target::all() {
let own = (crate::profile::Profile::of(target)
.unwrap()
.variants()
.into_iter())
.fold(
crate::profile::Overrides::default(),
|overrides, (name, variant)| overrides.with_quirk(name, variant),
);
let pages = |overrides: crate::profile::Overrides| {
let options = crate::Options {
configuration: crate::Configuration::of(target),
overrides,
..crate::Options::default()
};
crate::layout(
&package,
(&super::testing::Fake, &crate::ArtPictures::new()),
&options,
)
.unwrap()
.value
};
assert_eq!(
pages(own),
pages(crate::profile::Overrides::default()),
"{target:?}"
);
}
}
#[test]
fn cuts_a_picture_in_a_frame_by_a_clip_of_the_page_where_word_cuts_it() {
use f_office_paint::{GroupPlaces, Item};
// A frame 18 pt high, exactly, at the top of the body holds an inline picture of 72 by 36
// pt. Where Word cuts an inline picture to the box that holds it, the picture keeps its
// whole image, with no clip of its own, in a group of the page's items under a clip of the
// part that shows, the frame's 18 pt; the writer then writes the image whole under that
// clip. Where it does not, the image stays alone and whole.
let mut png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR".to_vec();
png.extend_from_slice(&20_u32.to_be_bytes());
png.extend_from_slice(&15_u32.to_be_bytes());
png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
let body = r#"<w:p><w:pPr><w:framePr w:w="2880" w:h="360" w:hRule="exact"/></w:pPr><w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><wp:inline><wp:extent cx="914400" cy="457200"/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="p1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#;
let bytes = crate::testing::docx(body)
.relationship(crate::testing::DOCUMENT, "p1", "image", "media/p.png")
.part("word/media/p.png", png)
.zip()
.unwrap();
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let shown = |variant: &str| {
let options = crate::Options {
overrides: crate::profile::Overrides::default()
.with_quirk("InlinePictureClip", variant),
..crate::Options::default()
};
let list = crate::layout(
&package,
(&super::testing::Fake, &crate::ArtPictures::new()),
&options,
)
.unwrap()
.value;
list.pages()[0].items().iter().find_map(|item| match item {
Item::Image(image) => Some((image.clip.is_some(), image.height, None)),
Item::Group(group) if group.places == GroupPlaces::Page => {
let [Item::Image(image)] = group.items.as_slice() else {
return None;
};
let ys: Vec<Length> = group
.clip
.as_ref()?
.commands
.iter()
.flat_map(f_office_paint::PathCommand::points)
.map(|point| point.y)
.collect();
let height = *ys.iter().max()? - *ys.iter().min()?;
Some((image.clip.is_some(), image.height, Some(height)))
}
_ => None,
})
};
let (picture, frame) = (
Length::from_units(36 * 25_400),
Length::from_units(18 * 25_400),
);
assert_eq!(shown("LineBox"), Some((false, picture, Some(frame))));
assert_eq!(shown("Unknown"), Some((false, picture, None)));
}
#[test]
fn draws_an_inline_vml_picture_that_takes_a_scaled_size_on_the_device_s_dots() {
use f_office_paint::Item;
// A picture 80 by 20.2 pt in a `w:pict` at the start of the body, of an image 20 by 15
// pixels at 96 an inch: 15 by 11.25 pt. Where it scales its image's natural size, it takes
// 5.333 and 1.796 of it, 79.995 by 20.205 pt, and its image lies on whole dots of the
// target's device, each edge in the nearest twip; where it keeps its CSS size, the image
// keeps that size, which is no whole number of dots of 0.12 or 0.24 pt.
let mut png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR".to_vec();
png.extend_from_slice(&20_u32.to_be_bytes());
png.extend_from_slice(&15_u32.to_be_bytes());
png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
let pict = r#"<w:p><w:r><w:pict><v:shape xmlns:v="urn:schemas-microsoft-com:vml" style="width:80pt;height:20.2pt"><v:imagedata r:id="p1"/></v:shape></w:pict></w:r></w:p>"#;
let bytes = crate::testing::docx(pict)
.relationship(crate::testing::DOCUMENT, "p1", "image", "media/p.png")
.part("word/media/p.png", png)
.zip()
.unwrap();
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let twip = Length::UNITS_PER_TWIP;
for target in crate::Target::all() {
let dot = crate::profile::Profile::of(target)
.unwrap()
.device_dot()
.units();
let image = |room: &str| {
let options = crate::Options {
configuration: crate::Configuration::of(target),
overrides: crate::profile::Overrides::default().with_quirk("VmlPictureRoom", room),
..crate::Options::default()
};
let list = crate::layout(
&package,
(&super::testing::Fake, &crate::ArtPictures::new()),
&options,
)
.unwrap()
.value;
list.pages()[0]
.items()
.iter()
.find_map(|item| match item {
Item::Image(image) => Some((
[
image.x,
image.y,
image.x + image.width,
image.y + image.height,
]
.map(Length::units),
(image.width.units(), image.height.units()),
)),
_ => None,
})
.unwrap()
};
let (edges, (width, height)) = image("NaturalScale");
assert!(edges.iter().all(|edge| edge % twip == 0), "{target}");
// 79.995 and 20.205 pt in whole dots, within half a twip of each written edge.
let whole_dots = |exact: i64, drawn: i64| {
let dots = f_office_units::div_round(exact, dot) * dot;
(drawn - dots).abs() <= twip
};
assert!(
whole_dots(79_995 * Length::UNITS_PER_POINT / 1000, width),
"{target}"
);
assert!(
whole_dots(20_205 * Length::UNITS_PER_POINT / 1000, height),
"{target}"
);
let (_, css) = image("AsWritten");
assert_eq!(
css,
(
80 * Length::UNITS_PER_POINT,
202 * Length::UNITS_PER_POINT / 10
),
"{target}"
);
}
}
#[test]
fn sizes_a_line_by_a_joined_variation_selector_where_the_target_joins_it() {
use super::EarlierPass;
use super::testing::{NORMAL, find_all, on_base_with, pass_on};
use crate::numbering::Numbering;
use crate::quirks::InvisibleCharacters;
use crate::text::ShaperSettings;
// "A ", a selector alone in a run of 24 pt, " B"; then "C" on the next line.
let selector = "<w:r><w:rPr><w:sz w:val=\"48\"/></w:rPr><w:t>\u{FE0F}</w:t></w:r>";
let body = format!(
"<w:p><w:r><w:t xml:space=\"preserve\">A </w:t></w:r>{selector}<w:r><w:t xml:space=\"preserve\"> B</w:t></w:r></w:p><w:p><w:r><w:t>C</w:t></w:r></w:p>"
);
let laid_out = |variant| {
let (device, quirks) = on_base_with(|p| p.with_variant(variant));
let settings = ShaperSettings::base_with(|p| p.with_variant(variant));
let pass = pass_on(
&body,
(NORMAL, None),
None,
Numbering::default(),
(device, quirks, EarlierPass::default()),
&(&super::testing::Fake as &dyn crate::Fonts, settings),
);
let at = |ch| find_all(&pass.list, ch);
(at('B'), at('C'), at('\u{FE0F}').len())
};
let (b_left, c_left, drawn_left) = laid_out(InvisibleCharacters::TakeNoRoom);
let (b_joined, c_joined, drawn_joined) =
laid_out(InvisibleCharacters::OperatorsDrawnSelectorsJoined);
// The selector takes no room and draws nothing either way, and its run of 24 pt makes the
// first line taller only where it joins.
assert_eq!((drawn_left, drawn_joined), (0, 0));
assert_eq!(b_left.first().map(|b| b.1), b_joined.first().map(|b| b.1));
let (Some(c_left), Some(c_joined)) = (c_left.first(), c_joined.first()) else {
panic!("no C");
};
assert!(c_joined.2 > c_left.2, "{c_joined:?} {c_left:?}");
}
#[test]
fn a_blanks_only_line_ending_in_a_manual_break_takes_the_breaks_face() {
use super::testing::{NORMAL, find, lay_out};
let measure = |runs: &str| {
let body = format!(
r#"<w:p><w:pPr><w:rPr><w:sz w:val="24"/></w:rPr></w:pPr>{runs}<w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:t>X</w:t></w:r></w:p>"#
);
let list = lay_out(&body, NORMAL, None);
find(&list, 'X').2
};
// Spaces/tabs before a 9 pt break take the 9 pt break's height, whether the blanks are 24 pt
// or absent; a 24 pt break after a 9 pt space takes the 24 pt break's height.
let empty_br9 = measure(r#"<w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:br/></w:r>"#);
let sp24_br9 = measure(
r#"<w:r><w:rPr><w:sz w:val="48"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:br/></w:r>"#,
);
let tab24_br9 = measure(
r#"<w:r><w:rPr><w:sz w:val="48"/></w:rPr><w:tab/></w:r><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:br/></w:r>"#,
);
let empty_br24 = measure(r#"<w:r><w:rPr><w:sz w:val="48"/></w:rPr><w:br/></w:r>"#);
let sp9_br24 = measure(
r#"<w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r><w:r><w:rPr><w:sz w:val="48"/></w:rPr><w:br/></w:r>"#,
);
// Non-breaking space (U+00A0) is non-blank text and keeps its own 24 pt height.
let nbsp24_br9 = measure(
"<w:r><w:rPr><w:sz w:val=\"48\"/></w:rPr><w:t>\u{00A0}</w:t></w:r><w:r><w:rPr><w:sz w:val=\"18\"/></w:rPr><w:br/></w:r>",
);
assert_eq!(sp24_br9, empty_br9);
assert_eq!(tab24_br9, empty_br9);
assert_eq!(sp9_br24, empty_br24);
assert_eq!(nbsp24_br9, empty_br24);
assert!(empty_br24 > empty_br9);
}
#[test]
fn wrapped_floating_overflowing_body_bottom_pushes_anchor_paragraph_to_next_page() {
use super::testing::{NORMAL, find, lay_out};
use crate::ns::{A, WP, WPS};
let filler: String = (0..40)
.map(|_| r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="293" w:lineRule="exact"/></w:pPr><w:r><w:t>L</w:t></w:r></w:p>"#)
.collect();
let anchor = |y_emu: i64, wrap: &str| {
format!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="293" w:lineRule="exact"/></w:pPr><w:r><w:drawing><wp:anchor xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>3810000</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>{y_emu}</wp:posOffset></wp:positionV><wp:extent cx="1524000" cy="1524000"/><wp:effectExtent l="0" t="0" r="0" b="0"/>{wrap}<wp:docPr id="1" name="B"/><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:anchor></w:drawing></w:r><w:r><w:t>A</w:t></w:r></w:p>"#
)
};
let sq = r#"<wp:wrapSquare wrapText="bothSides"/>"#;
// Mode 15 wrapped 120 pt box at y=658 overflows body_bottom (720) -> anchor moves to page 2.
let pushed = lay_out(&(filler.clone() + &anchor(0, sq)), NORMAL, Some(15));
assert_eq!(find(&pushed, 'A').0, 1);
// Negative offset (-80 pt) keeps box inside body_bottom -> anchor stays on page 1.
let neg_ok = lay_out(
&(filler.clone() + &anchor(-1_016_000, sq)),
NORMAL,
Some(15),
);
assert_eq!(find(&neg_ok, 'A').0, 0);
// wrapNone and mode 14 stay on page 1.
let unwrapped = lay_out(
&(filler.clone() + &anchor(0, "<wp:wrapNone/>")),
NORMAL,
Some(15),
);
assert_eq!(find(&unwrapped, 'A').0, 0);
let old_mode = lay_out(&(filler + &anchor(0, sq)), NORMAL, Some(14));
assert_eq!(find(&old_mode, 'A').0, 0);
}
#[test]
fn hanging_indent_first_line_beside_left_drawing_keeps_first_start_before_mode_15() {
use super::testing::{NORMAL, find, lay_out};
use crate::ns::{A, WP, WPS};
// 1-inch square wrap at left edge of column (914400 EMU = 72 pt, distR = 0).
let body = format!(
concat!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="exact"/></w:pPr>"#,
r#"<w:r><w:drawing><wp:anchor xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">"#,
r#"<wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH>"#,
r#"<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>"#,
r#"<wp:extent cx="914400" cy="914400"/><wp:effectExtent l="0" t="0" r="0" b="0"/>"#,
r#"<wp:wrapSquare wrapText="bothSides"/><wp:docPr id="1" name="B"/>"#,
r#"<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>"#,
r#"</wp:anchor></w:drawing></w:r><w:r><w:t>A</w:t></w:r></w:p>"#,
// left=720 (36 pt), hanging=240 (12 pt) -> first_start = 480 twips (24 pt = 100 dots at 300 dpi).
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="exact"/><w:ind w:left="720" w:hanging="240"/></w:pPr><w:r><w:t>H</w:t><w:tab/><w:t>T</w:t></w:r></w:p>"#,
),
WP = WP,
A = A,
WPS = WPS,
);
let m15 = lay_out(&body, NORMAL, Some(15));
let m14 = lay_out(&body, NORMAL, Some(14));
let units = |twips: i64| Length::from_twips(twips).unwrap().units();
// Mode 14 shifts the hanging-indent first line right by first_start (480 twips)
// and shifts its hanging tab stop to wrap_edge + left (720 twips past wrap_edge).
assert_eq!(find(&m14, 'H').1 - find(&m15, 'H').1, units(480));
assert_eq!(find(&m14, 'T').1 - find(&m15, 'H').1, units(720));
}
#[test]
fn keep_lines_paragraph_before_mode_15_shifts_to_wrap_top_when_line_overlaps_it() {
use super::testing::{NORMAL, find, lay_out};
use crate::ns::{A, WP, WPS};
// Anchor line is 240 twips (12 pt); box starts 18 pt (228600 EMU) below anchor top, i.e.,
// 6 pt below the second paragraph's natural top (12 pt).
let make = |keep: &str| {
format!(
concat!(
r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="exact"/></w:pPr>"#,
r#"<w:r><w:drawing><wp:anchor xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">"#,
r#"<wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH>"#,
r#"<wp:positionV relativeFrom="paragraph"><wp:posOffset>228600</wp:posOffset></wp:positionV>"#,
r#"<wp:extent cx="914400" cy="914400"/><wp:effectExtent l="0" t="0" r="0" b="0"/>"#,
r#"<wp:wrapSquare wrapText="bothSides"/><wp:docPr id="1" name="B"/>"#,
r#"<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>"#,
r#"</wp:anchor></w:drawing></w:r><w:r><w:t>A</w:t></w:r></w:p>"#,
r#"<w:p><w:pPr>{keep}<w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
),
WP = WP,
A = A,
WPS = WPS,
keep = keep,
)
};
let dots = |twips: i64| twips * 300 / 1440;
let m14_keep = lay_out(&make("<w:keepLines/>"), NORMAL, Some(14));
let m14_plain = lay_out(&make(""), NORMAL, Some(14));
let m15_keep = lay_out(&make("<w:keepLines/>"), NORMAL, Some(15));
// Mode 14 with keepLines moves B down by 6 pt (120 twips = 25 dots at 300 dpi) to the wrap top.
assert_eq!(find(&m14_keep, 'B').2 - find(&m14_plain, 'B').2, dots(120));
// Mode 15 with keepLines does not move B.
assert_eq!(find(&m15_keep, 'B').2, find(&m14_plain, 'B').2);
}