f-office 0.2.4

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Layout tests of paragraphs: spacing, lines kept together, tabs, the document grid and
//! right-to-left text.

use f_office_paint::Item;

use super::{
    CARLITO_FONTS, CARLITO_RUN, SECTION, baseline_of, capacity, carlito_line, docx, lines, para,
    placed, points, render,
};

#[test]
fn gives_tabs_no_room_when_the_default_stop_distance_is_zero() {
    let body = format!(
        "<w:p><w:r>{CARLITO_RUN}<w:tab/><w:tab/><w:tab/><w:t>Text</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let x = |settings: &str| placed(&render(&docx(&body, &[], settings)))[0][0].0;
    // With default stops every 36 pt, three tabs take the text 108 pt from the margin.
    assert!((x("") - 36.0 - 108.0).abs() <= 0.25, "{}", x(""));
    // With a distance of 0 there are no default stops, and the tabs take no room.
    let none = x(r#"<w:defaultTabStop w:val="0"/>"#);
    assert!((none - 36.0).abs() <= 0.25, "{none}");
}

#[test]
fn keeps_only_the_own_share_of_the_space_before_after_contextual_spacing() {
    let first = para("One").replacen(
        "<w:p>",
        r#"<w:p><w:pPr><w:spacing w:after="120"/><w:contextualSpacing/></w:pPr>"#,
        1,
    );
    let second = para("Two").replacen(
        "<w:p>",
        r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr>"#,
        1,
    );
    let body = format!("{first}{second}<w:sectPr>{SECTION}</w:sectPr>");
    let page = &lines(&render(&docx(&body, &[], "")))[0];
    let y = |text: &str| page.iter().find(|(_, t)| t == text).unwrap().0;
    let (_, line) = carlito_line();
    // Contextual spacing removes the 6 pt after "One", and of the 12 pt before "Two", only
    // the 6 pt beyond that space after stay.
    let gap = y("Two") - y("One");
    assert!((gap - line - 6.0).abs() <= 0.25, "{gap}");
}

#[test]
fn leaves_out_the_space_after_before_a_table_when_contextual_spacing_removes_it() {
    let table = format!(
        r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>"#,
        para("Cell")
    );
    let gap = |props: &str| {
        let head = para("Head").replacen("<w:p>", &format!("<w:p><w:pPr>{props}</w:pPr>"), 1);
        let body = format!("{head}{table}<w:sectPr>{SECTION}</w:sectPr>");
        let page = &lines(&render(&docx(&body, &[], "")))[0];
        let y = |text: &str| page.iter().find(|(_, t)| t == text).unwrap().0;
        y("Cell") - y("Head")
    };
    let (_, line) = carlito_line();
    // 10 pt after the paragraph stay above the table.
    let spaced = gap(r#"<w:spacing w:after="200"/>"#);
    assert!((spaced - line - 10.0).abs() <= 0.25, "{spaced}");
    // With contextual spacing, they go, since the first paragraph of the first cell has the
    // same style.
    let contextual = gap(r#"<w:spacing w:after="200"/><w:contextualSpacing/>"#);
    assert!((contextual - line).abs() <= 0.25, "{contextual}");
}

#[test]
fn keeps_a_paragraph_with_the_first_row_of_the_table_after_it() {
    let (_, line) = carlito_line();
    let filler: String = (1..capacity(line))
        .map(|i| para(&format!("Line {i}")))
        .collect();
    let table = format!(
        r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>"#,
        para("Cell")
    );
    let first_on_page_two = |keep: &str| {
        let head = para("Head").replacen("<w:p>", &format!("<w:p><w:pPr>{keep}</w:pPr>"), 1);
        let body = format!("{filler}{head}{table}<w:sectPr>{SECTION}</w:sectPr>");
        let pages = lines(&render(&docx(&body, &[], "")));
        pages[1][0].1.clone()
    };
    // The heading fits in the last line of page 1, but the row below it does not.
    assert_eq!(first_on_page_two(""), "Cell");
    assert_eq!(first_on_page_two("<w:keepNext/>"), "Head");
}

/// A paragraph whose lines are `names`, split by line breaks, with extra paragraph properties.
fn broken(names: &[String], ppr: &str) -> String {
    let runs: Vec<String> = names
        .iter()
        .map(|name| format!("<w:r>{CARLITO_RUN}<w:t>{name}</w:t><w:br/></w:r>"))
        .collect();
    let mut runs = runs.concat();
    runs.truncate(runs.len() - "<w:br/></w:r>".len());
    format!("<w:p><w:pPr>{ppr}</w:pPr>{runs}</w:r></w:p>")
}

#[test]
fn keeps_the_last_lines_of_a_paragraph_together() {
    // The page body is 128 pt high. Fill all but two lines, then add a paragraph of three.
    let (_, line) = carlito_line();
    let capacity = capacity(line);
    let first_on_page_two = |free: usize, tail: &[&str], ppr: &str| {
        let filler: Vec<String> = (0..capacity - free).map(|i| format!("F{i}")).collect();
        let tail: Vec<String> = tail.iter().map(|t| (*t).to_owned()).collect();
        let body = format!(
            "{}{}<w:sectPr>{SECTION}</w:sectPr>",
            broken(&filler, ""),
            broken(&tail, ppr)
        );
        let pages = lines(&render(&docx(&body, &[], "")));
        assert_eq!(pages.len(), 2, "{pages:?}");
        pages[1][0].1.clone()
    };
    // Only "Z" would move, which would leave it alone, and moving "Y" too would leave "X"
    // alone, so the whole paragraph moves.
    assert_eq!(first_on_page_two(2, &["X", "Y", "Z"], ""), "X");
    let off = r#"<w:widowControl w:val="0"/>"#;
    assert_eq!(first_on_page_two(2, &["X", "Y", "Z"], off), "Z");
    // With four lines, "Y" moves with "Z".
    assert_eq!(first_on_page_two(3, &["W", "X", "Y", "Z"], ""), "Y");
    // Only "X" would stay, so it moves with the rest.
    assert_eq!(first_on_page_two(1, &["X", "Y", "Z"], ""), "X");
    assert_eq!(first_on_page_two(1, &["X", "Y", "Z"], off), "Y");
    // Kept lines move whole even without widow control.
    let whole = r#"<w:widowControl w:val="0"/><w:keepLines/>"#;
    assert_eq!(first_on_page_two(3, &["W", "X", "Y", "Z"], whole), "W");
}

#[test]
fn leaves_out_automatic_space_above_the_first_paragraph() {
    let auto = r#"<w:pPr><w:spacing w:before="0" w:beforeAutospacing="1" w:after="0"/></w:pPr>"#;
    let para = |ppr: &str, text: &str| {
        format!(r"<w:p>{ppr}<w:r>{CARLITO_RUN}<w:t>{text}</w:t></w:r></w:p>")
    };
    let ys = |body: String| -> Vec<f64> {
        let body = format!("{body}<w:sectPr>{SECTION}</w:sectPr>");
        lines(&render(&docx(&body, &[], "")))[0]
            .iter()
            .map(|(y, _)| *y)
            .collect()
    };
    let plain = ys(para("", "A") + &para("", "B"));
    let spaced = ys(para(auto, "A") + &para(auto, "B"));
    // The first paragraph stays at the margin, and the second one gets its 14 pt.
    assert_eq!(spaced[0], plain[0]);
    assert!(
        (spaced[1] - plain[1] - 14.0).abs() <= 0.25,
        "{spaced:?} {plain:?}"
    );
}

#[test]
fn fills_whole_steps_of_the_document_grid_with_the_text_in_the_middle() {
    let page = |snap: &str| {
        let para = |text: &str| {
            format!(
                r#"<w:p><w:pPr><w:spacing w:after="0"/>{snap}</w:pPr><w:r>{CARLITO_RUN}<w:t>{text}</w:t></w:r></w:p>"#
            )
        };
        let body = format!(
            r#"{}{}<w:sectPr>{SECTION}<w:docGrid w:type="lines" w:linePitch="400"/></w:sectPr>"#,
            para("One"),
            para("Two"),
        );
        let list = render(&docx(&body, &[], ""));
        (baseline_of(&list, "One"), baseline_of(&list, "Two"))
    };
    let (ascent, line) = carlito_line();
    // A 10 pt line of 12.2 pt fills one step of 20 pt, with half the rest above it.
    let (one, two) = page("");
    assert!((two - one - 20.0).abs() <= 0.25, "{one} {two}");
    assert!(
        (one - (36.0 + (20.0 - line) / 2.0 + ascent)).abs() <= 0.25,
        "{one}"
    );
    // A paragraph that does not snap to the grid keeps its own line height.
    let (one, two) = page(r#"<w:snapToGrid w:val="0"/>"#);
    assert!((two - one - line).abs() <= 0.25, "{one} {two}");
}

#[test]
fn starts_a_right_to_left_paragraph_at_the_right_margin() {
    let paragraph = |bidi: &str| {
        let body = format!(
            "<w:p><w:pPr>{bidi}</w:pPr><w:r>{CARLITO_RUN}<w:t>Text</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
        );
        let list = render(&docx(&body, &[], ""));
        list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                Item::Glyphs(run) => Some((
                    points(run.glyphs[0].x.units()),
                    points(run.glyphs.last().unwrap().x.units()),
                )),
                _ => None,
            })
            .unwrap()
    };
    let (left, _) = paragraph("");
    assert!((left - 36.0).abs() <= 0.12, "{left}");
    // The page is 300 pt wide with margins of 36 pt, so the text ends near 264 pt.
    let (first, last) = paragraph("<w:bidi/>");
    assert!(
        first > 200.0 && last < 264.0 && last > 250.0,
        "{first} {last}"
    );
}

#[test]
fn keeps_a_heading_with_the_next_paragraph() {
    let (_, line) = carlito_line();
    let capacity = capacity(line);
    let filler: Vec<String> = (0..capacity - 2).map(|i| format!("F{i}")).collect();
    let heading = |ppr: &str| broken(&["H".to_owned()], ppr);
    let next = broken(&["A".to_owned(), "B".to_owned()], "");
    let pages_for = |ppr: &str| {
        let body = format!(
            "{}{}{next}<w:sectPr>{SECTION}</w:sectPr>",
            broken(&filler, ""),
            heading(ppr)
        );
        lines(&render(&docx(&body, &[], "")))
    };
    // Without the keep, "H" ends page 1 and "A" with "B" move on.
    let loose = pages_for("");
    assert_eq!(loose[1][0].1, "A");
    // With it, "H" moves with them, and its space before is dropped at the top of page 2.
    let kept = pages_for(r#"<w:keepNext/><w:spacing w:before="480"/>"#);
    let texts: Vec<&str> = kept[1].iter().map(|(_, t)| t.as_str()).collect();
    assert_eq!(texts, ["H", "A", "B"]);
    assert!(
        (kept[1][0].0 - loose[1][0].0).abs() < 1e-9,
        "{kept:?} {loose:?}"
    );
}

#[test]
fn rounds_the_margin_to_the_device_grid_but_not_the_indent() {
    // A left margin of 1418 twips (70.9 pt) lands on 295 device dots (70.80 pt), and an
    // indent of 709 twips (35.45 pt) is added to it as it is.
    let section = r#"<w:pgSz w:w="6000" w:h="4000"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="1418" w:header="240" w:footer="240"/>"#;
    let body = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r></w:p><w:p><w:pPr><w:ind w:left="709"/></w:pPr><w:r>{CARLITO_RUN}<w:t>B</w:t></w:r></w:p><w:sectPr>{section}</w:sectPr>"#
    );
    let list = render(&docx(&body, &[], ""));
    let starts: Vec<f64> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => run.glyphs.first().map(|g| points(g.x.units())),
            _ => None,
        })
        .collect();
    assert_eq!(starts.len(), 2, "{starts:?}");
    assert!((starts[0] - 70.80).abs() < 1e-9, "{starts:?}");
    assert!((starts[1] - 106.25).abs() < 1e-9, "{starts:?}");
}

#[test]
fn sizes_a_last_line_of_spaces_by_a_taller_paragraph_mark() {
    // A line of 10 pt spaces whose paragraph mark is 20 pt, then a line of text.
    let body = format!(
        r#"<w:p><w:pPr><w:rPr>{CARLITO_FONTS}<w:sz w:val="40"/></w:rPr></w:pPr><w:r>{CARLITO_RUN}<w:t xml:space="preserve">    </w:t></w:r></w:p>{}<w:sectPr>{SECTION}</w:sectPr>"#,
        para("Next")
    );
    let page = &lines(&render(&docx(&body, &[], "")))[0];
    let (ascent, line) = carlito_line();
    let (y, _) = page.iter().find(|(_, t)| t == "Next").unwrap();
    assert!((y - (36.0 + 2.0 * line + ascent)).abs() <= 0.25, "{page:?}");
}

#[test]
fn makes_no_stop_of_a_bar_tab_so_that_a_tab_goes_on_to_the_next_stop() {
    // A bar at 2 cm and a left stop at 5 cm, 1134 and 2835 twips.
    let tabs =
        r#"<w:tabs><w:tab w:val="bar" w:pos="1134"/><w:tab w:val="left" w:pos="2835"/></w:tabs>"#;
    let body = format!(
        "<w:p><w:pPr>{tabs}</w:pPr><w:r>{CARLITO_RUN}<w:t>A</w:t><w:tab/><w:t>B</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let list = render(&docx(&body, &[], ""));
    let b = list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Glyphs(run) if run.text.ends_with('B') => run.glyphs.last(),
            _ => None,
        })
        .unwrap();
    // The margin of 36 pt and the stop at 141.75 pt.
    let x = points(b.x.units());
    assert!((x - (36.0 + 141.75)).abs() <= 0.25, "{x}");
}

#[test]
fn puts_leader_dots_on_a_grid_from_the_left_edge_of_the_page_in_objects_of_32() {
    // A left margin of 36.5 pt, so that a grid from the margin differs from one from the page.
    let section = SECTION.replace(r#"w:left="720""#, r#"w:left="730""#);
    let body = format!(
        r#"<w:p><w:pPr><w:tabs><w:tab w:val="right" w:leader="dot" w:pos="6000"/></w:tabs></w:pPr><w:r>{CARLITO_RUN}<w:t>A</w:t><w:tab/><w:t>B</w:t></w:r></w:p><w:sectPr>{section}</w:sectPr>"#
    );
    let list = render(&docx(&body, &[], ""));
    let dots = list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Glyphs(run) if run.text.starts_with("...") => Some(run),
            _ => None,
        })
        .unwrap();
    // The dots 1, 33 and 65 start text objects of the PDF writer, each at its exact place, so
    // they lie 32 whole cells of the grid apart.
    let x = |index: usize| dots.glyphs[index].x.units();
    assert!(dots.glyphs.len() > 64, "{}", dots.glyphs.len());
    assert_eq!(x(64) - x(32), x(32) - x(0));
    let first = points(x(0));
    let step = points(x(32) - x(0)) / 32.0;
    let cells = first / step;
    assert!((cells - cells.round()).abs() < 1e-6, "{first} {step}");
}