1use std::collections::HashMap;
5use std::str::FromStr;
6use std::sync::Arc;
7
8#[cfg(feature = "text")]
9use fontdb::Database;
10use svgtypes::{Length, LengthUnit as Unit, PaintOrderKind, TransformOrigin};
11use tiny_skia_path::PathBuilder;
12
13use super::svgtree::{self, AId, EId, FromValue, SvgNode};
14use super::units::{self, convert_length};
15use super::{Error, Options, marker};
16use crate::parser::paint_server::process_paint;
17use crate::*;
18
19#[derive(Clone)]
20pub struct State<'a> {
21 pub(crate) parent_clip_path: Option<SvgNode<'a, 'a>>,
22 pub(crate) inside_marker: bool,
23 pub(crate) context_element: Option<(Option<Fill>, Option<Stroke>)>,
26 pub(crate) context_path: Option<(Transform, Option<NonZeroRect>)>,
29 pub(crate) fe_image_link: bool,
30 pub(crate) view_box: NonZeroRect,
32 pub(crate) use_size: (Option<f32>, Option<f32>),
36 pub(crate) opt: &'a Options<'a>,
37}
38
39pub struct Cache<'a> {
40 #[cfg(feature = "text")]
41 pub(crate) fonts: crate::text::cache::FontCache,
42
43 pub clip_paths: HashMap<String, Arc<ClipPath>>,
44 pub masks: HashMap<String, Arc<Mask>>,
45 pub filters: HashMap<String, Arc<filter::Filter>>,
46 pub paint: HashMap<String, Paint>,
47
48 svg_doc: &'a svgtree::Document<'a>,
50
51 linear_gradient_index: usize,
53 radial_gradient_index: usize,
54 pattern_index: usize,
55 clip_path_index: usize,
56 text_path_index: usize,
57 mask_index: usize,
58 filter_index: usize,
59 image_index: usize,
60}
61
62impl<'a> Cache<'a> {
63 pub(crate) fn new(
64 svg_doc: &'a svgtree::Document<'a>,
65 #[cfg(feature = "text")] fontdb: Arc<Database>,
66 ) -> Self {
67 Self {
68 #[cfg(feature = "text")]
69 fonts: crate::text::cache::FontCache::new(fontdb),
70
71 clip_paths: HashMap::new(),
72 masks: HashMap::new(),
73 filters: HashMap::new(),
74 paint: HashMap::new(),
75
76 svg_doc,
77 linear_gradient_index: 0,
78 radial_gradient_index: 0,
79 pattern_index: 0,
80 clip_path_index: 0,
81 text_path_index: 0,
82 mask_index: 0,
83 filter_index: 0,
84 image_index: 0,
85 }
86 }
87
88 pub(crate) fn gen_linear_gradient_id(&mut self) -> NonEmptyString {
90 loop {
91 self.linear_gradient_index += 1;
92 let new_id = format!("linearGradient{}", self.linear_gradient_index);
93 if self.svg_doc.element_by_id(&new_id).is_none() {
94 return NonEmptyString::new(new_id).unwrap();
95 }
96 }
97 }
98
99 pub(crate) fn gen_radial_gradient_id(&mut self) -> NonEmptyString {
100 loop {
101 self.radial_gradient_index += 1;
102 let new_id = format!("radialGradient{}", self.radial_gradient_index);
103 if self.svg_doc.element_by_id(&new_id).is_none() {
104 return NonEmptyString::new(new_id).unwrap();
105 }
106 }
107 }
108
109 pub(crate) fn gen_pattern_id(&mut self) -> NonEmptyString {
110 loop {
111 self.pattern_index += 1;
112 let new_id = format!("pattern{}", self.pattern_index);
113 if self.svg_doc.element_by_id(&new_id).is_none() {
114 return NonEmptyString::new(new_id).unwrap();
115 }
116 }
117 }
118
119 pub(crate) fn gen_clip_path_id(&mut self) -> NonEmptyString {
120 loop {
121 self.clip_path_index += 1;
122 let new_id = format!("clipPath{}", self.clip_path_index);
123 if self.svg_doc.element_by_id(&new_id).is_none() {
124 return NonEmptyString::new(new_id).unwrap();
125 }
126 }
127 }
128
129 pub(crate) fn gen_text_path_id(&mut self) -> NonEmptyString {
130 loop {
131 self.text_path_index += 1;
132 let new_id = format!("textPathPath{}", self.text_path_index);
133 if self.svg_doc.element_by_id(&new_id).is_none() {
134 return NonEmptyString::new(new_id).unwrap();
135 }
136 }
137 }
138
139 pub(crate) fn gen_mask_id(&mut self) -> NonEmptyString {
140 loop {
141 self.mask_index += 1;
142 let new_id = format!("mask{}", self.mask_index);
143 if self.svg_doc.element_by_id(&new_id).is_none() {
144 return NonEmptyString::new(new_id).unwrap();
145 }
146 }
147 }
148
149 pub(crate) fn gen_filter_id(&mut self) -> NonEmptyString {
150 loop {
151 self.filter_index += 1;
152 let new_id = format!("filter{}", self.filter_index);
153 if self.svg_doc.element_by_id(&new_id).is_none() {
154 return NonEmptyString::new(new_id).unwrap();
155 }
156 }
157 }
158
159 pub(crate) fn gen_image_id(&mut self) -> NonEmptyString {
160 loop {
161 self.image_index += 1;
162 let new_id = format!("image{}", self.image_index);
163 if self.svg_doc.element_by_id(&new_id).is_none() {
164 return NonEmptyString::new(new_id).unwrap();
165 }
166 }
167 }
168}
169
170impl<'a, 'input: 'a> SvgNode<'a, 'input> {
171 pub(crate) fn convert_length(
172 &self,
173 aid: AId,
174 object_units: Units,
175 state: &State,
176 def: Length,
177 ) -> f32 {
178 units::convert_length(
179 self.attribute(aid).unwrap_or(def),
180 *self,
181 aid,
182 object_units,
183 state,
184 )
185 }
186
187 pub fn convert_user_length(&self, aid: AId, state: &State, def: Length) -> f32 {
188 self.convert_length(aid, Units::UserSpaceOnUse, state, def)
189 }
190
191 pub fn parse_viewbox(&self) -> Option<NonZeroRect> {
192 let vb: svgtypes::ViewBox = self.attribute(AId::ViewBox)?;
193 NonZeroRect::from_xywh(vb.x as f32, vb.y as f32, vb.w as f32, vb.h as f32)
194 }
195
196 pub fn resolve_length(&self, aid: AId, state: &State, def: f32) -> f32 {
197 debug_assert!(
198 !matches!(aid, AId::BaselineShift | AId::FontSize),
199 "{} cannot be resolved via this function",
200 aid
201 );
202
203 if let Some(n) = self.ancestors().find(|n| n.has_attribute(aid)) {
204 if let Some(length) = n.attribute(aid) {
205 return units::convert_user_length(length, n, aid, state);
206 }
207 }
208
209 def
210 }
211
212 pub fn resolve_valid_length(
213 &self,
214 aid: AId,
215 state: &State,
216 def: f32,
217 ) -> Option<NonZeroPositiveF32> {
218 let n = self.resolve_length(aid, state, def);
219 NonZeroPositiveF32::new(n)
220 }
221
222 pub(crate) fn try_convert_length(
223 &self,
224 aid: AId,
225 object_units: Units,
226 state: &State,
227 ) -> Option<f32> {
228 Some(units::convert_length(
229 self.attribute(aid)?,
230 *self,
231 aid,
232 object_units,
233 state,
234 ))
235 }
236
237 pub fn has_valid_transform(&self, aid: AId) -> bool {
238 let attr = match self.attribute(aid) {
242 Some(attr) => attr,
243 None => return true,
244 };
245
246 let ts = match svgtypes::Transform::from_str(attr) {
247 Ok(v) => v,
248 Err(_) => return true,
249 };
250
251 let ts = Transform::from_row(
252 ts.a as f32,
253 ts.b as f32,
254 ts.c as f32,
255 ts.d as f32,
256 ts.e as f32,
257 ts.f as f32,
258 );
259 ts.is_valid()
260 }
261
262 pub fn is_visible_element(&self, opt: &crate::Options) -> bool {
263 self.attribute(AId::Display) != Some("none")
264 && self.has_valid_transform(AId::Transform)
265 && super::switch::is_condition_passed(*self, opt)
266 }
267}
268
269pub trait SvgColorExt {
270 fn split_alpha(self) -> (Color, Opacity);
271}
272
273impl SvgColorExt for svgtypes::Color {
274 fn split_alpha(self) -> (Color, Opacity) {
275 (
276 Color::new_rgb(self.red, self.green, self.blue),
277 Opacity::new_u8(self.alpha),
278 )
279 }
280}
281
282pub(crate) fn convert_doc(svg_doc: &svgtree::Document, opt: &Options) -> Result<Tree, Error> {
289 let svg = svg_doc.root_element();
290 let (size, restore_viewbox) = resolve_svg_size(&svg, opt);
291 let size = size?;
292 let view_box = ViewBox {
293 rect: svg
294 .parse_viewbox()
295 .unwrap_or_else(|| size.to_non_zero_rect(0.0, 0.0)),
296 aspect: svg.attribute(AId::PreserveAspectRatio).unwrap_or_default(),
297 };
298
299 let background_color = svg
300 .attribute::<&str>(AId::BackgroundColor)
301 .and_then(|s| svgtypes::Paint::from_str(s).ok())
302 .and_then(|paint| match paint {
303 svgtypes::Paint::Color(c) => Some(c),
304 _ => None,
305 });
306
307 let mut tree = Tree {
308 size,
309 root: Group::empty(),
310 linear_gradients: Vec::new(),
311 radial_gradients: Vec::new(),
312 patterns: Vec::new(),
313 clip_paths: Vec::new(),
314 masks: Vec::new(),
315 filters: Vec::new(),
316 #[cfg(feature = "text")]
317 fontdb: opt.fontdb.clone(),
318 };
319
320 if !svg.is_visible_element(opt) {
321 return Ok(tree);
322 }
323
324 let state = State {
325 parent_clip_path: None,
326 context_element: None,
327 context_path: None,
328 inside_marker: false,
329 fe_image_link: false,
330 view_box: view_box.rect,
331 use_size: (None, None),
332 opt,
333 };
334
335 let mut cache = Cache::new(
336 svg_doc,
337 #[cfg(feature = "text")]
338 opt.fontdb.clone(),
339 );
340
341 let root_state = State {
344 view_box: size.to_non_zero_rect(0.0, 0.0),
345 ..state.clone()
346 };
347 let svg_ts = svg.resolve_transform(AId::Transform, &root_state);
348 let root_ts = svg_ts.pre_concat(view_box.to_transform(tree.size()));
349 if root_ts.is_identity() && background_color.is_none() {
350 convert_children(svg_doc.root(), &state, &mut cache, &mut tree.root);
351 } else {
352 let mut g = Group::empty();
353
354 if let Some(background_color) = background_color {
355 if let Some(path) = background_path(background_color, view_box.rect.to_rect()) {
356 g.children.push(Node::Path(Box::new(path)));
357 }
358 }
359
360 g.transform = root_ts;
361 g.abs_transform = root_ts;
362 convert_children(svg_doc.root(), &state, &mut cache, &mut g);
363 tree.root.children.push(Node::Group(Box::new(g)));
364 }
365
366 cache.clip_paths.clear();
368 cache.masks.clear();
369 cache.filters.clear();
370 cache.paint.clear();
371
372 super::paint_server::update_paint_servers(
373 &mut tree.root,
374 Transform::default(),
375 None,
376 None,
377 &mut cache,
378 );
379 tree.collect_paint_servers();
380 tree.root.collect_clip_paths(&mut tree.clip_paths);
381 tree.root.collect_masks(&mut tree.masks);
382 tree.root.collect_filters(&mut tree.filters);
383
384 #[cfg(feature = "text")]
387 {
388 tree.fontdb = cache.fonts.fontdb;
389 }
390
391 if restore_viewbox {
392 calculate_svg_bbox(&mut tree);
393 }
394
395 Ok(tree)
396}
397
398fn background_path(background_color: svgtypes::Color, area: Rect) -> Option<Path> {
399 let path = PathBuilder::from_rect(area);
400
401 let fill = Fill {
402 paint: Paint::Color(Color::new_rgb(
403 background_color.red,
404 background_color.green,
405 background_color.blue,
406 )),
407 opacity: NormalizedF32::new(background_color.alpha as f32 / 255.0)?,
408 ..Default::default()
409 };
410
411 let mut path = Path::new_simple(Arc::new(path));
412 path.fill = Some(fill);
413
414 Some(path)
415}
416
417fn resolve_svg_size(svg: &SvgNode, opt: &Options) -> (Result<Size, Error>, bool) {
418 let mut state = State {
419 parent_clip_path: None,
420 context_element: None,
421 context_path: None,
422 inside_marker: false,
423 fe_image_link: false,
424 view_box: NonZeroRect::from_xywh(0.0, 0.0, 100.0, 100.0).unwrap(),
425 use_size: (None, None),
426 opt,
427 };
428
429 let def = Length::new(100.0, Unit::Percent);
430 let mut width: Length = svg.attribute(AId::Width).unwrap_or(def);
431 let mut height: Length = svg.attribute(AId::Height).unwrap_or(def);
432
433 let view_box = svg.parse_viewbox();
434
435 let restore_viewbox =
436 if (width.unit == Unit::Percent || height.unit == Unit::Percent) && view_box.is_none() {
437 if width.unit == Unit::Percent {
439 width = Length::new(
440 (width.number / 100.0) * state.opt.default_size.width() as f64,
441 Unit::None,
442 );
443 }
444
445 if height.unit == Unit::Percent {
446 height = Length::new(
447 (height.number / 100.0) * state.opt.default_size.height() as f64,
448 Unit::None,
449 );
450 }
451
452 true
453 } else {
454 false
455 };
456
457 let size = if let Some(vbox) = view_box {
458 state.view_box = vbox;
459
460 let w = if width.unit == Unit::Percent {
461 vbox.width() * (width.number as f32 / 100.0)
462 } else {
463 svg.convert_user_length(AId::Width, &state, def)
464 };
465
466 let h = if height.unit == Unit::Percent {
467 vbox.height() * (height.number as f32 / 100.0)
468 } else {
469 svg.convert_user_length(AId::Height, &state, def)
470 };
471
472 match (
475 svg.attribute::<Length>(AId::Width),
476 svg.attribute::<Length>(AId::Height),
477 ) {
478 (Some(_), None) => Size::from_wh(w, vbox.height() * w / vbox.width()),
479 (None, Some(_)) => Size::from_wh(vbox.width() * h / vbox.height(), h),
480 (_, _) => Size::from_wh(w, h),
481 }
482 } else {
483 Size::from_wh(
484 svg.convert_user_length(AId::Width, &state, def),
485 svg.convert_user_length(AId::Height, &state, def),
486 )
487 };
488
489 (size.ok_or(Error::InvalidSize), restore_viewbox)
490}
491
492fn calculate_svg_bbox(tree: &mut Tree) {
496 let size = tree
497 .root
498 .abs_bounding_box()
499 .and_then(|bbox| Size::from_wh(bbox.right(), bbox.bottom()));
500 if let Some(size) = size {
501 tree.size = size;
502 }
503}
504
505#[inline(never)]
506pub(crate) fn convert_children(
507 parent_node: SvgNode,
508 state: &State,
509 cache: &mut Cache,
510 parent: &mut Group,
511) {
512 for node in parent_node.children() {
513 convert_element(node, state, cache, parent);
514 }
515}
516
517#[inline(never)]
518pub(crate) fn convert_element(node: SvgNode, state: &State, cache: &mut Cache, parent: &mut Group) {
519 let tag_name = match node.tag_name() {
520 Some(v) => v,
521 None => return,
522 };
523
524 if !tag_name.is_graphic() && !matches!(tag_name, EId::G | EId::Switch | EId::Svg) {
525 return;
526 }
527
528 if !node.is_visible_element(state.opt) {
529 return;
530 }
531
532 if tag_name == EId::Use {
533 super::use_node::convert(node, state, cache, parent);
534 return;
535 }
536
537 if tag_name == EId::Switch {
538 super::switch::convert(node, state, cache, parent);
539 return;
540 }
541
542 if tag_name == EId::Svg && node.parent_element().is_some() {
549 super::use_node::convert_svg(node, state, cache, parent);
550
551 return;
552 }
553
554 if let Some(g) = convert_group(node, state, false, cache, parent, &|cache, g| {
555 convert_element_impl(tag_name, node, state, cache, g);
556 }) {
557 parent.children.push(Node::Group(Box::new(g)));
558 }
559}
560
561#[inline(never)]
562fn convert_element_impl(
563 tag_name: EId,
564 node: SvgNode,
565 state: &State,
566 cache: &mut Cache,
567 parent: &mut Group,
568) {
569 match tag_name {
570 EId::Rect
571 | EId::Circle
572 | EId::Ellipse
573 | EId::Line
574 | EId::Polyline
575 | EId::Polygon
576 | EId::Path => {
577 if let Some(path) = super::shapes::convert(node, state) {
578 convert_path(node, path, state, cache, parent);
579 }
580 }
581 EId::Image => {
582 super::image::convert(node, state, cache, parent);
583 }
584 EId::Text => {
585 #[cfg(feature = "text")]
586 {
587 super::text::convert(node, state, cache, parent);
588 }
589 }
590 EId::Svg => {
591 convert_children(node, state, cache, parent);
595 }
596 EId::G => {
597 convert_children(node, state, cache, parent);
598 }
599 _ => {}
600 }
601}
602
603#[inline(never)]
608pub(crate) fn convert_clip_path_elements(
609 clip_node: SvgNode,
610 state: &State,
611 cache: &mut Cache,
612 parent: &mut Group,
613) {
614 for node in clip_node.children() {
615 let tag_name = match node.tag_name() {
616 Some(v) => v,
617 None => continue,
618 };
619
620 if !tag_name.is_graphic() {
621 continue;
622 }
623
624 if !node.is_visible_element(state.opt) {
625 continue;
626 }
627
628 if tag_name == EId::Use {
629 super::use_node::convert(node, state, cache, parent);
630 continue;
631 }
632
633 if let Some(g) = convert_group(node, state, false, cache, parent, &|cache, g| {
634 convert_clip_path_elements_impl(tag_name, node, state, cache, g);
635 }) {
636 parent.children.push(Node::Group(Box::new(g)));
637 }
638 }
639}
640
641#[inline(never)]
642fn convert_clip_path_elements_impl(
643 tag_name: EId,
644 node: SvgNode,
645 state: &State,
646 cache: &mut Cache,
647 parent: &mut Group,
648) {
649 match tag_name {
650 EId::Rect | EId::Circle | EId::Ellipse | EId::Polyline | EId::Polygon | EId::Path => {
651 if let Some(path) = super::shapes::convert(node, state) {
652 convert_path(node, path, state, cache, parent);
653 }
654 }
655 EId::Text => {
656 #[cfg(feature = "text")]
657 {
658 super::text::convert(node, state, cache, parent);
659 }
660 }
661 _ => {
662 log::warn!("'{}' is no a valid 'clip-path' child.", tag_name);
663 }
664 }
665}
666
667#[derive(Clone, Copy, PartialEq, Debug)]
668enum Isolation {
669 Auto,
670 Isolate,
671}
672
673impl Default for Isolation {
674 fn default() -> Self {
675 Self::Auto
676 }
677}
678
679impl<'a, 'input: 'a> FromValue<'a, 'input> for Isolation {
680 fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
681 match value {
682 "auto" => Some(Isolation::Auto),
683 "isolate" => Some(Isolation::Isolate),
684 _ => None,
685 }
686 }
687}
688
689pub(crate) fn convert_group(
691 node: SvgNode,
692 state: &State,
693 force: bool,
694 cache: &mut Cache,
695 parent: &mut Group,
696 collect_children: &dyn Fn(&mut Cache, &mut Group),
697) -> Option<Group> {
698 let opacity = if state.parent_clip_path.is_none() {
700 node.attribute::<Opacity>(AId::Opacity)
701 .unwrap_or(Opacity::ONE)
702 } else {
703 Opacity::ONE
704 };
705
706 let is_root_svg = node.tag_name() == Some(EId::Svg) && node.parent_element().is_none();
707 let transform = if is_root_svg {
708 Transform::default()
710 } else {
711 node.resolve_transform(AId::Transform, state)
712 };
713 let blend_mode: BlendMode = node.attribute(AId::MixBlendMode).unwrap_or_default();
714 let isolation: Isolation = node.attribute(AId::Isolation).unwrap_or_default();
715 let isolate = isolation == Isolation::Isolate;
716
717 let is_g_or_use = matches!(node.tag_name(), Some(EId::G) | Some(EId::Use));
719 let id = if is_g_or_use && !state.inside_marker {
720 node.element_id().to_string()
721 } else {
722 String::new()
723 };
724
725 let abs_transform = parent.abs_transform.pre_concat(transform);
726 let mut g = Group {
727 id,
728 transform,
729 abs_transform,
730 opacity,
731 blend_mode,
732 isolate,
733 clip_path: None,
734 mask: None,
735 filters: Vec::new(),
736 is_context_element: false,
737 ..Group::empty()
738 };
739 collect_children(cache, &mut g);
740
741 let object_bbox = || g.bounding_box().and_then(|r| r.to_non_zero_rect());
742
743 let mut clip_path = None;
747 if let Some(link) = node.attribute::<SvgNode>(AId::ClipPath) {
748 clip_path = super::clippath::convert(link, state, &object_bbox, cache);
749 if clip_path.is_none() {
750 return None;
751 }
752 }
753
754 let mut mask = None;
755 if state.parent_clip_path.is_none() {
756 if let Some(link) = node.attribute::<SvgNode>(AId::Mask) {
757 mask = super::mask::convert(link, state, &object_bbox, cache);
758 if mask.is_none() {
759 return None;
760 }
761 }
762 }
763
764 let filters = {
765 let mut filters = Vec::new();
766 if state.parent_clip_path.is_none() {
767 if node.attribute(AId::Filter) == Some("none") {
768 } else if node.has_attribute(AId::Filter) {
770 if let Ok(f) = super::filter::convert(node, state, object_bbox(), cache) {
771 filters = f;
772 } else {
773 return None;
786 }
787 }
788 }
789
790 filters
791 };
792
793 let required = opacity.get().approx_ne_ulps(&1.0, 4)
794 || clip_path.is_some()
795 || mask.is_some()
796 || !filters.is_empty()
797 || !transform.is_identity()
798 || blend_mode != BlendMode::Normal
799 || isolate
800 || is_g_or_use
801 || force;
802
803 if !required {
804 parent.children.append(&mut g.children);
805 return None;
806 }
807
808 g.clip_path = clip_path;
809 g.mask = mask;
810 g.filters = filters;
811
812 Some(g)
813}
814
815fn convert_path(
816 node: SvgNode,
817 tiny_skia_path: Arc<tiny_skia_path::Path>,
818 state: &State,
819 cache: &mut Cache,
820 parent: &mut Group,
821) {
822 debug_assert!(tiny_skia_path.len() >= 2);
823 if tiny_skia_path.len() < 2 {
824 return;
825 }
826
827 let has_bbox = tiny_skia_path.bounds().width() > 0.0 && tiny_skia_path.bounds().height() > 0.0;
828 let mut fill = super::style::resolve_fill(node, has_bbox, state, cache);
829 let mut stroke = super::style::resolve_stroke(node, has_bbox, state, cache);
830 let visibility: Visibility = node.find_attribute(AId::Visibility).unwrap_or_default();
831 let mut visible = visibility == Visibility::Visible;
832 let rendering_mode: ShapeRendering = node
833 .find_attribute(AId::ShapeRendering)
834 .unwrap_or(state.opt.shape_rendering);
835
836 let raw_paint_order: svgtypes::PaintOrder =
838 node.find_attribute(AId::PaintOrder).unwrap_or_default();
839 let paint_order = svg_paint_order_to_usvg(raw_paint_order);
840 let path_transform = parent.abs_transform;
841
842 if fill.is_none() && stroke.is_none() {
845 visible = false;
846 }
847
848 if let Some(fill) = fill.as_mut() {
849 if let (Some(ContextElement::PathNode), Some((context_transform, context_bbox))) =
850 (fill.context_element, state.context_path)
851 {
852 process_paint(
853 &mut fill.paint,
854 true,
855 context_transform,
856 context_bbox.map(|r| r.to_rect()),
857 path_transform,
858 Some(tiny_skia_path.bounds()),
859 cache,
860 );
861 fill.context_element = None;
862 }
863 }
864
865 if let Some(stroke) = stroke.as_mut() {
866 if let (Some(ContextElement::PathNode), Some((context_transform, context_bbox))) =
867 (stroke.context_element, state.context_path)
868 {
869 process_paint(
870 &mut stroke.paint,
871 true,
872 context_transform,
873 context_bbox.map(|r| r.to_rect()),
874 path_transform,
875 Some(tiny_skia_path.bounds()),
876 cache,
877 );
878 stroke.context_element = None;
879 }
880 }
881
882 let mut marker = None;
883 if marker::is_valid(node) && visibility == Visibility::Visible {
884 let mut marker_group = Group {
885 abs_transform: parent.abs_transform,
886 ..Group::empty()
887 };
888
889 let mut marker_state = state.clone();
890
891 let bbox = tiny_skia_path
892 .compute_tight_bounds()
893 .and_then(|r| r.to_non_zero_rect());
894
895 let fill = fill.clone().map(|mut f| {
896 f.context_element = Some(ContextElement::PathNode);
897 f
898 });
899
900 let stroke = stroke.clone().map(|mut s| {
901 s.context_element = Some(ContextElement::PathNode);
902 s
903 });
904
905 marker_state.context_element = Some((fill, stroke));
906 marker_state.context_path = Some((path_transform, bbox));
907
908 marker::convert(
909 node,
910 &tiny_skia_path,
911 &marker_state,
912 cache,
913 &mut marker_group,
914 );
915 marker = Some(marker_group);
916 }
917
918 let id = if !state.inside_marker {
920 node.element_id().into()
921 } else {
922 Box::default()
923 };
924
925 let path = Path::new(
926 id,
927 visible,
928 fill,
929 stroke,
930 paint_order,
931 rendering_mode,
932 tiny_skia_path,
933 path_transform,
934 );
935
936 match (raw_paint_order.order, marker) {
937 ([PaintOrderKind::Markers, _, _], Some(markers_node)) => {
938 parent.children.push(Node::Group(Box::new(markers_node)));
939 parent.children.push(Node::Path(Box::new(path.clone())));
940 }
941 ([first, PaintOrderKind::Markers, last], Some(markers_node)) => {
942 append_single_paint_path(first, &path, parent);
943 parent.children.push(Node::Group(Box::new(markers_node)));
944 append_single_paint_path(last, &path, parent);
945 }
946 ([_, _, PaintOrderKind::Markers], Some(markers_node)) => {
947 parent.children.push(Node::Path(Box::new(path.clone())));
948 parent.children.push(Node::Group(Box::new(markers_node)));
949 }
950 _ => parent.children.push(Node::Path(Box::new(path.clone()))),
951 }
952}
953
954fn append_single_paint_path(paint_order_kind: PaintOrderKind, path: &Path, parent: &mut Group) {
955 match paint_order_kind {
956 PaintOrderKind::Fill => {
957 if path.fill.is_some() {
958 let mut fill_path = path.clone();
959 fill_path.stroke = None;
960 fill_path.id = Box::default();
961 parent.children.push(Node::Path(Box::new(fill_path)));
962 }
963 }
964 PaintOrderKind::Stroke => {
965 if path.stroke.is_some() {
966 let mut stroke_path = path.clone();
967 stroke_path.fill = None;
968 stroke_path.id = Box::default();
969 parent.children.push(Node::Path(Box::new(stroke_path)));
970 }
971 }
972 _ => {}
973 }
974}
975
976pub fn svg_paint_order_to_usvg(order: svgtypes::PaintOrder) -> PaintOrder {
977 match (order.order[0], order.order[1]) {
978 (svgtypes::PaintOrderKind::Stroke, _) => PaintOrder::StrokeAndFill,
979 (svgtypes::PaintOrderKind::Markers, svgtypes::PaintOrderKind::Stroke) => {
980 PaintOrder::StrokeAndFill
981 }
982 _ => PaintOrder::FillAndStroke,
983 }
984}
985
986impl SvgNode<'_, '_> {
987 pub(crate) fn resolve_transform(&self, transform_aid: AId, state: &State) -> Transform {
988 let mut transform: Transform = self.attribute(transform_aid).unwrap_or_default();
989 let transform_origin = self
990 .attribute::<TransformOrigin>(AId::TransformOrigin)
991 .or_else(|| {
992 if self.tag_name() == Some(EId::Svg) && self.parent_element().is_none() {
994 Some(TransformOrigin::new(
995 Length::new(50.0, Unit::Percent),
996 Length::new(50.0, Unit::Percent),
997 Length::zero(),
998 ))
999 } else {
1000 None
1001 }
1002 });
1003
1004 if let Some(transform_origin) = transform_origin {
1005 let dx = convert_length(
1006 transform_origin.x_offset,
1007 *self,
1008 AId::Width,
1009 Units::UserSpaceOnUse,
1010 state,
1011 );
1012 let dy = convert_length(
1013 transform_origin.y_offset,
1014 *self,
1015 AId::Height,
1016 Units::UserSpaceOnUse,
1017 state,
1018 );
1019 transform = Transform::default()
1020 .pre_translate(dx, dy)
1021 .pre_concat(transform)
1022 .pre_translate(-dx, -dy);
1023 }
1024
1025 transform
1026 }
1027}