mod geometry;
use kurbo::{Affine, BezPath, PathEl, Point, Vec2};
use roxmltree::{Document, Node};
use svgtypes::{
Align, AspectRatio, Length, LengthUnit, Paint, TransformListParser, TransformListToken,
};
use crate::{
composition::ImageRendering,
layout::{InkExtent, Rect},
Error, Result,
};
use geometry::{Cap, FillRule, Join, Pen};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Precision {
Continuous,
OutwardQuantum,
}
#[derive(Default)]
struct InkUnion {
proven: Option<Rect>,
possible: Option<Rect>,
}
impl InkUnion {
fn add(&mut self, ink: InkExtent, limit: Rect) {
let (destination, rect) = match ink {
InkExtent::Empty => return,
InkExtent::Bounds(rect) => (&mut self.proven, rect),
InkExtent::Unknown => (&mut self.possible, limit),
};
*destination = Some(destination.map_or(rect, |prior| prior.union(rect)));
}
fn finish(self) -> InkExtent {
if self
.possible
.is_some_and(|possible| !self.proven.is_some_and(|proven| proven.contains(possible)))
{
InkExtent::Unknown
} else {
self.proven.map_or(InkExtent::Empty, InkExtent::Bounds)
}
}
}
#[derive(Clone, Copy)]
struct Frame {
transform: Affine,
viewport: (f64, f64),
clip: Rect,
}
impl Frame {
fn mapped_rect(self, rect: Rect) -> Result<Option<Rect>> {
if !axis_aligned(self.transform) {
return Ok(None);
}
Ok(Some(map_rect(rect, self.transform)?))
}
fn length(self, node: Node<'_, '_>, name: &str, default: f64, axis: usize) -> Option<f64> {
let Some(value) = node.attribute(name) else {
return Some(default);
};
let length = value.parse::<Length>().ok()?;
let base = match axis {
0 => self.viewport.0,
1 => self.viewport.1,
_ => self.viewport.0.hypot(self.viewport.1) / 2_f64.sqrt(),
};
let number = match length.unit {
LengthUnit::None | LengthUnit::Px => length.number,
LengthUnit::Percent => length.number * base / 100.,
_ => return None,
};
number.is_finite().then_some(number)
}
fn point(self, node: Node<'_, '_>, x: &str, y: &str) -> Option<Point> {
Some(Point::new(
self.length(node, x, 0., 0)?,
self.length(node, y, 0., 1)?,
))
}
fn rect(self, node: Node<'_, '_>) -> Option<Rect> {
let p = self.point(node, "x", "y")?;
Rect::new(
p.x,
p.y,
self.length(node, "width", 0., 0)?,
self.length(node, "height", 0., 1)?,
)
.ok()
}
}
fn axis_aligned(transform: Affine) -> bool {
let [a, b, c, d, _, _] = transform.as_coeffs();
(b == 0. && c == 0. && a != 0. && d != 0.) || (a == 0. && d == 0. && b != 0. && c != 0.)
}
fn map_rect(rect: Rect, transform: Affine) -> Result<Rect> {
let first = transform * Point::new(rect.left(), rect.top());
let last = transform * Point::new(rect.left() + rect.width(), rect.top() + rect.height());
Rect::new(
first.x.min(last.x),
first.y.min(last.y),
(last.x - first.x).abs(),
(last.y - first.y).abs(),
)
}
fn transform(node: Node<'_, '_>) -> Option<Affine> {
let mut transform = Affine::IDENTITY;
if let Some(value) = node.attribute("transform") {
for token in TransformListParser::from(value) {
let next = match token.ok()? {
TransformListToken::Matrix { a, b, c, d, e, f } => Affine::new([a, b, c, d, e, f]),
TransformListToken::Translate { tx, ty } => Affine::translate(Vec2::new(tx, ty)),
TransformListToken::Scale { sx, sy } => Affine::scale_non_uniform(sx, sy),
TransformListToken::Rotate { angle } => Affine::rotate(angle.to_radians()),
TransformListToken::SkewX { angle } => {
Affine::new([1., 0., angle.to_radians().tan(), 1., 0., 0.])
}
TransformListToken::SkewY { angle } => {
Affine::new([1., angle.to_radians().tan(), 0., 1., 0., 0.])
}
};
transform *= next;
}
}
transform.is_finite().then_some(transform)
}
fn view_box(node: Node<'_, '_>, viewport: Rect) -> Option<(Affine, (f64, f64))> {
let x = viewport.left();
let y = viewport.top();
let w = viewport.width();
let h = viewport.height();
let Some(value) = node.attribute("viewBox") else {
return Some((Affine::translate(Vec2::new(x, y)), (w, h)));
};
let view = value.parse::<svgtypes::ViewBox>().ok()?;
if view.w <= 0. || view.h <= 0. {
return None;
}
let aspect = node
.attribute("preserveAspectRatio")
.unwrap_or("xMidYMid meet")
.parse::<AspectRatio>()
.ok()?;
let (sx, sy) = (w / view.w, h / view.h);
let offset = Affine::translate(Vec2::new(-view.x, -view.y));
let mapping = if aspect.align == Align::None {
Affine::translate(Vec2::new(x, y)) * Affine::scale_non_uniform(sx, sy) * offset
} else {
let scale = if aspect.slice { sx.max(sy) } else { sx.min(sy) };
let (fx, fy) = match aspect.align {
Align::XMinYMin => (0., 0.),
Align::XMidYMin => (0.5, 0.),
Align::XMaxYMin => (1., 0.),
Align::XMinYMid => (0., 0.5),
Align::XMidYMid => (0.5, 0.5),
Align::XMaxYMid => (1., 0.5),
Align::XMinYMax => (0., 1.),
Align::XMidYMax => (0.5, 1.),
Align::XMaxYMax => (1., 1.),
Align::None => unreachable!(),
};
Affine::translate(Vec2::new(
x + (w - view.w * scale) * fx,
y + (h - view.h * scale) * fy,
)) * Affine::scale(scale)
* offset
};
Some((mapping, (view.w, view.h)))
}
fn opacity(node: Node<'_, '_>, attr: &str) -> Option<bool> {
let value = node.attribute(attr).unwrap_or("1").parse::<Length>().ok()?;
(value.number.is_finite() && matches!(value.unit, LengthUnit::None | LengthUnit::Percent))
.then_some(value.number > 0.)
}
fn color_support(paint: &str) -> Option<bool> {
match Paint::from_str(paint).ok()? {
Paint::None => Some(false),
Paint::Color(color) if color.alpha > 0 => Some(true),
Paint::Color(_)
if paint == "transparent"
|| (paint.starts_with('#') && paint.len() == 9 && paint.ends_with("00"))
|| (paint.starts_with('#') && paint.len() == 5 && paint.ends_with('0')) =>
{
Some(false)
}
_ => None,
}
}
fn fill_rule(node: Node<'_, '_>, attribute: &str) -> Option<FillRule> {
parse_fill_rule(node.attribute(attribute).unwrap_or("nonzero"))
}
fn parse_fill_rule(value: &str) -> Option<FillRule> {
match value {
"nonzero" => Some(FillRule::NonZero),
"evenodd" => Some(FillRule::EvenOdd),
_ => None,
}
}
fn parse_path(node: Node<'_, '_>) -> Option<BezPath> {
let d = node.attribute("d")?;
if d.contains(['A', 'a']) {
return None;
}
BezPath::from_svg(d).ok()
}
fn polygon_path(points: &[Point], close: bool) -> BezPath {
let mut path = BezPath::new();
if let Some((&first, rest)) = points.split_first() {
path.move_to(first);
for &point in rest {
path.line_to(point);
}
if close {
path.close_path();
}
}
path
}
fn points(node: Node<'_, '_>, frame: Frame) -> Option<Vec<Point>> {
if node.has_tag_name("line") {
return Some(vec![
frame.point(node, "x1", "y1")?,
frame.point(node, "x2", "y2")?,
]);
}
let mut numbers = svgtypes::NumberListParser::from(node.attribute("points")?);
let mut points = Vec::new();
while let Some(x) = numbers.next() {
let x = x.ok()?;
let y = numbers.next()?.ok()?;
if !x.is_finite() || !y.is_finite() {
return None;
}
points.push(Point::new(x, y));
}
Some(points)
}
fn linear_path_stroke(path: &BezPath, pen: &Pen, frame: Frame) -> Result<InkExtent> {
let mut points = Vec::new();
let mut ink = InkExtent::Empty;
for element in path.elements() {
match element {
PathEl::MoveTo(point) => {
ink = ink.union(geometry::linear_stroke(
&points,
false,
pen,
frame.transform,
frame.clip,
)?);
points.clear();
points.push(*point);
}
PathEl::LineTo(point) => points.push(*point),
PathEl::ClosePath => {
ink = ink.union(geometry::linear_stroke(
&points,
true,
pen,
frame.transform,
frame.clip,
)?);
points.truncate(1);
}
_ => return Ok(InkExtent::Unknown),
}
}
Ok(ink.union(geometry::linear_stroke(
&points,
false,
pen,
frame.transform,
frame.clip,
)?))
}
fn pen(node: Node<'_, '_>, frame: Frame) -> Option<Pen> {
let radius = frame.length(node, "stroke-width", 1., 2)? / 2.;
if radius < 0. {
return None;
}
let cap = match node.attribute("stroke-linecap").unwrap_or("butt") {
"butt" => Cap::Butt,
"round" => Cap::Round,
"square" => Cap::Square,
_ => return None,
};
let join = match node.attribute("stroke-linejoin").unwrap_or("miter") {
"miter" => Join::Miter(
node.attribute("stroke-miterlimit")
.unwrap_or("4")
.parse()
.ok()?,
),
"round" => Join::Round,
"bevel" => Join::Bevel,
_ => return None,
};
let mut dash = Vec::new();
if let Some(value) = node
.attribute("stroke-dasharray")
.filter(|value| *value != "none")
{
for value in svgtypes::NumberListParser::from(value) {
let value = value.ok()?;
if value <= 0. || !value.is_finite() {
return None;
}
dash.push(value);
}
if dash.len() % 2 != 0 {
dash.extend_from_within(..);
}
}
if node
.attribute("stroke-dashoffset")
.is_some_and(|value| value != "0")
{
return None;
}
Some(Pen {
radius,
cap,
join,
dash,
})
}
enum Clip {
Empty,
Rect(Rect),
Path(BezPath, FillRule),
Unknown,
}
struct Search {
precision: Precision,
issue: std::cell::RefCell<Option<String>>,
}
impl Search {
fn record(&self, node: Node<'_, '_>) {
let mut issue = self.issue.borrow_mut();
if issue.is_none() {
let tag = node.tag_name().name();
*issue = Some(
node.attribute("id")
.map_or_else(|| format!("SVG {tag}"), |id| format!("SVG {tag} {id:?}")),
);
}
}
}
struct Drawing<'a, 'input> {
document: &'a Document<'input>,
native: bool,
search: &'a Search,
}
impl<'a, 'input> Drawing<'a, 'input> {
fn definition(&self, reference: &str) -> Option<Node<'a, 'input>> {
let id = reference.strip_prefix("url(#")?.strip_suffix(')')?;
self.document
.descendants()
.find(|node| node.attribute("id") == Some(id))
}
fn paint(&self, node: Node<'_, '_>, name: &str) -> Option<bool> {
let alpha = opacity(
node,
if name == "fill" {
"fill-opacity"
} else {
"stroke-opacity"
},
)?;
if !alpha {
return Some(false);
}
let value = node
.attribute(name)
.unwrap_or(if name == "fill" { "black" } else { "none" });
if !value.starts_with("url(") {
return color_support(value);
}
let gradient = self.definition(value)?;
if !gradient.has_tag_name("linearGradient") && !gradient.has_tag_name("radialGradient") {
return None;
}
if gradient.attribute("href").is_some() || gradient.attribute("style").is_some() {
return None;
}
let mut yes = false;
let mut no = false;
for stop in gradient.children().filter(Node::is_element) {
if !stop.has_tag_name("stop") || stop.attribute("style").is_some() {
return None;
}
if opacity(stop, "stop-opacity")?
&& color_support(stop.attribute("stop-color").unwrap_or("black"))?
{
yes = true;
} else {
no = true;
}
}
if yes && no {
None
} else {
Some(yes)
}
}
fn clip(&self, node: Node<'_, '_>, frame: Frame) -> Result<Clip> {
let Some(reference) = node.attribute("clip-path").filter(|value| *value != "none") else {
return Ok(Clip::Rect(frame.clip));
};
let Some(definition) = self.definition(reference) else {
return Ok(Clip::Unknown);
};
if !definition.has_tag_name("clipPath")
|| definition
.attribute("clipPathUnits")
.is_some_and(|units| units != "userSpaceOnUse")
|| definition.attribute("clip-path").is_some()
|| definition.attribute("style").is_some()
{
return Ok(Clip::Unknown);
}
let mut children = definition.children().filter(Node::is_element);
let Some(child) = children.next() else {
return Ok(Clip::Empty);
};
if children.next().is_some()
|| child.attribute("clip-path").is_some()
|| child.attribute("style").is_some()
|| child.attribute("display").is_some()
|| child.attribute("visibility").is_some()
{
return Ok(Clip::Unknown);
}
let (Some(a), Some(b)) = (transform(definition), transform(child)) else {
return Ok(Clip::Unknown);
};
let frame = Frame {
transform: frame.transform * a * b,
..frame
};
if child.has_tag_name("rect")
&& child.attribute("rx").is_none()
&& child.attribute("ry").is_none()
{
if let Some(rect) = frame.rect(child) {
if let Some(rect) = frame.mapped_rect(rect)? {
return Ok(rect
.intersection(frame.clip)
.map_or(Clip::Empty, Clip::Rect));
}
}
}
let path = match child.tag_name().name() {
"path" => parse_path(child),
"polygon" => points(child, frame).map(|points| polygon_path(&points, true)),
"rect" if child.attribute("rx").is_none() && child.attribute("ry").is_none() => frame
.rect(child)
.map(|rect| polygon_path(&geometry::corners(rect), true)),
_ => None,
};
let rule = child
.attribute("clip-rule")
.or_else(|| definition.attribute("clip-rule"))
.unwrap_or("nonzero");
let (Some(path), Some(rule)) = (path, parse_fill_rule(rule)) else {
return Ok(Clip::Unknown);
};
let path = frame.transform * geometry::close_for_fill(&path);
Ok(Clip::Path(path, rule))
}
fn children(&self, node: Node<'_, '_>, frame: Frame) -> Result<InkExtent> {
self.children_with_seed(node, frame, InkExtent::Empty)
}
fn children_with_seed(
&self,
node: Node<'_, '_>,
frame: Frame,
seed: InkExtent,
) -> Result<InkExtent> {
let mut ink = InkUnion::default();
ink.add(seed, frame.clip);
for child in node.children().filter(Node::is_element) {
crate::operation::check()?;
let extent = self.node(child, frame)?;
if extent == InkExtent::Unknown {
if let Some(limit) = self.possible_child(child, frame)? {
self.search.record(child);
ink.add(extent, limit);
}
} else {
ink.add(extent, frame.clip);
}
}
Ok(ink.finish())
}
fn possible_child(&self, node: Node<'_, '_>, mut frame: Frame) -> Result<Option<Rect>> {
if self.admitted(node, false)
&& matches!(node.tag_name().name(), "image" | "svg")
&& node.attribute("overflow") != Some("visible")
{
if let (Some(local), Some(rect)) = (transform(node), frame.rect(node)) {
frame.transform *= local;
if let Some(mapped) = frame.mapped_rect(rect)? {
return Ok(mapped.intersection(frame.clip));
}
}
}
Ok(Some(frame.clip))
}
fn node(&self, node: Node<'_, '_>, mut frame: Frame) -> Result<InkExtent> {
use InkExtent::{Empty, Unknown};
if matches!(
node.tag_name().name(),
"defs" | "title" | "desc" | "metadata" | "style"
) {
return Ok(Empty);
}
if !self.admitted(node, false) || opacity(node, "opacity").is_none() {
return Ok(Unknown);
}
if node.attribute("display") == Some("none") || opacity(node, "opacity") == Some(false) {
return Ok(Empty);
}
if let Some(visibility) = node.attribute("visibility") {
match visibility {
"visible" => {}
"hidden" | "collapse" if !node.children().any(|child| child.is_element()) => {
return Ok(Empty)
}
_ => return Ok(Unknown),
}
}
let Some(transform) = transform(node) else {
return Ok(Unknown);
};
frame.transform *= transform;
if !frame.transform.is_finite() {
return Ok(Unknown);
}
if frame.transform.determinant() == 0. {
use crate::numeric::binary::units;
let [a, b, c, d, _, _] = frame.transform.as_coeffs();
return Ok(if units(a)? * units(d)? == units(b)? * units(c)? {
Empty
} else {
Unknown
});
}
let clip = self.clip(node, frame)?;
match clip {
Clip::Empty => return Ok(Empty),
Clip::Unknown => return Ok(Unknown),
Clip::Rect(rect) => frame.clip = rect,
Clip::Path(_, _) => {}
}
if let Clip::Path(ref path, rule) = clip {
match geometry::covers_rect(path, rule, frame.clip)? {
Some(false) => return Ok(Empty),
Some(true) => {}
None => {
match geometry::filled_path(path, rule, frame.clip, self.search.precision)? {
InkExtent::Empty => return Ok(Empty),
InkExtent::Bounds(bounds) => {
frame.clip = bounds;
if node.has_tag_name("g") {
return self.clipped_children(node, frame, path, rule);
}
}
InkExtent::Unknown => return Ok(Unknown),
}
}
}
}
let ink = match node.tag_name().name() {
"g" => self.children(node, frame)?,
"svg" => self.viewport(node, frame)?,
"image" => self.image(node, frame)?,
_ => self.shape(node, frame)?,
};
if let (Clip::Path(path, rule), InkExtent::Bounds(bounds)) = (clip, ink) {
if let Some(inside) = geometry::covers_rect(&path, rule, bounds)? {
return Ok(if inside { ink } else { Empty });
}
if node.has_tag_name("rect")
&& axis_aligned(frame.transform)
&& node.attribute("rx").is_none()
&& node.attribute("ry").is_none()
&& self.paint(node, "fill") == Some(true)
&& self.paint(node, "stroke") == Some(false)
{
return geometry::filled_path(&path, rule, bounds, self.search.precision);
}
return Ok(Unknown);
}
Ok(ink)
}
fn clipped_children(
&self,
node: Node<'_, '_>,
frame: Frame,
path: &BezPath,
rule: FillRule,
) -> Result<InkExtent> {
let mut union = InkUnion::default();
for child in node.children().filter(Node::is_element) {
crate::operation::check()?;
let ink = self.node(child, frame)?;
let extent = if let InkExtent::Bounds(bounds) = ink {
match geometry::covers_rect(path, rule, bounds)? {
Some(true) => ink,
Some(false) => InkExtent::Empty,
None if child.has_tag_name("rect")
&& child.attribute("rx").is_none()
&& child.attribute("ry").is_none()
&& child.attribute("clip-path").is_none()
&& transform(child)
.is_some_and(|local| axis_aligned(frame.transform * local))
&& self.paint(child, "fill") == Some(true)
&& self.paint(child, "stroke") == Some(false) =>
{
geometry::filled_path(path, rule, bounds, self.search.precision)?
}
None => InkExtent::Unknown,
}
} else {
ink
};
let limit = if let InkExtent::Bounds(bounds) = ink {
bounds
} else {
frame.clip
};
if extent == InkExtent::Unknown {
self.search.record(child);
}
union.add(extent, limit);
}
Ok(union.finish())
}
fn viewport(&self, node: Node<'_, '_>, frame: Frame) -> Result<InkExtent> {
let Some(rect) = frame.rect(node) else {
return Ok(InkExtent::Unknown);
};
let Some(mapped) = frame.mapped_rect(rect)? else {
return Ok(InkExtent::Unknown);
};
let clip = if node.attribute("overflow") == Some("visible") {
frame.clip
} else {
let Some(clip) = mapped.intersection(frame.clip) else {
return Ok(InkExtent::Empty);
};
clip
};
let Some((mapping, viewport)) = view_box(node, rect) else {
return Ok(InkExtent::Unknown);
};
self.children(
node,
Frame {
transform: frame.transform * mapping,
viewport,
clip,
},
)
}
fn image(&self, node: Node<'_, '_>, frame: Frame) -> Result<InkExtent> {
let Some(rect) = frame.rect(node) else {
return Ok(InkExtent::Unknown);
};
let Some(object) = frame.mapped_rect(rect)? else {
return Ok(InkExtent::Unknown);
};
let Some(clip) = object.intersection(frame.clip) else {
return Ok(InkExtent::Empty);
};
if node.attribute("preserveAspectRatio") != Some("none") {
return Ok(InkExtent::Unknown);
}
let Some(href) = node
.attribute("href")
.filter(|value| value.starts_with("data:") && !value.contains('#'))
else {
return Ok(InkExtent::Unknown);
};
let (mime, bytes) = crate::composition::read_data_uri(href)?;
let [scale_x, skew_y, skew_x, scale_y, _, _] = frame.transform.as_coeffs();
if scale_x <= 0. || scale_y <= 0. || skew_y != 0. || skew_x != 0. {
return Ok(InkExtent::Unknown);
}
match mime.as_str() {
"image/png" => {
let rendering = if node.attribute("image-rendering") == Some("crisp-edges") {
ImageRendering::CrispEdges
} else {
ImageRendering::Auto
};
crate::composition::png_alpha_ink(&bytes, object, clip, rendering)
}
"image/svg+xml" => {
let source = std::str::from_utf8(&bytes).map_err(|error| {
Error::Render(format!("retained SVG image: {error}").into())
})?;
let document = Document::parse(source).map_err(|error| {
Error::Render(format!("retained SVG image: {error}").into())
})?;
let root = document.root_element();
let size = |name: &str| {
root.attribute(name)?
.parse::<f64>()
.ok()
.filter(|value| value.is_finite() && *value > 0.)
};
let (Some(w), Some(h)) = (size("width"), size("height")) else {
return Ok(InkExtent::Unknown);
};
let source_box = Rect::new(0., 0., w, h)?;
let transform = Affine::translate(Vec2::new(object.left(), object.top()))
* Affine::scale_non_uniform(object.width() / w, object.height() / h);
svg_document_ink(
&document,
source_box,
transform,
clip,
false,
self.search,
InkExtent::Empty,
)
}
_ => Ok(InkExtent::Unknown),
}
}
fn shape(&self, node: Node<'_, '_>, frame: Frame) -> Result<InkExtent> {
let (Some(fill), Some(stroke)) = (self.paint(node, "fill"), self.paint(node, "stroke"))
else {
return Ok(InkExtent::Unknown);
};
if !fill && !stroke {
return Ok(InkExtent::Empty);
}
let pen = if stroke {
let Some(pen) = pen(node, frame) else {
return Ok(InkExtent::Unknown);
};
(pen.radius > 0.).then_some(pen)
} else {
None
};
match node.tag_name().name() {
"circle" | "ellipse" => ellipse(node, frame, fill, pen.as_ref()),
"rect" => rectangle(node, frame, fill, pen.as_ref()),
"line" | "polyline" | "polygon" => {
let Some(points) = points(node, frame) else {
return Ok(InkExtent::Unknown);
};
let path = polygon_path(&points, node.has_tag_name("polygon"));
self.painted_path(
node,
frame,
&path,
fill && !node.has_tag_name("line"),
pen.as_ref(),
)
}
"path" => {
let Some(path) = parse_path(node) else {
return Ok(InkExtent::Unknown);
};
self.painted_path(node, frame, &path, fill, pen.as_ref())
}
_ => Ok(InkExtent::Unknown),
}
}
fn painted_path(
&self,
node: Node<'_, '_>,
frame: Frame,
path: &BezPath,
fill: bool,
pen: Option<&Pen>,
) -> Result<InkExtent> {
let mut ink = InkUnion::default();
if fill {
let Some(rule) = fill_rule(node, "fill-rule") else {
return Ok(InkExtent::Unknown);
};
let path = frame.transform * geometry::close_for_fill(path);
let fill = geometry::filled_path(&path, rule, frame.clip, self.search.precision)?;
let limit =
geometry::path_bounds(&path)?.and_then(|rect| rect.intersection(frame.clip));
if let Some(limit) = limit {
ink.add(fill, limit);
} else if fill != InkExtent::Empty {
ink.add(fill, frame.clip);
}
}
if let Some(pen) = pen {
ink.add(linear_path_stroke(path, pen, frame)?, frame.clip);
}
Ok(ink.finish())
}
fn admitted(&self, node: Node<'_, '_>, root: bool) -> bool {
let container = matches!(node.tag_name().name(), "g" | "svg");
node.attributes().all(|attr| match attr.name() {
"class" => self.native,
"style" => {
(self.native && attr.value() == "vector-effect:none")
|| (root && forced_image_size(node, attr.value()))
}
"id"
| "transform"
| "opacity"
| "clip-path"
| "display"
| "visibility"
| "width"
| "height"
| "x"
| "y"
| "viewBox"
| "preserveAspectRatio"
| "overflow"
| "version"
| "role" => true,
"fill" | "fill-opacity" | "fill-rule" | "stroke" | "stroke-opacity"
| "stroke-width" | "stroke-linecap" | "stroke-linejoin" | "stroke-miterlimit"
| "stroke-dasharray" | "stroke-dashoffset" | "rx" | "ry" | "cx" | "cy" | "r" | "x1"
| "x2" | "y1" | "y2" | "d" | "points" | "href" | "image-rendering" => !container,
_ => false,
})
}
}
fn ellipse(node: Node<'_, '_>, frame: Frame, fill: bool, pen: Option<&Pen>) -> Result<InkExtent> {
let Some(center) = frame.point(node, "cx", "cy") else {
return Ok(InkExtent::Unknown);
};
let radii = if node.has_tag_name("circle") {
let Some(r) = frame.length(node, "r", 0., 2) else {
return Ok(InkExtent::Unknown);
};
(r, r)
} else {
let (Some(rx), Some(ry)) = (
frame.length(node, "rx", 0., 0),
frame.length(node, "ry", 0., 1),
) else {
return Ok(InkExtent::Unknown);
};
(rx, ry)
};
if radii.0 <= 0. || radii.1 <= 0. {
return Ok(InkExtent::Empty);
}
if let Some(pen) = pen {
if radii.0.to_bits() != radii.1.to_bits() || !pen.dash.is_empty() {
return Ok(InkExtent::Unknown);
}
let outer = (radii.0 + pen.radius, radii.1 + pen.radius);
let inner = (!fill).then_some((radii.0 - pen.radius, radii.1 - pen.radius));
geometry::ellipse_band(center, outer, inner, frame.transform, frame.clip)
} else if fill {
geometry::ellipse_band(center, radii, None, frame.transform, frame.clip)
} else {
Ok(InkExtent::Empty)
}
}
fn rectangle(node: Node<'_, '_>, frame: Frame, fill: bool, pen: Option<&Pen>) -> Result<InkExtent> {
let Some(rect) = frame.rect(node) else {
return Ok(InkExtent::Unknown);
};
if rect.width() == 0. || rect.height() == 0. {
return Ok(InkExtent::Empty);
}
let (Some(rx), Some(ry)) = (
frame.length(node, "rx", 0., 0),
frame.length(node, "ry", 0., 1),
) else {
return Ok(InkExtent::Unknown);
};
let rx = if node.attribute("rx").is_none() {
ry
} else {
rx
}
.min(rect.width() / 2.);
let ry = if node.attribute("ry").is_none() {
rx
} else {
ry
}
.min(rect.height() / 2.);
if rx < 0. || ry < 0. {
return Ok(InkExtent::Unknown);
}
if rx == 0. || ry == 0. {
let mut ink = if fill {
geometry::rectangle(rect, frame.transform, frame.clip)?
} else {
InkExtent::Empty
};
if let Some(pen) = pen {
ink = ink.union(geometry::linear_stroke(
&geometry::corners(rect),
true,
pen,
frame.transform,
frame.clip,
)?);
}
Ok(ink)
} else if rx.to_bits() == ry.to_bits() {
geometry::rounded_rectangle(rect, rx, fill, pen, frame.transform, frame.clip)
} else {
Ok(InkExtent::Unknown)
}
}
fn forced_image_size(node: Node<'_, '_>, value: &str) -> bool {
let (Some(w), Some(h)) = (node.attribute("width"), node.attribute("height")) else {
return false;
};
value == format!(";width:{w}px !important;height:{h}px !important;")
}
fn svg_document_ink(
document: &Document<'_>,
viewport: Rect,
placement: Affine,
clip: Rect,
native: bool,
search: &Search,
seed: InkExtent,
) -> Result<InkExtent> {
let Some(clip) = map_rect(viewport, placement)?.intersection(clip) else {
return Ok(InkExtent::Empty);
};
let root = document.root_element();
let drawing = Drawing {
document,
native,
search,
};
if !root.has_tag_name("svg")
|| !drawing.admitted(root, true)
|| document.descendants().any(|node| {
node.has_tag_name("style")
&& !(native && node.text() == Some(super::svg_backend::NATIVE_STROKE_STYLE))
})
{
search.record(root);
return Ok(InkExtent::Unknown);
}
if root.attribute("display") == Some("none") || opacity(root, "opacity") == Some(false) {
return Ok(InkExtent::Empty);
}
if root.attribute("clip-path").is_some()
|| root.attribute("visibility").is_some()
|| root.attribute("transform").is_some()
|| opacity(root, "opacity").is_none()
{
return Ok(InkExtent::Unknown);
}
let Some((transform, viewport)) = view_box(root, viewport) else {
return Ok(InkExtent::Unknown);
};
drawing.children_with_seed(
root,
Frame {
transform: placement * transform,
viewport,
clip,
},
seed,
)
}
pub(crate) fn svg_ink(
source: &str,
viewport: Rect,
clip: Rect,
native: bool,
precision: Precision,
seed: InkExtent,
) -> Result<InkExtent> {
let document = Document::parse(source)
.map_err(|error| Error::Render(format!("visible ink SVG: {error}").into()))?;
let search = Search {
precision,
issue: std::cell::RefCell::new(None),
};
let extent = svg_document_ink(
&document,
viewport,
Affine::IDENTITY,
clip,
native,
&search,
seed,
)?;
if extent == InkExtent::Unknown && precision == Precision::OutwardQuantum {
let issue = search
.issue
.into_inner()
.unwrap_or_else(|| "frozen scene".to_owned());
Err(Error::Render(format!("cannot determine actual visible ink for {issue}; use an explicit rectangle or pixel coverage").into()))
} else {
Ok(extent)
}
}