use f_office_paint::{FillRule, Item, PathCommand, PathItem, Point, Rgb, stroke};
use f_office_units::{Edges, Length};
use f_office_warnings::{Name, Warnings};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::dash::{DashStyle, MAX_DASHES};
use crate::guide::{self, Formula, Guides, Operand};
use crate::line_end::{LineEnds, head_tangent, tail_tangent, trim_polyline};
use crate::{A, COORDINATE_LIMIT, Warning, element_name, enumeration};
use f_office_units::fixed::{
self, FULL_TURN, HALF_TURN, ONE, QUARTER_TURN, UNIT, product, rounded,
};
pub(crate) const FILL: &Values<bool> = &Values::new(&[
own("none", false),
own("norm", true),
another("lighten", true),
another("lightenLess", true),
another("darken", true),
another("darkenLess", true),
]);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CustomGeometry {
formulas: Vec<Formula>,
paths: Vec<PathDefinition>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LiteralStep {
Move([i64; 2]),
Line([i64; 2]),
Cubic([[i64; 2]; 3]),
QuadX([i64; 2]),
QuadY([i64; 2]),
BoxArc {
bounds: [i64; 4],
start: [i64; 2],
end: [i64; 2],
clockwise: bool,
move_to_start: bool,
},
AngleEllipse {
center: [i64; 2],
radii: [i64; 2],
start_fd: i64,
sweep_fd: i64,
move_to_start: bool,
},
Close,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralPath {
pub size: [i64; 2],
pub steps: Vec<LiteralStep>,
pub filled: bool,
pub stroked: bool,
}
const QUARTER_TURN_ANG: i64 = f_office_units::scale::QUARTER_TURN;
const FULL_TURN_ANG: i64 = f_office_units::scale::FULL_TURN;
const DEG_UNITS: i128 = f_office_units::scale::DEGREE as i128;
fn literal_operand(value: i64) -> Option<Operand> {
(-COORDINATE_LIMIT..=COORDINATE_LIMIT)
.contains(&value)
.then_some(Operand::Number(value))
}
struct LiteralBuilder {
pen: [i64; 2],
start: [i64; 2],
has_pen: bool,
out: Vec<Step>,
}
impl LiteralBuilder {
fn new(capacity: usize) -> Self {
Self {
pen: [0, 0],
start: [0, 0],
has_pen: false,
out: Vec::with_capacity(capacity),
}
}
fn push(&mut self, step: LiteralStep) -> Option<()> {
let op = literal_operand;
match step {
LiteralStep::Move([x, y]) => self.move_or_line([x, y], true)?,
LiteralStep::Line([x, y]) => self.move_or_line([x, y], false)?,
LiteralStep::Cubic([[x1, y1], [x2, y2], [x3, y3]]) => {
self.pen = [x3, y3];
self.has_pen = true;
self.out.push(Step::Cubic([
[op(x1)?, op(y1)?],
[op(x2)?, op(y2)?],
[op(x3)?, op(y3)?],
]));
}
LiteralStep::QuadX(end) => self.push_quad_arc(end, true)?,
LiteralStep::QuadY(end) => self.push_quad_arc(end, false)?,
LiteralStep::BoxArc {
bounds,
start,
end,
clockwise,
move_to_start,
} => self.push_box_arc(bounds, start, end, clockwise, move_to_start)?,
LiteralStep::AngleEllipse {
center,
radii,
start_fd,
sweep_fd,
move_to_start,
} => self.push_angle_ellipse(center, radii, start_fd, sweep_fd, move_to_start)?,
LiteralStep::Close => {
self.pen = self.start;
self.out.push(Step::Close);
}
}
Some(())
}
fn move_or_line(&mut self, point: [i64; 2], as_move: bool) -> Option<()> {
let ops = [literal_operand(point[0])?, literal_operand(point[1])?];
self.pen = point;
self.has_pen = true;
if as_move {
self.start = point;
self.out.push(Step::Move(ops));
} else {
self.out.push(Step::Line(ops));
}
Some(())
}
fn push_quad_arc(&mut self, to: [i64; 2], horizontal_first: bool) -> Option<()> {
let dx = to[0].checked_sub(self.pen[0])?;
let dy = to[1].checked_sub(self.pen[1])?;
self.pen = to;
if dx == 0 || dy == 0 {
self.out.push(Step::Line([
literal_operand(to[0])?,
literal_operand(to[1])?,
]));
return Some(());
}
let (start_angle, sweep_angle) = quad_arc_angles(dx, dy, horizontal_first);
self.out.push(Step::Arc([
literal_operand(dx.abs())?,
literal_operand(dy.abs())?,
Operand::Number(start_angle),
Operand::Number(sweep_angle),
]));
Some(())
}
fn push_box_arc(
&mut self,
bounds: [i64; 4],
start_ray: [i64; 2],
end_ray: [i64; 2],
clockwise: bool,
move_to_start: bool,
) -> Option<()> {
let [left, top, right, bottom] = bounds;
let center2 = [
i128::from(left) + i128::from(right),
i128::from(top) + i128::from(bottom),
];
let rx = i64::try_from((i128::from(right) - i128::from(left)).abs() / 2).ok()?;
let ry = i64::try_from((i128::from(bottom) - i128::from(top)).abs() / 2).ok()?;
if rx == 0 || ry == 0 {
return self.move_or_line(end_ray, move_to_start || !self.has_pen);
}
let ray_ang = |ray: [i64; 2]| -> Option<i64> {
let raw = fixed::angle_of(
2 * i128::from(ray[0]) - center2[0],
2 * i128::from(ray[1]) - center2[1],
);
Some(
i64::try_from(rounded(raw, ONE))
.ok()?
.rem_euclid(FULL_TURN_ANG),
)
};
let (start_angle, end_angle) = (ray_ang(start_ray)?, ray_ang(end_ray)?);
let sweep_angle = arc_swing(start_angle, end_angle, clockwise);
self.push_ellipse_arc(center2, [rx, ry], start_angle, sweep_angle, move_to_start)
}
fn push_angle_ellipse(
&mut self,
center: [i64; 2],
radii: [i64; 2],
start_fd: i64,
sweep_fd: i64,
move_to_start: bool,
) -> Option<()> {
let [rx, ry] = [radii[0].abs(), radii[1].abs()];
if rx == 0 || ry == 0 {
return self.move_or_line(center, move_to_start || !self.has_pen);
}
let start_cw = -rounded(i128::from(start_fd) * DEG_UNITS, ONE);
let sweep_cw = -rounded(i128::from(sweep_fd) * DEG_UNITS, ONE);
let full = i128::from(FULL_TURN_ANG);
let start_angle = i64::try_from(start_cw.rem_euclid(full)).ok()?;
let sweep_angle = i64::try_from(sweep_cw.clamp(-full, full)).ok()?;
let center2 = [i128::from(center[0]) * 2, i128::from(center[1]) * 2];
self.push_ellipse_arc(center2, [rx, ry], start_angle, sweep_angle, move_to_start)
}
fn push_ellipse_arc(
&mut self,
center2: [i128; 2],
radii: [i64; 2],
start_angle: i64,
sweep_angle: i64,
move_to_start: bool,
) -> Option<()> {
let start_pt = ellipse_point(center2, radii, start_angle)?;
let end_pt = ellipse_point(
center2,
radii,
(start_angle + sweep_angle).rem_euclid(FULL_TURN_ANG),
)?;
self.move_or_line(start_pt, move_to_start || !self.has_pen)?;
self.out.push(Step::Arc([
literal_operand(radii[0])?,
literal_operand(radii[1])?,
Operand::Number(start_angle),
Operand::Number(sweep_angle),
]));
self.pen = end_pt;
Some(())
}
}
fn quad_arc_angles(dx: i64, dy: i64, horizontal_first: bool) -> (i64, i64) {
let same_sign = (dx > 0) == (dy > 0);
if horizontal_first {
let start = if dy > 0 {
3 * QUARTER_TURN_ANG
} else {
QUARTER_TURN_ANG
};
let sweep = if same_sign {
QUARTER_TURN_ANG
} else {
-QUARTER_TURN_ANG
};
(start, sweep)
} else {
let start = if dx > 0 { 2 * QUARTER_TURN_ANG } else { 0 };
let sweep = if same_sign {
-QUARTER_TURN_ANG
} else {
QUARTER_TURN_ANG
};
(start, sweep)
}
}
fn arc_swing(start: i64, end: i64, clockwise: bool) -> i64 {
if clockwise {
let delta = (end - start).rem_euclid(FULL_TURN_ANG);
if delta == 0 { FULL_TURN_ANG } else { delta }
} else {
let delta = (start - end).rem_euclid(FULL_TURN_ANG);
-if delta == 0 { FULL_TURN_ANG } else { delta }
}
}
fn ellipse_point(center2: [i128; 2], radii: [i64; 2], ang_deg60: i64) -> Option<[i64; 2]> {
let [wr, hr] = [i128::from(radii[0]) * ONE, i128::from(radii[1]) * ONE];
let t = parametric(i128::from(ang_deg60) * ONE, [wr, hr]);
let [sin, cos] = fixed::sin_cos(t);
let px = rounded(center2[0] * (ONE / 2) + product(wr, cos), ONE);
let py = rounded(center2[1] * (ONE / 2) + product(hr, sin), ONE);
Some([i64::try_from(px).ok()?, i64::try_from(py).ok()?])
}
impl CustomGeometry {
#[must_use]
pub fn from_literal_paths(paths: Vec<LiteralPath>) -> Option<Self> {
if paths.is_empty() {
return None;
}
let mut defs = Vec::with_capacity(paths.len());
for path in paths {
let [w, h] = path.size;
if !(1..=COORDINATE_LIMIT).contains(&w) || !(1..=COORDINATE_LIMIT).contains(&h) {
return None;
}
let mut builder = LiteralBuilder::new(path.steps.len());
for step in path.steps {
builder.push(step)?;
}
defs.push(PathDefinition {
size: [w, h],
steps: builder.out,
filled: path.filled,
stroked: path.stroked,
});
}
Some(Self {
formulas: Vec::new(),
paths: defs,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PathDefinition {
pub(crate) size: [i64; 2],
pub(crate) steps: Vec<Step>,
pub(crate) filled: bool,
pub(crate) stroked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Step {
Move([Operand; 2]),
Line([Operand; 2]),
Arc([Operand; 4]),
Quad([[Operand; 2]; 2]),
Cubic([[Operand; 2]; 3]),
Close,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CustomPath {
size: [i64; 2],
segments: Vec<Segment>,
filled: bool,
stroked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Segment {
Move([i64; 2]),
Line([i64; 2]),
Quad([[i64; 2]; 2]),
Cubic([[i64; 2]; 3]),
Close,
}
#[derive(Clone, Copy, Debug)]
pub struct Place {
pub frame: Edges<Length>,
pub flip: [bool; 2],
pub quarters: i64,
}
#[must_use]
pub fn read(
doc: &Document,
geometry: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<CustomGeometry> {
let mut guides = Guides::default();
for list in ["avLst", "gdLst"].map(|name| doc.child(geometry, A, name)) {
let entries = list.into_iter().flat_map(|list| doc.child_elements(list));
for gd in entries.filter(|node| doc.is(*node, A, "gd")) {
let name = doc.attribute(gd, None, "name").unwrap_or_default();
let read = doc
.attribute(gd, None, "fmla")
.and_then(|formula| guides.add(name, formula));
if read.is_none() {
warnings.push(Warning::InvalidValue {
element: element_name(doc, gd),
attribute: Name::new("fmla"),
});
return None;
}
}
}
let Some(list) = doc.child(geometry, A, "pathLst") else {
warnings.push(Warning::InvalidChildren {
element: element_name(doc, geometry),
});
return None;
};
let paths: Vec<PathDefinition> = doc
.child_elements(list)
.filter(|node| doc.is(*node, A, "path"))
.map(|node| read_path(doc, node, &guides, warnings))
.collect::<Option<_>>()?;
(!paths.is_empty()).then(|| CustomGeometry::new(guides, paths))
}
fn read_path(
doc: &Document,
node: NodeId,
guides: &Guides<'_>,
warnings: &mut Warnings<Warning>,
) -> Option<PathDefinition> {
let mut size = |name: &str| match coordinate(doc, node, (name, 0), warnings) {
Coordinate::Missing | Coordinate::Unreadable => Some(0),
Coordinate::Guide(_) => {
warnings.push(Warning::InvalidValue {
element: element_name(doc, node),
attribute: Name::new(name),
});
Some(0)
}
Coordinate::Value(value) => Some(value),
Coordinate::Outside => None,
};
let size = [size("w")?, size("h")?];
let steps = doc
.child_elements(node)
.map(|child| read_step(doc, child, guides, warnings))
.collect::<Option<Vec<Step>>>()?;
Some(PathDefinition {
size,
steps,
filled: enumeration(doc, node, "fill", (FILL, warnings)).unwrap_or(true),
stroked: stroked(doc.attribute(node, None, "stroke")),
})
}
pub(crate) fn stroked(value: Option<&str>) -> bool {
!value.is_some_and(|value| ["0", "false"].contains(&value))
}
const POINT_STEPS: [&str; 5] = ["close", "moveTo", "lnTo", "quadBezTo", "cubicBezTo"];
fn read_step(
doc: &Document,
child: NodeId,
guides: &Guides<'_>,
warnings: &mut Warnings<Warning>,
) -> Option<Step> {
if doc.is(child, A, "arcTo") {
let mut at = |name| operand(doc, child, name, guides, warnings);
return Some(Step::Arc([
at("wR")?,
at("hR")?,
at("stAng")?,
at("swAng")?,
]));
}
let Some(kind) = POINT_STEPS.iter().position(|name| doc.is(child, A, name)) else {
warnings.push(Warning::InvalidChildren {
element: Name::new("path"),
});
return None;
};
let step = step_of(kind, &points(doc, child, guides, warnings)?);
if step.is_none() {
warnings.push(Warning::InvalidChildren {
element: element_name(doc, child),
});
}
step
}
fn step_of(kind: usize, all: &[[Operand; 2]]) -> Option<Step> {
let at = |i: usize| all.get(i).copied();
Some(match kind {
0 => Step::Close,
1 => Step::Move(at(0)?),
2 => Step::Line(at(0)?),
3 => Step::Quad([at(0)?, at(1)?]),
_ => Step::Cubic([at(0)?, at(1)?, at(2)?]),
})
}
fn points(
doc: &Document,
step: NodeId,
guides: &Guides<'_>,
warnings: &mut Warnings<Warning>,
) -> Option<Vec<[Operand; 2]>> {
doc.child_elements(step)
.filter(|pt| doc.is(*pt, A, "pt"))
.map(|pt| {
let mut at = |name| operand(doc, pt, name, guides, warnings);
Some([at("x")?, at("y")?])
})
.collect()
}
fn operand(
doc: &Document,
node: NodeId,
name: &str,
guides: &Guides<'_>,
warnings: &mut Warnings<Warning>,
) -> Option<Operand> {
match coordinate(doc, node, (name, -COORDINATE_LIMIT), warnings) {
Coordinate::Value(value) => Some(Operand::Number(value)),
Coordinate::Guide(text) => {
let found = guides.guide(text);
if found.is_none() {
warnings.push(Warning::InvalidValue {
element: element_name(doc, node),
attribute: Name::new(name),
});
}
found
}
Coordinate::Missing => {
warnings.push(Warning::InvalidValue {
element: element_name(doc, node),
attribute: Name::new(name),
});
None
}
Coordinate::Unreadable | Coordinate::Outside => None,
}
}
enum Coordinate<'a> {
Missing,
Unreadable,
Guide(&'a str),
Value(i64),
Outside,
}
fn coordinate<'a>(
doc: &'a Document,
node: NodeId,
(name, low): (&str, i64),
warnings: &mut Warnings<Warning>,
) -> Coordinate<'a> {
let Some(text) = doc.attribute(node, None, name) else {
return Coordinate::Missing;
};
let Ok(value) = text.parse::<i64>() else {
let number_like = text
.chars()
.next()
.is_none_or(|first| first.is_ascii_digit() || matches!(first, '+' | '-'));
return if number_like {
warnings.push(Warning::InvalidValue {
element: element_name(doc, node),
attribute: Name::new(name),
});
Coordinate::Unreadable
} else {
Coordinate::Guide(text)
};
};
if (low..=COORDINATE_LIMIT).contains(&value) {
return Coordinate::Value(value);
}
warnings.push(Warning::InvalidValue {
element: element_name(doc, node),
attribute: Name::new(name),
});
Coordinate::Outside
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutOfRange;
const POINT_LIMIT: i64 = 1 << 61;
impl CustomGeometry {
pub(crate) fn new(guides: Guides<'_>, paths: Vec<PathDefinition>) -> Self {
Self {
formulas: guides.into_formulas(),
paths,
}
}
fn paths(
&self,
frame: Edges<Length>,
drawn: impl Fn(&PathDefinition) -> bool,
) -> Result<Vec<CustomPath>, OutOfRange> {
let sides = [frame.width().units(), frame.height().units()];
let size = sides.map(|side| i128::from(side) * ONE / 2);
let values = guide::values(&self.formulas, size).ok_or(OutOfRange)?;
self.paths
.iter()
.filter(|path| drawn(path))
.map(|path| path.in_box(&values, sides))
.collect()
}
}
#[derive(Clone, Copy, Debug)]
struct Axis {
extent: i64,
scale: i64,
}
impl Axis {
fn new(size: i64, box_side: i64) -> Result<Self, OutOfRange> {
if size <= 0 {
return Ok(Self {
extent: box_side,
scale: 2,
});
}
let scale = ((box_side.max(0) + size - 1) / size).max(1);
let extent = size.checked_mul(scale).ok_or(OutOfRange)?;
Ok(Self { extent, scale })
}
fn place(self, values: &[i128], operand: Operand) -> Result<i64, OutOfRange> {
match operand {
Operand::Number(number) => number
.checked_mul(self.scale)
.filter(|place| place.abs() <= POINT_LIMIT)
.ok_or(OutOfRange),
Operand::Guide(_) => self.whole(guide::value(values, operand)),
}
}
fn whole(self, value: i128) -> Result<i64, OutOfRange> {
value
.checked_mul(i128::from(self.scale))
.map(|scaled| rounded(scaled, ONE))
.and_then(|place| i64::try_from(place).ok())
.filter(|place| place.abs() <= POINT_LIMIT)
.ok_or(OutOfRange)
}
}
impl PathDefinition {
fn in_box(&self, values: &[i128], sides: [i64; 2]) -> Result<CustomPath, OutOfRange> {
let axes = [
Axis::new(self.size[0], sides[0])?,
Axis::new(self.size[1], sides[1])?,
];
let value = |operand| guide::value(values, operand);
let place = |[x, y]: [Operand; 2]| -> Result<[i64; 2], OutOfRange> {
Ok([axes[0].place(values, x)?, axes[1].place(values, y)?])
};
let whole = |[x, y]: [i128; 2]| -> Result<[i64; 2], OutOfRange> {
Ok([axes[0].whole(x)?, axes[1].whole(y)?])
};
let mut segments = Vec::with_capacity(self.steps.len());
let (mut start, mut pen) = ([0; 2], [0; 2]);
for step in &self.steps {
match *step {
Step::Move(p) => {
(start, pen) = (p.map(value), p.map(value));
segments.push(Segment::Move(place(p)?));
}
Step::Line(p) => {
pen = p.map(value);
segments.push(Segment::Line(place(p)?));
}
Step::Quad([c, p]) => {
pen = p.map(value);
segments.push(Segment::Quad([place(c)?, place(p)?]));
}
Step::Cubic([c1, c2, p]) => {
pen = p.map(value);
segments.push(Segment::Cubic([place(c1)?, place(c2)?, place(p)?]));
}
Step::Arc([wr, hr, angle, swing]) => {
let radii = [value(wr), value(hr)];
for [c1, c2, end] in arc(pen, radii, [value(angle), value(swing)])? {
segments.push(Segment::Cubic([whole(c1)?, whole(c2)?, whole(end)?]));
pen = end;
}
}
Step::Close => {
pen = start;
segments.push(Segment::Close);
}
}
}
Ok(CustomPath {
size: [axes[0].extent, axes[1].extent],
segments,
filled: self.filled,
stroked: self.stroked,
})
}
}
fn arc(
pen: [i128; 2],
radii: [i128; 2],
[angle, swing]: [i128; 2],
) -> Result<Vec<[[i128; 2]; 3]>, OutOfRange> {
if swing.abs() > FULL_TURN {
return Err(OutOfRange);
}
if swing == 0 {
return Ok(Vec::new());
}
let [wr, hr] = radii;
let from = parametric(angle, radii);
let sweep = parametric(angle + swing, radii) - from;
let [sin, cos] = fixed::sin_cos(from);
let center = [pen[0] - product(wr, cos), pen[1] - product(hr, sin)];
let point_and_tangent = |t: i128| {
let [sin, cos] = fixed::sin_cos(t);
(
[center[0] + product(wr, cos), center[1] + product(hr, sin)],
[-product(wr, sin), product(hr, cos)],
)
};
let count: i128 = match sweep.abs() {
size if size <= QUARTER_TURN => 1,
size if size <= HALF_TURN => 2,
size if size <= 3 * QUARTER_TURN => 3,
_ => 4,
};
Ok((0..count)
.map(|k| {
let a = from + rounded(sweep * k, count);
let b = from + rounded(sweep * (k + 1), count);
let [sin, cos] = fixed::sin_cos(rounded(b - a, 4));
let kappa = rounded(4 * sin * UNIT, 3 * cos);
let ((start, out), (end, back)) = (point_and_tangent(a), point_and_tangent(b));
[
[
start[0] + product(kappa, out[0]),
start[1] + product(kappa, out[1]),
],
[
end[0] - product(kappa, back[0]),
end[1] - product(kappa, back[1]),
],
end,
]
})
.collect())
}
#[must_use]
pub fn circle_arc(
center: Point,
radius: Length,
[angle, swing]: [i64; 2],
) -> Option<(Point, Vec<PathCommand>)> {
let value = |length: Length| {
let units = i128::from(length.units());
(units.abs() < fixed::LIMIT / ONE).then_some(units * ONE)
};
let point = |[x, y]: [i128; 2]| {
Some(Point {
x: Length::from_units(i64::try_from(rounded(x, ONE)).ok()?),
y: Length::from_units(i64::try_from(rounded(y, ONE)).ok()?),
})
};
let (r, x, y) = (value(radius)?, value(center.x)?, value(center.y)?);
let from = i128::from(angle) * ONE;
let [sin, cos] = fixed::sin_cos(from);
let pen = [x + product(r, cos), y + product(r, sin)];
let curves = arc(pen, [r, r], [from, i128::from(swing) * ONE]).ok()?;
let commands = curves
.into_iter()
.map(|[c1, c2, end]| Some(PathCommand::CubicTo(point(c1)?, point(c2)?, point(end)?)))
.collect::<Option<_>>()?;
Some((point(pen)?, commands))
}
fn parametric(angle: i128, [wr, hr]: [i128; 2]) -> i128 {
let [sin, cos] = fixed::sin_cos(angle);
let t = fixed::angle_of(hr * cos, wr * sin);
let gap = t - angle;
angle + gap - FULL_TURN * rounded(gap, FULL_TURN)
}
impl Place {
fn on_page(&self, path: &CustomPath, p: [i64; 2]) -> Result<Point, OutOfRange> {
self.map(path.size, p).map(point)
}
fn map(&self, size: [i64; 2], [px, py]: [i64; 2]) -> Result<(Length, Length), OutOfRange> {
let (x, y) = (self.frame.left, self.frame.top);
let (w, h) = (self.frame.width(), self.frame.height());
let along = |value: i64, length: Length, extent: i64, flip: bool| {
let value = if flip { extent - value } else { value };
if extent == 0 {
return Ok(Length::ZERO);
}
let share = i128::from(value) * i128::from(length.units()) / i128::from(extent);
i64::try_from(share)
.ok()
.filter(|share| (-Length::FILE_LIMIT..=Length::FILE_LIMIT).contains(share))
.map(Length::from_units)
.ok_or(OutOfRange)
};
let point = (
x + along(px, w, size[0], self.flip[0])?,
y + along(py, h, size[1], self.flip[1])?,
);
let center = (x + w.div_toward_zero(2), y + h.div_toward_zero(2));
Ok(turned(point, center, self.quarters))
}
}
pub(crate) fn turned(
(x, y): (Length, Length),
center: (Length, Length),
quarters: i64,
) -> (Length, Length) {
let (mut dx, mut dy) = (x - center.0, y - center.1);
for _ in 0..quarters {
(dx, dy) = (-dy, dx);
}
(center.0 + dx, center.1 + dy)
}
const fn point((x, y): (Length, Length)) -> Point {
Point { x, y }
}
pub fn items(
geometry: &CustomGeometry,
place: &Place,
fill: Option<Rgb>,
line: Option<(Rgb, Length)>,
) -> Result<Vec<Item>, OutOfRange> {
items_styled(geometry, place, fill, line, None, LineEnds::default())
}
pub(crate) fn items_styled(
geometry: &CustomGeometry,
place: &Place,
fill: Option<Rgb>,
line: Option<(Rgb, Length)>,
dash: Option<&DashStyle>,
ends: LineEnds,
) -> Result<Vec<Item>, OutOfRange> {
let (filled, stroked) = fill_and_stroke(geometry, place, fill, line, dash, ends)?;
Ok(filled.into_iter().chain(stroked).map(Item::Path).collect())
}
pub(crate) fn fill_and_stroke(
geometry: &CustomGeometry,
place: &Place,
fill: Option<Rgb>,
line: Option<(Rgb, Length)>,
dash: Option<&DashStyle>,
ends: LineEnds,
) -> Result<(Option<PathItem>, Option<PathItem>), OutOfRange> {
let paths = geometry.paths(place.frame, |path| {
(path.filled && fill.is_some()) || (path.stroked && line.is_some())
})?;
let filled = if let Some(color) = fill {
let mut commands = Vec::new();
for path in paths.iter().filter(|p| p.filled) {
commands.extend(outline(path, place)?);
}
(!commands.is_empty()).then_some(PathItem {
commands,
color,
fill_rule: FillRule::EvenOdd,
})
} else {
None
};
let stroked = if let Some((color, half)) = line {
let mut commands = Vec::new();
for path in paths.iter().filter(|p| p.stroked) {
for (subpath, closed) in subpaths(path, place)? {
stroke_subpath(&subpath, closed, half, dash, ends, &mut commands);
}
}
(!commands.is_empty()).then_some(PathItem {
commands,
color,
fill_rule: FillRule::NonZero,
})
} else {
None
};
Ok((filled, stroked))
}
fn stroke_subpath(
points: &[Point],
closed: bool,
half: Length,
dash: Option<&DashStyle>,
ends: LineEnds,
out: &mut Vec<PathCommand>,
) {
let width = half * 2;
if !closed && ends.any() {
let head_t = ends.head.and_then(|_| head_tangent(points));
let tail_t = ends.tail.and_then(|_| tail_tangent(points));
let head_trim = ends.head.map_or(Length::ZERO, |e| e.shorten(width));
let tail_trim = ends.tail.map_or(Length::ZERO, |e| e.shorten(width));
let trimmed = trim_polyline(points, head_trim, tail_trim);
if !trimmed.is_empty() {
stroke_flat_or_dashed(&trimmed, half, dash, out);
}
if let (Some(end), Some((from, tip))) = (ends.head, head_t) {
out.extend(end.commands(from, tip, width));
}
if let (Some(end), Some((from, tip))) = (ends.tail, tail_t) {
out.extend(end.commands(from, tip, width));
}
return;
}
if let Some(style) = dash
&& let Some(dashed) = stroke::dashes(points, half, &style.pattern, style.cap, MAX_DASHES)
{
out.extend(dashed);
return;
}
for pair in points.windows(2) {
if let [a, b] = pair {
out.extend(stroke::piece(*a, *b, half).into_iter().flatten());
}
}
}
fn stroke_flat_or_dashed(
points: &[Point],
half: Length,
dash: Option<&DashStyle>,
out: &mut Vec<PathCommand>,
) {
if let Some(style) = dash
&& let Some(dashed) = stroke::dashes(points, half, &style.pattern, style.cap, MAX_DASHES)
{
out.extend(dashed);
return;
}
let mut prev_end = None;
for pair in points.windows(2) {
if let [a, b] = pair
&& let Some(band) = stroke::band(*a, *b, half)
{
if let Some(joint) = prev_end {
out.extend(stroke::disc(joint, half));
}
out.extend(band);
prev_end = Some(*b);
}
}
}
fn outline(path: &CustomPath, place: &Place) -> Result<Vec<PathCommand>, OutOfRange> {
path.segments
.iter()
.map(|segment| {
Ok(match *segment {
Segment::Move(p) => PathCommand::MoveTo(place.on_page(path, p)?),
Segment::Line(p) => PathCommand::LineTo(place.on_page(path, p)?),
Segment::Quad([c, p]) => {
PathCommand::QuadTo(place.on_page(path, c)?, place.on_page(path, p)?)
}
Segment::Cubic([c1, c2, p]) => PathCommand::CubicTo(
place.on_page(path, c1)?,
place.on_page(path, c2)?,
place.on_page(path, p)?,
),
Segment::Close => PathCommand::Close,
})
})
.collect()
}
fn subpaths(path: &CustomPath, place: &Place) -> Result<Vec<(Vec<Point>, bool)>, OutOfRange> {
let mut all = Vec::new();
let mut current: Vec<Point> = Vec::new();
let origin = point((Length::ZERO, Length::ZERO));
let (mut start, mut at) = (origin, origin);
for segment in &path.segments {
match *segment {
Segment::Move(p) => {
finish_subpath(&mut all, &mut current, false);
start = place.on_page(path, p)?;
at = start;
current.push(start);
}
Segment::Close => {
ensure_start(&mut current, at);
current.push(start);
at = start;
finish_subpath(&mut all, &mut current, true);
}
other => {
ensure_start(&mut current, at);
at = extend_subpath(&mut current, at, other, path, place)?;
}
}
}
finish_subpath(&mut all, &mut current, false);
Ok(all)
}
fn finish_subpath(all: &mut Vec<(Vec<Point>, bool)>, current: &mut Vec<Point>, closed: bool) {
if current.len() >= 2 {
all.push((std::mem::take(current), closed));
} else {
current.clear();
}
}
fn ensure_start(current: &mut Vec<Point>, at: Point) {
if current.is_empty() {
current.push(at);
}
}
fn extend_subpath(
current: &mut Vec<Point>,
at: Point,
segment: Segment,
path: &CustomPath,
place: &Place,
) -> Result<Point, OutOfRange> {
match segment {
Segment::Line(p) => {
let next = place.on_page(path, p)?;
current.push(next);
Ok(next)
}
Segment::Quad([c, p]) => {
let end = place.on_page(path, p)?;
current.extend(stroke::cubic_points(stroke::quad_as_cubic(
at,
place.on_page(path, c)?,
end,
)));
Ok(end)
}
Segment::Cubic([c1, c2, p]) => {
let end = place.on_page(path, p)?;
current.extend(stroke::cubic_points([
at,
place.on_page(path, c1)?,
place.on_page(path, c2)?,
end,
]));
Ok(end)
}
Segment::Move(_) | Segment::Close => Ok(at),
}
}
#[cfg(test)]
mod tests;