f-office-drawingml 0.3.0

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
use f_office_paint::{Item, PathCommand, Rgb};
use f_office_units::{Edges, Length};
use f_office_warnings::Warnings;

use super::{definition, definitions::DEFINITIONS, geometry, read, text_rect};
use crate::custom::{CustomGeometry, Place, items};
use crate::shape::SHAPE_TYPES;

/// The box at the origin of `width` by `height` units, unturned.
fn place(width: i64, height: i64) -> Place {
    let units = Length::from_units;
    Place {
        frame: Edges::placed(Length::ZERO, Length::ZERO, units(width), units(height)).unwrap(),
        flip: [false, false],
        quarters: 0,
    }
}

/// The ends of the moves and lines of the fill of `geometry` in `place`, in units.
fn corners(geometry: &CustomGeometry, place: &Place) -> Vec<(i64, i64)> {
    let red = Rgb { r: 255, g: 0, b: 0 };
    let items = items(geometry, place, Some(red), None).unwrap();
    let Some(Item::Path(fill)) = items.first() else {
        panic!("{items:?}");
    };
    fill.commands
        .iter()
        .filter_map(|command| match command {
            PathCommand::MoveTo(p) | PathCommand::LineTo(p) => Some((p.x.units(), p.y.units())),
            _ => None,
        })
        .collect()
}

#[test]
fn reads_every_definition_and_draws_it_in_boxes_of_any_shape() {
    assert_eq!(DEFINITIONS.len(), 186);
    assert!(DEFINITIONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
    let black = Rgb::BLACK;
    for (name, _) in DEFINITIONS {
        let mut warnings = Warnings::new();
        let found = geometry(name, &[], &mut warnings).unwrap_or_else(|| panic!("{name}"));
        // Only a fill mode that F-Office draws as another warns.
        assert!(
            warnings
                .iter()
                .all(|(warning, _)| warning.kind() == "drawingml-value-not-supported"),
            "{name}"
        );
        for [width, height] in [[1_200, 800], [800, 1_200], [0, 800], [800, 0], [0, 0]] {
            let line = Some((black, Length::from_units(10)));
            assert!(
                items(&found, &place(width, height), Some(black), line).is_ok(),
                "{name} {width} {height}"
            );
        }
    }
}

/// The definitions and the names of `ST_ShapeType` agree: each name but `upArrow` has a
/// definition, and each definition has a name of the type, which `a:prstGeom` reads.
#[test]
fn defines_each_shape_type_but_up_arrow_and_no_other_name() {
    let defined: Vec<&str> = DEFINITIONS.iter().map(|&(name, _)| name).collect();
    let undefined: Vec<&str> = SHAPE_TYPES
        .into_iter()
        .filter(|name| !defined.contains(name))
        .collect();
    assert_eq!(undefined, ["upArrow"]);
    let outside: Vec<&str> = defined
        .into_iter()
        .filter(|name| !SHAPE_TYPES.contains(name))
        .collect();
    assert_eq!(outside, [] as [&str; 0]);
}

#[test]
fn has_no_definition_of_up_arrow_or_of_a_name_outside_the_file() {
    let mut warnings = Warnings::new();
    assert!(geometry("upArrow", &[], &mut warnings).is_none());
    assert!(geometry("nothing", &[], &mut warnings).is_none());
    assert!(definition("upDownArrow").is_some());
}

#[test]
fn draws_a_chevron_with_the_adjust_value_of_its_shape() {
    // A box 2,000 by 1,000 units is 1,000 by 500 EMUs. The point of the chevron lies `adj`
    // 100,000ths of the shorter side, 50,000 by default, from the right edge: 250 EMUs.
    let mut warnings = Warnings::new();
    let chevron = geometry("chevron", &[], &mut warnings).unwrap();
    assert_eq!(
        corners(&chevron, &place(2_000, 1_000)),
        [
            (0, 0),
            (1_500, 0),
            (2_000, 500),
            (1_500, 1_000),
            (0, 1_000),
            (500, 500)
        ]
    );
    let narrow = geometry("chevron", &[("adj", "val 25000")], &mut warnings).unwrap();
    assert_eq!(corners(&narrow, &place(2_000, 1_000))[1], (1_750, 0));
    assert!(warnings.is_empty());
    // An adjust value whose formula does not read keeps the default, with a warning.
    let unread = geometry("chevron", &[("adj", "val wide")], &mut warnings).unwrap();
    assert_eq!(corners(&unread, &place(2_000, 1_000))[1], (1_500, 0));
    let kinds: Vec<_> = warnings.iter().map(|(warning, _)| warning.kind()).collect();
    assert_eq!(kinds, ["drawingml-invalid-value"]);
}

#[test]
fn ends_the_arc_of_the_preset_arc_where_its_own_guides_put_the_end() {
    // The definition of `arc` computes the end of its arc, (x2, y2), from the end angle with
    // `cat2` and `sat2`; a path added to the definition marks that point. The arc, drawn from
    // its start with `arcTo`, must end there on an ellipse three times as wide as high.
    let text = format!(
        "{}p 0 0 norm true\nM x2 y2\nL x2 y2\n",
        definition("arc").unwrap()
    );
    let adjust = [("adj1", "val 1000000"), ("adj2", "val 7000000")];
    let mut warnings = Warnings::new();
    let arc = read(&text, &adjust, &mut warnings).unwrap();
    let red = Rgb { r: 255, g: 0, b: 0 };
    let items = items(&arc, &place(3_000, 1_000), Some(red), None).unwrap();
    let Some(Item::Path(fill)) = items.first() else {
        panic!("{items:?}");
    };
    // The fill holds the filled path of the arc, then the mark.
    let end = fill
        .commands
        .iter()
        .rev()
        .find_map(|command| match command {
            PathCommand::CubicTo(_, _, end) => Some((end.x.units(), end.y.units())),
            _ => None,
        });
    let mark = fill
        .commands
        .iter()
        .rev()
        .find_map(|command| match command {
            PathCommand::MoveTo(mark) => Some((mark.x.units(), mark.y.units())),
            _ => None,
        });
    let ((x, y), (mark_x, mark_y)) = (end.unwrap(), mark.unwrap());
    assert!(
        (x - mark_x).abs() <= 1 && (y - mark_y).abs() <= 1,
        "{x} {y} {mark_x} {mark_y}"
    );
}

#[test]
fn lays_the_text_rectangle_of_a_preset_on_its_box() {
    let points = |p: i64| Length::from_points(p).unwrap();
    let (width, height) = (points(180), points(90));
    // The triangle's rectangle runs from a quarter of the width to three quarters of it, and
    // from the middle of the height to the bottom.
    let triangle = text_rect("triangle", &[]).unwrap();
    assert_eq!(
        triangle.insets_in(width, height),
        Some(Edges {
            left: points(45),
            top: points(45),
            right: points(45),
            bottom: Length::ZERO,
        })
    );
    // An adjust value moves the apex, and the rectangle with it.
    let leaning = text_rect("triangle", &[("adj", "val 20000")]).unwrap();
    assert_eq!(
        leaning.insets_in(width, height).map(|edges| edges.left),
        Some(points(18))
    );
    let whole = text_rect("rect", &[]).unwrap();
    assert_eq!(whole.insets_in(width, height), Some(Edges::default()));
    assert_eq!(text_rect("no such preset", &[]), None);
}