use f_office_drawingml::shape::turned_clockwise;
use f_office_paint::{FillRule, Item, PathCommand, PathItem, Point, Rgb};
use f_office_units::scale::QUARTER_TURN;
use f_office_units::{Edges, Length};
use crate::OutlineCommand;
pub(super) struct Letter {
pub(super) advance: u16,
pub(super) outline: Vec<OutlineCommand>,
}
#[derive(Clone, Copy)]
pub(super) struct Em {
pub(super) units_per_em: u16,
pub(super) descent: u16,
}
pub(super) fn letter_items(
letters: &[Letter],
em: Em,
frame: Edges<Length>,
(rotation, color): (i64, Rgb),
) -> Option<Vec<Item>> {
let total: i64 = letters.iter().map(|letter| i64::from(letter.advance)).sum();
let units_per_em = i64::from(em.units_per_em);
if total == 0 || units_per_em == 0 {
return Some(Vec::new());
}
let (left, top, right, bottom) = (
frame.left.units(),
frame.top.units(),
frame.right.units(),
frame.bottom.units(),
);
let (width, height) = (i128::from(right - left), i128::from(bottom - top));
let center = [left + (right - left) / 2, top + (bottom - top) / 2];
let mut items = Vec::new();
let mut pen = 0;
for letter in letters {
let place = |[u, v]: [i32; 2]| -> Option<Point> {
let across = i128::from(pen) + i128::from(u);
let up = i128::from(em.descent) + i128::from(v);
let x = i128::from(left) + f_office_units::div_round_i128(across * width, total.into());
let y = i128::from(bottom)
- f_office_units::div_round_i128(up * height, units_per_em.into());
let [x, y] = turned_clockwise(
[i64::try_from(x).ok()?, i64::try_from(y).ok()?],
center,
rotation,
)?;
Some(Point {
x: Length::from_units(x),
y: Length::from_units(y),
})
};
let commands = letter
.outline
.iter()
.map(|command| {
Some(match *command {
OutlineCommand::MoveTo(p) => PathCommand::MoveTo(place(p)?),
OutlineCommand::LineTo(p) => PathCommand::LineTo(place(p)?),
OutlineCommand::QuadTo(c, p) => PathCommand::QuadTo(place(c)?, place(p)?),
OutlineCommand::CubicTo(c, d, p) => {
PathCommand::CubicTo(place(c)?, place(d)?, place(p)?)
}
OutlineCommand::Close => PathCommand::Close,
})
})
.collect::<Option<Vec<_>>>()?;
if !commands.is_empty() {
items.push(Item::Path(PathItem {
commands,
color,
fill_rule: FillRule::NonZero,
}));
}
pen += i64::from(letter.advance);
}
Some(items)
}
pub(super) fn aligned_extents(
items: &[Item],
frame: Edges<Length>,
rotation: i64,
) -> Edges<Length> {
let (left, top, right, bottom) = (
frame.left.units(),
frame.top.units(),
frame.right.units(),
frame.bottom.units(),
);
let center = [left + (right - left) / 2, top + (bottom - top) / 2];
let (width, height) = (right - left, bottom - top);
let (across, down) = if swaps_sides(rotation) {
(height, width)
} else {
(width, height)
};
let mut ink = Ink {
left: center[0] - across / 2,
top: center[1] - down / 2,
right: center[0] - across / 2 + across,
bottom: center[1] - down / 2 + down,
};
for item in items {
let Item::Path(path) = item else {
continue;
};
let mut at = None;
for command in &path.commands {
if let PathCommand::QuadTo(control, end) = *command {
if let Some(start) = at {
ink.take_curve(start, control, end);
}
ink.take(end);
at = Some(end);
continue;
}
for point in command.points() {
ink.take(point);
at = Some(point);
}
}
}
Edges {
left: Length::from_units(left - ink.left),
top: Length::from_units(top - ink.top),
right: Length::from_units(ink.right - right),
bottom: Length::from_units(ink.bottom - bottom),
}
}
const fn swaps_sides(rotation: i64) -> bool {
(rotation.rem_euclid(2 * QUARTER_TURN) + QUARTER_TURN / 2) / QUARTER_TURN == 1
}
struct Ink {
left: i64,
top: i64,
right: i64,
bottom: i64,
}
impl Ink {
fn take(&mut self, point: Point) {
let (x, y) = (point.x.units(), point.y.units());
self.left = self.left.min(x);
self.right = self.right.max(x);
self.top = self.top.min(y);
self.bottom = self.bottom.max(y);
}
fn take_curve(&mut self, start: Point, control: Point, end: Point) {
if let Some(x) = curve_extreme([start.x.units(), control.x.units(), end.x.units()]) {
self.left = self.left.min(x);
self.right = self.right.max(x);
}
if let Some(y) = curve_extreme([start.y.units(), control.y.units(), end.y.units()]) {
self.top = self.top.min(y);
self.bottom = self.bottom.max(y);
}
}
}
pub(super) fn curve_extreme([p0, p1, p2]: [i64; 3]) -> Option<i64> {
let (p0, p1, p2) = (i128::from(p0), i128::from(p1), i128::from(p2));
let bend = p0 - 2 * p1 + p2;
let lead = p0 - p1;
let inside = (bend > 0 && 0 < lead && lead < bend) || (bend < 0 && bend < lead && lead < 0);
if !inside {
return None;
}
let (reach, bend) = if bend < 0 {
(p1 * p1 - p0 * p2, -bend)
} else {
(p0 * p2 - p1 * p1, bend)
};
i64::try_from(f_office_units::div_round_i128(reach, bend)).ok()
}
#[cfg(test)]
mod tests {
use super::{Em, Letter, aligned_extents, curve_extreme, letter_items, swaps_sides};
use crate::OutlineCommand;
use f_office_paint::{Item, PathCommand, Point, Rgb};
use f_office_units::scale::QUARTER_TURN;
use f_office_units::{Edges, Length};
fn squares() -> Vec<Letter> {
let square = vec![
OutlineCommand::MoveTo([0, 0]),
OutlineCommand::LineTo([100, 0]),
OutlineCommand::LineTo([100, 100]),
OutlineCommand::Close,
];
(0..2)
.map(|_| Letter {
advance: 200,
outline: square.clone(),
})
.collect()
}
fn points(items: &[Item]) -> Vec<Vec<(i64, i64)>> {
let point = |p: Point| (p.x.units() / 25_400, p.y.units() / 25_400);
items
.iter()
.map(|item| match item {
Item::Path(path) => path
.commands
.iter()
.flat_map(PathCommand::points)
.map(point)
.collect(),
_ => Vec::new(),
})
.collect()
}
fn frame() -> Edges<Length> {
let pt = |points: i64| Length::from_units(points * 25_400);
Edges {
left: pt(100),
top: pt(200),
right: pt(500),
bottom: pt(300),
}
}
#[test]
fn stretches_the_advances_across_the_box_and_the_em_to_its_height() {
let em = Em {
units_per_em: 1_000,
descent: 200,
};
let items = letter_items(&squares(), em, frame(), (0, Rgb::BLACK));
assert_eq!(
points(&items.unwrap_or_default()),
[
vec![(100, 280), (200, 280), (200, 270)],
vec![(300, 280), (400, 280), (400, 270)],
]
);
}
#[test]
fn turns_the_line_clockwise_about_the_center_of_the_box() {
let em = Em {
units_per_em: 1_000,
descent: 200,
};
let items = letter_items(&squares(), em, frame(), (QUARTER_TURN, Rgb::BLACK));
let points = points(&items.unwrap_or_default());
assert_eq!(points[0][0], (270, 50));
assert_eq!(points[1][1], (270, 350));
}
fn in_points(edges: Edges<Length>) -> [i64; 4] {
[edges.left, edges.top, edges.right, edges.bottom].map(|side| side.units() / 25_400)
}
#[test]
fn aligns_a_line_inside_its_box_by_the_box() {
let em = Em {
units_per_em: 1_000,
descent: 200,
};
let items = letter_items(&squares(), em, frame(), (0, Rgb::BLACK)).unwrap_or_default();
assert_eq!(in_points(aligned_extents(&items, frame(), 0)), [0, 0, 0, 0]);
let tall = [Letter {
advance: 200,
outline: vec![
OutlineCommand::MoveTo([0, 0]),
OutlineCommand::LineTo([0, 1_100]),
OutlineCommand::Close,
],
}];
let items = letter_items(&tall, em, frame(), (0, Rgb::BLACK)).unwrap_or_default();
assert_eq!(
in_points(aligned_extents(&items, frame(), 0)),
[0, 30, 0, 0]
);
let arch = [Letter {
advance: 200,
outline: vec![
OutlineCommand::MoveTo([0, 0]),
OutlineCommand::QuadTo([50, 2_300], [100, 0]),
OutlineCommand::Close,
],
}];
let items = letter_items(&arch, em, frame(), (0, Rgb::BLACK)).unwrap_or_default();
assert_eq!(
in_points(aligned_extents(&items, frame(), 0)),
[0, 35, 0, 0]
);
}
#[test]
fn swaps_the_box_from_the_nearest_odd_quarter_turn() {
let em = Em {
units_per_em: 1_000,
descent: 200,
};
let items = letter_items(&squares(), em, frame(), (QUARTER_TURN, Rgb::BLACK));
let extents = aligned_extents(&items.unwrap_or_default(), frame(), QUARTER_TURN);
assert_eq!(in_points(extents), [-150, 150, -150, 150]);
let degrees = |degrees: i64| swaps_sides(degrees * QUARTER_TURN / 90);
assert_eq!(
[44, 45, 134, 135, 224, 225, 314, 315, -45, -46].map(degrees),
[
false, true, true, false, false, true, true, false, false, true
]
);
}
#[test]
fn counts_a_quadratic_curve_by_its_furthest_point() {
assert_eq!(curve_extreme([0, 10, 0]), Some(5));
assert_eq!(curve_extreme([10, -10, 10]), Some(0));
assert_eq!(curve_extreme([0, 20, 10]), Some(13));
assert_eq!(curve_extreme([0, 5, 10]), None);
assert_eq!(curve_extreme([0, 8, 10]), None);
}
}