f-office-drawingml 0.3.0

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
//! Shape guides (ECMA-376 Part 1, 20.1.9.11 `gd`): the named values of a geometry, each the
//! result of a formula whose arguments are whole numbers, the built-in guides of the shape's
//! size (20.1.10.56) and the guides before it. The adjust values (`a:avLst`, 20.1.9.5) and the
//! guides (`a:gdLst`, 20.1.9.12) of a geometry are guides of one list, in this order.
//!
//! F-Office computes the guides in whole numbers of 65,536ths of their unit ([`fixed`]), and
//! a value beyond [`fixed::LIMIT`] leaves the geometry out of range.

use crate::COORDINATE_LIMIT;
use f_office_units::fixed::{self, ONE, product, root, rounded};
use f_office_units::scale::QUARTER_TURN;

/// An operand of a formula or of a path: a whole number, or the value of a guide by its place
/// in the values of the geometry ([`values`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Operand {
    /// A whole number, from `-COORDINATE_LIMIT` to `COORDINATE_LIMIT`.
    Number(i64),
    /// The value of the guide at this place.
    Guide(usize),
}

/// The formulas of a guide (`fmla`, ECMA-376 Part 1, 20.1.9.11), whose arguments are `x`, `y`
/// and `z`. Angles are in 60,000ths of a degree.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Operation {
    /// `*/ x y z`: x × y ÷ z.
    MultiplyDivide,
    /// `+- x y z`: x + y − z.
    AddSubtract,
    /// `+/ x y z`: (x + y) ÷ z.
    AddDivide,
    /// `?: x y z`: y where x is above 0, else z.
    IfElse,
    /// `abs x`: the size of x.
    Absolute,
    /// `at2 x y`: the angle of the point (x, y), arctan(y ÷ x) in its quarter.
    ArcTangent,
    /// `cat2 x y z`: x × cos(arctan(z ÷ y)), the angle in its quarter: x × y ÷ √(y² + z²), and
    /// x where y and z are 0.
    CosineArcTangent,
    /// `cos x y`: x × cos(y).
    Cosine,
    /// `max x y`: the larger of x and y.
    Maximum,
    /// `min x y`: the smaller of x and y.
    Minimum,
    /// `mod x y z`: √(x² + y² + z²).
    Modulus,
    /// `pin x y z`: y, but x where y is below x and z where y is above z.
    Pin,
    /// `sat2 x y z`: x × sin(arctan(z ÷ y)), the angle in its quarter: x × z ÷ √(y² + z²), and 0
    /// where y and z are 0.
    SineArcTangent,
    /// `sin x y`: x × sin(y).
    Sine,
    /// `sqrt x`: √x, out of range for an x below 0.
    SquareRoot,
    /// `tan x y`: x × tan(y), which is 0 where cos(y) is 0, as a division by 0.
    Tangent,
    /// `val x`: x.
    Value,
}

/// The name of each formula and the number of its arguments.
const OPERATIONS: [(&str, Operation, usize); 17] = [
    ("*/", Operation::MultiplyDivide, 3),
    ("+-", Operation::AddSubtract, 3),
    ("+/", Operation::AddDivide, 3),
    ("?:", Operation::IfElse, 3),
    ("abs", Operation::Absolute, 1),
    ("at2", Operation::ArcTangent, 2),
    ("cat2", Operation::CosineArcTangent, 3),
    ("cos", Operation::Cosine, 2),
    ("max", Operation::Maximum, 2),
    ("min", Operation::Minimum, 2),
    ("mod", Operation::Modulus, 3),
    ("pin", Operation::Pin, 3),
    ("sat2", Operation::SineArcTangent, 3),
    ("sin", Operation::Sine, 2),
    ("sqrt", Operation::SquareRoot, 1),
    ("tan", Operation::Tangent, 2),
    ("val", Operation::Value, 1),
];

/// What a built-in guide measures of the shape.
#[derive(Clone, Copy, Debug)]
enum Measure {
    Width,
    Height,
    Shortest,
    Longest,
    /// The left or the top edge, 0.
    Origin,
    /// An angle, in 60,000ths of a degree.
    Angle(i64),
}

/// The built-in guides (ECMA-376 Part 1, 20.1.10.56): each is a measure of the shape divided by
/// a whole number. `wd32`, a 32nd of the width, is not in the standard's list, but the
/// definitions of `ribbon`, `ribbon2` and `leftRightRibbon` use it.
const BUILT_IN: [(&str, Measure, i64); 37] = [
    ("3cd4", Measure::Angle(16_200_000), 1),
    ("3cd8", Measure::Angle(8_100_000), 1),
    ("5cd8", Measure::Angle(13_500_000), 1),
    ("7cd8", Measure::Angle(18_900_000), 1),
    ("b", Measure::Height, 1),
    ("cd2", Measure::Angle(10_800_000), 1),
    ("cd4", Measure::Angle(QUARTER_TURN), 1),
    ("cd8", Measure::Angle(2_700_000), 1),
    ("h", Measure::Height, 1),
    ("hc", Measure::Width, 2),
    ("hd2", Measure::Height, 2),
    ("hd3", Measure::Height, 3),
    ("hd4", Measure::Height, 4),
    ("hd5", Measure::Height, 5),
    ("hd6", Measure::Height, 6),
    ("hd8", Measure::Height, 8),
    ("l", Measure::Origin, 1),
    ("ls", Measure::Longest, 1),
    ("r", Measure::Width, 1),
    ("ss", Measure::Shortest, 1),
    ("ssd2", Measure::Shortest, 2),
    ("ssd4", Measure::Shortest, 4),
    ("ssd6", Measure::Shortest, 6),
    ("ssd8", Measure::Shortest, 8),
    ("ssd16", Measure::Shortest, 16),
    ("ssd32", Measure::Shortest, 32),
    ("t", Measure::Origin, 1),
    ("vc", Measure::Height, 2),
    ("w", Measure::Width, 1),
    ("wd2", Measure::Width, 2),
    ("wd3", Measure::Width, 3),
    ("wd4", Measure::Width, 4),
    ("wd5", Measure::Width, 5),
    ("wd6", Measure::Width, 6),
    ("wd8", Measure::Width, 8),
    ("wd10", Measure::Width, 10),
    ("wd32", Measure::Width, 32),
];

impl Measure {
    /// The measure, as a value, of a shape whose width and height are the values `size`.
    fn of(self, [width, height]: [i128; 2]) -> i128 {
        match self {
            Self::Width => width,
            Self::Height => height,
            Self::Shortest => width.min(height),
            Self::Longest => width.max(height),
            Self::Origin => 0,
            Self::Angle(angle) => i128::from(angle) * ONE,
        }
    }
}

/// One formula of a guide, with its operands; the operands after the formula's arguments are 0.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Formula {
    operation: Operation,
    operands: [Operand; 3],
}

impl Formula {
    /// The value of the formula, with the values of the guides before it in `values`, or
    /// `None` when it lies beyond [`fixed::LIMIT`] or is the root of a value below 0.
    fn value(self, values: &[i128]) -> Option<i128> {
        let [x, y, z] = self.operands.map(|operand| value(values, operand));
        let result = match self.operation {
            Operation::MultiplyDivide => rounded(x * y, z),
            Operation::AddSubtract => x + y - z,
            Operation::AddDivide => rounded((x + y) * ONE, z),
            Operation::IfElse => {
                if x > 0 {
                    y
                } else {
                    z
                }
            }
            Operation::Absolute => x.abs(),
            Operation::ArcTangent => fixed::angle_of(x, y),
            Operation::CosineArcTangent => match hypotenuse(y, z) {
                0 => x,
                side => rounded(x * y, side),
            },
            Operation::Cosine => product(x, fixed::sin_cos(y)[1]),
            Operation::Maximum => x.max(y),
            Operation::Minimum => x.min(y),
            Operation::Modulus => root(square(x) + square(y) + square(z)),
            Operation::Pin => pinned(x, y, z),
            Operation::SineArcTangent => rounded(x * z, hypotenuse(y, z)),
            Operation::Sine => product(x, fixed::sin_cos(y)[0]),
            Operation::SquareRoot => {
                let x = u128::try_from(x).ok()?;
                root(x * ONE.cast_unsigned())
            }
            Operation::Tangent => {
                let [sin, cos] = fixed::sin_cos(y);
                rounded(x * sin, cos)
            }
            Operation::Value => x,
        };
        (result.abs() <= fixed::LIMIT).then_some(result)
    }
}

/// The square of a value, in 65,536ths of 65,536ths: three such squares fit in a `u128`.
fn square(value: i128) -> u128 {
    value.unsigned_abs() * value.unsigned_abs()
}

/// √(`a`² + `b`²), a value.
fn hypotenuse(a: i128, b: i128) -> i128 {
    root(square(a) + square(b))
}

/// `value`, but `low` where it is below `low` and `high` where it is above `high`, in this
/// order, as the formula `pin` says; unlike `Ord::clamp`, it takes a `low` above `high`.
fn pinned(low: i128, value: i128, high: i128) -> i128 {
    if value < low {
        low
    } else if value > high {
        high
    } else {
        value
    }
}

/// The value of `operand` among the values of a geometry: a whole number in 65,536ths, or
/// the value of a guide.
pub(crate) fn value(values: &[i128], operand: Operand) -> i128 {
    match operand {
        Operand::Number(number) => i128::from(number) * ONE,
        Operand::Guide(place) => values.get(place).copied().unwrap_or_default(),
    }
}

/// The values of the built-in guides of a shape whose width and height are the values `size`,
/// in EMUs, followed by the values of `formulas` in order: the values that an
/// [`Operand::Guide`] names by its place. `None` when a formula has no value
/// ([`Formula::value`]).
pub(crate) fn values(formulas: &[Formula], size: [i128; 2]) -> Option<Vec<i128>> {
    let mut values: Vec<i128> = BUILT_IN
        .iter()
        .map(|&(_, measure, divisor)| rounded(measure.of(size), i128::from(divisor)))
        .collect();
    values.reserve(formulas.len());
    for formula in formulas {
        let value = formula.value(&values)?;
        values.push(value);
    }
    Some(values)
}

/// The guides of a geometry as its reader meets them: their names, which the guides after them
/// and the paths name, and their formulas in order.
#[derive(Debug, Default)]
pub(crate) struct Guides<'a> {
    names: Vec<&'a str>,
    formulas: Vec<Formula>,
}

impl<'a> Guides<'a> {
    /// Adds the guide `name` whose formula is `text`, or gives `None` when the formula does not
    /// read: an unknown formula, fewer arguments than the formula takes, or an argument that is
    /// neither a whole number within [`COORDINATE_LIMIT`] nor the name of a guide before it or
    /// of a built-in guide. Words after the formula's arguments are left out: the standard's
    /// definitions of `circularArrow`, `leftCircularArrow` and `leftRightCircularArrow` give
    /// `+-` a fourth argument, 0.
    pub(crate) fn add(&mut self, name: &'a str, text: &str) -> Option<()> {
        let mut words = text.split_whitespace();
        let first = words.next()?;
        let &(_, operation, count) = OPERATIONS.iter().find(|(name, ..)| *name == first)?;
        let mut operands = [Operand::Number(0); 3];
        for operand in operands.iter_mut().take(count) {
            *operand = self.operand(words.next()?)?;
        }
        self.names.push(name);
        self.formulas.push(Formula {
            operation,
            operands,
        });
        Some(())
    }

    /// The operand that `text` gives: a whole number within [`COORDINATE_LIMIT`], or else a
    /// guide's name ([`Self::guide`]).
    pub(crate) fn operand(&self, text: &str) -> Option<Operand> {
        match text.parse::<i64>() {
            Ok(number) => (-COORDINATE_LIMIT..=COORDINATE_LIMIT)
                .contains(&number)
                .then_some(Operand::Number(number)),
            Err(_) => self.guide(text),
        }
    }

    /// The guide named `name`: the last one of that name so far, or else the built-in guide of
    /// that name.
    pub(crate) fn guide(&self, name: &str) -> Option<Operand> {
        match self.names.iter().rposition(|own| *own == name) {
            Some(place) => Some(Operand::Guide(BUILT_IN.len() + place)),
            None => BUILT_IN
                .iter()
                .position(|(built_in, ..)| *built_in == name)
                .map(Operand::Guide),
        }
    }

    /// The formulas of the guides, in order.
    pub(crate) fn into_formulas(self) -> Vec<Formula> {
        self.formulas
    }
}

#[cfg(test)]
mod tests;