f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
use f_office_paint::DisplayList;
use f_office_units::Length;

use crate::grid::DOT;
use crate::layout::testing::{LARGE_LABELS, find, lay_out_with_numbering_as, on_base};
use crate::ns::W;
use crate::quirks::{CenteredLine, CenteredMultiple};

/// The fake fonts' win line is 1 pt per point of size, 0.8 pt of it above the baseline, so the
/// middle of a win line lies 0.3 pt per point of size above its baseline.
const MIDDLE_PER_POINT: i64 = 3;

/// Dots in `tenths` of a point.
fn dots(tenths: i64) -> i64 {
    f_office_units::div_round(tenths * Length::UNITS_PER_POINT / 10, DOT)
}

/// Lays out `body` with the lists of `numbering`, where the target's centered lines take the
/// variant `variant`.
fn lay_out(body: &str, numbering: &str, variant: CenteredLine) -> DisplayList {
    let numbering = format!(r#"<w:numbering xmlns:w="{W}">{numbering}</w:numbering>"#);
    lay_out_with_numbering_as(body, &numbering, variant)
}

/// A paragraph of the text alignment `alignment` and the spacing `spacing`, with the runs
/// `runs` of (text, size in half points), and a list's `numbering` properties.
fn paragraph(alignment: &str, spacing: &str, list: &str, runs: &[(&str, u32)]) -> String {
    let runs = runs
        .iter()
        .map(|(text, size)| {
            format!(r#"<w:r><w:rPr><w:sz w:val="{size}"/></w:rPr><w:t>{text}</w:t></w:r>"#)
        })
        .collect::<Vec<_>>()
        .concat();
    format!(
        r#"<w:p><w:pPr>{list}<w:spacing w:before="0" w:after="0" {spacing}/><w:textAlignment w:val="{alignment}"/></w:pPr>{runs}</w:p>"#
    )
}

const SINGLE: &str = r#"w:line="240" w:lineRule="auto""#;

#[test]
fn the_base_profile_keeps_the_pieces_of_a_centered_line_on_one_baseline() {
    assert_eq!(on_base().1.centered_line, CenteredLine::OnBaseline);
}

#[test]
fn shares_the_middles_of_two_sizes_and_keeps_the_line_height() {
    let body = paragraph("center", SINGLE, "", &[("a", 24), ("b", 40)])
        + &paragraph("center", SINGLE, "", &[("c", 24)]);
    let still = lay_out(&body, "", CenteredLine::OnBaseline);
    let moved = lay_out(&body, "", CenteredLine::MiddlesShared);
    assert_eq!(find(&still, 'a').2, find(&still, 'b').2);
    // The 12 pt run's middle lies 3.6 pt above its baseline, the 20 pt run's 6 pt above its own.
    assert_eq!(
        find(&moved, 'b').2 - find(&moved, 'a').2,
        dots(MIDDLE_PER_POINT * 8)
    );
    assert_eq!(find(&moved, 'b').2, find(&still, 'b').2);
    // One face at two sizes: the tallest win line holds the deepest descent, so the line keeps
    // its height.
    assert_eq!(find(&moved, 'c').2, find(&still, 'c').2);
}

#[test]
fn a_list_label_counts_for_the_top_and_its_descent_stays_out() {
    let list = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>"#;
    let body = paragraph("center", SINGLE, list, &[("a", 24)])
        + &paragraph("center", SINGLE, "", &[("c", 24)]);
    let still = lay_out(&body, LARGE_LABELS, CenteredLine::OnBaseline);
    let moved = lay_out(&body, LARGE_LABELS, CenteredLine::MiddlesShared);
    // The 20 pt label keeps its place, and the 12 pt text's middle comes onto the label's
    // middle, 2.4 pt higher.
    assert_eq!(find(&moved, '1').2, find(&still, '1').2);
    assert_eq!(
        find(&still, 'a').2 - find(&moved, 'a').2,
        dots(MIDDLE_PER_POINT * 8)
    );
    // Without the alignment the line is the label's ascent (16 pt) and the text's descent
    // (2.4 pt) tall; with it, it ends at the text's win bottom, half the label's win line and
    // half the text's below the middle: 16 pt.
    assert_eq!(find(&still, 'c').2 - find(&moved, 'c').2, dots(24));
}

#[test]
fn leaves_other_alignments_and_spacings_on_one_baseline() {
    let exact = r#"w:line="480" w:lineRule="exact""#;
    let multiple = r#"w:line="360" w:lineRule="auto""#;
    for body in [
        paragraph("top", SINGLE, "", &[("a", 20), ("b", 40)]),
        paragraph("baseline", SINGLE, "", &[("a", 20), ("b", 40)]),
        paragraph("center", exact, "", &[("a", 20), ("b", 40)]),
        paragraph("center", multiple, "", &[("a", 20), ("b", 40)]),
    ] {
        let moved = lay_out(&body, "", CenteredLine::MiddlesShared);
        assert_eq!(find(&moved, 'a').2, find(&moved, 'b').2, "{body}");
    }
}

/// Lays out `body` where the target's centered lines of multiple spacing take the variant
/// `variant`.
fn lay_out_multiple(body: &str, variant: CenteredMultiple) -> DisplayList {
    let numbering = format!(r#"<w:numbering xmlns:w="{W}"></w:numbering>"#);
    lay_out_with_numbering_as(body, &numbering, variant)
}

const MULTIPLE: &str = r#"w:line="360" w:lineRule="auto""#;

#[test]
fn the_base_profile_keeps_a_centered_line_of_multiple_spacing_on_its_baseline() {
    assert_eq!(on_base().1.centered_multiple, CenteredMultiple::OnBaseline);
}

#[test]
fn rounds_the_middle_of_a_centered_line_of_multiple_spacing() {
    let body = paragraph("center", MULTIPLE, "", &[("a", 20)]);
    let still = lay_out_multiple(&body, CenteredMultiple::OnBaseline);
    let moved = lay_out_multiple(&body, CenteredMultiple::MiddleRounded);
    // A 10 pt line at 1.5 lines without space before, on the test device's dots of 0.24 pt:
    // the win top 33 1/3 dots, the descent 8 1/3 and the height 62.5. The middle lies 12.5
    // dots above the baseline, so it goes the larger of round(33 1/3 - 12.5) = 21 and
    // round(62.5) - round(20 5/6) - round(20 5/6) = 21 below the box's top. The pixel line at
    // 42 pels is 34 above and 8 below the baseline, so the baseline lies 13 below the middle:
    // 34 below the top, where the box puts it at 33.
    let dot = crate::grid::base_device().dots(1).units();
    assert_eq!(baseline(&moved, 'a') - baseline(&still, 'a'), dot);
}

#[test]
fn leaves_single_spacing_other_alignments_and_two_faces_to_the_box() {
    for body in [
        paragraph("center", SINGLE, "", &[("a", 22)]),
        paragraph("top", MULTIPLE, "", &[("a", 22)]),
        paragraph("center", MULTIPLE, "", &[("a", 22), ("b", 40)]),
    ] {
        let still = lay_out_multiple(&body, CenteredMultiple::OnBaseline);
        let moved = lay_out_multiple(&body, CenteredMultiple::MiddleRounded);
        assert_eq!(baseline(&moved, 'a'), baseline(&still, 'a'), "{body}");
    }
}

/// The baseline of the first glyph of `ch` in `list`, in half-EMUs.
fn baseline(list: &DisplayList, ch: char) -> i64 {
    list.pages()
        .iter()
        .flat_map(f_office_paint::Page::painted)
        .filter_map(|item| match item {
            f_office_paint::Painted::Glyphs(run) => Some(run),
            _ => None,
        })
        .flat_map(|run| {
            run.glyphs
                .iter()
                .filter(|glyph| {
                    run.glyph_text(glyph)
                        .is_some_and(|text| text.starts_with(ch))
                })
                .map(|glyph| glyph.y.units())
        })
        .next()
        .unwrap()
}