use std::sync::Arc;
use valo_pathops::{SkPath, SkPathBuilder, SkPathFillType, SkPathOp, SkPathVerb, SkPoint};
use crate::{FillRule, Path, PathBuilder, PathElement, Point};
pub use valo_pathops::PathOpsError as PathOperationError;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PathOperation {
Difference,
Intersect,
Union,
Xor,
ReverseDifference,
}
impl Path {
pub fn combine(
&self,
fill_rule: FillRule,
operation: PathOperation,
other: &Path,
other_fill_rule: FillRule,
) -> Result<Arc<Path>, PathOperationError> {
let result = valo_pathops::op(
&to_skia_path(self, fill_rule),
&to_skia_path(other, other_fill_rule),
to_skia_op(operation),
)?;
Ok(from_skia_path(&result))
}
}
fn to_skia_op(operation: PathOperation) -> SkPathOp {
match operation {
PathOperation::Difference => SkPathOp::Difference,
PathOperation::Intersect => SkPathOp::Intersect,
PathOperation::Union => SkPathOp::Union,
PathOperation::Xor => SkPathOp::Xor,
PathOperation::ReverseDifference => SkPathOp::ReverseDifference,
}
}
fn to_skia_path(path: &Path, fill_rule: FillRule) -> SkPath {
let mut builder = SkPathBuilder::with_fill_type(match fill_rule {
FillRule::NonZero => SkPathFillType::Winding,
FillRule::EvenOdd => SkPathFillType::EvenOdd,
});
for element in path.elements() {
match element {
PathElement::MoveTo(p) => builder.move_to(to_skia_point(p)),
PathElement::LineTo(p) => builder.line_to(to_skia_point(p)),
PathElement::QuadTo(c, p) => builder.quad_to(to_skia_point(c), to_skia_point(p)),
PathElement::ConicTo(c, p, weight) => {
builder.conic_to(to_skia_point(c), to_skia_point(p), weight)
}
PathElement::CubicTo(c1, c2, p) => {
builder.cubic_to(to_skia_point(c1), to_skia_point(c2), to_skia_point(p))
}
PathElement::Close => builder.close(),
};
}
builder.detach()
}
fn from_skia_path(path: &SkPath) -> Arc<Path> {
let mut builder = PathBuilder::new();
let mut points = path.points().iter().map(|p| Point::new(p.x, p.y));
let mut weights = path.conic_weights().iter();
let mut next_point = || {
points
.next()
.expect("Skia's path has a point per verb point")
};
for verb in path.verbs() {
match verb {
SkPathVerb::Move => builder.move_to(next_point()),
SkPathVerb::Line => builder.line_to(next_point()),
SkPathVerb::Quad => {
let control = next_point();
builder.quad_to(control, next_point())
}
SkPathVerb::Conic => {
let control = next_point();
let weight = *weights.next().expect("Skia's path has a weight per conic");
builder.conic_to(control, next_point(), weight)
}
SkPathVerb::Cubic => {
let control1 = next_point();
let control2 = next_point();
builder.cubic_to(control1, control2, next_point())
}
SkPathVerb::Close => builder.close(),
};
}
builder.build()
}
fn to_skia_point(point: Point) -> SkPoint {
SkPoint {
x: point.x,
y: point.y,
}
}