use std::collections::HashSet;
use std::fmt::Write;
#[derive(Default)]
struct Bounds(Option<(f64, f64, f64, f64)>);
impl Bounds {
fn include(&mut self, x: f64, y: f64) -> Option<()> {
if !x.is_finite() || !y.is_finite() {
return None;
}
self.0 = Some(match self.0 {
Some((left, top, right, bottom)) => {
(left.min(x), top.min(y), right.max(x), bottom.max(y))
}
None => (x, y, x, y),
});
Some(())
}
}
fn coverage_bounds(node: roxmltree::Node<'_, '_>) -> Option<(f64, f64, f64, f64)> {
let mut bounds = Bounds::default();
for segment in svgtypes::SimplifyingPathParser::from(node.attribute("d")?) {
use svgtypes::SimplePathSegment as S;
match segment.ok()? {
S::MoveTo { x, y } | S::LineTo { x, y } => bounds.include(x, y)?,
S::CurveTo {
x1,
y1,
x2,
y2,
x,
y,
} => {
bounds.include(x1, y1)?;
bounds.include(x2, y2)?;
bounds.include(x, y)?;
}
S::Quadratic { x1, y1, x, y } => {
bounds.include(x1, y1)?;
bounds.include(x, y)?;
}
S::ClosePath => (),
}
}
let (left, top, right, bottom) = bounds.0?;
let width: f64 = node.attribute("stroke-width")?.parse().ok()?;
let miter: f64 = node
.attribute("stroke-miterlimit")
.unwrap_or("4")
.parse()
.ok()?;
if !width.is_finite() || width <= 0.0 || !miter.is_finite() {
return None;
}
let margin = width * miter.max(std::f64::consts::SQRT_2) / 2.0;
let rect = (
left - margin,
top - margin,
right - left + 2.0 * margin,
bottom - top + 2.0 * margin,
);
[rect.0, rect.1, rect.2, rect.3]
.iter()
.all(|v| v.is_finite())
.then_some(rect)
}
pub(super) fn apply(svg: &[u8]) -> Option<Vec<u8>> {
let source = std::str::from_utf8(svg).ok()?;
let document = roxmltree::Document::parse(source).ok()?;
let root = document.root_element();
if !matches!(root.tag_name().name(), "svg" | "g") {
return None;
}
let mut ids: HashSet<_> = root
.descendants()
.filter_map(|node| node.attribute("id"))
.map(str::to_string)
.collect();
let digest = super::resources::resource_digest_hex(svg);
let mut edits = Vec::new();
let mut definitions = String::from("<defs>");
for node in root.descendants().filter(|node| {
node.has_tag_name("path")
&& node.attribute("data-rhwp-emf-device-stroke") == Some("1")
&& node
.attribute("stroke")
.is_some_and(|stroke| stroke != "none")
}) {
if node.has_attribute("transform") || node.has_attribute("mask") {
return None;
}
let (x, y, width, height) = coverage_bounds(node)?;
let mut serial = edits.len();
let id = loop {
let candidate = format!("rhwp-print-coverage-{digest}-{serial}");
if ids.insert(candidate.clone()) {
break candidate;
}
serial += 1;
};
write!(definitions, "<mask id=\"{id}\" maskUnits=\"userSpaceOnUse\" maskContentUnits=\"userSpaceOnUse\" x=\"{x:.9}\" y=\"{y:.9}\" width=\"{width:.9}\" height=\"{height:.9}\"><path").ok()?;
for name in [
"d",
"stroke-width",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"fill-rule",
] {
if let Some(value) = node.attribute(name) {
write!(
definitions,
" {name}=\"{}\"",
quick_xml::escape::escape(value)
)
.ok()?;
}
}
let fill = if node.attribute("fill") == Some("none") {
"none"
} else {
"white"
};
write!(definitions, " fill=\"{fill}\" stroke=\"white\"/></mask>").ok()?;
let range = node.range();
let tag = &source[range.clone()];
let close = tag.find('>')?;
let position = range.start + close - usize::from(tag[..close].ends_with('/'));
edits.push((position, format!(" mask=\"url(#{id})\"")));
}
if edits.is_empty() {
return None;
}
definitions.push_str("</defs>");
let root_start = root.range().start;
let insert = root_start + source[root_start..].find('>')? + 1;
edits.push((insert, definitions));
edits.sort_by(|a, b| b.0.cmp(&a.0));
let mut result = source.to_string();
for (position, value) in edits {
result.insert_str(position, &value);
}
Some(result.into_bytes())
}