f-office-drawingml 0.3.0

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
//! DrawingML parts that DOCX, PPTX and XLSX share.
//!
//! This crate covers shapes and preset geometry, fills, lines, pictures, themes and colors,
//! and turns them into display list items. Text inside a shape belongs to the format crates,
//! because each Office app lays out that text by its own rules.

#![deny(clippy::float_arithmetic)]

use f_office_units::Length;
use f_office_units::measure::universal_measure;
use f_office_units::scale::EMUS_PER_INCH;
use f_office_warnings::{Name, Warnings};
use f_office_xml::enumeration::{Drawn, Values};
use f_office_xml::{Document, NodeId};

pub mod color;
pub mod custom;
mod dash;
pub mod effect;
pub mod gradient;
mod guide;
mod line_end;
mod preset;
pub mod shape;
pub mod theme;
mod warning;

pub use warning::{Feature, Warning};

/// Reads an `xsd:boolean` of DrawingML, such as `flipH` or `behindDoc`: `1` and `true` are
/// true, and every other value is false. DrawingML does not use `ST_OnOff`, so `on` is
/// false here.
#[must_use]
pub fn boolean(value: &str) -> bool {
    matches!(value, "1" | "true")
}

/// Reads a length in EMU of DrawingML (`ST_Coordinate`, `ST_Coordinate32`,
/// `ST_PositiveCoordinate`, `ST_LineWidth` and the text of `wp:posOffset`): a whole number, or
/// a universal measure such as `2in` in whole EMU, rounded as
/// [`universal_measure`] rounds. A universal measure reads also where the schema takes a
/// whole number only, and no other value reads: a number with a fraction, text, a number
/// followed by text, or a space around the number. A value
/// beyond [`COORDINATE_LIMIT`], the bound of the widest of these types, does not read either,
/// so that the sums and products of the values fit.
#[must_use]
pub fn emus(value: &str) -> Option<i64> {
    value
        .parse::<i64>()
        .ok()
        .or_else(|| universal_measure(value, EMUS_PER_INCH))
        .filter(|emus| (-COORDINATE_LIMIT..=COORDINATE_LIMIT).contains(emus))
}

/// Reads a length in EMU of DrawingML as [`emus`] reads it, as a length: the bound of
/// [`emus`] and the conversion are one read, and no value within [`COORDINATE_LIMIT`] lies
/// beyond the range of a length.
#[must_use]
pub fn emu_length(value: &str) -> Option<Length> {
    emus(value).and_then(Length::from_emus)
}

/// The largest distance from zero of a coordinate of DrawingML in EMU: the bound of
/// `ST_Coordinate` and of `ST_PositiveCoordinate` (ECMA-376 Part 1, 20.1.10.16 and 20.1.10.42),
/// such as the size and the points of a custom path. It lies within [`Length::FILE_LIMIT`].
pub const COORDINATE_LIMIT: i64 = 27_273_042_316_900;

/// Reads a whole number of DrawingML (`xsd:int`, `xsd:unsignedInt`), such as an angle
/// (`ST_Angle`), a text size in hundredths of a point (`ST_TextFontSize`), a spacing in
/// hundredths of a point (`ST_TextSpacingPoint`), or the count and the index of a chart's
/// points: an optional sign and decimal digits, without a fraction or a space around them, as
/// [`emus`] reads a whole number; no other form reads. A number beyond the range of both
/// types, from the least `xsd:int` to the largest `xsd:unsignedInt`, does not read either.
#[must_use]
pub fn integer(value: &str) -> Option<i64> {
    value
        .parse()
        .ok()
        .filter(|number| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(number))
}

/// Reads a share of a bar chart in percent (`ST_GapAmount` of `c:gapWidth` and `ST_Overlap`
/// of `c:overlap`, each a whole number with or without `%`): a whole number, as [`integer`]
/// reads it, with an optional `%`.
#[must_use]
pub fn chart_percent(value: &str) -> Option<i64> {
    integer(value.strip_suffix('%').unwrap_or(value))
}

/// The value of the attribute `name` of `node`, in no namespace, read by `parse`: `None` when
/// it is missing, and when it does not read, with a warning that it counts as missing.
fn attribute_of<T>(
    doc: &Document,
    node: NodeId,
    name: &str,
    parse: impl FnOnce(&str) -> Option<T>,
    warnings: &mut Warnings<Warning>,
) -> Option<T> {
    let value = parse(doc.attribute(node, None, name)?);
    if value.is_none() {
        warnings.push(Warning::InvalidValue {
            element: element_name(doc, node),
            attribute: Name::new(name),
        });
    }
    value
}

/// The length of the attribute `name` of `node`, in no namespace, as [`emu_length`] reads it:
/// `None` when it is missing, and when it does not read, with a warning that it counts as
/// missing.
fn emus_of(
    doc: &Document,
    node: NodeId,
    name: &str,
    warnings: &mut Warnings<Warning>,
) -> Option<Length> {
    attribute_of(doc, node, name, emu_length, warnings)
}

/// The whole number of the attribute `name` of `node`, in no namespace, as [`integer`] reads
/// it, such as an angle: `None` when it is missing, and when it does not read or lies beyond
/// the range of its type, with a warning that it counts as missing.
fn integer_of(
    doc: &Document,
    node: NodeId,
    name: &str,
    warnings: &mut Warnings<Warning>,
) -> Option<i64> {
    attribute_of(doc, node, name, integer, warnings)
}

/// The case of the attribute `name` of `node`, in no namespace, as the table of its simple type
/// `table` reads it: `None` when the attribute is missing, and when its value is no name of the
/// table, with a warning that it counts as missing. A name that F-Office draws as another
/// name's case, or as nothing, reads as the case of its table, with a warning. The DrawingML
/// types restrict `xsd:token`, but the readers take each name as it is spelled, so a name with
/// space around it is no name of the table.
fn enumeration<T: Clone>(
    doc: &Document,
    node: NodeId,
    name: &str,
    (table, warnings): (&'static Values<T>, &mut Warnings<Warning>),
) -> Option<T> {
    let value = doc.attribute(node, None, name)?;
    case_of(value, (&element_name(doc, node), name), (table, warnings))
}

/// The case of `value`, the value of the attribute `name` of an element `element`, as
/// [`enumeration`] reads it, with its warnings.
fn case_of<T: Clone>(
    value: &str,
    (element, name): (&Name, &str),
    (table, warnings): (&'static Values<T>, &mut Warnings<Warning>),
) -> Option<T> {
    let Some((case, spelling, drawn)) = table.find(value) else {
        warnings.push(Warning::InvalidValue {
            element: element.clone(),
            attribute: Name::new(name),
        });
        return None;
    };
    if drawn == Drawn::AsAnother {
        warnings.push(Warning::ValueNotSupported {
            element: element.clone(),
            attribute: Name::new(name),
            value: Name::new(spelling),
        });
    }
    Some(case.clone())
}

/// The local name of the element `node`, or an empty name.
fn element_name(doc: &Document, node: NodeId) -> Name {
    doc.element(node)
        .map_or_default(|element| Name::new(element.name.local))
}

/// The DrawingML main namespace.
const A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";

#[cfg(test)]
mod tests {
    use super::{chart_percent, emus, integer};

    #[test]
    fn reads_a_whole_number_or_a_universal_measure_of_emu() {
        let cases = [
            ("914400", Some(914_400)),
            ("-457200", Some(-457_200)),
            ("1in", Some(914_400)),
            ("3pt", Some(38_100)),
            ("914400.7", None),
            ("27273042316900", Some(27_273_042_316_900)),
            ("-27273042316900", Some(-27_273_042_316_900)),
            ("27273042316901", None),
            ("-27273042316901", None),
            ("29826161in", Some(27_273_041_618_400)),
            ("29826162in", None),
            ("wide", None),
            ("914400x", None),
            (" 914400 ", None),
        ];
        for (text, expected) in cases {
            assert_eq!(emus(text), expected, "{text}");
        }
    }

    #[test]
    fn reads_a_whole_number_with_a_sign_only() {
        let cases = [
            ("5400000", Some(5_400_000)),
            ("-5400000", Some(-5_400_000)),
            ("+1100", Some(1_100)),
            ("1100.5", None),
            ("4294967295", Some(4_294_967_295)),
            ("-2147483648", Some(-2_147_483_648)),
            ("4294967296", None),
            ("-2147483649", None),
            (" 1100 ", None),
            ("11pt", None),
            ("wide", None),
        ];
        for (text, expected) in cases {
            assert_eq!(integer(text), expected, "{text}");
        }
    }

    #[test]
    fn reads_a_share_of_a_bar_chart_with_or_without_a_percent_sign() {
        let cases = [
            ("150", Some(150)),
            ("150%", Some(150)),
            ("-27%", Some(-27)),
            ("150%%", None),
            ("150.5%", None),
            ("wide", None),
        ];
        for (text, expected) in cases {
            assert_eq!(chart_percent(text), expected, "{text}");
        }
    }

    #[test]
    fn rounds_a_universal_measure_at_half_an_emu_up() {
        // 0.005 pt is 63.5 EMU.
        assert_eq!(emus("0.005pt"), Some(64));
        assert_eq!(emus("-0.005pt"), Some(-63));
    }
}