f-office-docx 0.2.4

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("baseline", 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}");
    }
}

#[test]
fn aligns_exact_lines_at_center_and_top_with_and_without_space_for_ul() {
    // 20 pt exact line with 12 pt ('a', win_top 9.6 pt, descent 2.4 pt, middle 3.6 pt = 15 dots)
    // and 20 pt ('b', win_top 16 pt, descent 4 pt, middle 6 pt = 25 dots), followed by a
    // reference paragraph ('r').
    let exact = r#"w:line="400" w:lineRule="exact""#;
    let body = paragraph("center", exact, "", &[("a", 24), ("b", 40)])
        + &paragraph("top", exact, "", &[("c", 24)])
        + &paragraph("baseline", exact, "", &[("r", 24)]);
    let still = lay_out(&body, "", CenteredLine::OnBaseline);
    let moved = lay_out(&body, "", CenteredLine::MiddlesShared);
    let shifts =
        |list: &DisplayList| ['a', 'b', 'c', 'r'].map(|ch| find(list, ch).2 - find(&still, ch).2);
    // Without spaceForUL: center shifts down by (win_top - descent)/2 (3.6 pt and 6 pt), top
    // shifts down by win_top (9.6 pt), and the following line keeps its place.
    assert_eq!(shifts(&moved), [dots(36), dots(60), dots(96), 0]);
    // With spaceForUL: the 20 pt exact line's alignment box rises 3/5 * 20 = 12 pt above the
    // baseline, so center moves up by 6 pt (-2.4 pt for 12 pt, 0 pt for 20 pt) and top moves up
    // by 12 pt (-2.4 pt for 12 pt).
    let with_ul = lay_out_with_space_for_ul(&body);
    assert_eq!(shifts(&with_ul), [-dots(24), 0, -dots(24), 0]);
}

fn lay_out_with_space_for_ul(body: &str) -> DisplayList {
    use crate::body::Body;
    use crate::layout::testing::{Fake, base_context, on_base_with, parse, sections_of};
    use crate::layout::{Context, Layout, Stories};
    use crate::reader::PartReader;
    use crate::styles::{FontTable, Settings, SpaceForUl, Styles, Theme};
    use crate::text::{Shaper, ShaperSettings};

    let (device, quirks) = on_base_with(|p| p.with_variant(CenteredLine::MiddlesShared));
    let settings_xml =
        format!(r#"<w:settings xmlns:w="{W}"><w:compat><w:spaceForUL/></w:compat></w:settings>"#);
    let settings_doc = parse(&settings_xml);
    let settings = Settings::read(
        &mut PartReader::new(&settings_doc),
        settings_doc.root().unwrap(),
    );
    assert_eq!(settings.space_for_ul, SpaceForUl::On);
    let doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
    let body = Body::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        (
            crate::reader::settings::ReaderSettings::of(&quirks),
            settings.mode_rules,
        ),
    );
    let styles = Styles::default();
    let context = Context {
        device,
        quirks,
        ..base_context(&styles, &settings)
    };
    let stories = context.for_stories();
    let sections = sections_of(&body, &Stories::default());
    let (theme, table, shaper) = (
        Theme::default(),
        FontTable::default(),
        ShaperSettings::base(),
    );
    Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &table, &shaper),
    )
    .run_with_wraps(&body)
    .list
}

/// 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()
}