f-office-drawingml 0.2.2

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
//! The preset shapes (`a:prstGeom`, ECMA-376 Part 1, 20.1.9.18) that F-Office draws from their
//! definitions in the standard's `presetShapeDefinitions.xml`. Each definition is stored in
//! the table of [`definitions`] as lines of text:
//!
//! - `a NAME FORMULA`: an adjust value (`a:avLst`, 20.1.9.5), with its formula when the shape
//!   gives none of that name;
//! - `g NAME FORMULA`: a guide (`a:gdLst`, 20.1.9.12);
//! - `r L T R B`: the text rectangle (`a:rect`, 20.1.9.22), each edge a whole number or a
//!   guide's name;
//! - `p W H FILL STROKE`: a path (`a:path`, 20.1.9.15) with its width and height, 0 where the
//!   definition gives none, its fill mode and whether it is stroked, as the attributes `w`,
//!   `h`, `fill` and `stroke` give them, with their defaults;
//! - `M X Y`, `L X Y`, `A WR HR START SWING`, `Q X1 Y1 X Y`, `C X1 Y1 X2 Y2 X Y` and `Z`: a step
//!   of the last path (`a:moveTo`, `a:lnTo`, `a:arcTo`, `a:quadBezTo`, `a:cubicBezTo` and
//!   `a:close`).
//!
//! A geometry from a definition is a [`CustomGeometry`], and draws as the custom geometries do.
//! Its text rectangle is a [`TextRect`].

use f_office_units::{Edges, Length};
use f_office_warnings::{Name, Warnings};

use crate::custom::{CustomGeometry, FILL, PathDefinition, Step, stroked};
use crate::guide::{self, Formula, Guides, Operand};
use crate::{Warning, case_of};
use f_office_units::fixed::{ONE, rounded};

mod definitions;

/// The definition of the preset shape `name`, or `None` when the file has none.
fn definition(name: &str) -> Option<&'static str> {
    let place = definitions::DEFINITIONS
        .binary_search_by(|(own, _)| (*own).cmp(name))
        .ok()?;
    definitions::DEFINITIONS.get(place).map(|(_, text)| *text)
}

/// The geometry of the preset shape `name` from its definition, with the shape's own adjust
/// values `adjust` (each a name and a formula, from the `a:avLst` of its `a:prstGeom`) in place
/// of those of the same name: one whose formula does not read keeps the definition's, with a
/// warning. A path whose fill mode F-Office draws as another warns of it. `None` when the file
/// has no definition of `name`.
pub(crate) fn geometry(
    name: &str,
    adjust: &[(&str, &str)],
    warnings: &mut Warnings<Warning>,
) -> Option<CustomGeometry> {
    read(definition(name)?, adjust, warnings)
}

/// The geometry of the definition `text`, as [`geometry`] reads it.
fn read(
    text: &str,
    adjust: &[(&str, &str)],
    warnings: &mut Warnings<Warning>,
) -> Option<CustomGeometry> {
    let mut guides = Guides::default();
    let mut paths: Vec<PathDefinition> = Vec::new();
    for line in text.lines() {
        let (kind, rest) = line.split_once(' ').unwrap_or((line, ""));
        match kind {
            "a" | "g" => add_guide(&mut guides, (kind, rest), adjust, warnings)?,
            "r" => {}
            "p" => paths.push(path(rest, warnings)?),
            _ => {
                let step = step(kind, rest, &guides)?;
                paths.last_mut()?.steps.push(step);
            }
        }
    }
    Some(CustomGeometry::new(guides, paths))
}

/// Adds the guide of a line of the `kind` `a` or `g` with the words `rest` to `guides`, or an
/// adjust value of `adjust` in place of the definition's, as [`geometry`] says.
fn add_guide<'a>(
    guides: &mut Guides<'a>,
    (kind, rest): (&str, &'a str),
    adjust: &[(&str, &str)],
    warnings: &mut Warnings<Warning>,
) -> Option<()> {
    let (guide, formula) = rest.split_once(' ')?;
    let own = adjust
        .iter()
        .rev()
        .find(|(own, _)| kind == "a" && *own == guide);
    if let Some((_, own)) = own {
        if guides.add(guide, own).is_some() {
            return Some(());
        }
        warnings.push(Warning::InvalidValue {
            element: Name::new("gd"),
            attribute: Name::new("fmla"),
        });
    }
    guides.add(guide, formula)
}

/// The text rectangle of a preset shape (`a:rect` of its definition, ECMA-376 Part 1,
/// 20.1.9.22): the edges of the part of its box that its text lies in, before the insets of its
/// text body, as the guides of the shape's size and adjust values give them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextRect {
    formulas: Vec<Formula>,
    /// The left, top, right and bottom edges.
    edges: [Operand; 4],
}

impl TextRect {
    /// The distances of the rectangle from the edges of a box of `width` by `height`, each to
    /// the nearest unit, or `None` when a guide is out of range or a distance does not fit in a
    /// length.
    #[must_use]
    pub fn insets_in(&self, width: Length, height: Length) -> Option<Edges<Length>> {
        // A unit of a box is half an EMU, and the guides measure the box in EMUs.
        let size = [width, height].map(|side| i128::from(side.units()) * ONE / 2);
        let values = guide::values(&self.formulas, size)?;
        let place = |operand| {
            i64::try_from(rounded(guide::value(&values, operand) * 2, ONE))
                .ok()
                .map(Length::from_units)
        };
        let [left, top, right, bottom] = self.edges;
        Some(Edges {
            left: place(left)?,
            top: place(top)?,
            right: width.checked_sub(place(right)?)?,
            bottom: height.checked_sub(place(bottom)?)?,
        })
    }
}

/// The text rectangle of the preset shape `name` with the shape's own adjust values `adjust`,
/// as [`geometry`] takes them but without its warnings, or `None` when the file has no
/// definition of `name` or the definition has no text rectangle.
pub(crate) fn text_rect(name: &str, adjust: &[(&str, &str)]) -> Option<TextRect> {
    let mut guides = Guides::default();
    let mut warnings = Warnings::new();
    for line in definition(name)?.lines() {
        let (kind, rest) = line.split_once(' ').unwrap_or((line, ""));
        // The lines before the text rectangle are guides, and the paths follow it.
        match kind {
            "p" => return None,
            "r" => {
                let edges: Vec<Operand> = rest
                    .split_whitespace()
                    .map(|word| guides.operand(word))
                    .collect::<Option<_>>()?;
                let edges = <[Operand; 4]>::try_from(edges).ok()?;
                return Some(TextRect {
                    formulas: guides.into_formulas(),
                    edges,
                });
            }
            _ => add_guide(&mut guides, (kind, rest), adjust, &mut warnings)?,
        }
    }
    None
}

/// The path of a line `p W H FILL STROKE`, without its steps.
fn path(rest: &str, warnings: &mut Warnings<Warning>) -> Option<PathDefinition> {
    let words: Vec<&str> = rest.split_whitespace().collect();
    let [width, height, fill, stroke] = words.as_slice() else {
        return None;
    };
    let filled = case_of(fill, (&Name::new("path"), "fill"), (FILL, warnings))?;
    Some(PathDefinition {
        size: [width.parse().ok()?, height.parse().ok()?],
        steps: Vec::new(),
        filled,
        stroked: stroked(Some(stroke)),
    })
}

/// The step of the kind `kind` with the values `rest`, each a whole number or a guide's name.
fn step(kind: &str, rest: &str, guides: &Guides<'_>) -> Option<Step> {
    let values: Vec<Operand> = rest
        .split_whitespace()
        .map(|word| guides.operand(word))
        .collect::<Option<_>>()?;
    Some(match (kind, values.as_slice()) {
        ("M", &[x, y]) => Step::Move([x, y]),
        ("L", &[x, y]) => Step::Line([x, y]),
        ("A", &[wr, hr, start, swing]) => Step::Arc([wr, hr, start, swing]),
        ("Q", &[x1, y1, x, y]) => Step::Quad([[x1, y1], [x, y]]),
        ("C", &[x1, y1, x2, y2, x, y]) => Step::Cubic([[x1, y1], [x2, y2], [x, y]]),
        ("Z", &[]) => Step::Close,
        _ => return None,
    })
}

#[cfg(test)]
mod tests;