Skip to main content

rsvg/
structure.rs

1//! Structural elements in SVG: the `g`, `switch`, `svg`, `use`, `symbol`, `clip_path`, `mask`, `link` elements.
2
3use markup5ever::{expanded_name, local_name, ns};
4
5use crate::aspect_ratio::*;
6use crate::bbox::BoundingBox;
7use crate::coord_units;
8use crate::coord_units::CoordUnits;
9use crate::document::{AcquiredNodes, NodeId};
10use crate::drawing_ctx::{DrawingCtx, SvgNesting, Viewport};
11use crate::element::{DrawResult, ElementData, ElementTrait, set_attribute};
12use crate::error::*;
13use crate::href::{is_href, set_href};
14use crate::layout::{self, Layer, LayerKind, LayoutViewport, StackingContext};
15use crate::length::*;
16use crate::node::{CascadedValues, Node, NodeBorrow, NodeDraw};
17use crate::parsers::{Parse, ParseValue};
18use crate::properties::ComputedValues;
19use crate::rect::Rect;
20use crate::session::Session;
21use crate::viewbox::*;
22use crate::xml::Attributes;
23
24#[derive(Default)]
25pub struct Group();
26
27impl ElementTrait for Group {
28    fn draw(
29        &self,
30        node: &Node,
31        acquired_nodes: &mut AcquiredNodes<'_>,
32        cascaded: &CascadedValues<'_>,
33        viewport: &Viewport,
34        draw_ctx: &mut DrawingCtx,
35        _clipping: bool,
36    ) -> DrawResult {
37        let values = cascaded.get();
38
39        let elt = node.borrow_element();
40        let stacking_ctx = Box::new(StackingContext::new(
41            draw_ctx,
42            acquired_nodes,
43            &elt,
44            values.transform(),
45            None,
46            values,
47            viewport,
48        ));
49
50        draw_ctx.with_discrete_layer(
51            &stacking_ctx,
52            acquired_nodes,
53            viewport,
54            None,
55            false,
56            &mut |an, dc, new_viewport| node.draw_children(an, cascaded, new_viewport, dc),
57        )
58    }
59
60    fn layout(
61        &self,
62        node: &Node,
63        acquired_nodes: &mut AcquiredNodes<'_>,
64        cascaded: &CascadedValues<'_>,
65        viewport: &Viewport,
66        draw_ctx: &mut DrawingCtx,
67    ) -> Result<Option<Layer>, Box<InternalRenderingError>> {
68        let mut child_layers = Vec::new();
69
70        for child in node.children().filter(|c| c.is_element()) {
71            let elt = child.borrow_element();
72
73            let layer = elt.layout(
74                &child,
75                acquired_nodes,
76                &CascadedValues::clone_with_node(cascaded, &child),
77                viewport,
78                draw_ctx,
79            )?;
80
81            if let Some(layer) = layer {
82                child_layers.push(layer);
83            }
84        }
85
86        self.layout_with_children(
87            draw_ctx,
88            node,
89            acquired_nodes,
90            cascaded,
91            child_layers,
92            viewport,
93        )
94    }
95}
96
97fn extents_of_transformed_children(layers: &[Layer]) -> Option<Rect> {
98    let mut result_bbox = BoundingBox::new();
99
100    for layer in layers {
101        if let Some(extents) = layer.kind.local_extents() {
102            let bbox = BoundingBox::new()
103                .with_transform(layer.stacking_ctx.transform)
104                .with_rect(extents);
105            result_bbox.insert(&bbox);
106        }
107    }
108
109    result_bbox.rect
110}
111
112impl Group {
113    fn layout_with_children(
114        &self,
115        draw_ctx: &DrawingCtx,
116        node: &Node,
117        acquired_nodes: &mut AcquiredNodes<'_>,
118        cascaded: &CascadedValues<'_>,
119        child_layers: Vec<Layer>,
120        viewport: &Viewport,
121    ) -> Result<Option<Layer>, Box<InternalRenderingError>> {
122        let values = cascaded.get();
123
124        let extents = extents_of_transformed_children(&child_layers);
125
126        let group = Box::new(layout::Group {
127            children: child_layers,
128            establish_viewport: None,
129            extents,
130        });
131
132        let elt = node.borrow_element();
133        let stacking_ctx = StackingContext::new(
134            draw_ctx,
135            acquired_nodes,
136            &elt,
137            values.transform(),
138            None,
139            values,
140            viewport,
141        );
142
143        Ok(Some(Layer {
144            kind: LayerKind::Group(group),
145            stacking_ctx,
146        }))
147    }
148}
149
150/// A no-op node that does not render anything
151///
152/// Sometimes we just need a node that can contain children, but doesn't
153/// render itself or its children.  This is just that kind of node.
154#[derive(Default)]
155pub struct NonRendering;
156
157impl ElementTrait for NonRendering {}
158
159/// The `<switch>` element.
160#[derive(Default)]
161pub struct Switch();
162
163impl ElementTrait for Switch {
164    fn draw(
165        &self,
166        node: &Node,
167        acquired_nodes: &mut AcquiredNodes<'_>,
168        cascaded: &CascadedValues<'_>,
169        viewport: &Viewport,
170        draw_ctx: &mut DrawingCtx,
171        _clipping: bool,
172    ) -> DrawResult {
173        let values = cascaded.get();
174
175        let switch_elt = node.borrow_element();
176        let child_that_matches = node.children().filter(|c| c.is_element()).find(|c| {
177            let elt = c.borrow_element();
178            elt.get_cond(draw_ctx.user_language(), draw_ctx.session())
179        });
180
181        if let Some(child) = child_that_matches {
182            let stacking_ctx = Box::new(StackingContext::new(
183                draw_ctx,
184                acquired_nodes,
185                &switch_elt,
186                values.transform(),
187                None,
188                values,
189                viewport,
190            ));
191
192            draw_ctx.with_discrete_layer(
193                &stacking_ctx,
194                acquired_nodes,
195                viewport,
196                None,
197                false,
198                &mut |an, dc, new_viewport| {
199                    child.draw(
200                        an,
201                        &CascadedValues::clone_with_node(cascaded, &child),
202                        new_viewport,
203                        dc,
204                        false,
205                    )
206                },
207            )
208        } else {
209            Ok(viewport.empty_bbox())
210        }
211    }
212}
213
214/// Intrinsic dimensions of an SVG document fragment: its `width/height` properties and  `viewBox` attribute.
215///
216/// Note that in SVG2, `width` and `height` are properties, not
217/// attributes.  If either is omitted, it defaults to `auto`. which
218/// computes to `100%`.
219///
220/// The `viewBox` attribute can also be omitted, hence an `Option`.
221#[derive(Debug, Copy, Clone, PartialEq)]
222pub struct IntrinsicDimensions {
223    /// Computed value of the `width` property.
224    pub width: ULength<Horizontal>,
225
226    /// Computed value of the `height` property.
227    pub height: ULength<Vertical>,
228
229    /// Contents of the `viewBox` attribute.
230    pub vbox: Option<ViewBox>,
231}
232
233/// The `<svg>` element.
234///
235/// Note that its x/y/width/height are properties in SVG2, so they are
236/// defined as part of [the properties machinery](properties.rs).
237#[derive(Default)]
238pub struct Svg {
239    preserve_aspect_ratio: AspectRatio,
240    vbox: Option<ViewBox>,
241}
242
243impl Svg {
244    pub fn get_intrinsic_dimensions(&self, values: &ComputedValues) -> IntrinsicDimensions {
245        let w = match values.width().0 {
246            LengthOrAuto::Auto => ULength::<Horizontal>::parse_str("100%").unwrap(),
247            LengthOrAuto::Length(l) => l,
248        };
249
250        let h = match values.height().0 {
251            LengthOrAuto::Auto => ULength::<Vertical>::parse_str("100%").unwrap(),
252            LengthOrAuto::Length(l) => l,
253        };
254
255        IntrinsicDimensions {
256            width: w,
257            height: h,
258            vbox: self.vbox,
259        }
260    }
261
262    fn get_unnormalized_offset(
263        &self,
264        values: &ComputedValues,
265    ) -> (Length<Horizontal>, Length<Vertical>) {
266        // these defaults are per the spec
267        let x = values.x().0;
268        let y = values.y().0;
269
270        (x, y)
271    }
272
273    fn get_unnormalized_size(
274        &self,
275        values: &ComputedValues,
276    ) -> (ULength<Horizontal>, ULength<Vertical>) {
277        // these defaults are per the spec
278        let w = match values.width().0 {
279            LengthOrAuto::Auto => ULength::<Horizontal>::parse_str("100%").unwrap(),
280            LengthOrAuto::Length(l) => l,
281        };
282        let h = match values.height().0 {
283            LengthOrAuto::Auto => ULength::<Vertical>::parse_str("100%").unwrap(),
284            LengthOrAuto::Length(l) => l,
285        };
286        (w, h)
287    }
288
289    fn get_viewport(
290        &self,
291        params: &NormalizeParams,
292        values: &ComputedValues,
293        outermost: bool,
294    ) -> Rect {
295        // x & y attributes have no effect on outermost svg
296        // http://www.w3.org/TR/SVG/struct.html#SVGElement
297        let (nx, ny) = if outermost {
298            (0.0, 0.0)
299        } else {
300            let (x, y) = self.get_unnormalized_offset(values);
301            (x.to_user(params), y.to_user(params))
302        };
303
304        let (w, h) = self.get_unnormalized_size(values);
305        let (nw, nh) = (w.to_user(params), h.to_user(params));
306
307        Rect::new(nx, ny, nx + nw, ny + nh)
308    }
309
310    pub fn get_viewbox(&self) -> Option<ViewBox> {
311        self.vbox
312    }
313
314    pub fn get_preserve_aspect_ratio(&self) -> AspectRatio {
315        self.preserve_aspect_ratio
316    }
317
318    fn make_svg_viewport(
319        &self,
320        node: &Node,
321        cascaded: &CascadedValues<'_>,
322        current_viewport: &Viewport,
323        draw_ctx: &mut DrawingCtx,
324    ) -> LayoutViewport {
325        let values = cascaded.get();
326
327        let params = NormalizeParams::new(values, current_viewport);
328
329        let has_parent = node.parent().is_some();
330
331        // From https://www.w3.org/TR/SVG2/embedded.html#ImageElement:
332        //
333        // For `image` elements embedding an SVG image, the `preserveAspectRatio`
334        // attribute on the root element in the referenced SVG image must be ignored,
335        // and instead treated as if it had a value of `none`. (see
336        // `preserveAspectRatio` for details).  This ensures that the
337        // `preserveAspectRatio` attribute on the referencing `image` has its
338        // intended effect, even if it is none.
339        //
340        let preserve_aspect_ratio = match (has_parent, draw_ctx.svg_nesting()) {
341            // we are a toplevel, and referenced from <image> => preserveAspectRatio=none
342            (false, SvgNesting::ReferencedFromImageElement) => AspectRatio::none(),
343
344            // otherwise just use our specified preserveAspectRatio
345            _ => self.preserve_aspect_ratio,
346        };
347
348        let svg_viewport = self.get_viewport(&params, values, !has_parent);
349
350        let is_measuring_toplevel_svg = !has_parent && draw_ctx.is_measuring();
351
352        let (geometry, vbox) = if is_measuring_toplevel_svg {
353            // We are obtaining the toplevel SVG's geometry.  This means, don't care about the
354            // DrawingCtx's viewport, just use the SVG's intrinsic dimensions and see how far
355            // it wants to extend.
356            (svg_viewport, self.vbox)
357        } else {
358            (
359                // The client's viewport overrides the toplevel's x/y/w/h viewport
360                if has_parent {
361                    svg_viewport
362                } else {
363                    draw_ctx.toplevel_viewport()
364                },
365                // Use our viewBox if available, or try to derive one from
366                // the intrinsic dimensions.
367                self.vbox.or_else(|| {
368                    Some(ViewBox::from(Rect::from_size(
369                        svg_viewport.width(),
370                        svg_viewport.height(),
371                    )))
372                }),
373            )
374        };
375
376        LayoutViewport {
377            geometry,
378            vbox,
379            preserve_aspect_ratio,
380            overflow: values.overflow(),
381        }
382    }
383}
384
385impl ElementTrait for Svg {
386    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) {
387        for (attr, value) in attrs.iter() {
388            match attr.expanded() {
389                expanded_name!("", "preserveAspectRatio") => {
390                    set_attribute(&mut self.preserve_aspect_ratio, attr.parse(value), session)
391                }
392                expanded_name!("", "viewBox") => {
393                    set_attribute(&mut self.vbox, attr.parse(value), session)
394                }
395                _ => (),
396            }
397        }
398    }
399
400    fn draw(
401        &self,
402        node: &Node,
403        acquired_nodes: &mut AcquiredNodes<'_>,
404        cascaded: &CascadedValues<'_>,
405        viewport: &Viewport,
406        draw_ctx: &mut DrawingCtx,
407        _clipping: bool,
408    ) -> DrawResult {
409        let values = cascaded.get();
410
411        let elt = node.borrow_element();
412        let stacking_ctx = Box::new(StackingContext::new(
413            draw_ctx,
414            acquired_nodes,
415            &elt,
416            values.transform(),
417            None,
418            values,
419            viewport,
420        ));
421
422        let layout_viewport = self.make_svg_viewport(node, cascaded, viewport, draw_ctx);
423
424        draw_ctx.with_discrete_layer(
425            &stacking_ctx,
426            acquired_nodes,
427            viewport,
428            Some(layout_viewport),
429            false,
430            &mut |an, dc, new_viewport| node.draw_children(an, cascaded, new_viewport, dc),
431        )
432    }
433
434    fn layout(
435        &self,
436        node: &Node,
437        acquired_nodes: &mut AcquiredNodes<'_>,
438        cascaded: &CascadedValues<'_>,
439        viewport: &Viewport,
440        draw_ctx: &mut DrawingCtx,
441    ) -> Result<Option<Layer>, Box<InternalRenderingError>> {
442        let mut child_layers = Vec::new();
443
444        for child in node.children().filter(|c| c.is_element()) {
445            let elt = child.borrow_element();
446
447            let layer = elt.layout(
448                &child,
449                acquired_nodes,
450                &CascadedValues::clone_with_node(cascaded, &child),
451                viewport,
452                draw_ctx,
453            )?;
454
455            if let Some(layer) = layer {
456                child_layers.push(layer);
457            }
458        }
459
460        let values = cascaded.get();
461        let extents = extents_of_transformed_children(&child_layers);
462
463        let layout_viewport = self.make_svg_viewport(node, cascaded, viewport, draw_ctx);
464
465        let group = Box::new(layout::Group {
466            children: child_layers,
467            establish_viewport: Some(layout_viewport),
468            extents,
469        });
470
471        let elt = node.borrow_element();
472        let stacking_ctx = StackingContext::new(
473            draw_ctx,
474            acquired_nodes,
475            &elt,
476            values.transform(),
477            None,
478            values,
479            viewport,
480        );
481
482        Ok(Some(Layer {
483            kind: LayerKind::Group(group),
484            stacking_ctx,
485        }))
486    }
487}
488
489/// The `<use>` element.
490pub struct Use {
491    link: Option<NodeId>,
492    x: Length<Horizontal>,
493    y: Length<Vertical>,
494    width: ULength<Horizontal>,
495    height: ULength<Vertical>,
496}
497
498impl Use {
499    pub fn get_rect(&self, params: &NormalizeParams) -> Rect {
500        let x = self.x.to_user(params);
501        let y = self.y.to_user(params);
502        let w = self.width.to_user(params);
503        let h = self.height.to_user(params);
504
505        Rect::new(x, y, x + w, y + h)
506    }
507
508    pub fn get_link(&self) -> Option<NodeId> {
509        self.link.clone()
510    }
511}
512
513impl Default for Use {
514    fn default() -> Use {
515        Use {
516            link: None,
517            x: Default::default(),
518            y: Default::default(),
519            width: ULength::<Horizontal>::parse_str("100%").unwrap(),
520            height: ULength::<Vertical>::parse_str("100%").unwrap(),
521        }
522    }
523}
524
525impl ElementTrait for Use {
526    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) {
527        for (attr, value) in attrs.iter() {
528            match attr.expanded() {
529                ref a if is_href(a) => {
530                    let mut href = None;
531                    set_attribute(
532                        &mut href,
533                        NodeId::parse(value).map(Some).attribute(attr.clone()),
534                        session,
535                    );
536                    set_href(a, &mut self.link, href);
537                }
538                expanded_name!("", "x") => set_attribute(&mut self.x, attr.parse(value), session),
539                expanded_name!("", "y") => set_attribute(&mut self.y, attr.parse(value), session),
540                expanded_name!("", "width") => {
541                    set_attribute(&mut self.width, attr.parse(value), session)
542                }
543                expanded_name!("", "height") => {
544                    set_attribute(&mut self.height, attr.parse(value), session)
545                }
546                _ => (),
547            }
548        }
549    }
550
551    fn draw(
552        &self,
553        node: &Node,
554        acquired_nodes: &mut AcquiredNodes<'_>,
555        cascaded: &CascadedValues<'_>,
556        viewport: &Viewport,
557        draw_ctx: &mut DrawingCtx,
558        clipping: bool,
559    ) -> DrawResult {
560        if let Some(link) = self.link.as_ref() {
561            let values = cascaded.get();
562            let params = NormalizeParams::new(values, viewport);
563            let rect = self.get_rect(&params);
564
565            let use_node_name = format!("{node}");
566
567            let stroke_paint = values.stroke().0.resolve(
568                acquired_nodes,
569                &use_node_name,
570                values.stroke_opacity().0,
571                values.color().0,
572                cascaded.context_fill.clone(),
573                cascaded.context_stroke.clone(),
574                draw_ctx.session(),
575            );
576
577            let fill_paint = values.fill().0.resolve(
578                acquired_nodes,
579                &use_node_name,
580                values.fill_opacity().0,
581                values.color().0,
582                cascaded.context_fill.clone(),
583                cascaded.context_stroke.clone(),
584                draw_ctx.session(),
585            );
586
587            draw_ctx.draw_from_use_node(
588                node,
589                acquired_nodes,
590                values,
591                rect,
592                link,
593                clipping,
594                viewport,
595                fill_paint,
596                stroke_paint,
597            )
598        } else {
599            Ok(viewport.empty_bbox())
600        }
601    }
602}
603
604/// The `<symbol>` element.
605#[derive(Default)]
606pub struct Symbol {
607    preserve_aspect_ratio: AspectRatio,
608    vbox: Option<ViewBox>,
609}
610
611impl Symbol {
612    pub fn get_viewbox(&self) -> Option<ViewBox> {
613        self.vbox
614    }
615
616    pub fn get_preserve_aspect_ratio(&self) -> AspectRatio {
617        self.preserve_aspect_ratio
618    }
619}
620
621impl ElementTrait for Symbol {
622    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) {
623        for (attr, value) in attrs.iter() {
624            match attr.expanded() {
625                expanded_name!("", "preserveAspectRatio") => {
626                    set_attribute(&mut self.preserve_aspect_ratio, attr.parse(value), session)
627                }
628                expanded_name!("", "viewBox") => {
629                    set_attribute(&mut self.vbox, attr.parse(value), session)
630                }
631                _ => (),
632            }
633        }
634    }
635}
636
637coord_units!(ClipPathUnits, CoordUnits::UserSpaceOnUse);
638
639/// The `<clipPath>` element.
640#[derive(Default)]
641pub struct ClipPath {
642    units: ClipPathUnits,
643}
644
645impl ClipPath {
646    pub fn get_units(&self) -> CoordUnits {
647        CoordUnits::from(self.units)
648    }
649}
650
651impl ElementTrait for ClipPath {
652    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) {
653        for (attr, value) in attrs.iter() {
654            if attr.expanded() == expanded_name!("", "clipPathUnits") {
655                set_attribute(&mut self.units, attr.parse(value), session);
656            }
657        }
658    }
659}
660
661coord_units!(MaskUnits, CoordUnits::ObjectBoundingBox);
662coord_units!(MaskContentUnits, CoordUnits::UserSpaceOnUse);
663
664/// The `<mask>` element.
665pub struct Mask {
666    x: Length<Horizontal>,
667    y: Length<Vertical>,
668    width: ULength<Horizontal>,
669    height: ULength<Vertical>,
670
671    units: MaskUnits,
672    content_units: MaskContentUnits,
673}
674
675impl Default for Mask {
676    fn default() -> Mask {
677        Mask {
678            // these values are per the spec
679            x: Length::<Horizontal>::parse_str("-10%").unwrap(),
680            y: Length::<Vertical>::parse_str("-10%").unwrap(),
681            width: ULength::<Horizontal>::parse_str("120%").unwrap(),
682            height: ULength::<Vertical>::parse_str("120%").unwrap(),
683
684            units: MaskUnits::default(),
685            content_units: MaskContentUnits::default(),
686        }
687    }
688}
689
690impl Mask {
691    pub fn get_units(&self) -> CoordUnits {
692        CoordUnits::from(self.units)
693    }
694
695    pub fn get_content_units(&self) -> CoordUnits {
696        CoordUnits::from(self.content_units)
697    }
698
699    pub fn get_rect(&self, params: &NormalizeParams) -> Rect {
700        let x = self.x.to_user(params);
701        let y = self.y.to_user(params);
702        let w = self.width.to_user(params);
703        let h = self.height.to_user(params);
704
705        Rect::new(x, y, x + w, y + h)
706    }
707}
708
709impl ElementTrait for Mask {
710    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) {
711        for (attr, value) in attrs.iter() {
712            match attr.expanded() {
713                expanded_name!("", "x") => set_attribute(&mut self.x, attr.parse(value), session),
714                expanded_name!("", "y") => set_attribute(&mut self.y, attr.parse(value), session),
715                expanded_name!("", "width") => {
716                    set_attribute(&mut self.width, attr.parse(value), session)
717                }
718                expanded_name!("", "height") => {
719                    set_attribute(&mut self.height, attr.parse(value), session)
720                }
721                expanded_name!("", "maskUnits") => {
722                    set_attribute(&mut self.units, attr.parse(value), session)
723                }
724                expanded_name!("", "maskContentUnits") => {
725                    set_attribute(&mut self.content_units, attr.parse(value), session)
726                }
727                _ => (),
728            }
729        }
730    }
731}
732
733/// The `<a>` element.
734#[derive(Default)]
735pub struct Link {
736    pub link: Option<String>,
737}
738
739impl ElementTrait for Link {
740    fn set_attributes(&mut self, attrs: &Attributes, _session: &Session) {
741        for (attr, value) in attrs.iter() {
742            let expanded = attr.expanded();
743            if is_href(&expanded) {
744                set_href(&expanded, &mut self.link, Some(value.to_owned()));
745            }
746        }
747    }
748
749    fn draw(
750        &self,
751        node: &Node,
752        acquired_nodes: &mut AcquiredNodes<'_>,
753        cascaded: &CascadedValues<'_>,
754        viewport: &Viewport,
755        draw_ctx: &mut DrawingCtx,
756        _clipping: bool,
757    ) -> DrawResult {
758        // If this element is inside of <text>, do not draw it.
759        // The <text> takes care of it.
760        for an in node.ancestors() {
761            if matches!(&*an.borrow_element_data(), ElementData::Text(_)) {
762                return Ok(viewport.empty_bbox());
763            }
764        }
765
766        let cascaded = CascadedValues::clone_with_node(cascaded, node);
767        let values = cascaded.get();
768
769        let elt = node.borrow_element();
770
771        let link_is_empty = self.link.as_ref().map(|l| l.is_empty()).unwrap_or(true);
772
773        let link_target = if link_is_empty {
774            None
775        } else {
776            self.link.clone()
777        };
778
779        let stacking_ctx = Box::new(StackingContext::new_with_link(
780            draw_ctx,
781            acquired_nodes,
782            &elt,
783            values.transform(),
784            values,
785            viewport,
786            link_target,
787        ));
788
789        draw_ctx.with_discrete_layer(
790            &stacking_ctx,
791            acquired_nodes,
792            viewport,
793            None,
794            false,
795            &mut |an, dc, new_viewport| node.draw_children(an, &cascaded, new_viewport, dc),
796        )
797    }
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803
804    use crate::accept_language::UserLanguage;
805    use crate::document::Document;
806    use crate::dpi::Dpi;
807    use crate::drawing_ctx::{RenderingConfiguration, SvgNesting};
808
809    #[test]
810    fn computes_group_extents() {
811        let document = Document::load_from_bytes(
812            br#"<?xml version="1.0" encoding="UTF-8"?>
813<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
814  <g id="a">
815    <g transform="translate(10, 10) scale(2, 3)">
816      <rect x="0" y="0" width="5" height="10"/>
817    </g>
818    <rect x="0" y="0" width="5" height="10" transform="scale(2) translate(-10, -20)"/>
819  </g>
820</svg>
821"#,
822        );
823
824        let a = document.lookup_internal_node("a").unwrap();
825
826        let elt = a.borrow_element();
827
828        let mut acquired_nodes = AcquiredNodes::new(&document, None);
829        let cascaded = CascadedValues::new_from_node(&a);
830
831        let dpi = Dpi::new(96.0, 96.0);
832
833        let viewport = Viewport::new(dpi.clone(), 100.0, 100.0);
834
835        let surface = cairo::RecordingSurface::create(cairo::Content::ColorAlpha, None).unwrap();
836        let cr = cairo::Context::new(&surface).unwrap();
837
838        let config = RenderingConfiguration {
839            dpi,
840            cancellable: None,
841            user_language: UserLanguage::LanguageTags(crate::accept_language::LanguageTags::empty()),
842            svg_nesting: SvgNesting::Standalone,
843            measuring: false,
844            testing: true,
845        };
846
847        let mut draw_ctx = DrawingCtx::new(Session::default(), &cr, &viewport, config, Vec::new());
848
849        let layout = elt.layout(&a, &mut acquired_nodes, &cascaded, &viewport, &mut draw_ctx);
850
851        match layout {
852            Ok(Some(Layer {
853                kind: LayerKind::Group(ref group),
854                ..
855            })) => {
856                assert_eq!(group.extents, Some(Rect::new(-20.0, -40.0, 20.0, 40.0)));
857            }
858
859            Err(_) => panic!("layout should not produce an InternalRenderingError"),
860
861            _ => panic!("layout object is not a LayerKind::Group"),
862        }
863    }
864}