Skip to main content

script/dom/svg/
svgsvgelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6
7use atomic_refcell::AtomicRefCell;
8use base64::Engine as _;
9use cssparser::Parser;
10use dom_struct::dom_struct;
11use html5ever::{LocalName, Prefix, local_name, ns};
12use js::context::{JSContext, NoGC};
13use js::rust::HandleObject;
14use layout_api::SVGElementData;
15use servo_url::ServoUrl;
16use style::attr::{AttrValue, parse_double};
17use style::parser::ParserContext;
18use style::str::char_is_whitespace;
19use style::stylesheets::Origin;
20use style::values::specified::LengthPercentage;
21use style_traits::ParsingMode;
22use uuid::Uuid;
23use xml5ever::serialize::TraversalScope;
24
25use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
26use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
27use crate::dom::bindings::inheritance::Castable;
28use crate::dom::bindings::reflector::DomGlobal;
29use crate::dom::bindings::root::{DomRoot, LayoutDom};
30use crate::dom::bindings::str::DOMString;
31use crate::dom::console::Console;
32use crate::dom::document::Document;
33use crate::dom::element::attributes::storage::AttrRef;
34use crate::dom::element::{AttributeMutation, Element};
35use crate::dom::iterators::ShadowIncluding;
36use crate::dom::node::virtualmethods::VirtualMethods;
37use crate::dom::node::{
38    ChildrenMutation, CloneChildrenFlag, Node, NodeDamage, NodeTraits, UnbindContext,
39};
40use crate::dom::svg::svggraphicselement::SVGGraphicsElement;
41
42#[dom_struct]
43pub(crate) struct SVGSVGElement {
44    svggraphicselement: SVGGraphicsElement,
45    #[no_trace]
46    uuid: Uuid,
47    viewbox_ratio: Cell<Option<f32>>,
48    // The XML source of subtree rooted at this SVG element, serialized into
49    // a base64 encoded `data:` url. This is cached to avoid recomputation
50    // on each layout and must be invalidated when the subtree changes.
51    #[no_trace]
52    cached_serialized_data_url: AtomicRefCell<Option<Result<ServoUrl, ()>>>,
53}
54
55impl SVGSVGElement {
56    fn new_inherited(
57        local_name: LocalName,
58        prefix: Option<Prefix>,
59        document: &Document,
60    ) -> SVGSVGElement {
61        SVGSVGElement {
62            svggraphicselement: SVGGraphicsElement::new_inherited(local_name, prefix, document),
63            uuid: Uuid::new_v4(),
64            viewbox_ratio: Default::default(),
65            cached_serialized_data_url: Default::default(),
66        }
67    }
68
69    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
70    pub(crate) fn new(
71        cx: &mut js::context::JSContext,
72        local_name: LocalName,
73        prefix: Option<Prefix>,
74        document: &Document,
75        proto: Option<HandleObject>,
76    ) -> DomRoot<SVGSVGElement> {
77        Node::reflect_node_with_proto(
78            cx,
79            Box::new(SVGSVGElement::new_inherited(local_name, prefix, document)),
80            document,
81            proto,
82        )
83    }
84
85    pub(crate) fn serialize_and_cache_subtree(&self, cx: &mut js::context::JSContext) {
86        let document_fragment = self.owner_document().CreateDocumentFragment(cx);
87        let cloned_node = Node::clone(
88            cx,
89            self.upcast(),
90            None,
91            CloneChildrenFlag::CloneChildren,
92            None,
93        );
94        if document_fragment
95            .upcast::<Node>()
96            .AppendChild(cx, &cloned_node)
97            .is_err()
98        {
99            error!("Unable to clone SVG tree");
100            *self.cached_serialized_data_url.borrow_mut() = Some(Err(()));
101            return;
102        }
103
104        self.process_use_elements(cx, &cloned_node);
105
106        let Ok(xml_source) = cloned_node.xml_serialize(TraversalScope::IncludeNode) else {
107            *self.cached_serialized_data_url.borrow_mut() = Some(Err(()));
108            return;
109        };
110
111        let xml_source: String = xml_source.into();
112        let base64_encoded_source = base64::engine::general_purpose::STANDARD.encode(xml_source);
113        let data_url = format!("data:image/svg+xml;base64,{base64_encoded_source}");
114        match ServoUrl::parse(&data_url) {
115            Ok(url) => *self.cached_serialized_data_url.borrow_mut() = Some(Ok(url)),
116            Err(error) => error!("Unable to parse serialized SVG data url: {error}"),
117        };
118    }
119
120    fn process_use_elements(&self, cx: &mut JSContext, root_node: &Node) {
121        for node in root_node.traverse_preorder(ShadowIncluding::No) {
122            if let Some(element) = node.downcast::<Element>() &&
123                element.local_name() == &local_name!("use")
124            {
125                self.process_single_use_element(cx, element, root_node)
126            }
127        }
128    }
129
130    fn process_single_use_element(
131        &self,
132        cx: &mut JSContext,
133        use_element: &Element,
134        root_node: &Node,
135    ) {
136        let href = use_element.get_string_attribute(&local_name!("href"));
137        let Some(id_string) = href.str().strip_prefix("#").map(DOMString::from) else {
138            return;
139        };
140
141        let document = self.upcast::<Node>().owner_doc();
142        let Some(referenced_element) = document.GetElementById(cx, id_string) else {
143            return;
144        };
145        let referenced_node = referenced_element.upcast::<Node>();
146
147        // Don't use this node if it doesn't have an `<svg>` ancestor.
148        if !referenced_node
149            .inclusive_ancestors_unrooted(cx.no_gc(), ShadowIncluding::No)
150            .any(|ancestor| ancestor.is::<SVGSVGElement>())
151        {
152            return;
153        };
154
155        // Don't use this node if it already exists within the same `<svg>` element.
156        if referenced_node
157            .inclusive_ancestors_unrooted(cx.no_gc(), ShadowIncluding::No)
158            .any(|ancestor| *ancestor == self.upcast())
159        {
160            return;
161        };
162
163        let cloned_node = Node::clone(
164            cx,
165            referenced_node,
166            None,
167            CloneChildrenFlag::CloneChildren,
168            None,
169        );
170        let _ = root_node.AppendChild(cx, &cloned_node);
171    }
172
173    fn invalidate_cached_serialized_subtree_and_rasterization_result(&self, no_gc: &NoGC) {
174        let owner_window = self.owner_window();
175        owner_window
176            .image_cache()
177            .evict_rasterized_image(&self.uuid);
178        if let Some(Ok(url)) = &*self.cached_serialized_data_url.borrow() {
179            owner_window.layout_mut().remove_cached_image(url);
180            owner_window.image_cache().evict_completed_image(
181                url,
182                owner_window.origin().immutable(),
183                &None,
184            );
185        }
186
187        *self.cached_serialized_data_url.borrow_mut() = None;
188        self.upcast::<Node>().dirty(no_gc, NodeDamage::Other);
189    }
190
191    /// <https://www.w3.org/TR/SVG11/coords.html#ViewBoxAttribute>
192    pub fn ratio_from_view_box(&self, view_box: Option<&DOMString>) -> Option<f32> {
193        let view_box = view_box?;
194
195        let view_box_str = view_box.str();
196        let mut iter = view_box_str
197            .split(|c| char_is_whitespace(c) || c == ',')
198            .filter(|part| !part.is_empty());
199        let _min_x = iter.next().and_then(|string| parse_double(string).ok())?;
200        let _min_y = iter.next().and_then(|string| parse_double(string).ok())?;
201
202        let width = iter.next().and_then(|string| parse_double(string).ok())?;
203        if width == 0f64 {
204            return None;
205        }
206        let height = iter.next().and_then(|string| parse_double(string).ok())?;
207        if height == 0f64 {
208            return None;
209        }
210        if width < 0f64 || height < 0f64 {
211            Console::error_to_console(
212                &self.global(),
213                "ViewBox does not have valid dimension".into(),
214            );
215            return None;
216        }
217
218        if iter.next().is_none() {
219            Some(width as f32 / height as f32)
220        } else {
221            None
222        }
223    }
224}
225
226impl<'dom> LayoutDom<'dom, SVGSVGElement> {
227    pub(crate) fn data(self) -> SVGElementData<'dom> {
228        let svg_id = self.unsafe_get().uuid;
229        let element = self.upcast::<Element>();
230        let width = element.get_attr_for_layout(&ns!(), &local_name!("width"));
231        let height = element.get_attr_for_layout(&ns!(), &local_name!("height"));
232        let view_box_ratio = self.unsafe_get().viewbox_ratio.get();
233        SVGElementData {
234            source: self
235                .unsafe_get()
236                .cached_serialized_data_url
237                .borrow()
238                .clone(),
239            width,
240            height,
241            view_box_ratio,
242            svg_id,
243        }
244    }
245}
246
247impl VirtualMethods for SVGSVGElement {
248    fn super_type(&self) -> Option<&dyn VirtualMethods> {
249        Some(self.upcast::<SVGGraphicsElement>() as &dyn VirtualMethods)
250    }
251
252    fn attribute_mutated(
253        &self,
254        cx: &mut js::context::JSContext,
255        attr: AttrRef<'_>,
256        mutation: AttributeMutation,
257    ) {
258        self.super_type()
259            .unwrap()
260            .attribute_mutated(cx, attr, mutation);
261
262        self.invalidate_cached_serialized_subtree_and_rasterization_result(cx.no_gc());
263    }
264
265    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
266        match attr.local_name() {
267            &local_name!("width") | &local_name!("height") => true,
268            _ => self
269                .super_type()
270                .unwrap()
271                .attribute_affects_presentational_hints(attr),
272        }
273    }
274
275    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
276        match *name {
277            local_name!("width") | local_name!("height") => {
278                let value = &value.str();
279                let parser = &mut Parser::new(value);
280                let doc = self.owner_document();
281                let url = doc.url().into_url().into();
282                let context = ParserContext::new(
283                    Origin::Author,
284                    &url,
285                    None,
286                    ParsingMode::ALLOW_UNITLESS_LENGTH,
287                    doc.quirks_mode(),
288                    /* namespaces = */ Default::default(),
289                    None,
290                    None,
291                    /* attr_taint = */ Default::default(),
292                );
293                let val = LengthPercentage::parse_quirky(
294                    &context,
295                    parser,
296                    style::values::specified::AllowQuirks::Always,
297                );
298                AttrValue::LengthPercentage(value.to_string(), val.ok())
299            },
300
301            local_name!("viewBox") => {
302                let viewbox_ratio = self.ratio_from_view_box(Some(&value));
303                self.viewbox_ratio.set(viewbox_ratio);
304                self.super_type()
305                    .unwrap()
306                    .parse_plain_attribute(name, value)
307            },
308            _ => self
309                .super_type()
310                .unwrap()
311                .parse_plain_attribute(name, value),
312        }
313    }
314
315    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
316        if let Some(super_type) = self.super_type() {
317            super_type.children_changed(cx, mutation);
318        }
319
320        self.invalidate_cached_serialized_subtree_and_rasterization_result(cx.no_gc());
321    }
322
323    fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext<'_>) {
324        if let Some(s) = self.super_type() {
325            s.unbind_from_tree(cx, context);
326        }
327
328        self.invalidate_cached_serialized_subtree_and_rasterization_result(cx.no_gc());
329    }
330}