1use std::collections::HashMap;
19use std::sync::Arc;
20
21use aylis_core::{Brush, Canvas, Color, GradientStop, LineCap, LineJoin, Path, PointF, RectF, Stroke};
22use roxmltree::{Document, Node};
23
24use crate::geom::{Affine, has_figures, rect_path};
25
26#[derive(Clone, Debug)]
27enum Paint {
28 Color(Color),
29 Current(f32),
31 Brush(Brush),
32 Pattern(Arc<Pattern>, f32),
34}
35
36#[derive(Clone, Debug)]
37struct Shape {
38 path: Path,
39 id: Option<String>,
41 fixed_stroke: bool,
44 fill: Option<Paint>,
45 stroke: Option<(Paint, Stroke)>,
46}
47
48#[derive(Clone, Debug)]
50enum Item {
51 Shape(Shape),
52 Group(Arc<Group>),
53}
54
55#[derive(Debug)]
58struct Group {
59 items: Vec<Item>,
60 clip: Vec<Path>,
62 mask: Option<Mask>,
63}
64
65#[derive(Debug)]
67struct Mask {
68 region: Path,
69 items: Vec<Item>,
70 luminance: bool,
72}
73
74#[derive(Debug)]
76struct Pattern {
77 size: (f32, f32),
79 to_parent: Affine,
81 items: Vec<Item>,
83 overflows: bool,
85}
86
87#[derive(Clone, Debug)]
89pub struct SvgImage {
90 view: RectF,
91 items: Vec<Item>,
92 costly: bool,
94 uid: u64,
96}
97
98#[derive(Clone, Debug)]
99struct Gradient {
100 radial: bool,
101 user_units: bool,
102 coords: HashMap<&'static str, f32>,
103 transform: Affine,
104 stops: Vec<GradientStop>,
105}
106
107#[derive(Clone, Debug)]
109struct Inherited {
110 fill: String,
111 stroke: String,
112 stroke_width: f32,
113 fill_opacity: f32,
114 stroke_opacity: f32,
115 fill_rule_even_odd: bool,
116 clip_rule_even_odd: bool,
117 cap: LineCap,
118 join: LineJoin,
119 dash: Option<Vec<f32>>,
120 color: Option<Color>,
121 id: Option<String>,
122 fixed_stroke: bool,
123}
124
125impl Default for Inherited {
126 fn default() -> Self {
127 Self {
128 fill: "black".into(),
129 stroke: "none".into(),
130 stroke_width: 1.0,
131 fill_opacity: 1.0,
132 stroke_opacity: 1.0,
133 fill_rule_even_odd: false,
134 clip_rule_even_odd: false,
135 cap: LineCap::Butt,
136 join: LineJoin::Miter,
137 dash: None,
138 color: None,
139 id: None,
140 fixed_stroke: false,
141 }
142 }
143}
144
145fn prop<'a>(node: Node<'a, 'a>, name: &str) -> Option<&'a str> {
147 if let Some(style) = node.attribute("style") {
148 for decl in style.split(';') {
149 if let Some((k, v)) = decl.split_once(':') {
150 if k.trim() == name {
151 return Some(v.trim());
152 }
153 }
154 }
155 }
156 node.attribute(name).map(str::trim)
157}
158
159fn length(s: &str, percent_of: f32) -> Option<f32> {
161 let s = s.trim();
162 if let Some(p) = s.strip_suffix('%') {
163 return p.trim().parse::<f32>().ok().map(|v| v / 100.0 * percent_of);
164 }
165 let end = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(s.len());
166 let v: f32 = s[..end].parse().ok()?;
167 Some(match &s[end..] {
168 "pt" => v * 4.0 / 3.0,
169 "pc" => v * 16.0,
170 "in" => v * 96.0,
171 "cm" => v * 96.0 / 2.54,
172 "mm" => v * 96.0 / 25.4,
173 "em" | "rem" => v * 16.0,
174 _ => v,
175 })
176}
177
178fn numbers(s: &str) -> Vec<f32> {
179 s.split(|c: char| c == ',' || c.is_whitespace()).filter(|t| !t.is_empty()).filter_map(|t| t.parse().ok()).collect()
180}
181
182const NAMED: [(&str, u32); 40] = [
183 ("black", 0x000000), ("white", 0xFFFFFF), ("red", 0xFF0000), ("green", 0x008000), ("blue", 0x0000FF),
184 ("yellow", 0xFFFF00), ("cyan", 0x00FFFF), ("aqua", 0x00FFFF), ("magenta", 0xFF00FF), ("fuchsia", 0xFF00FF),
185 ("gray", 0x808080), ("grey", 0x808080), ("silver", 0xC0C0C0), ("maroon", 0x800000), ("olive", 0x808000),
186 ("lime", 0x00FF00), ("teal", 0x008080), ("navy", 0x000080), ("purple", 0x800080), ("orange", 0xFFA500),
187 ("pink", 0xFFC0CB), ("brown", 0xA52A2A), ("gold", 0xFFD700), ("indigo", 0x4B0082), ("violet", 0xEE82EE),
188 ("darkgray", 0xA9A9A9), ("darkgrey", 0xA9A9A9), ("lightgray", 0xD3D3D3), ("lightgrey", 0xD3D3D3),
189 ("darkred", 0x8B0000), ("darkgreen", 0x006400), ("darkblue", 0x00008B), ("lightblue", 0xADD8E6),
190 ("skyblue", 0x87CEEB), ("tomato", 0xFF6347), ("coral", 0xFF7F50), ("salmon", 0xFA8072), ("crimson", 0xDC143C),
191 ("whitesmoke", 0xF5F5F5), ("dimgray", 0x696969),
192];
193
194fn css_color(s: &str) -> Option<Color> {
196 let s = s.trim();
197 if let Some(hex) = s.strip_prefix('#') {
198 if hex.len() == 3 || hex.len() == 4 {
199 let expanded: String = hex.chars().flat_map(|c| [c, c]).collect();
200 return Color::from_hex(&format!("#{expanded}"));
201 }
202 return Color::from_hex(s);
203 }
204 let lower = s.to_ascii_lowercase();
205 if let Some(inner) = lower.strip_prefix("rgba(").or_else(|| lower.strip_prefix("rgb(")).and_then(|r| r.strip_suffix(')')) {
206 let parts: Vec<&str> = inner.split([',', ' ', '/']).filter(|p| !p.is_empty()).collect();
207 let channel = |p: &str| -> Option<u8> {
208 if let Some(v) = p.strip_suffix('%') { v.parse::<f32>().ok().map(|v| (v * 2.55).round().clamp(0.0, 255.0) as u8) } else { p.parse::<f32>().ok().map(|v| v.round().clamp(0.0, 255.0) as u8) }
209 };
210 let (r, g, b) = (channel(parts.first()?)?, channel(parts.get(1)?)?, channel(parts.get(2)?)?);
211 let a = parts.get(3).and_then(|a| if let Some(v) = a.strip_suffix('%') { v.parse::<f32>().ok().map(|v| v / 100.0) } else { a.parse::<f32>().ok() }).unwrap_or(1.0);
212 return Some(Color::rgba(r, g, b, (a.clamp(0.0, 1.0) * 255.0).round() as u8));
213 }
214 if lower == "transparent" {
215 return Some(Color::TRANSPARENT);
216 }
217 NAMED.iter().find(|(n, _)| *n == lower).map(|(_, v)| Color::rgb((v >> 16) as u8, (v >> 8) as u8, *v as u8))
218}
219
220fn parse_transform(s: &str) -> Affine {
222 let mut m = Affine::IDENTITY;
223 let mut rest = s;
224 while let Some(open) = rest.find('(') {
225 let name = rest[..open].trim().trim_start_matches(',').trim();
226 let Some(close) = rest[open..].find(')') else { break };
227 let v = numbers(&rest[open + 1..open + close]);
228 let g = |i: usize, d: f32| v.get(i).copied().unwrap_or(d);
229 let t = match name {
230 "matrix" if v.len() >= 6 => Affine::new(v[0], v[1], v[2], v[3], v[4], v[5]),
231 "translate" => Affine::translate(g(0, 0.0), g(1, 0.0)),
232 "scale" => Affine::scale(g(0, 1.0), g(1, g(0, 1.0))),
233 "rotate" => {
234 let (cx, cy) = (g(1, 0.0), g(2, 0.0));
235 Affine::translate(cx, cy).then(Affine::rotate(g(0, 0.0))).then(Affine::translate(-cx, -cy))
236 }
237 "skewX" => Affine::skew_x(g(0, 0.0)),
238 "skewY" => Affine::skew_y(g(0, 0.0)),
239 _ => Affine::IDENTITY,
240 };
241 m = m.then(t);
242 rest = &rest[open + close + 1..];
243 }
244 m
245}
246
247fn href<'a>(node: Node<'a, 'a>) -> Option<&'a str> {
248 node.attributes().find(|a| a.name() == "href").map(|a| a.value().trim_start_matches('#'))
249}
250
251fn url_id(spec: &str) -> Option<&str> {
253 let inner = spec.trim().strip_prefix("url(")?.split(')').next()?;
254 Some(inner.trim().trim_matches(['\'', '"']).trim_start_matches('#'))
255}
256
257fn read_gradients(doc: &Document) -> HashMap<String, Gradient> {
258 let mut raw: Vec<(String, Node)> = Vec::new();
259 for n in doc.descendants() {
260 if matches!(n.tag_name().name(), "linearGradient" | "radialGradient") {
261 if let Some(id) = n.attribute("id") {
262 raw.push((id.to_string(), n));
263 }
264 }
265 }
266 let by_id: HashMap<&str, Node> = raw.iter().map(|(id, n)| (id.as_str(), *n)).collect();
267 let mut out = HashMap::new();
268 for (id, node) in &raw {
269 let mut chain = vec![*node];
271 while let Some(next) = href(*chain.last().unwrap()).and_then(|h| by_id.get(h)) {
272 if chain.len() > 8 {
273 break;
274 }
275 chain.push(*next);
276 }
277 let attr = |name: &str| chain.iter().find_map(|n| n.attribute(name));
278 let stops_node = chain.iter().find(|n| n.children().any(|c| c.tag_name().name() == "stop"));
279 let stops: Vec<GradientStop> = stops_node
280 .map(|n| {
281 n.children()
282 .filter(|c| c.tag_name().name() == "stop")
283 .map(|s| {
284 let offset = prop(s, "offset").and_then(|o| length(o, 1.0)).unwrap_or(0.0).clamp(0.0, 1.0);
285 let color = prop(s, "stop-color").and_then(css_color).unwrap_or(Color::BLACK);
286 let opacity = prop(s, "stop-opacity").and_then(|o| o.parse::<f32>().ok()).unwrap_or(1.0);
287 GradientStop::new(offset, color.with_opacity(opacity))
288 })
289 .collect()
290 })
291 .unwrap_or_default();
292 let radial = node.tag_name().name() == "radialGradient";
293 let user_units = attr("gradientUnits") == Some("userSpaceOnUse");
294 let mut coords = HashMap::new();
295 let defaults: &[(&'static str, f32)] =
296 if radial { &[("cx", 0.5), ("cy", 0.5), ("r", 0.5)] } else { &[("x1", 0.0), ("y1", 0.0), ("x2", 1.0), ("y2", 0.0)] };
297 for (k, d) in defaults {
298 let v = attr(k).and_then(|v| if v.ends_with('%') { length(v, 1.0) } else { v.parse().ok() }).unwrap_or(*d);
299 coords.insert(*k, v);
300 }
301 if radial {
302 for (k, base) in [("fx", "cx"), ("fy", "cy")] {
303 let v = attr(k).and_then(|v| v.parse().ok()).unwrap_or(coords[base]);
304 coords.insert(k, v);
305 }
306 }
307 let transform = attr("gradientTransform").map(parse_transform).unwrap_or_default();
308 out.insert(id.clone(), Gradient { radial, user_units, coords, transform, stops });
309 }
310 out
311}
312
313fn items_bounds(items: &[Item]) -> Option<RectF> {
316 let mut out: Option<RectF> = None;
317 let mut add = |b: RectF| {
318 out = Some(match out {
319 None => b,
320 Some(a) => {
321 let (x, y) = (a.x.min(b.x), a.y.min(b.y));
322 RectF::new(x, y, a.right().max(b.right()) - x, a.bottom().max(b.bottom()) - y)
323 }
324 });
325 };
326 for item in items {
327 match item {
328 Item::Shape(s) => add(s.path.bounds()),
329 Item::Group(g) => {
330 if let Some(b) = items_bounds(&g.items) {
331 add(b);
332 }
333 }
334 }
335 }
336 out
337}
338
339fn items_reach(items: &[Item]) -> Option<RectF> {
341 let mut out: Option<RectF> = None;
342 for item in items {
343 let b = match item {
344 Item::Shape(s) => Some(s.path.bounds().inflate(s.stroke.as_ref().map_or(0.0, |(_, st)| st.width / 2.0 * 1.5))),
345 Item::Group(g) => items_reach(&g.items),
346 };
347 if let Some(b) = b {
348 out = Some(match out {
349 None => b,
350 Some(a) => {
351 let (x, y) = (a.x.min(b.x), a.y.min(b.y));
352 RectF::new(x, y, a.right().max(b.right()) - x, a.bottom().max(b.bottom()) - y)
353 }
354 });
355 }
356 }
357 out
358}
359
360fn unit_box(b: RectF) -> Affine {
362 Affine::new(b.width, 0.0, 0.0, b.height, b.x, b.y)
363}
364
365fn costly(items: &[Item]) -> bool {
366 items.iter().any(|i| match i {
367 Item::Group(_) => true,
368 Item::Shape(s) => matches!(s.fill, Some(Paint::Pattern(..))) || matches!(s.stroke, Some((Paint::Pattern(..), _))),
369 })
370}
371
372struct Reader<'a> {
373 gradients: HashMap<String, Gradient>,
374 ids: HashMap<&'a str, Node<'a, 'a>>,
375 items: Vec<Item>,
376 view_w: f32,
377 clip_mode: bool,
380}
381
382impl<'a> Reader<'a> {
383 fn paint(&mut self, spec: &str, opacity: f32, local_bounds: RectF, m: Affine, depth: usize) -> Option<Paint> {
384 let spec = spec.trim();
385 if spec == "none" || opacity <= 0.0 {
386 return None;
387 }
388 if spec == "currentColor" {
389 return Some(Paint::Current(opacity));
390 }
391 if let Some(id) = url_id(spec) {
392 if let Some(node) = self.ids.get(id).copied().filter(|n| n.tag_name().name() == "pattern") {
393 return self.pattern(node, local_bounds, m, depth).map(|p| Paint::Pattern(Arc::new(p), opacity));
394 }
395 let g = self.gradients.get(id)?;
396 if g.stops.is_empty() {
397 return None;
398 }
399 if g.stops.len() == 1 {
400 return Some(Paint::Color(g.stops[0].color.with_opacity(opacity)));
401 }
402 let unit = if g.user_units { Affine::IDENTITY } else { unit_box(local_bounds) };
404 let gm = m.then(unit).then(g.transform);
405 let stops = g.stops.iter().map(|s| GradientStop::new(s.offset, s.color.with_opacity(opacity))).collect();
406 let c = |k: &str| g.coords.get(k).copied().unwrap_or(0.0);
407 let brush = if g.radial {
408 Brush::Radial { center: gm.apply(PointF::new(c("cx"), c("cy"))), radius: (c("r") * gm.scale_factor()).max(0.01), stops }
409 } else {
410 Brush::Linear { start: gm.apply(PointF::new(c("x1"), c("y1"))), end: gm.apply(PointF::new(c("x2"), c("y2"))), stops }
411 };
412 return Some(Paint::Brush(brush));
413 }
414 css_color(spec).map(|c| Paint::Color(c.with_opacity(opacity)))
415 }
416
417 fn collect(&mut self, node: Node<'a, 'a>, m: Affine, clip_mode: bool, depth: usize) -> Vec<Item> {
419 let outer = std::mem::take(&mut self.items);
420 let outer_mode = std::mem::replace(&mut self.clip_mode, clip_mode);
421 for child in node.children() {
422 self.walk(child, m, &Inherited::default(), 1.0, depth + 1);
423 }
424 self.clip_mode = outer_mode;
425 std::mem::replace(&mut self.items, outer)
426 }
427
428 fn pattern(&mut self, node: Node<'a, 'a>, bbox: RectF, m: Affine, depth: usize) -> Option<Pattern> {
431 if depth > 32 {
432 return None;
433 }
434 let mut chain = vec![node];
435 while let Some(next) = href(*chain.last()?).and_then(|h| self.ids.get(h).copied()).filter(|n| n.tag_name().name() == "pattern") {
436 if chain.len() > 8 {
437 break;
438 }
439 chain.push(next);
440 }
441 let attr = |name: &str| chain.iter().find_map(|n| n.attribute(name));
442 let user_units = attr("patternUnits") == Some("userSpaceOnUse");
443 let content_box = attr("patternContentUnits") == Some("objectBoundingBox");
444 let percent_of = if user_units { self.view_w } else { 1.0 };
445 let num = |k: &str| attr(k).and_then(|v| length(v, percent_of)).unwrap_or(0.0);
446 let (x, y, w, h) = (num("x"), num("y"), num("width"), num("height"));
447 let tile = if user_units { RectF::new(x, y, w, h) } else { RectF::new(bbox.x + x * bbox.width, bbox.y + y * bbox.height, w * bbox.width, h * bbox.height) };
448 if !(tile.width > 0.0 && tile.height > 0.0) {
449 return None;
450 }
451 let transform = attr("patternTransform").map(parse_transform).unwrap_or_default();
452 let view = attr("viewBox").map(numbers).filter(|v| v.len() == 4 && v[2] > 0.0 && v[3] > 0.0);
455 let content = if let Some(v) = view {
456 let s = (tile.width / v[2]).min(tile.height / v[3]);
457 Affine::translate((tile.width - v[2] * s) / 2.0, (tile.height - v[3] * s) / 2.0).then(Affine::scale(s, s)).then(Affine::translate(-v[0], -v[1]))
458 } else if content_box {
459 Affine::scale(bbox.width, bbox.height)
460 } else {
461 Affine::IDENTITY
462 };
463 let source = chain.iter().copied().find(|n| n.children().any(|c| c.is_element()))?;
464 let items = self.collect(source, content, false, depth);
465 let reach = items_reach(&items)?;
466 let overflows = reach.x < 0.0 || reach.y < 0.0 || reach.right() > tile.width || reach.bottom() > tile.height;
467 Some(Pattern {
468 size: (tile.width, tile.height),
469 to_parent: m.then(transform).then(Affine::translate(tile.x, tile.y)),
470 items,
471 overflows,
472 })
473 }
474
475 fn clip_paths(&mut self, node: Node<'a, 'a>, m: Affine, bbox: RectF, depth: usize) -> Vec<Path> {
477 let mut cm = if node.attribute("clipPathUnits") == Some("objectBoundingBox") { unit_box(bbox) } else { m };
478 if let Some(t) = node.attribute("transform") {
479 cm = cm.then(parse_transform(t));
480 }
481 self.collect(node, cm, true, depth)
482 .into_iter()
483 .filter_map(|i| match i {
484 Item::Shape(s) => Some(s.path),
485 Item::Group(_) => None,
486 })
487 .collect()
488 }
489
490 fn mask(&mut self, node: Node<'a, 'a>, m: Affine, bbox: RectF, depth: usize) -> Mask {
492 let user_units = node.attribute("maskUnits") == Some("userSpaceOnUse");
493 let region = if user_units {
494 let num = |k: &str, d: &str| length(node.attribute(k).unwrap_or(d), self.view_w).unwrap_or(0.0);
495 rect_path(&m, RectF::new(num("x", "-10%"), num("y", "-10%"), num("width", "120%"), num("height", "120%")))
496 } else {
497 let num = |k: &str, d: &str| length(node.attribute(k).unwrap_or(d), 1.0).unwrap_or(0.0);
498 rect_path(&unit_box(bbox), RectF::new(num("x", "-10%"), num("y", "-10%"), num("width", "120%"), num("height", "120%")))
499 };
500 let cm = if node.attribute("maskContentUnits") == Some("objectBoundingBox") { unit_box(bbox) } else { m };
501 let items = self.collect(node, cm, false, depth);
502 let luminance = prop(node, "mask-type") != Some("alpha");
503 Mask { region, items, luminance }
504 }
505
506 fn reference(&self, spec: Option<&str>, tag: &str) -> Option<Node<'a, 'a>> {
508 let id = url_id(spec?)?;
509 self.ids.get(id).copied().filter(|n| n.tag_name().name() == tag)
510 }
511
512 fn inherit(&self, node: Node, parent: &Inherited) -> Inherited {
513 let mut s = parent.clone();
514 if let Some(v) = prop(node, "fill") {
515 s.fill = v.to_string();
516 }
517 if let Some(v) = prop(node, "stroke") {
518 s.stroke = v.to_string();
519 }
520 if let Some(v) = prop(node, "stroke-width").and_then(|v| length(v, self.view_w)) {
521 s.stroke_width = v;
522 }
523 if let Some(v) = prop(node, "fill-opacity").and_then(|v| length(v, 1.0)) {
524 s.fill_opacity = v;
525 }
526 if let Some(v) = prop(node, "stroke-opacity").and_then(|v| length(v, 1.0)) {
527 s.stroke_opacity = v;
528 }
529 if let Some(v) = prop(node, "fill-rule") {
530 s.fill_rule_even_odd = v == "evenodd";
531 }
532 if let Some(v) = prop(node, "clip-rule") {
533 s.clip_rule_even_odd = v == "evenodd";
534 }
535 if let Some(v) = prop(node, "stroke-linecap") {
536 s.cap = match v {
537 "round" => LineCap::Round,
538 "square" => LineCap::Square,
539 _ => LineCap::Butt,
540 };
541 }
542 if let Some(v) = prop(node, "stroke-linejoin") {
543 s.join = match v {
544 "round" => LineJoin::Round,
545 "bevel" => LineJoin::Bevel,
546 _ => LineJoin::Miter,
547 };
548 }
549 if let Some(v) = prop(node, "stroke-dasharray") {
550 let d = numbers(v);
551 s.dash = (!d.is_empty() && d.iter().any(|x| *x > 0.0)).then_some(d);
552 }
553 if let Some(c) = prop(node, "color").and_then(css_color) {
554 s.color = Some(c);
555 }
556 s
557 }
558
559 fn walk(&mut self, node: Node<'a, 'a>, m: Affine, style: &Inherited, opacity: f32, depth: usize) {
560 if depth > 32 || !node.is_element() {
561 return;
562 }
563 if prop(node, "display") == Some("none") || prop(node, "visibility") == Some("hidden") {
564 return;
565 }
566 let name = node.tag_name().name();
567 if matches!(
568 name,
569 "defs" | "clipPath" | "mask" | "symbol" | "title" | "desc" | "metadata" | "style" | "linearGradient" | "radialGradient" | "pattern" | "filter" | "marker" | "text" | "image"
570 ) {
571 return;
572 }
573 let m = match node.attribute("transform") {
574 Some(t) => m.then(parse_transform(t)),
575 None => m,
576 };
577 let mut style = self.inherit(node, style);
578 if let Some(id) = node.attribute("id") {
579 style.id = Some(id.to_string());
580 }
581 if let Some(effect) = prop(node, "vector-effect") {
582 style.fixed_stroke = effect == "non-scaling-stroke";
583 }
584 let opacity = opacity * prop(node, "opacity").and_then(|v| length(v, 1.0)).unwrap_or(1.0);
585 let (clip, mask) = if self.clip_mode {
588 (None, None)
589 } else {
590 (self.reference(prop(node, "clip-path"), "clipPath"), self.reference(prop(node, "mask"), "mask"))
591 };
592 if clip.is_none() && mask.is_none() {
593 self.content(node, name, m, &style, opacity, depth);
594 return;
595 }
596 let outer = std::mem::take(&mut self.items);
597 self.content(node, name, m, &style, opacity, depth);
598 let items = std::mem::replace(&mut self.items, outer);
599 let Some(bbox) = items_bounds(&items) else { return };
600 let clip = match clip {
601 Some(c) => {
602 let paths = self.clip_paths(c, m, bbox, depth + 1);
603 if paths.is_empty() {
604 return;
606 }
607 paths
608 }
609 None => Vec::new(),
610 };
611 let mask = mask.map(|k| self.mask(k, m, bbox, depth + 1));
612 self.items.push(Item::Group(Arc::new(Group { items, clip, mask })));
613 }
614
615 fn content(&mut self, node: Node<'a, 'a>, name: &str, m: Affine, style: &Inherited, opacity: f32, depth: usize) {
617 let num = |k: &str, of: f32| node.attribute(k).and_then(|v| length(v, of)).unwrap_or(0.0);
618 let w = self.view_w;
619 let mut path = Path::new();
620 match name {
621 "svg" | "g" | "a" | "switch" => {
622 let m = if name == "svg" && node.parent_element().is_some() { m.then(Affine::translate(num("x", w), num("y", w))) } else { m };
623 for child in node.children() {
624 self.walk(child, m, style, opacity, depth + 1);
625 }
626 return;
627 }
628 "use" => {
629 if let Some(target) = href(node).and_then(|h| self.ids.get(h).copied()) {
630 let m = m.then(Affine::translate(num("x", w), num("y", w)));
631 if target.tag_name().name() == "symbol" {
632 for child in target.children() {
633 self.walk(child, m, style, opacity, depth + 1);
634 }
635 } else {
636 self.walk(target, m, style, opacity, depth + 1);
637 }
638 }
639 return;
640 }
641 "path" => {
642 if let Some(p) = node.attribute("d").and_then(Path::from_svg) {
643 path = p;
644 }
645 }
646 "rect" => {
647 let (x, y, rw, rh) = (num("x", w), num("y", w), num("width", w), num("height", w));
648 let rx = node.attribute("rx").or(node.attribute("ry")).and_then(|v| length(v, w)).unwrap_or(0.0);
649 if rw > 0.0 && rh > 0.0 {
650 path.rect(RectF::new(x, y, rw, rh), rx.min(rw / 2.0).min(rh / 2.0));
651 }
652 }
653 "circle" => {
654 let r = num("r", w);
655 if r > 0.0 {
656 path.ellipse(RectF::new(num("cx", w) - r, num("cy", w) - r, 2.0 * r, 2.0 * r));
657 }
658 }
659 "ellipse" => {
660 let (rx, ry) = (num("rx", w), num("ry", w));
661 if rx > 0.0 && ry > 0.0 {
662 path.ellipse(RectF::new(num("cx", w) - rx, num("cy", w) - ry, 2.0 * rx, 2.0 * ry));
663 }
664 }
665 "line" => {
666 path.move_to(num("x1", w), num("y1", w)).line_to(num("x2", w), num("y2", w));
667 }
668 "polyline" | "polygon" => {
669 let v = numbers(node.attribute("points").unwrap_or(""));
670 let pts: Vec<PointF> = v.chunks_exact(2).map(|c| PointF::new(c[0], c[1])).collect();
671 if pts.len() >= 2 {
672 path.polygon(&pts, name == "polygon");
673 }
674 }
675 _ => return,
676 }
677 if !has_figures(&path) {
678 return;
679 }
680 if self.clip_mode {
681 if name == "line" || name == "polyline" {
683 return;
684 }
685 let mut path = m.path(&path);
686 path.even_odd = style.clip_rule_even_odd;
687 self.items.push(Item::Shape(Shape { path, id: None, fixed_stroke: false, fill: Some(Paint::Color(Color::BLACK)), stroke: None }));
688 return;
689 }
690 let bounds = path.bounds();
691 let fill = if name == "line" {
692 None
693 } else {
694 self.paint(&style.fill, style.fill_opacity * opacity, bounds, m, depth)
695 };
696 let stroke = self.paint(&style.stroke, style.stroke_opacity * opacity, bounds, m, depth).map(|p| {
697 let width = if style.fixed_stroke { style.stroke_width } else { style.stroke_width * m.scale_factor() };
698 let mut s = Stroke::new(Color::BLACK, width);
699 s.cap = style.cap;
700 s.join = style.join;
701 s.dash = style.dash.as_ref().map(|d| d.iter().map(|x| x * m.scale_factor()).collect());
702 (p, s)
703 });
704 if fill.is_none() && stroke.is_none() {
705 return;
706 }
707 let mut path = m.path(&path);
708 path.even_odd = style.fill_rule_even_odd;
709 let fix = |p: Paint| match (p, style.color) {
711 (Paint::Current(o), Some(c)) => Paint::Color(c.with_opacity(o)),
712 (p, _) => p,
713 };
714 self.items.push(Item::Shape(Shape { path, id: style.id.clone(), fixed_stroke: style.fixed_stroke, fill: fill.map(fix), stroke: stroke.map(|(p, s)| (fix(p), s)) }));
715 }
716}
717
718fn for_each_shape<'s>(items: &'s [Item], f: &mut dyn FnMut(&'s Shape)) {
721 for item in items {
722 match item {
723 Item::Shape(s) => f(s),
724 Item::Group(g) => for_each_shape(&g.items, f),
725 }
726 }
727}
728
729const MAX_TILES: i64 = 20_000;
732
733struct Look<'h> {
735 current: Color,
736 highlight: &'h [&'h str],
737 highlight_color: Color,
738}
739
740impl Look<'_> {
741 fn brush(&self, p: &Paint, m: &Affine) -> Brush {
742 match p {
743 Paint::Color(c) => Brush::Solid(*c),
744 Paint::Current(o) => Brush::Solid(self.current.with_opacity(*o)),
745 Paint::Brush(b) => map_brush(b, m),
746 Paint::Pattern(..) => Brush::Solid(Color::TRANSPARENT),
748 }
749 }
750}
751
752fn draw_items(canvas: &mut dyn Canvas, items: &[Item], m: Affine, visible: Option<RectF>, look: &Look<'_>, depth: usize) {
755 if depth > 32 {
756 return;
757 }
758 for item in items {
759 match item {
760 Item::Shape(shape) => draw_shape(canvas, shape, m, visible, look, depth),
761 Item::Group(g) => draw_group(canvas, g, m, visible, look, depth),
762 }
763 }
764}
765
766fn draw_shape(canvas: &mut dyn Canvas, shape: &Shape, m: Affine, visible: Option<RectF>, look: &Look<'_>, depth: usize) {
767 if let Some(v) = visible {
769 let reach = shape.stroke.as_ref().map_or(0.0, |(_, s)| if shape.fixed_stroke { s.width / m.scale_factor().max(1e-6) } else { s.width });
770 if !shape.path.bounds().inflate(reach).intersects(v) {
771 return;
772 }
773 }
774 let path = m.path(&shape.path);
775 if shape.id.as_deref().is_some_and(|id| look.highlight.contains(&id)) {
776 canvas.fill_path(&path, &Brush::Solid(look.highlight_color));
777 } else if let Some(f) = &shape.fill {
778 match f {
779 Paint::Pattern(pattern, opacity) => {
780 canvas.save();
781 canvas.clip_path(&path, false);
782 draw_pattern(canvas, pattern, *opacity, m, path.bounds(), look, depth);
783 canvas.restore();
784 }
785 f => canvas.fill_path(&path, &look.brush(f, &m)),
786 }
787 }
788 if let Some((p, s)) = &shape.stroke {
789 let mut s = s.clone();
790 if !shape.fixed_stroke {
791 s.width *= m.scale_factor();
792 }
793 s.dash = s.dash.map(|d| d.iter().map(|x| x * m.scale_factor()).collect());
794 if let Paint::Pattern(pattern, opacity) = p {
795 if canvas.begin_masked(false) {
797 draw_pattern(canvas, pattern, *opacity, m, path.bounds().inflate(s.width), look, depth);
798 canvas.begin_mask();
799 s.brush = Brush::Solid(Color::BLACK);
800 canvas.stroke_path(&path, &s);
801 canvas.end_mask();
802 }
803 return;
804 }
805 s.brush = look.brush(p, &m);
806 canvas.stroke_path(&path, &s);
807 }
808}
809
810fn draw_pattern(canvas: &mut dyn Canvas, pattern: &Pattern, opacity: f32, m: Affine, area: RectF, look: &Look<'_>, depth: usize) {
813 let to_canvas = m.then(pattern.to_parent);
814 let Some(back) = to_canvas.invert() else { return };
815 let (w, h) = pattern.size;
816 let span = back.bounds(area);
817 let (i0, i1) = ((span.x / w).floor() as i64, (span.right() / w).ceil() as i64);
818 let (j0, j1) = ((span.y / h).floor() as i64, (span.bottom() / h).ceil() as i64);
819 if (i1 - i0).saturating_mul(j1 - j0) > MAX_TILES {
820 return;
821 }
822 if opacity < 1.0 {
823 canvas.save_layer(opacity);
824 }
825 for j in j0..j1 {
826 for i in i0..i1 {
827 let tm = to_canvas.then(Affine::translate(i as f32 * w, j as f32 * h));
828 if pattern.overflows {
829 canvas.save();
830 canvas.clip_path(&rect_path(&tm, RectF::new(0.0, 0.0, w, h)), false);
831 }
832 draw_items(canvas, &pattern.items, tm, None, look, depth + 1);
833 if pattern.overflows {
834 canvas.restore();
835 }
836 }
837 }
838 if opacity < 1.0 {
839 canvas.restore();
840 }
841}
842
843fn draw_group(canvas: &mut dyn Canvas, g: &Group, m: Affine, visible: Option<RectF>, look: &Look<'_>, depth: usize) {
844 canvas.save();
845 let mut clip_mask = false;
847 match g.clip.as_slice() {
848 [] => {}
849 [one] => canvas.clip_path(&m.path(one), false),
850 many => {
851 clip_mask = canvas.begin_masked(false);
852 if !clip_mask {
853 let mut all = Path::new();
854 for p in many {
855 all.append(p);
856 }
857 canvas.clip_rect(m.bounds(all.bounds()));
858 }
859 }
860 }
861 match &g.mask {
862 Some(mask) if canvas.begin_masked(false) => {
863 draw_items(canvas, &g.items, m, visible, look, depth + 1);
864 if mask.luminance {
865 canvas.begin_luminance_mask();
866 } else {
867 canvas.begin_mask();
868 }
869 canvas.save();
870 canvas.clip_path(&m.path(&mask.region), false);
871 draw_items(canvas, &mask.items, m, None, look, depth + 1);
872 canvas.restore();
873 canvas.end_mask();
874 }
875 _ => draw_items(canvas, &g.items, m, visible, look, depth + 1),
876 }
877 if clip_mask {
878 canvas.begin_mask();
879 for p in &g.clip {
880 canvas.fill_path(&m.path(p), &Brush::Solid(Color::BLACK));
881 }
882 canvas.end_mask();
883 }
884 canvas.restore();
885}
886
887impl SvgImage {
888 pub fn parse(text: &str) -> Result<SvgImage, String> {
890 let doc = Document::parse_with_options(text, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() })
891 .map_err(|e| format!("SVG inválido: {e}"))?;
892 let root = doc.root_element();
893 if root.tag_name().name() != "svg" {
894 return Err("não é um SVG (a raiz não é <svg>)".into());
895 }
896 let width = root.attribute("width").and_then(|v| length(v, 100.0));
897 let height = root.attribute("height").and_then(|v| length(v, 100.0));
898 let view = root
899 .attribute("viewBox")
900 .map(numbers)
901 .filter(|v| v.len() == 4 && v[2] > 0.0 && v[3] > 0.0)
902 .map(|v| RectF::new(v[0], v[1], v[2], v[3]))
903 .unwrap_or_else(|| RectF::new(0.0, 0.0, width.unwrap_or(100.0), height.unwrap_or(100.0)));
904 let ids = doc.descendants().filter_map(|n| Some((n.attribute("id")?, n))).collect();
905 let mut reader = Reader { gradients: read_gradients(&doc), ids, items: Vec::new(), view_w: view.width, clip_mode: false };
906 reader.walk(root, Affine::IDENTITY, &Inherited::default(), 1.0, 0);
907 let uid = {
908 use std::hash::{Hash, Hasher};
909 let mut h = std::collections::hash_map::DefaultHasher::new();
910 text.hash(&mut h);
911 h.finish()
912 };
913 let costly = costly(&reader.items);
914 Ok(SvgImage { view, items: reader.items, costly, uid })
915 }
916
917 pub fn view_box(&self) -> RectF {
919 self.view
920 }
921
922 pub fn shape_count(&self) -> usize {
925 let mut n = 0;
926 for_each_shape(&self.items, &mut |_| n += 1);
927 n
928 }
929
930 pub fn has_effects(&self) -> bool {
932 self.costly
933 }
934
935 pub fn fill_outlines(&self) -> (Vec<Path>, usize) {
940 let (mut filled, mut stroke_only) = (Vec::new(), 0);
941 for_each_shape(&self.items, &mut |s| {
942 if s.fill.is_some() {
943 filled.push(s.path.clone());
944 } else if s.stroke.is_some() {
945 stroke_only += 1;
946 }
947 });
948 (filled, stroke_only)
949 }
950
951 pub fn bounds_of(&self, id: &str) -> Option<RectF> {
953 let mut out: Option<RectF> = None;
954 for_each_shape(&self.items, &mut |s| {
955 if s.id.as_deref() != Some(id) {
956 return;
957 }
958 let b = s.path.bounds();
959 out = Some(match out {
960 None => b,
961 Some(a) => {
962 let (x, y) = (a.x.min(b.x), a.y.min(b.y));
963 RectF::new(x, y, (a.x + a.width).max(b.x + b.width) - x, (a.y + a.height).max(b.y + b.height) - y)
964 }
965 });
966 });
967 out
968 }
969
970 pub fn render(&self, canvas: &mut dyn Canvas, dest: RectF, current: Color) {
972 self.render_part(canvas, self.view, dest, current, &[], current);
973 }
974
975 pub fn render_part(&self, canvas: &mut dyn Canvas, view: RectF, dest: RectF, current: Color, highlight: &[&str], highlight_color: Color) {
983 if !self.costly {
984 self.render_visible(canvas, view, dest, None, current, highlight, highlight_color);
985 return;
986 }
987 let key = {
988 use std::hash::{Hash, Hasher};
989 let mut h = std::collections::hash_map::DefaultHasher::new();
990 (self.uid, current, highlight_color, highlight).hash(&mut h);
991 for v in [view.x, view.y, view.width, view.height, dest.width, dest.height] {
992 v.to_bits().hash(&mut h);
993 }
994 h.finish()
995 };
996 if !canvas.begin_cached(key, dest) {
997 self.render_visible(canvas, view, dest, None, current, highlight, highlight_color);
998 canvas.end_cached();
999 }
1000 }
1001
1002 #[allow(clippy::too_many_arguments)]
1005 pub(crate) fn render_visible(&self, canvas: &mut dyn Canvas, view: RectF, dest: RectF, visible: Option<RectF>, current: Color, highlight: &[&str], highlight_color: Color) {
1006 let m = Affine::rect_to_rect(view, dest);
1007 let visible = visible.map(|v| {
1010 let (sx, sy) = (dest.width / view.width.max(1e-6), dest.height / view.height.max(1e-6));
1011 RectF::new(view.x + (v.x - dest.x) / sx, view.y + (v.y - dest.y) / sy, v.width / sx, v.height / sy)
1012 });
1013 let look = Look { current, highlight, highlight_color };
1014 draw_items(canvas, &self.items, m, visible, &look, 0);
1015 }
1016}
1017
1018fn map_brush(b: &Brush, m: &Affine) -> Brush {
1019 match b {
1020 Brush::Linear { start, end, stops } => Brush::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone() },
1021 Brush::Radial { center, radius, stops } => Brush::Radial { center: m.apply(*center), radius: radius * m.scale_factor(), stops: stops.clone() },
1022 Brush::Sweep { center, start_angle, stops } => Brush::Sweep { center: m.apply(*center), start_angle: *start_angle, stops: stops.clone() },
1023 other => other.clone(),
1024 }
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029 use super::*;
1030
1031 fn shapes(svg: &SvgImage) -> Vec<&Shape> {
1032 let mut out = Vec::new();
1033 for_each_shape(&svg.items, &mut |s| out.push(s));
1034 out
1035 }
1036
1037 #[test]
1038 fn shapes_styles_and_transforms() {
1039 let svg = SvgImage::parse(
1040 r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50">
1041 <defs><linearGradient id="g"><stop offset="0" stop-color="red"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>
1042 <g transform="translate(10 0)" fill="currentColor">
1043 <rect x="0" y="0" width="20" height="10" rx="2"/>
1044 <circle cx="50" cy="25" r="10" style="fill:url(#g);stroke:#000;stroke-width:2"/>
1045 </g>
1046 <path d="M0 0L10 10" stroke="black" fill="none"/>
1047 <text>ignorado</text>
1048 </svg>"##,
1049 )
1050 .unwrap();
1051 assert_eq!(svg.view_box(), RectF::new(0.0, 0.0, 100.0, 50.0));
1052 assert_eq!(svg.shape_count(), 3);
1053 assert!(!svg.has_effects());
1054 let s = shapes(&svg);
1055 assert!(matches!(s[0].fill, Some(Paint::Current(_))));
1056 assert_eq!(s[0].path.bounds().x, 10.0, "o transform do grupo");
1057 assert!(matches!(s[1].fill, Some(Paint::Brush(Brush::Linear { .. }))));
1058 assert!(s[1].stroke.is_some());
1059 assert!(s[2].fill.is_none());
1060 }
1061
1062 #[test]
1063 fn ids_bounds_and_fixed_strokes() {
1064 let svg = SvgImage::parse(
1066 r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
1067 <g fill="currentColor" stroke="black" vector-effect="non-scaling-stroke">
1068 <path id="m1" d="M10 10L30 10L30 40Z"/>
1069 <g id="m2"><rect x="50" y="50" width="20" height="10"/><rect x="80" y="60" width="10" height="30"/></g>
1070 </g>
1071 </svg>"##,
1072 )
1073 .unwrap();
1074 let s = shapes(&svg);
1075 assert_eq!(s[0].id.as_deref(), Some("m1"));
1076 assert_eq!(s[2].id.as_deref(), Some("m2"), "o id do grupo vale para os filhos");
1077 assert!(s.iter().all(|s| s.fixed_stroke));
1078 assert_eq!(svg.bounds_of("m1"), Some(RectF::new(10.0, 10.0, 20.0, 30.0)));
1079 assert_eq!(svg.bounds_of("m2"), Some(RectF::new(50.0, 50.0, 40.0, 40.0)), "a união das formas do grupo");
1080 assert_eq!(svg.bounds_of("m3"), None);
1081 }
1082
1083 #[test]
1084 fn colors_and_transforms_parse() {
1085 assert_eq!(css_color("#f00"), Some(Color::rgb(255, 0, 0)));
1086 assert_eq!(css_color("rgb(0, 128, 255)"), Some(Color::rgb(0, 128, 255)));
1087 assert_eq!(css_color("teal"), Some(Color::rgb(0, 128, 128)));
1088 let m = parse_transform("translate(10,20) scale(2)");
1089 assert_eq!(m.apply(PointF::new(1.0, 1.0)), PointF::new(12.0, 22.0));
1090 assert!(SvgImage::parse("<html/>").is_err());
1091 let back = m.invert().unwrap();
1092 assert_eq!(back.apply(PointF::new(12.0, 22.0)), PointF::new(1.0, 1.0));
1093 }
1094
1095 #[test]
1096 fn clip_mask_and_pattern_are_read() {
1097 let svg = SvgImage::parse(
1098 r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
1099 <defs>
1100 <clipPath id="c" clipPathUnits="objectBoundingBox"><circle cx="0.5" cy="0.5" r="0.5"/></clipPath>
1101 <mask id="k"><rect width="100" height="100" fill="white"/><circle cx="50" cy="50" r="10" fill="black"/></mask>
1102 <pattern id="p" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5" fill="red"/></pattern>
1103 </defs>
1104 <rect x="20" y="20" width="40" height="40" clip-path="url(#c)" fill="blue"/>
1105 <g mask="url(#k)"><rect width="100" height="100" fill="url(#p)"/></g>
1106 </svg>"##,
1107 )
1108 .unwrap();
1109 assert!(svg.has_effects());
1110 assert_eq!(svg.shape_count(), 2, "as formas do recorte e da máscara não contam");
1111 let Item::Group(clip) = &svg.items[0] else { panic!("o recorte vira grupo") };
1112 assert_eq!(clip.clip.len(), 1);
1113 assert_eq!(clip.clip[0].bounds(), RectF::new(20.0, 20.0, 40.0, 40.0), "objectBoundingBox: a caixa do retângulo");
1114 let Item::Group(masked) = &svg.items[1] else { panic!("a máscara vira grupo") };
1115 let mask = masked.mask.as_ref().unwrap();
1116 assert!(mask.luminance);
1117 assert_eq!(mask.items.len(), 2);
1118 assert_eq!(mask.region.bounds(), RectF::new(-10.0, -10.0, 120.0, 120.0), "a área padrão: 10% em volta da caixa");
1119 let Item::Shape(filled) = &masked.items[0] else { panic!() };
1120 let Some(Paint::Pattern(p, _)) = &filled.fill else { panic!("o preenchimento com o padrão") };
1121 assert_eq!(p.size, (10.0, 10.0));
1122 assert!(!p.overflows);
1123 }
1124}