Skip to main content

usvg/tree/
mod.rs

1// Copyright 2019 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4pub mod filter;
5mod geom;
6mod text;
7
8use std::fmt::Display;
9use std::sync::{Arc, OnceLock};
10
11pub use strict_num::{self, ApproxEqUlps, NonZeroPositiveF32, NormalizedF32, PositiveF32};
12
13pub use tiny_skia_path;
14
15pub use self::geom::*;
16pub use self::text::*;
17
18use crate::OptionLog;
19
20/// An alias to `NormalizedF32`.
21pub type Opacity = NormalizedF32;
22
23// Must not be clone-able to preserve ID uniqueness.
24#[derive(Debug)]
25pub(crate) struct NonEmptyString(String);
26
27impl NonEmptyString {
28    pub(crate) fn new(string: String) -> Option<Self> {
29        if string.trim().is_empty() {
30            return None;
31        }
32
33        Some(NonEmptyString(string))
34    }
35
36    pub(crate) fn get(&self) -> &str {
37        &self.0
38    }
39
40    pub(crate) fn take(self) -> String {
41        self.0
42    }
43}
44
45/// A non-zero `f32`.
46///
47/// Just like `f32` but immutable and guarantee to never be zero.
48#[derive(Clone, Copy, Debug)]
49pub struct NonZeroF32(f32);
50
51impl NonZeroF32 {
52    /// Creates a new `NonZeroF32` value.
53    #[inline]
54    pub fn new(n: f32) -> Option<Self> {
55        if n.approx_eq_ulps(&0.0, 4) {
56            None
57        } else {
58            Some(NonZeroF32(n))
59        }
60    }
61
62    /// Returns an underlying value.
63    #[inline]
64    pub fn get(&self) -> f32 {
65        self.0
66    }
67}
68
69#[derive(Clone, Copy, PartialEq, Debug)]
70pub(crate) enum Units {
71    UserSpaceOnUse,
72    ObjectBoundingBox,
73}
74
75// `Units` cannot have a default value, because it changes depending on an element.
76
77impl std::fmt::Display for Units {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Units::UserSpaceOnUse => write!(f, "userSpaceOnUse"),
81            Units::ObjectBoundingBox => write!(f, "objectBoundingBox"),
82        }
83    }
84}
85
86/// A visibility property.
87///
88/// `visibility` attribute in the SVG.
89#[allow(missing_docs)]
90#[derive(Clone, Copy, PartialEq, Debug)]
91pub(crate) enum Visibility {
92    Visible,
93    Hidden,
94    Collapse,
95}
96
97impl Default for Visibility {
98    fn default() -> Self {
99        Self::Visible
100    }
101}
102
103/// A shape rendering method.
104///
105/// `shape-rendering` attribute in the SVG.
106#[derive(Clone, Copy, PartialEq, Debug)]
107#[allow(missing_docs)]
108pub enum ShapeRendering {
109    OptimizeSpeed,
110    CrispEdges,
111    GeometricPrecision,
112}
113
114impl ShapeRendering {
115    /// Checks if anti-aliasing should be enabled.
116    pub fn use_shape_antialiasing(self) -> bool {
117        match self {
118            ShapeRendering::OptimizeSpeed => false,
119            ShapeRendering::CrispEdges => false,
120            ShapeRendering::GeometricPrecision => true,
121        }
122    }
123}
124
125impl Default for ShapeRendering {
126    fn default() -> Self {
127        Self::GeometricPrecision
128    }
129}
130
131impl std::str::FromStr for ShapeRendering {
132    type Err = &'static str;
133
134    fn from_str(s: &str) -> Result<Self, Self::Err> {
135        match s {
136            "optimizeSpeed" => Ok(ShapeRendering::OptimizeSpeed),
137            "crispEdges" => Ok(ShapeRendering::CrispEdges),
138            "geometricPrecision" => Ok(ShapeRendering::GeometricPrecision),
139            _ => Err("invalid"),
140        }
141    }
142}
143
144/// A text rendering method.
145///
146/// `text-rendering` attribute in the SVG.
147#[allow(missing_docs)]
148#[derive(Clone, Copy, PartialEq, Debug)]
149pub enum TextRendering {
150    OptimizeSpeed,
151    OptimizeLegibility,
152    GeometricPrecision,
153}
154
155impl Default for TextRendering {
156    fn default() -> Self {
157        Self::OptimizeLegibility
158    }
159}
160
161impl std::str::FromStr for TextRendering {
162    type Err = &'static str;
163
164    fn from_str(s: &str) -> Result<Self, Self::Err> {
165        match s {
166            "optimizeSpeed" => Ok(TextRendering::OptimizeSpeed),
167            "optimizeLegibility" => Ok(TextRendering::OptimizeLegibility),
168            "geometricPrecision" => Ok(TextRendering::GeometricPrecision),
169            _ => Err("invalid"),
170        }
171    }
172}
173
174/// An image rendering method.
175///
176/// `image-rendering` attribute in the SVG.
177#[allow(missing_docs)]
178#[derive(Clone, Copy, PartialEq, Debug)]
179pub enum ImageRendering {
180    OptimizeQuality,
181    OptimizeSpeed,
182    // The following can only appear as presentation attributes.
183    Smooth,
184    HighQuality,
185    CrispEdges,
186    Pixelated,
187}
188
189impl Default for ImageRendering {
190    fn default() -> Self {
191        Self::OptimizeQuality
192    }
193}
194
195impl std::str::FromStr for ImageRendering {
196    type Err = &'static str;
197
198    fn from_str(s: &str) -> Result<Self, Self::Err> {
199        match s {
200            "optimizeQuality" => Ok(ImageRendering::OptimizeQuality),
201            "optimizeSpeed" => Ok(ImageRendering::OptimizeSpeed),
202            "smooth" => Ok(ImageRendering::Smooth),
203            "high-quality" => Ok(ImageRendering::HighQuality),
204            "crisp-edges" => Ok(ImageRendering::CrispEdges),
205            "pixelated" => Ok(ImageRendering::Pixelated),
206            _ => Err("invalid"),
207        }
208    }
209}
210
211/// A blending mode property.
212///
213/// `mix-blend-mode` attribute in the SVG.
214#[allow(missing_docs)]
215#[derive(Clone, Copy, PartialEq, Debug)]
216pub enum BlendMode {
217    Normal,
218    Multiply,
219    Screen,
220    Overlay,
221    Darken,
222    Lighten,
223    ColorDodge,
224    ColorBurn,
225    HardLight,
226    SoftLight,
227    Difference,
228    Exclusion,
229    Hue,
230    Saturation,
231    Color,
232    Luminosity,
233    PlusLighter,
234}
235
236impl Default for BlendMode {
237    fn default() -> Self {
238        Self::Normal
239    }
240}
241
242impl Display for BlendMode {
243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        let blend_mode = match self {
245            BlendMode::Normal => "normal",
246            BlendMode::Multiply => "multiply",
247            BlendMode::Screen => "screen",
248            BlendMode::Overlay => "overlay",
249            BlendMode::Darken => "darken",
250            BlendMode::Lighten => "lighten",
251            BlendMode::ColorDodge => "color-dodge",
252            BlendMode::ColorBurn => "color-burn",
253            BlendMode::HardLight => "hard-light",
254            BlendMode::SoftLight => "soft-light",
255            BlendMode::Difference => "difference",
256            BlendMode::Exclusion => "exclusion",
257            BlendMode::Hue => "hue",
258            BlendMode::Saturation => "saturation",
259            BlendMode::Color => "color",
260            BlendMode::Luminosity => "luminosity",
261            BlendMode::PlusLighter => "plus-lighter",
262        };
263        write!(f, "{blend_mode}")
264    }
265}
266
267/// A spread method.
268///
269/// `spreadMethod` attribute in the SVG.
270#[allow(missing_docs)]
271#[derive(Clone, Copy, PartialEq, Debug)]
272pub enum SpreadMethod {
273    Pad,
274    Reflect,
275    Repeat,
276}
277
278impl Default for SpreadMethod {
279    fn default() -> Self {
280        Self::Pad
281    }
282}
283
284/// A generic gradient.
285#[derive(Debug)]
286pub struct BaseGradient {
287    pub(crate) id: NonEmptyString,
288    pub(crate) units: Units, // used only during parsing
289    pub(crate) transform: Transform,
290    pub(crate) spread_method: SpreadMethod,
291    pub(crate) stops: Vec<Stop>,
292}
293
294impl BaseGradient {
295    /// Element's ID.
296    ///
297    /// Taken from the SVG itself.
298    /// Used only during SVG writing. `resvg` doesn't rely on this property.
299    pub fn id(&self) -> &str {
300        self.id.get()
301    }
302
303    /// Gradient transform.
304    ///
305    /// `gradientTransform` in SVG.
306    pub fn transform(&self) -> Transform {
307        self.transform
308    }
309
310    /// Gradient spreading method.
311    ///
312    /// `spreadMethod` in SVG.
313    pub fn spread_method(&self) -> SpreadMethod {
314        self.spread_method
315    }
316
317    /// A list of `stop` elements.
318    pub fn stops(&self) -> &[Stop] {
319        &self.stops
320    }
321}
322
323/// A linear gradient.
324///
325/// `linearGradient` element in SVG.
326#[derive(Debug)]
327pub struct LinearGradient {
328    pub(crate) base: BaseGradient,
329    pub(crate) x1: f32,
330    pub(crate) y1: f32,
331    pub(crate) x2: f32,
332    pub(crate) y2: f32,
333}
334
335impl LinearGradient {
336    /// `x1` coordinate.
337    pub fn x1(&self) -> f32 {
338        self.x1
339    }
340
341    /// `y1` coordinate.
342    pub fn y1(&self) -> f32 {
343        self.y1
344    }
345
346    /// `x2` coordinate.
347    pub fn x2(&self) -> f32 {
348        self.x2
349    }
350
351    /// `y2` coordinate.
352    pub fn y2(&self) -> f32 {
353        self.y2
354    }
355}
356
357impl std::ops::Deref for LinearGradient {
358    type Target = BaseGradient;
359
360    fn deref(&self) -> &Self::Target {
361        &self.base
362    }
363}
364
365/// A radial gradient.
366///
367/// `radialGradient` element in SVG.
368#[derive(Debug)]
369pub struct RadialGradient {
370    pub(crate) base: BaseGradient,
371    pub(crate) cx: f32,
372    pub(crate) cy: f32,
373    pub(crate) r: PositiveF32,
374    pub(crate) fx: f32,
375    pub(crate) fy: f32,
376    pub(crate) fr: PositiveF32,
377}
378
379impl RadialGradient {
380    /// `cx` coordinate.
381    pub fn cx(&self) -> f32 {
382        self.cx
383    }
384
385    /// `cy` coordinate.
386    pub fn cy(&self) -> f32 {
387        self.cy
388    }
389
390    /// Gradient radius.
391    pub fn r(&self) -> PositiveF32 {
392        self.r
393    }
394
395    /// `fx` coordinate.
396    pub fn fx(&self) -> f32 {
397        self.fx
398    }
399
400    /// `fy` coordinate.
401    pub fn fy(&self) -> f32 {
402        self.fy
403    }
404
405    /// Focal radius.
406    pub fn fr(&self) -> PositiveF32 {
407        self.fr
408    }
409}
410
411impl std::ops::Deref for RadialGradient {
412    type Target = BaseGradient;
413
414    fn deref(&self) -> &Self::Target {
415        &self.base
416    }
417}
418
419/// An alias to `NormalizedF32`.
420pub type StopOffset = NormalizedF32;
421
422/// Gradient's stop element.
423///
424/// `stop` element in SVG.
425#[derive(Clone, Copy, Debug)]
426pub struct Stop {
427    pub(crate) offset: StopOffset,
428    pub(crate) color: Color,
429    pub(crate) opacity: Opacity,
430}
431
432impl Stop {
433    /// Gradient stop offset.
434    ///
435    /// `offset` in SVG.
436    pub fn offset(&self) -> StopOffset {
437        self.offset
438    }
439
440    /// Gradient stop color.
441    ///
442    /// `stop-color` in SVG.
443    pub fn color(&self) -> Color {
444        self.color
445    }
446
447    /// Gradient stop opacity.
448    ///
449    /// `stop-opacity` in SVG.
450    pub fn opacity(&self) -> Opacity {
451        self.opacity
452    }
453}
454
455/// A pattern element.
456///
457/// `pattern` element in SVG.
458#[derive(Debug)]
459pub struct Pattern {
460    pub(crate) id: NonEmptyString,
461    pub(crate) units: Units,         // used only during parsing
462    pub(crate) content_units: Units, // used only during parsing
463    pub(crate) transform: Transform,
464    pub(crate) rect: NonZeroRect,
465    pub(crate) view_box: Option<ViewBox>,
466    pub(crate) root: Group,
467}
468
469impl Pattern {
470    /// Element's ID.
471    ///
472    /// Taken from the SVG itself.
473    /// Used only during SVG writing. `resvg` doesn't rely on this property.
474    pub fn id(&self) -> &str {
475        self.id.get()
476    }
477
478    /// Pattern transform.
479    ///
480    /// `patternTransform` in SVG.
481    pub fn transform(&self) -> Transform {
482        self.transform
483    }
484
485    /// Pattern rectangle.
486    ///
487    /// `x`, `y`, `width` and `height` in SVG.
488    pub fn rect(&self) -> NonZeroRect {
489        self.rect
490    }
491
492    /// Pattern children.
493    pub fn root(&self) -> &Group {
494        &self.root
495    }
496}
497
498/// An alias to `NonZeroPositiveF32`.
499pub type StrokeWidth = NonZeroPositiveF32;
500
501/// A `stroke-miterlimit` value.
502///
503/// Just like `f32` but immutable and guarantee to be >=1.0.
504#[derive(Clone, Copy, Debug)]
505pub struct StrokeMiterlimit(f32);
506
507impl StrokeMiterlimit {
508    /// Creates a new `StrokeMiterlimit` value.
509    #[inline]
510    pub fn new(n: f32) -> Self {
511        debug_assert!(n.is_finite());
512        debug_assert!(n >= 1.0);
513
514        let n = if !(n >= 1.0) { 1.0 } else { n };
515
516        StrokeMiterlimit(n)
517    }
518
519    /// Returns an underlying value.
520    #[inline]
521    pub fn get(&self) -> f32 {
522        self.0
523    }
524}
525
526impl Default for StrokeMiterlimit {
527    #[inline]
528    fn default() -> Self {
529        StrokeMiterlimit::new(4.0)
530    }
531}
532
533impl From<f32> for StrokeMiterlimit {
534    #[inline]
535    fn from(n: f32) -> Self {
536        Self::new(n)
537    }
538}
539
540impl PartialEq for StrokeMiterlimit {
541    #[inline]
542    fn eq(&self, other: &Self) -> bool {
543        self.0.approx_eq_ulps(&other.0, 4)
544    }
545}
546
547/// A line cap.
548///
549/// `stroke-linecap` attribute in the SVG.
550#[allow(missing_docs)]
551#[derive(Clone, Copy, PartialEq, Debug)]
552pub enum LineCap {
553    Butt,
554    Round,
555    Square,
556}
557
558impl Default for LineCap {
559    fn default() -> Self {
560        Self::Butt
561    }
562}
563
564/// A line join.
565///
566/// `stroke-linejoin` attribute in the SVG.
567#[allow(missing_docs)]
568#[derive(Clone, Copy, PartialEq, Debug)]
569pub enum LineJoin {
570    Miter,
571    MiterClip,
572    Round,
573    Bevel,
574}
575
576impl Default for LineJoin {
577    fn default() -> Self {
578        Self::Miter
579    }
580}
581
582/// A stroke style.
583#[derive(Clone, Debug)]
584pub struct Stroke {
585    pub(crate) paint: Paint,
586    pub(crate) dasharray: Option<Vec<f32>>,
587    pub(crate) dashoffset: f32,
588    pub(crate) miterlimit: StrokeMiterlimit,
589    pub(crate) opacity: Opacity,
590    pub(crate) width: StrokeWidth,
591    pub(crate) linecap: LineCap,
592    pub(crate) linejoin: LineJoin,
593    // Whether the current stroke needs to be resolved relative
594    // to a context element.
595    pub(crate) context_element: Option<ContextElement>,
596}
597
598impl Stroke {
599    /// Stroke paint.
600    pub fn paint(&self) -> &Paint {
601        &self.paint
602    }
603
604    /// Stroke dash array.
605    pub fn dasharray(&self) -> Option<&[f32]> {
606        self.dasharray.as_deref()
607    }
608
609    /// Stroke dash offset.
610    pub fn dashoffset(&self) -> f32 {
611        self.dashoffset
612    }
613
614    /// Stroke miter limit.
615    pub fn miterlimit(&self) -> StrokeMiterlimit {
616        self.miterlimit
617    }
618
619    /// Stroke opacity.
620    pub fn opacity(&self) -> Opacity {
621        self.opacity
622    }
623
624    /// Stroke width.
625    pub fn width(&self) -> StrokeWidth {
626        self.width
627    }
628
629    /// Stroke linecap.
630    pub fn linecap(&self) -> LineCap {
631        self.linecap
632    }
633
634    /// Stroke linejoin.
635    pub fn linejoin(&self) -> LineJoin {
636        self.linejoin
637    }
638
639    /// Converts into a `tiny_skia_path::Stroke` type.
640    pub fn to_tiny_skia(&self) -> tiny_skia_path::Stroke {
641        let mut stroke = tiny_skia_path::Stroke {
642            width: self.width.get(),
643            miter_limit: self.miterlimit.get(),
644            line_cap: match self.linecap {
645                LineCap::Butt => tiny_skia_path::LineCap::Butt,
646                LineCap::Round => tiny_skia_path::LineCap::Round,
647                LineCap::Square => tiny_skia_path::LineCap::Square,
648            },
649            line_join: match self.linejoin {
650                LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
651                LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
652                LineJoin::Round => tiny_skia_path::LineJoin::Round,
653                LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
654            },
655            // According to the spec, dash should not be accounted during
656            // bbox calculation.
657            dash: None,
658        };
659
660        if let Some(ref list) = self.dasharray {
661            stroke.dash = tiny_skia_path::StrokeDash::new(list.clone(), self.dashoffset);
662        }
663
664        stroke
665    }
666}
667
668/// A fill rule.
669///
670/// `fill-rule` attribute in the SVG.
671#[allow(missing_docs)]
672#[derive(Clone, Copy, PartialEq, Debug)]
673pub enum FillRule {
674    NonZero,
675    EvenOdd,
676}
677
678impl Default for FillRule {
679    fn default() -> Self {
680        Self::NonZero
681    }
682}
683
684#[derive(Clone, Copy, PartialEq, Debug)]
685pub(crate) enum ContextElement {
686    /// The current context element is a use node. Since we can get
687    /// the bounding box of a use node only once we have converted
688    /// all elements, we need to fix the transform and units of
689    /// the stroke/fill after converting the whole tree.
690    UseNode,
691    /// The current context element is a path node (i.e. only applicable
692    /// if we draw the marker of a path). Since we already know the bounding
693    /// box of the path when rendering the markers, we can convert them directly,
694    /// so we do it while parsing.
695    PathNode,
696}
697
698/// A fill style.
699#[derive(Clone, Debug)]
700pub struct Fill {
701    pub(crate) paint: Paint,
702    pub(crate) opacity: Opacity,
703    pub(crate) rule: FillRule,
704    // Whether the current fill needs to be resolved relative
705    // to a context element.
706    pub(crate) context_element: Option<ContextElement>,
707}
708
709impl Fill {
710    /// Fill paint.
711    pub fn paint(&self) -> &Paint {
712        &self.paint
713    }
714
715    /// Fill opacity.
716    pub fn opacity(&self) -> Opacity {
717        self.opacity
718    }
719
720    /// Fill rule.
721    pub fn rule(&self) -> FillRule {
722        self.rule
723    }
724}
725
726impl Default for Fill {
727    fn default() -> Self {
728        Fill {
729            paint: Paint::Color(Color::black()),
730            opacity: Opacity::ONE,
731            rule: FillRule::default(),
732            context_element: None,
733        }
734    }
735}
736
737/// A 8-bit RGB color.
738#[derive(Clone, Copy, PartialEq, Debug)]
739#[allow(missing_docs)]
740pub struct Color {
741    pub red: u8,
742    pub green: u8,
743    pub blue: u8,
744}
745
746impl Color {
747    /// Constructs a new `Color` from RGB values.
748    #[inline]
749    pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {
750        Color { red, green, blue }
751    }
752
753    /// Constructs a new `Color` set to black.
754    #[inline]
755    pub fn black() -> Color {
756        Color::new_rgb(0, 0, 0)
757    }
758
759    /// Constructs a new `Color` set to white.
760    #[inline]
761    pub fn white() -> Color {
762        Color::new_rgb(255, 255, 255)
763    }
764}
765
766/// A paint style.
767///
768/// `paint` value type in the SVG.
769#[allow(missing_docs)]
770#[derive(Clone, Debug)]
771pub enum Paint {
772    Color(Color),
773    LinearGradient(Arc<LinearGradient>),
774    RadialGradient(Arc<RadialGradient>),
775    Pattern(Arc<Pattern>),
776}
777
778impl PartialEq for Paint {
779    #[inline]
780    fn eq(&self, other: &Self) -> bool {
781        match (self, other) {
782            (Self::Color(lc), Self::Color(rc)) => lc == rc,
783            (Self::LinearGradient(lg1), Self::LinearGradient(lg2)) => Arc::ptr_eq(lg1, lg2),
784            (Self::RadialGradient(rg1), Self::RadialGradient(rg2)) => Arc::ptr_eq(rg1, rg2),
785            (Self::Pattern(p1), Self::Pattern(p2)) => Arc::ptr_eq(p1, p2),
786            _ => false,
787        }
788    }
789}
790
791/// A clip-path element.
792///
793/// `clipPath` element in SVG.
794#[derive(Debug)]
795pub struct ClipPath {
796    pub(crate) id: NonEmptyString,
797    pub(crate) transform: Transform,
798    pub(crate) clip_path: Option<Arc<ClipPath>>,
799    pub(crate) root: Group,
800}
801
802impl ClipPath {
803    pub(crate) fn empty(id: NonEmptyString) -> Self {
804        ClipPath {
805            id,
806            transform: Transform::default(),
807            clip_path: None,
808            root: Group::empty(),
809        }
810    }
811
812    /// Element's ID.
813    ///
814    /// Taken from the SVG itself.
815    /// Used only during SVG writing. `resvg` doesn't rely on this property.
816    pub fn id(&self) -> &str {
817        self.id.get()
818    }
819
820    /// Clip path transform.
821    ///
822    /// `transform` in SVG.
823    pub fn transform(&self) -> Transform {
824        self.transform
825    }
826
827    /// Additional clip path.
828    ///
829    /// `clip-path` in SVG.
830    pub fn clip_path(&self) -> Option<&ClipPath> {
831        self.clip_path.as_deref()
832    }
833
834    /// Clip path children.
835    pub fn root(&self) -> &Group {
836        &self.root
837    }
838}
839
840/// A mask type.
841#[derive(Clone, Copy, PartialEq, Debug)]
842pub enum MaskType {
843    /// Indicates that the luminance values of the mask should be used.
844    Luminance,
845    /// Indicates that the alpha values of the mask should be used.
846    Alpha,
847}
848
849impl Default for MaskType {
850    fn default() -> Self {
851        Self::Luminance
852    }
853}
854
855/// A mask element.
856///
857/// `mask` element in SVG.
858#[derive(Debug)]
859pub struct Mask {
860    pub(crate) id: NonEmptyString,
861    pub(crate) rect: NonZeroRect,
862    pub(crate) kind: MaskType,
863    pub(crate) mask: Option<Arc<Mask>>,
864    pub(crate) root: Group,
865}
866
867impl Mask {
868    /// Element's ID.
869    ///
870    /// Taken from the SVG itself.
871    /// Used only during SVG writing. `resvg` doesn't rely on this property.
872    pub fn id(&self) -> &str {
873        self.id.get()
874    }
875
876    /// Mask rectangle.
877    ///
878    /// `x`, `y`, `width` and `height` in SVG.
879    pub fn rect(&self) -> NonZeroRect {
880        self.rect
881    }
882
883    /// Mask type.
884    ///
885    /// `mask-type` in SVG.
886    pub fn kind(&self) -> MaskType {
887        self.kind
888    }
889
890    /// Additional mask.
891    ///
892    /// `mask` in SVG.
893    pub fn mask(&self) -> Option<&Mask> {
894        self.mask.as_deref()
895    }
896
897    /// Mask children.
898    ///
899    /// A mask can have no children, in which case the whole element should be masked out.
900    pub fn root(&self) -> &Group {
901        &self.root
902    }
903}
904
905/// Node's kind.
906#[allow(missing_docs)]
907#[derive(Clone, Debug)]
908pub enum Node {
909    Group(Box<Group>),
910    Path(Box<Path>),
911    Image(Box<Image>),
912    Text(Box<Text>),
913}
914
915impl Node {
916    /// Returns node's ID.
917    pub fn id(&self) -> &str {
918        match self {
919            Node::Group(e) => e.id.as_str(),
920            Node::Path(e) => &e.id,
921            Node::Image(e) => e.id.as_str(),
922            Node::Text(e) => e.id.as_str(),
923        }
924    }
925
926    /// Returns node's absolute transform.
927    ///
928    /// This method is cheap since absolute transforms are already resolved.
929    pub fn abs_transform(&self) -> Transform {
930        match self {
931            Node::Group(group) => group.abs_transform(),
932            Node::Path(path) => path.abs_transform(),
933            Node::Image(image) => image.abs_transform(),
934            Node::Text(text) => text.abs_transform(),
935        }
936    }
937
938    /// Returns node's bounding box in object coordinates, if any.
939    pub fn bounding_box(&self) -> Option<Rect> {
940        match self {
941            Node::Group(group) => group.bounding_box(),
942            Node::Path(path) => path.bounding_box(),
943            Node::Image(image) => Some(image.bounding_box()),
944            Node::Text(text) => Some(text.bounding_box()),
945        }
946    }
947
948    /// Returns node's bounding box in canvas coordinates, if any.
949    pub fn abs_bounding_box(&self) -> Option<Rect> {
950        match self {
951            Node::Group(group) => group.abs_bounding_box(),
952            Node::Path(path) => path.abs_bounding_box(),
953            Node::Image(image) => Some(image.abs_bounding_box()),
954            Node::Text(text) => Some(text.abs_bounding_box()),
955        }
956    }
957
958    /// Returns node's bounding box, including stroke, in object coordinates, if any.
959    pub fn stroke_bounding_box(&self) -> Option<Rect> {
960        match self {
961            Node::Group(group) => group.stroke_bounding_box(),
962            Node::Path(path) => path.stroke_bounding_box(),
963            // Image cannot be stroked.
964            Node::Image(image) => Some(image.bounding_box()),
965            Node::Text(text) => Some(text.stroke_bounding_box()),
966        }
967    }
968
969    /// Returns node's bounding box, including stroke, in canvas coordinates, if any.
970    pub fn abs_stroke_bounding_box(&self) -> Option<Rect> {
971        match self {
972            Node::Group(group) => group.abs_stroke_bounding_box(),
973            Node::Path(path) => path.abs_stroke_bounding_box(),
974            // Image cannot be stroked.
975            Node::Image(image) => Some(image.abs_bounding_box()),
976            Node::Text(text) => Some(text.abs_stroke_bounding_box()),
977        }
978    }
979
980    /// Element's "layer" bounding box in canvas units, if any.
981    ///
982    /// For most nodes this is just `abs_bounding_box`,
983    /// but for groups this is `abs_layer_bounding_box`.
984    ///
985    /// See [`Group::layer_bounding_box`] for details.
986    pub fn abs_layer_bounding_box(&self) -> Option<NonZeroRect> {
987        match self {
988            Node::Group(group) => group.abs_layer_bounding_box(),
989            // Hor/ver path without stroke can return None. This is expected.
990            Node::Path(path) => path.abs_bounding_box()?.to_non_zero_rect(),
991            Node::Image(image) => image.abs_bounding_box().to_non_zero_rect(),
992            Node::Text(text) => text.abs_bounding_box().to_non_zero_rect(),
993        }
994    }
995
996    /// Maps a rect in this node's object coordinates into its parent's coordinates.
997    fn to_parent_coordinates(&self, rect: Rect) -> Rect {
998        match self {
999            Node::Group(group) => rect.transform(group.transform).unwrap_or(rect),
1000            _ => rect,
1001        }
1002    }
1003
1004    /// Calls a closure for each subroot this `Node` has.
1005    ///
1006    /// The [`Tree::root`](Tree::root) field contain only render-able SVG elements.
1007    /// But some elements, specifically clip paths, masks, patterns and feImage
1008    /// can store their own SVG subtrees.
1009    /// And while one can access them manually, it's pretty verbose.
1010    /// This methods allows looping over _all_ SVG elements present in the `Tree`.
1011    ///
1012    /// # Example
1013    ///
1014    /// ```no_run
1015    /// fn all_nodes(parent: &usvg::Group) {
1016    ///     for node in parent.children() {
1017    ///         // do stuff...
1018    ///
1019    ///         if let usvg::Node::Group(g) = node {
1020    ///             all_nodes(g);
1021    ///         }
1022    ///
1023    ///         // handle subroots as well
1024    ///         node.subroots(|subroot| all_nodes(subroot));
1025    ///     }
1026    /// }
1027    /// ```
1028    pub fn subroots<F: FnMut(&Group)>(&self, mut f: F) {
1029        match self {
1030            Node::Group(group) => group.subroots(&mut f),
1031            Node::Path(path) => path.subroots(&mut f),
1032            Node::Image(image) => image.subroots(&mut f),
1033            Node::Text(text) => text.subroots(&mut f),
1034        }
1035    }
1036}
1037
1038/// A group container.
1039///
1040/// The preprocessor will remove all groups that don't impact rendering.
1041/// Those that left is just an indicator that a new canvas should be created.
1042///
1043/// `g` element in SVG.
1044#[derive(Clone, Debug)]
1045pub struct Group {
1046    pub(crate) id: String,
1047    pub(crate) transform: Transform,
1048    pub(crate) abs_transform: Transform,
1049    pub(crate) opacity: Opacity,
1050    pub(crate) blend_mode: BlendMode,
1051    pub(crate) isolate: bool,
1052    pub(crate) clip_path: Option<Arc<ClipPath>>,
1053    /// Whether the group is a context element (i.e. a use node)
1054    pub(crate) is_context_element: bool,
1055    pub(crate) mask: Option<Arc<Mask>>,
1056    pub(crate) filters: Vec<Arc<filter::Filter>>,
1057    // Calculated from `children` on first access and cached, so they must
1058    // only be accessed once the group is complete.
1059    pub(crate) bounding_boxes: OnceLock<Box<GroupBoundingBoxes>>,
1060    pub(crate) children: Vec<Node>,
1061}
1062
1063// Boxed, because most nodes never have their bounding boxes requested.
1064#[derive(Clone, Debug, Default)]
1065pub(crate) struct GroupBoundingBoxes {
1066    pub(crate) bounding_box: OnceLock<Option<Rect>>,
1067    pub(crate) abs_bounding_box: OnceLock<Option<Rect>>,
1068    pub(crate) stroke_bounding_box: OnceLock<Option<Rect>>,
1069    pub(crate) abs_stroke_bounding_box: OnceLock<Option<Rect>>,
1070    pub(crate) layer_bounding_box: OnceLock<Option<NonZeroRect>>,
1071    pub(crate) abs_layer_bounding_box: OnceLock<Option<NonZeroRect>>,
1072}
1073
1074impl Group {
1075    pub(crate) fn empty() -> Self {
1076        Group {
1077            id: String::new(),
1078            transform: Transform::default(),
1079            abs_transform: Transform::default(),
1080            opacity: Opacity::ONE,
1081            blend_mode: BlendMode::Normal,
1082            isolate: false,
1083            clip_path: None,
1084            mask: None,
1085            filters: Vec::new(),
1086            is_context_element: false,
1087            bounding_boxes: OnceLock::new(),
1088            children: Vec::new(),
1089        }
1090    }
1091
1092    /// Element's ID.
1093    ///
1094    /// Taken from the SVG itself.
1095    /// Isn't automatically generated.
1096    /// Can be empty.
1097    pub fn id(&self) -> &str {
1098        &self.id
1099    }
1100
1101    /// Element's transform.
1102    ///
1103    /// This is a relative transform. The one that is set via the `transform` attribute in SVG.
1104    pub fn transform(&self) -> Transform {
1105        self.transform
1106    }
1107
1108    /// Element's absolute transform.
1109    ///
1110    /// Contains all ancestors transforms including group's transform.
1111    ///
1112    /// Note that subroots, like clipPaths, masks and patterns, have their own root transform,
1113    /// which isn't affected by the node that references this subroot.
1114    pub fn abs_transform(&self) -> Transform {
1115        self.abs_transform
1116    }
1117
1118    /// Group opacity.
1119    ///
1120    /// After the group is rendered we should combine
1121    /// it with a parent group using the specified opacity.
1122    pub fn opacity(&self) -> Opacity {
1123        self.opacity
1124    }
1125
1126    /// Group blend mode.
1127    ///
1128    /// `mix-blend-mode` in SVG.
1129    pub fn blend_mode(&self) -> BlendMode {
1130        self.blend_mode
1131    }
1132
1133    /// Group isolation.
1134    ///
1135    /// `isolation` in SVG.
1136    pub fn isolate(&self) -> bool {
1137        self.isolate
1138    }
1139
1140    /// Element's clip path.
1141    pub fn clip_path(&self) -> Option<&ClipPath> {
1142        self.clip_path.as_deref()
1143    }
1144
1145    /// Element's mask.
1146    pub fn mask(&self) -> Option<&Mask> {
1147        self.mask.as_deref()
1148    }
1149
1150    /// Element's filters.
1151    pub fn filters(&self) -> &[Arc<filter::Filter>] {
1152        &self.filters
1153    }
1154
1155    /// Element's object bounding box.
1156    ///
1157    /// `objectBoundingBox` in SVG terms. Meaning it doesn't affected by parent transforms.
1158    ///
1159    /// Can be set to `None` in case of an empty group.
1160    pub fn bounding_box(&self) -> Option<Rect> {
1161        *self.bounding_boxes().bounding_box.get_or_init(|| {
1162            self.union_of_children(|child| Some(child.to_parent_coordinates(child.bounding_box()?)))
1163        })
1164    }
1165
1166    /// Element's bounding box in canvas coordinates.
1167    ///
1168    /// `userSpaceOnUse` in SVG terms.
1169    pub fn abs_bounding_box(&self) -> Option<Rect> {
1170        *self
1171            .bounding_boxes()
1172            .abs_bounding_box
1173            .get_or_init(|| self.union_of_children(Node::abs_bounding_box))
1174    }
1175
1176    /// Element's object bounding box including stroke.
1177    ///
1178    /// Similar to `bounding_box`, but includes stroke.
1179    pub fn stroke_bounding_box(&self) -> Option<Rect> {
1180        *self.bounding_boxes().stroke_bounding_box.get_or_init(|| {
1181            self.union_of_children(|child| {
1182                Some(child.to_parent_coordinates(child.stroke_bounding_box()?))
1183            })
1184        })
1185    }
1186
1187    /// Element's bounding box including stroke in user coordinates.
1188    ///
1189    /// Similar to `abs_bounding_box`, but includes stroke.
1190    pub fn abs_stroke_bounding_box(&self) -> Option<Rect> {
1191        *self
1192            .bounding_boxes()
1193            .abs_stroke_bounding_box
1194            .get_or_init(|| self.union_of_children(Node::abs_stroke_bounding_box))
1195    }
1196
1197    /// Element's "layer" bounding box in object units.
1198    ///
1199    /// Conceptually, this is `stroke_bounding_box` expanded and/or clipped
1200    /// by `filters_bounding_box`, but also including all the children.
1201    /// Groups without filters are additionally clipped by their clip path.
1202    /// This is the bounding box `resvg` will later use to allocate layers/pixmaps
1203    /// during isolated groups rendering.
1204    ///
1205    /// Only groups have it, because only groups can have filters.
1206    /// For other nodes layer bounding box is the same as stroke bounding box.
1207    ///
1208    /// Unlike other bounding boxes, cannot have zero size.
1209    pub fn layer_bounding_box(&self) -> Option<NonZeroRect> {
1210        *self
1211            .bounding_boxes()
1212            .layer_bounding_box
1213            .get_or_init(|| self.calculate_layer_bounding_box())
1214    }
1215
1216    /// Element's "layer" bounding box in canvas units.
1217    pub fn abs_layer_bounding_box(&self) -> Option<NonZeroRect> {
1218        *self
1219            .bounding_boxes()
1220            .abs_layer_bounding_box
1221            .get_or_init(|| {
1222                self.layer_bounding_box()
1223                    .and_then(|r| r.transform(self.abs_transform))
1224            })
1225    }
1226
1227    /// Group's children.
1228    pub fn children(&self) -> &[Node] {
1229        &self.children
1230    }
1231
1232    fn bounding_boxes(&self) -> &GroupBoundingBoxes {
1233        self.bounding_boxes.get_or_init(Box::default)
1234    }
1235
1236    /// Checks if this group should be isolated during rendering.
1237    pub fn should_isolate(&self) -> bool {
1238        self.isolate
1239            || self.opacity != Opacity::ONE
1240            || self.clip_path.is_some()
1241            || self.mask.is_some()
1242            || !self.filters.is_empty()
1243            || self.blend_mode != BlendMode::Normal // TODO: probably not needed?
1244    }
1245
1246    /// Returns `true` if the group has any children.
1247    pub fn has_children(&self) -> bool {
1248        !self.children.is_empty()
1249    }
1250
1251    /// Calculates a node's filter bounding box.
1252    ///
1253    /// Filters with `objectBoundingBox` and missing or zero `bounding_box` would be ignored.
1254    ///
1255    /// Note that a filter region can act like a clipping rectangle,
1256    /// therefore this function can produce a bounding box smaller than `bounding_box`.
1257    ///
1258    /// Returns `None` when then group has no filters.
1259    ///
1260    /// This function is very fast, that's why we do not store this bbox as a `Group` field.
1261    pub fn filters_bounding_box(&self) -> Option<NonZeroRect> {
1262        let mut full_region = BBox::default();
1263        for filter in &self.filters {
1264            full_region = full_region.expand(filter.rect);
1265        }
1266
1267        full_region.to_non_zero_rect()
1268    }
1269
1270    fn subroots(&self, f: &mut dyn FnMut(&Group)) {
1271        if let Some(ref clip) = self.clip_path {
1272            f(&clip.root);
1273
1274            if let Some(ref sub_clip) = clip.clip_path {
1275                f(&sub_clip.root);
1276            }
1277        }
1278
1279        if let Some(ref mask) = self.mask {
1280            f(&mask.root);
1281
1282            if let Some(ref sub_mask) = mask.mask {
1283                f(&sub_mask.root);
1284            }
1285        }
1286
1287        for filter in &self.filters {
1288            for primitive in &filter.primitives {
1289                if let filter::Kind::Image(ref image) = primitive.kind {
1290                    f(image.root());
1291                }
1292            }
1293        }
1294    }
1295}
1296
1297/// Representation of the [`paint-order`] property.
1298///
1299/// `usvg` will handle `markers` automatically,
1300/// therefore we provide only `fill` and `stroke` variants.
1301///
1302/// [`paint-order`]: https://www.w3.org/TR/SVG2/painting.html#PaintOrder
1303#[derive(Clone, Copy, PartialEq, Debug)]
1304#[allow(missing_docs)]
1305pub enum PaintOrder {
1306    FillAndStroke,
1307    StrokeAndFill,
1308}
1309
1310impl Default for PaintOrder {
1311    fn default() -> Self {
1312        Self::FillAndStroke
1313    }
1314}
1315
1316/// A path element.
1317#[derive(Clone, Debug)]
1318pub struct Path {
1319    pub(crate) id: Box<str>,
1320    pub(crate) visible: bool,
1321    pub(crate) fill: Option<Fill>,
1322    pub(crate) stroke: Option<Stroke>,
1323    pub(crate) paint_order: PaintOrder,
1324    pub(crate) rendering_mode: ShapeRendering,
1325    pub(crate) data: Arc<tiny_skia_path::Path>,
1326    pub(crate) abs_transform: Transform,
1327    pub(crate) bounding_boxes: OnceLock<Box<PathBoundingBoxes>>,
1328}
1329
1330// Boxed, because most nodes never have their bounding boxes requested.
1331#[derive(Clone, Debug, Default)]
1332pub(crate) struct PathBoundingBoxes {
1333    bounding_box: OnceLock<Option<Rect>>,
1334    abs_bounding_box: OnceLock<Option<Rect>>,
1335    stroke_bounding_box: OnceLock<Option<Rect>>,
1336    abs_stroke_bounding_box: OnceLock<Option<Rect>>,
1337}
1338
1339impl Path {
1340    pub(crate) fn new_simple(data: Arc<tiny_skia_path::Path>) -> Self {
1341        Self::new(
1342            Box::default(),
1343            true,
1344            None,
1345            None,
1346            PaintOrder::default(),
1347            ShapeRendering::default(),
1348            data,
1349            Transform::default(),
1350        )
1351    }
1352
1353    pub(crate) fn new(
1354        id: Box<str>,
1355        visible: bool,
1356        fill: Option<Fill>,
1357        stroke: Option<Stroke>,
1358        paint_order: PaintOrder,
1359        rendering_mode: ShapeRendering,
1360        data: Arc<tiny_skia_path::Path>,
1361        abs_transform: Transform,
1362    ) -> Self {
1363        Path {
1364            id,
1365            visible,
1366            fill,
1367            stroke,
1368            paint_order,
1369            rendering_mode,
1370            data,
1371            abs_transform,
1372            bounding_boxes: OnceLock::new(),
1373        }
1374    }
1375
1376    /// Element's ID.
1377    ///
1378    /// Taken from the SVG itself.
1379    /// Isn't automatically generated.
1380    /// Can be empty.
1381    pub fn id(&self) -> &str {
1382        &self.id
1383    }
1384
1385    /// Element visibility.
1386    pub fn is_visible(&self) -> bool {
1387        self.visible
1388    }
1389
1390    /// Fill style.
1391    pub fn fill(&self) -> Option<&Fill> {
1392        self.fill.as_ref()
1393    }
1394
1395    /// Stroke style.
1396    pub fn stroke(&self) -> Option<&Stroke> {
1397        self.stroke.as_ref()
1398    }
1399
1400    /// Fill and stroke paint order.
1401    ///
1402    /// Since markers will be replaced with regular nodes automatically,
1403    /// `usvg` doesn't provide the `markers` order type. It's was already done.
1404    ///
1405    /// `paint-order` in SVG.
1406    pub fn paint_order(&self) -> PaintOrder {
1407        self.paint_order
1408    }
1409
1410    /// Rendering mode.
1411    ///
1412    /// `shape-rendering` in SVG.
1413    pub fn rendering_mode(&self) -> ShapeRendering {
1414        self.rendering_mode
1415    }
1416
1417    // TODO: find a better name
1418    /// Segments list.
1419    ///
1420    /// All segments are in absolute coordinates.
1421    pub fn data(&self) -> &tiny_skia_path::Path {
1422        self.data.as_ref()
1423    }
1424
1425    /// Element's absolute transform.
1426    ///
1427    /// Contains all ancestors transforms including elements's transform.
1428    ///
1429    /// Note that this is not the relative transform present in SVG.
1430    /// The SVG one would be set only on groups.
1431    pub fn abs_transform(&self) -> Transform {
1432        self.abs_transform
1433    }
1434
1435    /// Element's object bounding box.
1436    ///
1437    /// `objectBoundingBox` in SVG terms. Meaning it doesn't affected by parent transforms.
1438    pub fn bounding_box(&self) -> Option<Rect> {
1439        *self
1440            .bounding_boxes()
1441            .bounding_box
1442            .get_or_init(|| self.data.compute_tight_bounds())
1443    }
1444
1445    /// Element's bounding box in canvas coordinates.
1446    ///
1447    /// `userSpaceOnUse` in SVG terms.
1448    pub fn abs_bounding_box(&self) -> Option<Rect> {
1449        *self.bounding_boxes().abs_bounding_box.get_or_init(|| {
1450            if self.abs_transform.has_skew() {
1451                self.abs_data()?.compute_tight_bounds()
1452            } else {
1453                // A transform without a skew can be performed just on a bbox.
1454                self.bounding_box()?.transform(self.abs_transform)
1455            }
1456        })
1457    }
1458
1459    /// Element's object bounding box including stroke.
1460    ///
1461    /// Will have the same value as `bounding_box` when path has no stroke.
1462    pub fn stroke_bounding_box(&self) -> Option<Rect> {
1463        *self.bounding_boxes().stroke_bounding_box.get_or_init(|| {
1464            Path::calculate_stroke_bbox(self.stroke.as_ref(), &self.data)
1465                .or_else(|| self.bounding_box())
1466        })
1467    }
1468
1469    /// Element's bounding box including stroke in canvas coordinates.
1470    ///
1471    /// Will have the same value as `abs_bounding_box` when path has no stroke.
1472    pub fn abs_stroke_bounding_box(&self) -> Option<Rect> {
1473        *self
1474            .bounding_boxes()
1475            .abs_stroke_bounding_box
1476            .get_or_init(|| {
1477                if self.stroke.is_none() {
1478                    self.abs_bounding_box()
1479                } else if self.abs_transform.has_skew() {
1480                    Path::calculate_stroke_bbox(self.stroke.as_ref(), &self.abs_data()?)
1481                        .or_else(|| self.abs_bounding_box())
1482                } else {
1483                    self.stroke_bounding_box()?.transform(self.abs_transform)
1484                }
1485            })
1486    }
1487
1488    fn bounding_boxes(&self) -> &PathBoundingBoxes {
1489        self.bounding_boxes.get_or_init(Box::default)
1490    }
1491
1492    fn abs_data(&self) -> Option<tiny_skia_path::Path> {
1493        self.data.as_ref().clone().transform(self.abs_transform)
1494    }
1495
1496    fn calculate_stroke_bbox(stroke: Option<&Stroke>, path: &tiny_skia_path::Path) -> Option<Rect> {
1497        let mut stroke = stroke?.to_tiny_skia();
1498        // According to the spec, dash should not be accounted during bbox calculation.
1499        stroke.dash = None;
1500
1501        // TODO: avoid for round and bevel caps
1502
1503        // Expensive, but there is not much we can do about it.
1504        if let Some(stroked_path) = path.stroke(&stroke, 1.0) {
1505            return stroked_path.compute_tight_bounds();
1506        }
1507
1508        None
1509    }
1510
1511    fn subroots(&self, f: &mut dyn FnMut(&Group)) {
1512        if let Some(Paint::Pattern(patt)) = self.fill.as_ref().map(|f| &f.paint) {
1513            f(patt.root());
1514        }
1515        if let Some(Paint::Pattern(patt)) = self.stroke.as_ref().map(|f| &f.paint) {
1516            f(patt.root());
1517        }
1518    }
1519}
1520
1521/// An embedded image kind.
1522#[derive(Clone)]
1523pub enum ImageKind {
1524    /// A reference to raw JPEG data. Should be decoded by the caller.
1525    JPEG(Arc<Vec<u8>>),
1526    /// A reference to raw PNG data. Should be decoded by the caller.
1527    PNG(Arc<Vec<u8>>),
1528    /// A reference to raw GIF data. Should be decoded by the caller.
1529    GIF(Arc<Vec<u8>>),
1530    /// A reference to raw WebP data. Should be decoded by the caller.
1531    WEBP(Arc<Vec<u8>>),
1532    /// A preprocessed SVG tree. Can be rendered as is.
1533    SVG(Tree),
1534}
1535
1536impl ImageKind {
1537    pub(crate) fn actual_size(&self) -> Option<Size> {
1538        match self {
1539            ImageKind::JPEG(data)
1540            | ImageKind::PNG(data)
1541            | ImageKind::GIF(data)
1542            | ImageKind::WEBP(data) => imagesize::blob_size(data)
1543                .ok()
1544                .and_then(|size| Size::from_wh(size.width as f32, size.height as f32))
1545                .log_none(|| log::warn!("Image has an invalid size. Skipped.")),
1546            ImageKind::SVG(svg) => Some(svg.size),
1547        }
1548    }
1549}
1550
1551impl std::fmt::Debug for ImageKind {
1552    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1553        match self {
1554            ImageKind::JPEG(_) => f.write_str("ImageKind::JPEG(..)"),
1555            ImageKind::PNG(_) => f.write_str("ImageKind::PNG(..)"),
1556            ImageKind::GIF(_) => f.write_str("ImageKind::GIF(..)"),
1557            ImageKind::WEBP(_) => f.write_str("ImageKind::WEBP(..)"),
1558            ImageKind::SVG(_) => f.write_str("ImageKind::SVG(..)"),
1559        }
1560    }
1561}
1562
1563/// A raster image element.
1564///
1565/// `image` element in SVG.
1566#[derive(Clone, Debug)]
1567pub struct Image {
1568    pub(crate) id: String,
1569    pub(crate) visible: bool,
1570    pub(crate) size: Size,
1571    pub(crate) rendering_mode: ImageRendering,
1572    pub(crate) kind: ImageKind,
1573    pub(crate) abs_transform: Transform,
1574    pub(crate) abs_bounding_box: NonZeroRect,
1575}
1576
1577impl Image {
1578    /// Element's ID.
1579    ///
1580    /// Taken from the SVG itself.
1581    /// Isn't automatically generated.
1582    /// Can be empty.
1583    pub fn id(&self) -> &str {
1584        &self.id
1585    }
1586
1587    /// Element visibility.
1588    pub fn is_visible(&self) -> bool {
1589        self.visible
1590    }
1591
1592    /// The actual image size.
1593    ///
1594    /// This is not `width` and `height` attributes,
1595    /// but rather the actual PNG/JPEG/GIF/SVG image size.
1596    pub fn size(&self) -> Size {
1597        self.size
1598    }
1599
1600    /// Rendering mode.
1601    ///
1602    /// `image-rendering` in SVG.
1603    pub fn rendering_mode(&self) -> ImageRendering {
1604        self.rendering_mode
1605    }
1606
1607    /// Image data.
1608    pub fn kind(&self) -> &ImageKind {
1609        &self.kind
1610    }
1611
1612    /// Element's absolute transform.
1613    ///
1614    /// Contains all ancestors transforms including elements's transform.
1615    ///
1616    /// Note that this is not the relative transform present in SVG.
1617    /// The SVG one would be set only on groups.
1618    pub fn abs_transform(&self) -> Transform {
1619        self.abs_transform
1620    }
1621
1622    /// Element's object bounding box.
1623    ///
1624    /// `objectBoundingBox` in SVG terms. Meaning it doesn't affected by parent transforms.
1625    pub fn bounding_box(&self) -> Rect {
1626        self.size.to_rect(0.0, 0.0).unwrap()
1627    }
1628
1629    /// Element's bounding box in canvas coordinates.
1630    ///
1631    /// `userSpaceOnUse` in SVG terms.
1632    pub fn abs_bounding_box(&self) -> Rect {
1633        self.abs_bounding_box.to_rect()
1634    }
1635
1636    fn subroots(&self, f: &mut dyn FnMut(&Group)) {
1637        if let ImageKind::SVG(ref tree) = self.kind {
1638            f(&tree.root);
1639        }
1640    }
1641}
1642
1643/// A nodes tree container.
1644#[allow(missing_debug_implementations)]
1645#[derive(Clone, Debug)]
1646pub struct Tree {
1647    pub(crate) size: Size,
1648    pub(crate) root: Group,
1649    pub(crate) linear_gradients: Vec<Arc<LinearGradient>>,
1650    pub(crate) radial_gradients: Vec<Arc<RadialGradient>>,
1651    pub(crate) patterns: Vec<Arc<Pattern>>,
1652    pub(crate) clip_paths: Vec<Arc<ClipPath>>,
1653    pub(crate) masks: Vec<Arc<Mask>>,
1654    pub(crate) filters: Vec<Arc<filter::Filter>>,
1655    #[cfg(feature = "text")]
1656    pub(crate) fontdb: Arc<fontdb::Database>,
1657}
1658
1659impl Tree {
1660    /// Image size.
1661    ///
1662    /// Size of an image that should be created to fit the SVG.
1663    ///
1664    /// `width` and `height` in SVG.
1665    ///
1666    /// Note that this does not necessarily represent the bounding box of the
1667    /// rendered contents. Use
1668    /// [`self.root().abs_layer_bounding_box()`](Group::abs_layer_bounding_box)
1669    /// to retrieve it instead.
1670    pub fn size(&self) -> Size {
1671        self.size
1672    }
1673
1674    /// The root element of the SVG tree.
1675    pub fn root(&self) -> &Group {
1676        &self.root
1677    }
1678
1679    /// Returns a renderable node by ID.
1680    ///
1681    /// If an empty ID is provided, than this method will always return `None`.
1682    pub fn node_by_id(&self, id: &str) -> Option<&Node> {
1683        if id.is_empty() {
1684            return None;
1685        }
1686
1687        node_by_id(&self.root, id)
1688    }
1689
1690    /// Checks if the current tree has any text nodes.
1691    pub fn has_text_nodes(&self) -> bool {
1692        has_text_nodes(&self.root)
1693    }
1694
1695    /// Checks if the current tree has any `defs` nodes.
1696    pub fn has_defs_nodes(&self) -> bool {
1697        !self.linear_gradients().is_empty()
1698            || !self.radial_gradients().is_empty()
1699            || !self.patterns().is_empty()
1700            || !self.filters().is_empty()
1701            || !self.clip_paths().is_empty()
1702            || !self.masks().is_empty()
1703    }
1704
1705    /// Returns a list of all unique [`LinearGradient`]s in the tree.
1706    pub fn linear_gradients(&self) -> &[Arc<LinearGradient>] {
1707        &self.linear_gradients
1708    }
1709
1710    /// Returns a list of all unique [`RadialGradient`]s in the tree.
1711    pub fn radial_gradients(&self) -> &[Arc<RadialGradient>] {
1712        &self.radial_gradients
1713    }
1714
1715    /// Returns a list of all unique [`Pattern`]s in the tree.
1716    pub fn patterns(&self) -> &[Arc<Pattern>] {
1717        &self.patterns
1718    }
1719
1720    /// Returns a list of all unique [`ClipPath`]s in the tree.
1721    pub fn clip_paths(&self) -> &[Arc<ClipPath>] {
1722        &self.clip_paths
1723    }
1724
1725    /// Returns a list of all unique [`Mask`]s in the tree.
1726    pub fn masks(&self) -> &[Arc<Mask>] {
1727        &self.masks
1728    }
1729
1730    /// Returns a list of all unique [`Filter`](filter::Filter)s in the tree.
1731    pub fn filters(&self) -> &[Arc<filter::Filter>] {
1732        &self.filters
1733    }
1734
1735    /// Returns the font database that applies to all text nodes in the tree.
1736    #[cfg(feature = "text")]
1737    pub fn fontdb(&self) -> &Arc<fontdb::Database> {
1738        &self.fontdb
1739    }
1740
1741    pub(crate) fn collect_paint_servers(&mut self) {
1742        loop_over_paint_servers(&self.root, &mut |paint| match paint {
1743            Paint::Color(_) => {}
1744            Paint::LinearGradient(lg) => {
1745                if !self
1746                    .linear_gradients
1747                    .iter()
1748                    .any(|other| Arc::ptr_eq(lg, other))
1749                {
1750                    self.linear_gradients.push(lg.clone());
1751                }
1752            }
1753            Paint::RadialGradient(rg) => {
1754                if !self
1755                    .radial_gradients
1756                    .iter()
1757                    .any(|other| Arc::ptr_eq(rg, other))
1758                {
1759                    self.radial_gradients.push(rg.clone());
1760                }
1761            }
1762            Paint::Pattern(patt) => {
1763                if !self.patterns.iter().any(|other| Arc::ptr_eq(patt, other)) {
1764                    self.patterns.push(patt.clone());
1765                }
1766            }
1767        });
1768    }
1769}
1770
1771fn node_by_id<'a>(parent: &'a Group, id: &str) -> Option<&'a Node> {
1772    for child in &parent.children {
1773        if child.id() == id {
1774            return Some(child);
1775        }
1776
1777        if let Node::Group(g) = child {
1778            if let Some(n) = node_by_id(g, id) {
1779                return Some(n);
1780            }
1781        }
1782    }
1783
1784    None
1785}
1786
1787fn has_text_nodes(root: &Group) -> bool {
1788    for node in &root.children {
1789        if let Node::Text(_) = node {
1790            return true;
1791        }
1792
1793        let mut has_text = false;
1794
1795        if let Node::Image(image) = node {
1796            if let ImageKind::SVG(tree) = &image.kind {
1797                if has_text_nodes(&tree.root) {
1798                    has_text = true;
1799                }
1800            }
1801        }
1802
1803        node.subroots(|subroot| has_text |= has_text_nodes(subroot));
1804
1805        if has_text {
1806            return true;
1807        }
1808    }
1809
1810    false
1811}
1812
1813fn loop_over_paint_servers(parent: &Group, f: &mut dyn FnMut(&Paint)) {
1814    fn push(paint: Option<&Paint>, f: &mut dyn FnMut(&Paint)) {
1815        if let Some(paint) = paint {
1816            f(paint);
1817        }
1818    }
1819
1820    for node in &parent.children {
1821        match node {
1822            Node::Group(group) => loop_over_paint_servers(group, f),
1823            Node::Path(path) => {
1824                push(path.fill.as_ref().map(|f| &f.paint), f);
1825                push(path.stroke.as_ref().map(|f| &f.paint), f);
1826            }
1827            Node::Image(_) => {}
1828            // Flattened text would be used instead.
1829            Node::Text(_) => {}
1830        }
1831
1832        node.subroots(|subroot| loop_over_paint_servers(subroot, f));
1833    }
1834}
1835
1836impl Group {
1837    pub(crate) fn collect_clip_paths(&self, clip_paths: &mut Vec<Arc<ClipPath>>) {
1838        for node in self.children() {
1839            if let Node::Group(g) = node {
1840                if let Some(clip) = &g.clip_path {
1841                    if !clip_paths.iter().any(|other| Arc::ptr_eq(clip, other)) {
1842                        clip_paths.push(clip.clone());
1843                    }
1844
1845                    if let Some(sub_clip) = &clip.clip_path {
1846                        if !clip_paths.iter().any(|other| Arc::ptr_eq(sub_clip, other)) {
1847                            clip_paths.push(sub_clip.clone());
1848                        }
1849                    }
1850                }
1851            }
1852
1853            node.subroots(|subroot| subroot.collect_clip_paths(clip_paths));
1854
1855            if let Node::Group(g) = node {
1856                g.collect_clip_paths(clip_paths);
1857            }
1858        }
1859    }
1860
1861    pub(crate) fn collect_masks(&self, masks: &mut Vec<Arc<Mask>>) {
1862        for node in self.children() {
1863            if let Node::Group(g) = node {
1864                if let Some(mask) = &g.mask {
1865                    if !masks.iter().any(|other| Arc::ptr_eq(mask, other)) {
1866                        masks.push(mask.clone());
1867                    }
1868
1869                    if let Some(sub_mask) = &mask.mask {
1870                        if !masks.iter().any(|other| Arc::ptr_eq(sub_mask, other)) {
1871                            masks.push(sub_mask.clone());
1872                        }
1873                    }
1874                }
1875            }
1876
1877            node.subroots(|subroot| subroot.collect_masks(masks));
1878
1879            if let Node::Group(g) = node {
1880                g.collect_masks(masks);
1881            }
1882        }
1883    }
1884
1885    pub(crate) fn collect_filters(&self, filters: &mut Vec<Arc<filter::Filter>>) {
1886        for node in self.children() {
1887            if let Node::Group(g) = node {
1888                for filter in g.filters() {
1889                    if !filters.iter().any(|other| Arc::ptr_eq(filter, other)) {
1890                        filters.push(filter.clone());
1891                    }
1892                }
1893            }
1894
1895            node.subroots(|subroot| subroot.collect_filters(filters));
1896
1897            if let Node::Group(g) = node {
1898                g.collect_filters(filters);
1899            }
1900        }
1901    }
1902
1903    fn union_of_children(&self, f: impl Fn(&Node) -> Option<Rect>) -> Option<Rect> {
1904        let mut bbox = BBox::default();
1905        for child in &self.children {
1906            if let Some(c_bbox) = f(child) {
1907                bbox = bbox.expand(c_bbox);
1908            }
1909        }
1910        bbox.to_rect()
1911    }
1912
1913    fn calculate_layer_bounding_box(&self) -> Option<NonZeroRect> {
1914        // Filter bbox has a higher priority than layers bbox.
1915        self.filters_bounding_box().or_else(|| {
1916            let layer_bbox = self.union_of_children(|child| match child {
1917                Node::Group(group) => group
1918                    .layer_bounding_box()
1919                    .and_then(|r| r.transform(group.transform))
1920                    .map(|r| r.to_rect()),
1921                // Not a group - no need to transform.
1922                _ => child.stroke_bounding_box(),
1923            })?;
1924            // Nothing outside the clip path is visible. Filtered groups use their filter
1925            // region instead, because filters are applied before clipping.
1926            // The clip's stroke bounding box is used because, unlike the object one,
1927            // it covers the glyph outlines of text.
1928            let layer_bbox = match &self.clip_path {
1929                Some(clip) => {
1930                    let clip_bbox = clip.root.stroke_bounding_box()?.transform(clip.transform)?;
1931                    layer_bbox.intersect(&clip_bbox)?
1932                }
1933                None => layer_bbox,
1934            };
1935            layer_bbox.to_non_zero_rect()
1936        })
1937    }
1938}
1939
1940#[cfg(test)]
1941mod tests {
1942    use super::*;
1943
1944    fn assert_no_bounding_boxes(group: &Group) {
1945        assert!(group.bounding_boxes.get().is_none());
1946
1947        for child in group.children() {
1948            match child {
1949                Node::Group(group) => assert_no_bounding_boxes(group),
1950                Node::Path(path) => assert!(path.bounding_boxes.get().is_none()),
1951                _ => {}
1952            }
1953        }
1954    }
1955
1956    fn parse(svg: &str) -> Tree {
1957        Tree::from_str(svg, &crate::Options::default()).unwrap()
1958    }
1959
1960    #[test]
1961    fn paths_in_groups_dont_calculate_bounding_boxes() {
1962        let tree = parse(
1963            r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
1964                <g transform="translate(10 20)" opacity="0.5">
1965                    <path d="M 20 20 C 80 0 120 200 180 180" fill="green" stroke="black" stroke-width="10"/>
1966                    <g transform="rotate(30)">
1967                        <rect x="20" y="20" width="100" height="100" stroke="blue"/>
1968                    </g>
1969                </g>
1970            </svg>"#,
1971        );
1972        assert_no_bounding_boxes(tree.root());
1973    }
1974
1975    #[test]
1976    fn user_space_clip_paths_dont_calculate_bounding_boxes() {
1977        let tree = parse(
1978            r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
1979                <clipPath id="clip">
1980                    <rect x="20" y="20" width="160" height="160"/>
1981                </clipPath>
1982                <g clip-path="url(#clip)">
1983                    <path d="M 20 20 C 80 0 120 200 180 180" fill="green" stroke="black" stroke-width="10"/>
1984                </g>
1985            </svg>"#,
1986        );
1987        assert_no_bounding_boxes(tree.root());
1988    }
1989
1990    #[test]
1991    fn use_elements_dont_calculate_bounding_boxes() {
1992        let tree = parse(
1993            r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200">
1994                <defs>
1995                    <path id="shape" d="M 20 20 C 80 0 120 200 180 180" stroke="black" stroke-width="10"/>
1996                </defs>
1997                <use xlink:href="#shape" fill="green"/>
1998                <use xlink:href="#shape" x="10" y="10" fill="blue"/>
1999            </svg>"##,
2000        );
2001        assert_no_bounding_boxes(tree.root());
2002    }
2003
2004    #[test]
2005    fn user_space_paint_servers_dont_calculate_bounding_boxes() {
2006        let tree = parse(
2007            r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
2008                <linearGradient id="lg" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="200" y2="0">
2009                    <stop offset="0" stop-color="white"/>
2010                    <stop offset="1" stop-color="black"/>
2011                </linearGradient>
2012                <path d="M 20 20 C 80 0 120 200 180 180" fill="url(#lg)" stroke="url(#lg)" stroke-width="10"/>
2013            </svg>"#,
2014        );
2015        assert_no_bounding_boxes(tree.root());
2016    }
2017}