f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
use f_office_units::Length;
use f_office_xml::{Document, Limits};

use super::{half_points, line, twips, whole};
use crate::ns::W;
use crate::params::MAX_FONT_SIZE;
use crate::reader::PartReader;
use crate::warnings::{Limit, ReadAs};

#[test]
fn parses_lengths_with_decimals_and_units() {
    let twips = |v| twips(v).map(|l| l.units() / Length::UNITS_PER_TWIP);
    let cases = [
        ("1440", Some(1_440)),
        ("11905.511811023622", Some(11_905)),
        ("11905.4", Some(11_905)),
        ("11905.99", Some(11_905)),
        // More than three decimals just below a whole twip: the thousandths drop the fourth
        // digit, and the twips drop the rest of the fraction, both toward zero.
        ("719.9999", Some(719)),
        ("-719.9999", Some(-719)),
        ("-360.75", Some(-360)),
        ("-360.25", Some(-360)),
        ("1in", Some(1_440)),
        ("2.54cm", Some(1_440)),
        ("25.4mm", Some(1_440)),
        ("12pt", Some(240)),
        ("1pc", Some(240)),
        ("1pi", Some(240)),
        ("-10.5", Some(-10)),
        ("abc", None),
        ("1.x", None),
    ];
    for (text, expected) in cases {
        assert_eq!(twips(text), expected, "{text}");
    }
}

#[test]
fn rounds_a_universal_measure_at_half_a_twip_up() {
    // 0.025 pt is half a twip.
    let twips = |v| twips(v).map(|l| l.units() / Length::UNITS_PER_TWIP);
    assert_eq!(twips("0.025pt"), Some(1));
    assert_eq!(twips("-0.025pt"), Some(0));
}

#[test]
fn reads_half_points_in_whole_half_points_and_drops_the_fraction() {
    let cases = [
        ("40", Some(40)),
        ("40.5", Some(40)),
        ("41.5", Some(41)),
        ("40.75", Some(40)),
        ("40.0", Some(40)),
        (" 22.5 ", Some(22)),
        ("-6.8", Some(-6)),
        ("21pt", Some(42)),
        ("20.25pt", Some(40)),
        ("3.4pt", Some(6)),
        ("-3pt", Some(-6)),
        ("1in", Some(144)),
        ("abc", None),
        ("40x", None),
        ("", None),
    ];
    for (text, expected) in cases {
        assert_eq!(half_points(text), expected, "{text}");
    }
}

#[test]
fn reads_a_whole_number_and_drops_the_fraction() {
    let cases = [
        ("15", Some(15)),
        ("15.6", Some(15)),
        ("4.6", Some(4)),
        ("-4.6", Some(-4)),
        ("2pt", None),
        ("thin", None),
        ("", None),
    ];
    for (text, expected) in cases {
        assert_eq!(whole(text), expected, "{text}");
    }
}

#[test]
fn reads_a_line_spacing_as_a_rounded_number_or_a_universal_measure() {
    let cases = [
        ("276", Some(276)),
        ("331.2", Some(331)),
        ("331.5", Some(332)),
        (" -10.5 ", Some(-10)),
        ("1pt", Some(20)),
        ("12.95pt", Some(259)),
        ("", None),
        ("wide", None),
    ];
    for (text, expected) in cases {
        assert_eq!(line(text), expected, "{text}");
    }
}

/// The values that a part reader reads from the attributes of one `w:sz` element, with its
/// warnings.
fn read(attributes: &str, read: impl Fn(&mut PartReader) -> Vec<Option<i64>>) -> Reading {
    let xml = format!(r#"<w:sz xmlns:w="{W}" {attributes}/>"#);
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let mut reader = PartReader::new(&doc);
    let values = read(&mut reader);
    let warnings = reader.invalid_values();
    (values, warnings)
}

type Reading = (Vec<Option<i64>>, Vec<(String, Option<String>, ReadAs, u32)>);

#[test]
fn reads_a_font_size_above_the_limit_as_the_limit_with_a_warning() {
    let above = MAX_FONT_SIZE + 1;
    let xml = format!(
        r#"<w:sz xmlns:w="{W}" w:val="{MAX_FONT_SIZE}" w:a="{above}" w:b="{}"/>"#,
        i64::MAX
    );
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let mut reader = PartReader::new(&doc);
    let root = doc.root().unwrap();
    let sizes = ["val", "a", "b", "c"].map(|name| reader.font_size(root, name));
    let limit = Some(MAX_FONT_SIZE);
    assert_eq!(sizes, [limit, limit, limit, None]);
    assert_eq!(reader.limits_reached(), [(Limit::FontSize, 2)]);
    // The limit is a length, and its product with 2^18 font units fits in an `i64`.
    let size = Length::from_half_points(MAX_FONT_SIZE).unwrap();
    assert!(size.units().checked_mul(1 << 18).is_some());
}

#[test]
fn reads_half_points_that_do_not_read_as_zero_with_a_warning() {
    let (values, warnings) = read(r#"w:val="thin" w:a="40x" w:b="40.5""#, |reader| {
        let root = reader.doc.root().unwrap();
        ["val", "a", "b", "c", "a"]
            .map(|name| reader.half_points(root, name))
            .to_vec()
    });
    assert_eq!(values, [Some(0), Some(0), Some(40), None, Some(0)]);
    let zero = |name: &str, count| ("sz".to_owned(), Some(name.to_owned()), ReadAs::Zero, count);
    assert_eq!(warnings, [zero("val", 1), zero("a", 2)]);
}

#[test]
fn counts_lengths_and_border_values_that_do_not_read_as_missing_with_a_warning() {
    let (values, warnings) = read(
        r#"w:val="2pt" w:space="wide" w:w="1in" w:h="tall" w:x="15.6""#,
        |reader| {
            let root = reader.doc.root().unwrap();
            let twips = |reader: &mut PartReader, name| {
                reader
                    .twips(root, name)
                    .map(|l| l.units() / Length::UNITS_PER_TWIP)
            };
            vec![
                reader.whole_number(root, "val"),
                reader.whole_number(root, "space"),
                reader.whole_number(root, "x"),
                twips(reader, "w"),
                twips(reader, "h"),
                reader.line(root, "h"),
            ]
        },
    );
    assert_eq!(values, [None, None, Some(15), Some(1_440), None, None]);
    let missing = |name: &str, count| {
        (
            "sz".to_owned(),
            Some(name.to_owned()),
            ReadAs::Missing,
            count,
        )
    };
    assert_eq!(
        warnings,
        [missing("val", 1), missing("space", 1), missing("h", 2)]
    );
}