use f_office_paint::{PathCommand, Point, stroke};
use f_office_units::Length;
use f_office_xml::{Document, NodeId};
use crate::A;
const MIN_END_SCALE: Length = Length::from_units(2 * Length::UNITS_PER_POINT);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EndKind {
Triangle,
Stealth,
Diamond,
Oval,
Arrow,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum EndSize {
Small,
#[default]
Medium,
Large,
}
impl EndSize {
fn parse(value: Option<&str>) -> Self {
match value {
Some("sm") => Self::Small,
Some("lg") => Self::Large,
_ => Self::Medium,
}
}
const fn factor(self) -> i64 {
match self {
Self::Small => 2,
Self::Medium => 3,
Self::Large => 5,
}
}
const fn stealth_notch(self) -> i64 {
match self {
Self::Small => 1,
Self::Medium => 2,
Self::Large => 3,
}
}
const fn arrow_length_halves(self) -> i64 {
match self {
Self::Small => 4,
Self::Medium => 6,
Self::Large => 9,
}
}
const fn arrow_half_width_quarters(self) -> i64 {
match self {
Self::Small => 5,
Self::Medium => 7,
Self::Large => 10,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LineEnd {
pub(crate) kind: EndKind,
pub(crate) width: EndSize,
pub(crate) length: EndSize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct LineEnds {
pub(crate) head: Option<LineEnd>,
pub(crate) tail: Option<LineEnd>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ReadEnds {
Omitted,
Present(LineEnds),
Unsupported,
}
impl LineEnds {
pub(crate) const fn any(self) -> bool {
self.head.is_some() || self.tail.is_some()
}
}
pub(crate) fn read_ends(doc: &Document, ln: NodeId) -> ReadEnds {
let head_node = doc.child(ln, A, "headEnd");
let tail_node = doc.child(ln, A, "tailEnd");
if head_node.is_none() && tail_node.is_none() {
return ReadEnds::Omitted;
}
let head = match head_node.map_or(ReadOne::None, |n| read_one(doc, n)) {
ReadOne::None => None,
ReadOne::End(end) => Some(end),
ReadOne::Unsupported => return ReadEnds::Unsupported,
};
let tail = match tail_node.map_or(ReadOne::None, |n| read_one(doc, n)) {
ReadOne::None => None,
ReadOne::End(end) => Some(end),
ReadOne::Unsupported => return ReadEnds::Unsupported,
};
ReadEnds::Present(LineEnds { head, tail })
}
enum ReadOne {
None,
End(LineEnd),
Unsupported,
}
fn read_one(doc: &Document, node: NodeId) -> ReadOne {
let kind = match doc.attribute(node, None, "type") {
None | Some("none") => return ReadOne::None,
Some("triangle") => EndKind::Triangle,
Some("stealth") => EndKind::Stealth,
Some("diamond") => EndKind::Diamond,
Some("oval") => EndKind::Oval,
Some("arrow") => EndKind::Arrow,
Some(_) => return ReadOne::Unsupported,
};
ReadOne::End(LineEnd {
kind,
width: EndSize::parse(doc.attribute(node, None, "w")),
length: EndSize::parse(doc.attribute(node, None, "len")),
})
}
impl LineEnd {
pub(crate) fn shorten(self, width: Length) -> Length {
let scale = width.max(MIN_END_SCALE);
match self.kind {
EndKind::Triangle => scale * self.length.factor() - scale.div_round(2),
EndKind::Stealth => scale * self.length.stealth_notch(),
EndKind::Diamond | EndKind::Oval => Length::ZERO,
EndKind::Arrow => {
let (back, half_span) = arrow_wing(scale, self.width, self.length);
arrow_miter(width.div_toward_zero(2), back, half_span)
}
}
}
pub(crate) fn commands(self, from: Point, tip: Point, width: Length) -> Vec<PathCommand> {
let dx = i128::from((tip.x - from.x).units());
let dy = i128::from((tip.y - from.y).units());
let len = (dx * dx + dy * dy).isqrt();
if len == 0 {
return Vec::new();
}
let frame = LocalFrame { tip, dx, dy, len };
let scale = width.max(MIN_END_SCALE);
let full_len = scale * self.length.factor();
let half_w = (scale * self.width.factor()).div_round(2);
match self.kind {
EndKind::Triangle => vec![
PathCommand::MoveTo(frame.at(Length::ZERO, Length::ZERO)),
PathCommand::LineTo(frame.at(-full_len, -half_w)),
PathCommand::LineTo(frame.at(-full_len, half_w)),
PathCommand::Close,
],
EndKind::Stealth => {
let notch = scale * self.length.stealth_notch();
vec![
PathCommand::MoveTo(frame.at(Length::ZERO, Length::ZERO)),
PathCommand::LineTo(frame.at(-full_len, -half_w)),
PathCommand::LineTo(frame.at(-notch, Length::ZERO)),
PathCommand::LineTo(frame.at(-full_len, half_w)),
PathCommand::Close,
]
}
EndKind::Diamond => {
let rx = full_len.div_round(2);
vec![
PathCommand::MoveTo(frame.at(rx, Length::ZERO)),
PathCommand::LineTo(frame.at(Length::ZERO, -half_w)),
PathCommand::LineTo(frame.at(-rx, Length::ZERO)),
PathCommand::LineTo(frame.at(Length::ZERO, half_w)),
PathCommand::Close,
]
}
EndKind::Oval => oval_commands(&frame, full_len.div_round(2), half_w),
EndKind::Arrow => arrow_commands(&frame, width, scale, self.width, self.length),
}
}
}
pub(crate) fn trim_polyline(points: &[Point], head: Length, tail: Length) -> Vec<Point> {
let trimmed = trim_start(points, head.max(Length::ZERO));
if trimmed.len() < 2 {
return Vec::new();
}
let mut rev: Vec<Point> = trimmed.into_iter().rev().collect();
rev = trim_start(&rev, tail.max(Length::ZERO));
if rev.len() < 2 {
return Vec::new();
}
rev.reverse();
rev
}
pub(crate) fn head_tangent(points: &[Point]) -> Option<(Point, Point)> {
let tip = *points.first()?;
let next = points
.iter()
.skip(1)
.copied()
.find(|p| p.x != tip.x || p.y != tip.y)?;
Some((next, tip))
}
pub(crate) fn tail_tangent(points: &[Point]) -> Option<(Point, Point)> {
let tip = *points.last()?;
let prev = points
.iter()
.rev()
.skip(1)
.copied()
.find(|p| p.x != tip.x || p.y != tip.y)?;
Some((prev, tip))
}
fn trim_start(points: &[Point], amount: Length) -> Vec<Point> {
if amount <= Length::ZERO || points.len() < 2 {
return points.to_vec();
}
let mut left = i128::from(amount.units());
for (idx, pair) in points.windows(2).enumerate() {
let [a, b] = *pair else { continue };
let dx = i128::from((b.x - a.x).units());
let dy = i128::from((b.y - a.y).units());
let seg = (dx * dx + dy * dy).isqrt();
if seg == 0 {
continue;
}
if left < seg {
let start = Point {
x: a.x + Length::from_units(round_div(dx * left, seg)),
y: a.y + Length::from_units(round_div(dy * left, seg)),
};
let mut out = Vec::with_capacity(points.len() - idx);
out.push(start);
if let Some(rest) = points.get(idx + 1..) {
out.extend_from_slice(rest);
}
return out;
}
left -= seg;
}
Vec::new()
}
struct LocalFrame {
tip: Point,
dx: i128,
dy: i128,
len: i128,
}
impl LocalFrame {
fn at(&self, along: Length, perp: Length) -> Point {
let a = i128::from(along.units());
let p = i128::from(perp.units());
Point {
x: self.tip.x + Length::from_units(round_div(self.dx * a - self.dy * p, self.len)),
y: self.tip.y + Length::from_units(round_div(self.dy * a + self.dx * p, self.len)),
}
}
}
fn oval_commands(frame: &LocalFrame, rx: Length, ry: Length) -> Vec<PathCommand> {
let kx = stroke::kappa(rx);
let ky = stroke::kappa(ry);
let zero = Length::ZERO;
vec![
PathCommand::MoveTo(frame.at(zero, -ry)),
PathCommand::CubicTo(frame.at(-kx, -ry), frame.at(-rx, -ky), frame.at(-rx, zero)),
PathCommand::CubicTo(frame.at(-rx, ky), frame.at(-kx, ry), frame.at(zero, ry)),
PathCommand::CubicTo(frame.at(kx, ry), frame.at(rx, ky), frame.at(rx, zero)),
PathCommand::CubicTo(frame.at(rx, -ky), frame.at(kx, -ry), frame.at(zero, -ry)),
PathCommand::Close,
]
}
fn arrow_wing(scale: Length, width: EndSize, length: EndSize) -> (Length, Length) {
let back = (scale * length.arrow_length_halves()).div_round(2);
let half_span = (scale * width.arrow_half_width_quarters()).div_round(4);
(back, half_span)
}
fn arrow_miter(half: Length, back: Length, half_span: Length) -> Length {
let dx = i128::from(back.units());
let dy = i128::from(half_span.units());
if dy <= 0 {
return Length::ZERO;
}
let arm = (dx * dx + dy * dy).isqrt();
Length::from_units(round_div(i128::from(half.units()) * arm, dy))
}
fn arrow_commands(
frame: &LocalFrame,
width: Length,
scale: Length,
w_size: EndSize,
l_size: EndSize,
) -> Vec<PathCommand> {
let half = width.div_toward_zero(2);
let (back, half_span) = arrow_wing(scale, w_size, l_size);
let dx = i128::from(back.units());
let dy = i128::from(half_span.units());
let arm = (dx * dx + dy * dy).isqrt();
if arm == 0 || dy == 0 {
return Vec::new();
}
let miter = Length::from_units(round_div(i128::from(half.units()) * arm, dy));
let nx = Length::from_units(round_div(dy * i128::from(half.units()), arm));
let ny = Length::from_units(round_div(dx * i128::from(half.units()), arm));
let back_x = -miter - back;
let w_top = frame.at(back_x, -half_span);
let w_bot = frame.at(back_x, half_span);
let mut commands = vec![
PathCommand::MoveTo(frame.at(back_x + nx, -half_span - ny)),
PathCommand::LineTo(frame.at(back_x - nx, -half_span + ny)),
PathCommand::LineTo(frame.at(-(miter * 2), Length::ZERO)),
PathCommand::LineTo(frame.at(back_x - nx, half_span - ny)),
PathCommand::LineTo(frame.at(back_x + nx, half_span + ny)),
PathCommand::LineTo(frame.at(Length::ZERO, Length::ZERO)),
PathCommand::Close,
];
commands.extend(stroke::disc(w_top, half));
commands.extend(stroke::disc(w_bot, half));
commands
}
fn round_div(num: i128, den: i128) -> i64 {
let rounded = if num >= 0 {
(num + den / 2) / den
} else {
(num - den / 2) / den
};
i64::try_from(rounded).unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
fn pt(x: i64, y: i64) -> Point {
Point {
x: Length::from_points(x).unwrap(),
y: Length::from_points(y).unwrap(),
}
}
#[test]
fn scales_arrowheads_with_two_point_minimum_floor() {
let tri = LineEnd {
kind: EndKind::Triangle,
width: EndSize::Medium,
length: EndSize::Medium,
};
let thin = Length::from_emus(9_525).unwrap(); let thick = Length::from_points(4).unwrap(); assert_eq!(tri.shorten(thin), Length::from_points(5).unwrap());
assert_eq!(tri.shorten(thick), Length::from_points(10).unwrap());
let stealth = LineEnd {
kind: EndKind::Stealth,
width: EndSize::Medium,
length: EndSize::Medium,
};
assert_eq!(stealth.shorten(thin), Length::from_points(4).unwrap());
assert_eq!(stealth.shorten(thick), Length::from_points(8).unwrap());
let oval = LineEnd {
kind: EndKind::Oval,
width: EndSize::Medium,
length: EndSize::Medium,
};
assert_eq!(oval.shorten(thick), Length::ZERO);
}
#[test]
fn trims_polylines_and_builds_all_five_arrowhead_shapes() {
let poly = [pt(0, 0), pt(100, 0), pt(100, 60)];
let trimmed = trim_polyline(
&poly,
Length::from_points(10).unwrap(),
Length::from_points(15).unwrap(),
);
assert_eq!(trimmed, vec![pt(10, 0), pt(100, 0), pt(100, 45)]);
assert_eq!(
trim_polyline(
&[pt(0, 0), pt(10, 0)],
Length::from_points(8).unwrap(),
Length::from_points(8).unwrap(),
),
Vec::new()
);
let w = Length::from_points(4).unwrap();
for kind in [
EndKind::Triangle,
EndKind::Stealth,
EndKind::Diamond,
EndKind::Oval,
EndKind::Arrow,
] {
let end = LineEnd {
kind,
width: EndSize::Medium,
length: EndSize::Medium,
};
assert_ne!(end.commands(pt(0, 0), pt(100, 0), w), Vec::new());
}
}
}