use pltrs_core::path::convert::{StringCodes, StringOptions};
use pltrs_core::{Affine2D, Path, Rgba};
use super::SvgRenderer;
use super::style::{Style, css};
use super::xml::XmlWriter;
use crate::gc::GraphicsContext;
use crate::vector::{repr, repr_str, short};
#[derive(Clone, Debug, PartialEq)]
enum ClipShape {
Path(Path, Affine2D),
Rect([f64; 4]),
}
#[derive(Clone, Debug, PartialEq)]
enum ClipKey {
Path(usize, Affine2D),
Rect([f64; 4]),
}
#[derive(Debug, Default)]
pub(super) struct Clips {
paths: Vec<Path>,
entries: Vec<(ClipKey, ClipShape, String)>,
}
#[derive(Clone, Debug, PartialEq)]
struct HatchKey {
pattern: String,
face: Option<Rgba>,
color: Rgba,
linewidth: f64,
}
#[derive(Debug, Default)]
pub(super) struct Hatches {
entries: Vec<(HatchKey, String)>,
}
const HATCH_SIZE: f64 = 72.0;
fn color_repr(color: Rgba) -> String {
format!(
"({}, {}, {}, {})",
repr(color.r),
repr(color.g),
repr(color.b),
repr(color.a)
)
}
pub(super) fn path_data(path: &Path, transform: Affine2D) -> String {
path.convert_to_string(&StringOptions {
transform,
codes: StringCodes::SVG,
..StringOptions::default()
})
}
impl SvgRenderer {
pub(super) fn clip_attribute(
&mut self,
gc: &GraphicsContext,
) -> Option<(&'static str, String)> {
let clip_path = gc
.clip_path
.as_ref()
.filter(|clip| clip.path.vertices().iter().all(|p| p.is_finite()));
let (key, shape, content) = if let Some(clip) = clip_path {
let flipped = clip.transform.then(self.flip());
let known = self.clips.paths.iter().position(|p| *p == clip.path);
let index = known.unwrap_or_else(|| {
self.clips.paths.push(clip.path.clone());
self.clips.paths.len() - 1
});
let values: Vec<String> = flipped.values().iter().map(|&v| repr(v)).collect();
(
ClipKey::Path(index, flipped),
ClipShape::Path(clip.path.clone(), flipped),
format!("({index}, '{}')", values.join(" ")),
)
} else {
let rect = gc.clip_rect?;
let (x, y, w, h) = rect.bounds();
let values = [x, self.height - (y + h), w, h];
let content: Vec<String> = values
.iter()
.map(|&v| format!("np.float64({})", repr(v)))
.collect();
(
ClipKey::Rect(values),
ClipShape::Rect(values),
format!("({})", content.join(", ")),
)
};
let known = self.clips.entries.iter().find(|(k, _, _)| *k == key);
let id = if let Some((_, _, id)) = known {
id.clone()
} else {
let id = self.make_id("p", &content);
self.clips.entries.push((key, shape, id.clone()));
id
};
Some(("clip-path", format!("url(#{id})")))
}
pub(super) fn hatch_id(&mut self, gc: &GraphicsContext, face: Option<Rgba>) -> Option<String> {
let hatch = gc.hatch.as_ref()?;
let key = HatchKey {
pattern: hatch.pattern.clone(),
face,
color: hatch.color,
linewidth: hatch.linewidth,
};
if let Some((_, id)) = self.hatches.entries.iter().find(|(k, _)| *k == key) {
return Some(id.clone());
}
let content = format!(
"({}, {}, {}, {})",
repr_str(&key.pattern),
face.map_or_else(|| "None".to_owned(), color_repr),
color_repr(key.color),
repr(key.linewidth)
);
let id = self.make_id("h", &content);
self.hatches.entries.push((key, id.clone()));
Some(id)
}
}
impl Clips {
pub(super) fn write(&self, writer: &mut XmlWriter) {
if self.entries.is_empty() {
return;
}
writer.start("defs", &[]);
for (_, shape, id) in &self.entries {
writer.start("clipPath", &[("id", id.clone())]);
match shape {
ClipShape::Path(path, transform) => {
writer.element("path", "", &[("d", path_data(path, *transform))]);
}
ClipShape::Rect([x, y, w, h]) => writer.element(
"rect",
"",
&[
("x", short(*x)),
("y", short(*y)),
("width", short(*w)),
("height", short(*h)),
],
),
}
writer.end(true);
}
writer.end(true);
}
}
impl Hatches {
pub(super) fn write(&self, writer: &mut XmlWriter) {
if self.entries.is_empty() {
return;
}
let size = HATCH_SIZE.to_string();
writer.start("defs", &[]);
for (key, id) in &self.entries {
writer.start(
"pattern",
&[
("id", id.clone()),
("patternUnits", "userSpaceOnUse".to_owned()),
("x", "0".to_owned()),
("y", "0".to_owned()),
("width", size.clone()),
("height", size.clone()),
],
);
let tile = Affine2D::scaling(HATCH_SIZE, HATCH_SIZE)
.scale(1.0, -1.0)
.translate(0.0, HATCH_SIZE);
let path =
pltrs_core::hatch::pattern_path(&key.pattern, pltrs_core::hatch::DEFAULT_DENSITY)
.unwrap_or_default();
let data = path_data(&path, tile);
let fill = key
.face
.map_or_else(|| "none".to_owned(), |face| face.to_hex(false));
let edge = (HATCH_SIZE + 1.0).to_string();
writer.element(
"rect",
"",
&[
("x", "0".to_owned()),
("y", "0".to_owned()),
("width", edge.clone()),
("height", edge),
("fill", fill),
],
);
let mut style: Style = vec![
("fill", key.color.to_hex(false)),
("stroke", key.color.to_hex(false)),
("stroke-width", repr(key.linewidth)),
("stroke-linecap", "butt".to_owned()),
("stroke-linejoin", "miter".to_owned()),
];
if key.color.a < 1.0 {
style.push(("stroke-opacity", repr(key.color.a)));
}
writer.element("path", "", &[("d", data), ("style", css(&style))]);
writer.end(true);
}
writer.end(true);
}
}