1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use std::fmt;

use log::warn;
use slab::Slab;

use crate::parser::parse_svg;

use crate::writer;
use crate::{
    AttributeQName,
    Attributes,
    AttributeValue,
    ElementId,
    FilterSvg,
    FilterSvgAttrs,
    Node,
    NodeData,
    NodeType,
    ParserError,
    QName,
    QNameRef,
    TagNameRef,
    WriteOptions,
};

/// Container of [`Node`]s.
///
/// Structure:
///
/// - [`Document`]
///     - root [`Node`]
///         - user defined [`Node`]
///             - [`TagName`]
///             - [`Attributes`]
///             - unique id
///         - user defined [`Node`]
///         - ...
///
/// The [`Document`] itself is just a container of [`Node`]s.
/// You can create new [`Node`]s only through the [`Document`].
/// Parsing and generating of the SVG data also done through it.
///
/// The [`Node`] represents any kind of an XML node.
/// It can be an element, a comment, a text, etc. There are no different structs for each type.
///
/// The [`TagName`] represents a tag name of the element node. It's an enum of
/// [`ElementId`] and `String` types. The [`ElementId`] contains all possible
/// SVG element names and `String` used for non-SVG elements. Such separation used for
/// performance reasons.
///
/// The [`Attributes`] container wraps a `Vec` of [`Attribute`]'s.
///
/// At last, the `id` attribute is stored as a separate value and not as part of the [`Attributes`].
///
/// [`Attribute`]: struct.Attribute.html
/// [`Attributes`]: struct.Attributes.html
/// [`Document`]: struct.Document.html
/// [`ElementId`]: enum.ElementId.html
/// [`Node`]: type.Node.html
/// [`TagName`]: type.TagName.html
pub struct Document {
    root: Node,
    storage: Slab<Node>,
}

impl Document {
    /// Constructs a new `Document`.
    pub fn new() -> Document {
        let mut storage = Slab::new();
        let mut root = Node::new(NodeData {
            storage_key: None,
            node_type: NodeType::Root,
            tag_name: QName::Name(String::new()),
            id: String::new(),
            attributes: Attributes::new(),
            linked_nodes: Vec::new(),
            text: String::new(),
        });

        let key = storage.insert(root.clone());
        root.borrow_mut().storage_key = Some(key);

        Document {
            root,
            storage,
        }
    }

    /// Constructs a new `Document` from the text.
    ///
    /// [`ParseOptions`]: struct.ParseOptions.html
    ///
    /// **Note:** only SVG elements and attributes will be parsed.
    pub fn from_str(text: &str) -> Result<Document, ParserError> {
        parse_svg(text)
    }

    /// Writes a `Document` content to a string.
    pub fn to_string_with_opt(&self, opt: &WriteOptions) -> String {
        writer::write_dom(self, opt)
    }

    /// Constructs a new [`Node`] with [`NodeType`]::Element type.
    ///
    /// Constructed node do belong to this document, but not added to it tree structure.
    ///
    /// # Panics
    ///
    /// Panics if a string tag name is empty.
    ///
    /// [`Node`]: type.Node.html
    /// [`NodeType`]: enum.NodeType.html
    pub fn create_element<'a, T>(&mut self, tag_name: T) -> Node
        where TagNameRef<'a>: From<T>, T: Copy
    {
        let tn = QNameRef::from(tag_name);
        if let QNameRef::Name(name) = tn {
            if name.is_empty() {
                panic!("supplied tag name is empty");
            }
        }

        let mut node = Node::new(NodeData {
            storage_key: None,
            node_type: NodeType::Element,
            tag_name: QNameRef::from(tag_name).into(),
            id: String::new(),
            attributes: Attributes::new(),
            linked_nodes: Vec::new(),
            text: String::new(),
        });

        let key = self.storage.insert(node.clone());
        node.borrow_mut().storage_key = Some(key);

        node
    }

    // TODO: we can't have continuous text nodes.
    // TODO: doc should have only one declaration
    /// Constructs a new [`Node`] using the supplied [`NodeType`].
    ///
    /// Constructed node do belong to this document, but not added to it tree structure.
    ///
    /// This method should be used for any non-element nodes.
    ///
    /// [`Node`]: type.Node.html
    /// [`NodeType`]: enum.NodeType.html
    pub fn create_node<S: Into<String>>(&mut self, node_type: NodeType, text: S) -> Node {
        assert!(node_type != NodeType::Element && node_type != NodeType::Root);

        let mut node = Node::new(NodeData {
            storage_key: None,
            node_type,
            tag_name: QName::Name(String::new()),
            id: String::new(),
            attributes: Attributes::new(),
            linked_nodes: Vec::new(),
            text: text.into(),
        });

        let key = self.storage.insert(node.clone());
        node.borrow_mut().storage_key = Some(key);

        node
    }

    /// Returns the root [`Node`].
    ///
    /// [`Node`]: type.Node.html
    pub fn root(&self) -> Node {
        self.root.clone()
    }

    /// Returns the first child with `svg` tag name of the root [`Node`].
    ///
    /// In most of the cases result of this method and `first_element_child()` will be the same,
    /// but an additional check may be helpful.
    ///
    /// # Panics
    ///
    /// Panics if the root node is currently mutability borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::{Document, ElementId};
    ///
    /// let doc = Document::from_str(
    ///     "<!--comment--><svg xmlns='http://www.w3.org/2000/svg'/>").unwrap();
    ///
    /// assert_eq!(doc.svg_element().unwrap().has_tag_name(ElementId::Svg), true);
    /// ```
    ///
    /// [`Node`]: type.Node.html
    pub fn svg_element(&self) -> Option<Node> {
        for (id, n) in self.root().children().svg() {
            if id == ElementId::Svg {
                return Some(n.clone());
            }
        }

        None
    }

    /// Removes this node and all it children from the tree.
    ///
    /// Same as `detach()`, but also removes all linked attributes from the tree.
    ///
    /// # Panics
    ///
    /// Panics if the node or one of its adjoining nodes or any children node is currently borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::{Document, ElementId, AttributeId};
    ///
    /// let mut doc = Document::from_str(
    /// "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
    ///     <rect id='rect1'/>
    ///     <use xlink:href='#rect1'/>
    /// </svg>").unwrap();
    ///
    /// let mut rect_elem = doc.root().descendants().filter(|n| *n.id() == "rect1").next().unwrap();
    /// let use_elem = doc.root().descendants().filter(|n| n.has_tag_name(ElementId::Use)).next().unwrap();
    ///
    /// assert_eq!(use_elem.has_attribute(AttributeId::Href), true);
    ///
    /// // The 'remove' method will remove 'rect' element and all it's children.
    /// // Also it will remove all links to this element and it's children,
    /// // so 'use' element will no longer have the 'xlink:href' attribute.
    /// doc.remove_node(rect_elem);
    ///
    /// assert_eq!(use_elem.has_attribute(AttributeId::Href), false);
    /// ```
    pub fn remove_node(&mut self, node: Node) {
        let mut ids = Vec::with_capacity(16);
        self._remove(node.clone(), &mut ids);
    }

    fn _remove(&mut self, mut node: Node, ids: &mut Vec<AttributeQName>) {
        ids.clear();

        for (_, attr) in node.attributes().iter().svg() {
            match attr.value {
                  AttributeValue::Link(_)
                | AttributeValue::FuncLink(_)
                | AttributeValue::Paint(_, _) => {
                    ids.push(attr.name.clone())
                }
                _ => {}
            }
        }

        for name in ids.iter() {
            node.remove_attribute(name.as_ref());
        }

        // remove all attributes that linked to this node
        let linked_nodes = node.linked_nodes().clone();
        for mut linked in linked_nodes {
            ids.clear();

            for (_, attr) in linked.attributes().iter().svg() {
                match attr.value {
                      AttributeValue::Link(ref link)
                    | AttributeValue::FuncLink(ref link)
                    | AttributeValue::Paint(ref link, _) => {
                        if *link == node {
                            ids.push(attr.name.clone())
                        }
                    }
                    _ => {}
                }
            }

            for name in ids.iter() {
                linked.remove_attribute(name.as_ref());
            }
        }


        // repeat for children
        for child in node.children() {
            self._remove(child, ids);
        }

        node.detach();
        let key = node.borrow_mut().storage_key.take();

        if let Some(key) = key {
            self.storage.remove(key);
        } else {
            warn!("Node was already removed.")
        }
    }

    // TODO: maybe rename to retain to match Attributes::retain
    /// Removes only the children nodes specified by the predicate.
    ///
    /// Uses [remove()](#method.remove), not [detach()](#method.detach) internally.
    ///
    /// The `root` node will be ignored.
    pub fn drain<P>(&mut self, root: Node, f: P) -> usize
        where P: Fn(&Node) -> bool
    {
        let mut count = 0;
        self._drain(root, &f, &mut count);
        count
    }

    fn _drain<P>(&mut self, parent: Node, f: &P, count: &mut usize)
        where P: Fn(&Node) -> bool
    {
        let mut node = parent.first_child();
        while let Some(n) = node {
            if f(&n) {
                node = n.next_sibling();
                self.remove_node(n);
                *count += 1;
            } else {
                if n.has_children() {
                    self._drain(n.clone(), f, count);
                }

                node = n.next_sibling();
            }
        }
    }

    /// Returns a copy of a current node without children.
    ///
    /// All attributes except `id` will be copied, because `id` must be unique.
    pub fn copy_node(&mut self, node: Node) -> Node {
        match node.node_type() {
            NodeType::Element => {
                let mut elem = self.create_element(node.tag_name().as_ref());

                for attr in node.attributes().iter() {
                    elem.set_attribute(attr.clone());
                }

                elem
            }
            _ => {
                self.create_node(node.node_type(), node.text().clone())
            }
        }
    }

    /// Returns a deep copy of a current node with all it's children.
    ///
    /// All attributes except `id` will be copied, because `id` must be unique.
    pub fn copy_node_deep(&mut self, node: Node) -> Node {
        let mut root = self.copy_node(node.clone());
        self._make_deep_copy(&mut root, &node);
        root
    }

    fn _make_deep_copy(&mut self, parent: &mut Node, node: &Node) {
        for child in node.children() {
            let mut new_node = self.copy_node(child.clone());
            parent.append(new_node.clone());

            if child.has_children() {
                self._make_deep_copy(&mut new_node, &child);
            }
        }
    }
}

impl Drop for Document {
    fn drop(&mut self) {
        for (_, node) in self.storage.iter_mut() {
            node.attributes_mut().clear();
            node.linked_nodes_mut().clear();
            node.detach();
        }
    }
}

impl fmt::Display for Document {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let data = writer::write_dom(self, &WriteOptions::default());
        write!(f, "{}", data)
    }
}