f-office 0.3.0

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Tests that lay out small DOCX files, in one module for each topic, with the helpers that the
//! modules share.

mod drawings;
mod fields;
mod frames;
mod links;
mod notes;
mod pages;
mod paragraphs;
mod text;
mod text_map;

use f_office_docx::testing::{self, RELATIONSHIPS, WordParts as _};
use f_office_paint::{DisplayList, Item};

use super::{Document, FontDb, Options};
use crate::test_fonts::{CARLITO, CARLITO_FONTS, CARLITO_RUN, carlito};

/// A paragraph of Carlito text.
fn para(text: &str) -> String {
    format!(r#"<w:p><w:r>{CARLITO_RUN}<w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#)
}

/// The runs of a field with a stale stored result.
fn field(code: &str) -> String {
    format!(
        r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText>{code}</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r>{CARLITO_RUN}<w:t>99</w:t></w:r><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="end"/></w:r>"#
    )
}

/// Packs a DOCX file. `stories` are header (`h…`) and footer (`f…`) parts by relationship ID.
/// Its styles part has empty document defaults, which keep the text at the defaults of
/// ECMA-376, not those of Word's template.
fn docx(body: &str, stories: &[(&str, &str)], settings: &str) -> Vec<u8> {
    let package = stories
        .iter()
        .fold(testing::docx(body), |package, (id, xml)| {
            let (kind, root) = match id.chars().next() {
                Some('h') => ("header", "hdr"),
                Some('n') => ("footnotes", "footnotes"),
                Some('e') => ("endnotes", "endnotes"),
                _ => ("footer", "ftr"),
            };
            package.word_part(id, kind, &format!("{id}.xml"), root, xml)
        });
    package
        .word_part("s", "settings", "settings.xml", "settings", settings)
        .plain_styles()
        .zip()
        .unwrap()
}

fn render(docx: &[u8]) -> DisplayList {
    let fonts = carlito();
    // The tests read only the display list, so the helper keeps a copy of it.
    let document = Document::open(docx, &fonts, &Options::base())
        .unwrap()
        .value;
    document.display_list().clone()
}

/// The lines of each page as (baseline in points, text), from the top.
fn lines(list: &DisplayList) -> Vec<Vec<(f64, String)>> {
    list.pages()
        .iter()
        .map(|page| {
            let mut lines: Vec<(i64, String)> = Vec::new();
            for item in page.items() {
                let Item::Glyphs(run) = item else { continue };
                let Some(first) = run.glyphs.first() else {
                    continue;
                };
                let y = first.y.units();
                match lines.iter_mut().find(|(at, _)| *at == y) {
                    Some((_, text)) => text.push_str(&run.text),
                    None => lines.push((y, run.text.clone())),
                }
            }
            lines.sort_by_key(|(y, _)| *y);
            lines
                .into_iter()
                .map(|(y, text)| (points(y), text.trim().to_owned()))
                .collect()
        })
        .collect()
}

/// A length of the display list in points.
fn points(units: i64) -> f64 {
    let small = |value: i64| f64::from(i32::try_from(value).expect("a test page is small"));
    small(units) / small(super::Length::UNITS_PER_POINT)
}

/// How many lines of `line` points fit in the 128 pt body of the test page.
fn capacity(line: f64) -> usize {
    (1..1000)
        .filter(|n: &i32| f64::from(*n) * line <= 128.0)
        .count()
}

/// The ascent and the line height of 10 pt Carlito, in points, as the layout computes them.
fn carlito_line() -> (f64, f64) {
    let mut fonts = FontDb::new();
    let id = fonts.add_font(CARLITO.to_vec()).unwrap()[0];
    let m = fonts.metrics(id).unwrap();
    let em = f64::from(m.units_per_em);
    let line = f64::from(
        i32::from(m.hhea.ascender) - i32::from(m.hhea.descender) + i32::from(m.hhea.line_gap),
    ) / em
        * 10.0;
    let descent = f64::from(m.os2.as_ref().unwrap().win_descent) / em * 10.0;
    (line - descent, line)
}

/// A page of 300 by 200 points. Every distance is a whole number of grid steps of 0.24 pt.
const SECTION: &str = r#"<w:pgSz w:w="6000" w:h="4000"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720" w:header="240" w:footer="240"/>"#;

/// A run with a floating text box that says "Box", without wrap distances, with `place`: its
/// position, extent and wrap elements.
fn text_box(place: &str) -> String {
    format!(
        r#"<w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:anchor distT="0" distB="0" distL="0" distR="0">{place}<a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>Box</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
    )
}

/// A position from `from` at `x` and `y` EMU.
fn anchored_at(from: &str, x: i64, y: i64) -> String {
    format!(
        r#"<wp:positionH relativeFrom="{from}"><wp:posOffset>{x}</wp:posOffset></wp:positionH><wp:positionV relativeFrom="{from}"><wp:posOffset>{y}</wp:posOffset></wp:positionV>"#
    )
}

/// The text runs of each page as (x, baseline, text) in points, from the top and the left.
fn placed(list: &DisplayList) -> Vec<Vec<(f64, f64, String)>> {
    list.pages()
        .iter()
        .map(|page| {
            let mut runs: Vec<(f64, f64, String)> = page
                .items()
                .iter()
                .filter_map(|item| match item {
                    Item::Glyphs(run) => run
                        .glyphs
                        .first()
                        .map(|g| (points(g.x.units()), points(g.y.units()), run.text.clone())),
                    _ => None,
                })
                .collect();
            runs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
            runs
        })
        .collect()
}

/// The baseline of the first glyph of each run with this text on the first page.
fn baseline_of(list: &DisplayList, text: &str) -> f64 {
    list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Glyphs(run) if run.text == text => Some(points(run.glyphs[0].y.units())),
            _ => None,
        })
        .unwrap()
}

/// The settings of a document in compatibility mode `N`.
fn compatibility_mode(mode: u32) -> String {
    format!(
        r#"<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="{mode}"/></w:compat>"#
    )
}

/// The filled rectangles of the first page in points, as (x, y, width, height, color).
fn fills(list: &DisplayList) -> Vec<(f64, f64, f64, f64, [u8; 3])> {
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(rect) => Some((
                points(rect.x.units()),
                points(rect.y.units()),
                points(rect.width.units()),
                points(rect.height.units()),
                [rect.color.r, rect.color.g, rect.color.b],
            )),
            _ => None,
        })
        .collect()
}

/// A document with one header part, whose text nests four elements deep: the header, its
/// paragraph, its run and its text. The body's empty paragraph and its section nest less.
fn with_a_deep_header() -> Vec<u8> {
    docx(
        r#"<w:p/><w:sectPr><w:headerReference w:type="default" r:id="h1"/></w:sectPr>"#,
        &[("h1", "<w:p><w:r><w:t>a</w:t></w:r></w:p>")],
        "",
    )
}

/// `Document::open` of `docx` with the limits that `set` gives, as its error chain.
fn opened_within(docx: &[u8], set: impl Fn(&mut super::Limits)) -> Result<Document, String> {
    let mut options = Options::base();
    set(&mut options.limits);
    Document::open(docx, &FontDb::new(), &options)
        .map(|warned| warned.value)
        .map_err(|error| super::error_chain(&error))
}

#[test]
fn stops_at_a_limit_of_the_zip_file_that_the_options_set() {
    let file = with_a_deep_header();
    assert!(opened_within(&file, |_| {}).is_ok());
    let entries = opened_within(&file, |limits| limits.max_entries = 2).unwrap_err();
    assert!(
        entries.ends_with("package breaks the limit on the number of entries"),
        "{entries}"
    );
    let part = opened_within(&file, |limits| limits.max_part_size = 64).unwrap_err();
    assert!(
        part.ends_with("package breaks the limit on the size of a part"),
        "{part}"
    );
}

#[test]
fn stops_at_a_limit_of_the_main_document_or_the_package_relationships() {
    let file = docx(&para("a"), &[], "");
    let deep = opened_within(&file, |limits| limits.xml.max_depth = 3).unwrap_err();
    assert_eq!(
        deep,
        "the DOCX content could not be laid out: a part is not valid XML: XML nesting is too deep"
    );
    let nodes = opened_within(&file, |limits| limits.xml.max_nodes = 1).unwrap_err();
    assert!(
        nodes.starts_with("the DOCX content could not be laid out: the package could not be read")
            && nodes.ends_with("XML has too many nodes"),
        "{nodes}"
    );
}

#[test]
fn skips_another_part_that_breaks_an_xml_limit_with_a_warning() {
    use super::docx::{Reason, Warning as DocxWarning};
    let file = with_a_deep_header();
    let mut options = Options::base();
    options.limits.xml.max_depth = 3;
    let opened = Document::open(&file, &FontDb::new(), &options).unwrap();
    let skipped: Vec<_> = opened
        .warnings
        .iter()
        .filter_map(|(warning, _)| match warning {
            super::Warning::Docx(DocxWarning::PartSkipped { part, reason }) => {
                Some((part.as_str().to_owned(), *reason))
            }
            _ => None,
        })
        .collect();
    assert_eq!(skipped, [("word/h1.xml".to_owned(), Reason::NotXml)]);
    let open = Document::open(&file, &FontDb::new(), &Options::base()).unwrap();
    assert!(open.warnings.iter().all(|(warning, _)| !matches!(
        warning,
        super::Warning::Docx(DocxWarning::PartSkipped { .. })
    )));
}