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;
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)
}
pub(crate) fn geometry(
name: &str,
adjust: &[(&str, &str)],
warnings: &mut Warnings<Warning>,
) -> Option<CustomGeometry> {
read(definition(name)?, adjust, warnings)
}
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))
}
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)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextRect {
formulas: Vec<Formula>,
edges: [Operand; 4],
}
impl TextRect {
#[must_use]
pub fn insets_in(&self, width: Length, height: Length) -> Option<Edges<Length>> {
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)?)?,
})
}
}
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, ""));
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
}
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)),
})
}
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;