commit 9e28e39df07736891a6d168b4c14f99d9346a475
Author: Reizner Evgeniy <razrfalcon@gmail.com>
Date: Sun Jun 18 16:13:33 2017 +0300
Nodes doesn't store the list of linked elements now.
You should find linked elements manually from now.
This simplifies attributes processing, because you can modify 'Attributes' struct directly now.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f25c804..a1e73a8 100644
@@ -16,9 +16,16 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- `Node::text` returns `Ref<String>` now.
- Text will be preprocessed according to the
[spec](https://www.w3.org/TR/SVG11/text.html#WhiteSpace) now.
+- Nodes doesn't store the list of linked elements now.
+ You should find linked elements manually from now.
+ This simplifies attributes processing, because you can modify `Attributes` struct directly now.
### Removed
- `Error::UnresolvedAttribute`.
+- `Node::set_link_attribute`.
+- `Node::linked_nodes`.
+- `Node::is_used`.
+- `Node::uses_count`.
### Fixed
- Additional whitespace during ArcTo writing.
diff --git a/Cargo.toml b/Cargo.toml
index 4b208c8..cad201c 100644
@@ -24,6 +24,7 @@ version = "0.4"
[dev-dependencies]
time = "0.1"
+unindent = "0.1"
[features]
default = ["parsing"]
diff --git a/src/attribute/attributes.rs b/src/attribute/attributes.rs
index 3d7c7cd..234f604 100644
@@ -13,15 +13,13 @@ use {
AttributeValue
};
+// TODO: bench with HashTable
+// TODO: iter_svg() -> iter().svg() like in dom iterators
+
pub type SvgAttrFilter<'a> = Filter<Iter<'a, Attribute>, fn(&&Attribute) -> bool>;
pub type SvgAttrFilterMut<'a> = Filter<IterMut<'a, Attribute>, fn(&&mut Attribute) -> bool>;
/// Wrapper around attributes list.
-///
-/// More low level API than in `Node`, but it supports getting a reference to the attribute,
-/// and not only copy like `Node`'s API.
-///
-/// Use with care, since it didn't perform many checks from `Node`'s API.
pub struct Attributes(Vec<Attribute>);
impl Attributes {
@@ -94,9 +92,6 @@ impl Attributes {
}
/// Inserts a new attribute. Previous will be overwritten.
- ///
- /// **Warning:** this method did not perform any checks for linked attributes.
- /// If you want to insert an linked attribute - use `Node::set_link_attribute()`.
pub fn insert(&mut self, attr: Attribute) {
if self.0.capacity() == 0 {
self.0.reserve(16);
@@ -104,15 +99,13 @@ impl Attributes {
let idx = self.0.iter().position(|x| x.name == attr.name);
match idx {
+ // We use braces to discard return value.
Some(i) => { mem::replace(&mut self.0[i], attr); }
None => self.0.push(attr),
}
}
/// Creates a new attribute from name and value and inserts it. Previous will be overwritten.
- ///
- /// **Warning:** this method did not perform any checks for linked attributes.
- /// If you want to insert an linked attribute - use `Node::set_link_attribute()`.
pub fn insert_from<'a, N, T>(&mut self, name: N, value: T)
where AttributeNameRef<'a>: From<N>, N: Copy, AttributeValue: From<T>
{
@@ -120,9 +113,6 @@ impl Attributes {
}
/// Removes an existing attribute.
- ///
- /// **Warning:** this method did not perform any checks for linked attributes.
- /// If you want to remove an linked attribute - use `Node::remove_attribute()`.
pub fn remove<'a, N>(&mut self, name: N)
where AttributeNameRef<'a>: From<N>
{
diff --git a/src/dom/document.rs b/src/dom/document.rs
index 9a22144..444795a 100644
@@ -185,7 +185,6 @@ impl Document {
tag_name: tag_name.map(TagName::from),
id: String::new(),
attributes: Attributes::new(),
- linked_nodes: Vec::new(),
text: text,
})))
}
diff --git a/src/dom/iterators.rs b/src/dom/iterators.rs
index db3b9ef..9360ac4 100644
@@ -2,11 +2,9 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
-use std::cell::Ref;
use std::iter::Filter;
use super::node::Node;
-use super::node_data::WeakLink;
use super::node_type::NodeType;
// TODO: maybe can be implemented as template or trait
@@ -188,37 +186,3 @@ impl Iterator for Parents {
}
filter_svg!(Parents);
-
-/// An iterator over linked nodes.
-pub struct LinkedNodes<'a> {
- data: Ref<'a, Vec<WeakLink>>,
- idx: usize,
-}
-
-impl<'a> LinkedNodes<'a> {
- /// Constructs a new LinkedNodes iterator.
- pub fn new(data: Ref<'a, Vec<WeakLink>>) -> LinkedNodes<'a> {
- LinkedNodes {
- data: data,
- idx: 0,
- }
- }
-}
-
-impl<'a> Iterator for LinkedNodes<'a> {
- type Item = Node;
-
- fn next(&mut self) -> Option<Node> {
- let i = self.idx;
- self.idx += 1;
-
- if i < self.data.len() {
- match self.data[i].upgrade() {
- Some(n) => Some(Node(n)),
- None => None,
- }
- } else {
- None
- }
- }
-}
diff --git a/src/dom/node.rs b/src/dom/node.rs
index 7753755..ac1adfa 100644
@@ -10,7 +10,6 @@ use attribute::*;
use {
AttributeId,
ElementId,
- Error,
Name,
NameRef,
SvgId,
@@ -50,10 +49,6 @@ impl SvgId for ElementId {
/// - List of SVG attributes.
/// - List of unknown attributes.
/// - Optional text data, which is used by non-element nodes.
-///
-/// Most of the API are designed to work with SVG elements and attributes.
-/// Processing of non-SVG data is pretty hard/verbose, since it's an SVG DOM, not an XML.
-// TODO: maybe copyable
pub struct Node(pub Rc<RefCell<NodeData>>);
impl Node {
@@ -65,6 +60,8 @@ impl Node {
/// - Panics if the node is a root node.
pub fn document(&self) -> Document {
// TODO: will fail on root node
+ debug_assert!(self.node_type() != NodeType::Root);
+
Document { root: Node(self.0.borrow().doc.as_ref().unwrap().upgrade().unwrap()) }
}
@@ -137,6 +134,8 @@ impl Node {
self.first_child().is_some()
}
+ // TODO: add has_single_child
+
/// Returns the first child of this node, unless it has no child.
///
/// # Panics
@@ -196,54 +195,59 @@ impl Node {
/// Removes this node and all it children from the tree.
///
- /// Same as `detach()`, but also unlinks all linked nodes and attributes.
+ /// Same as `detach()`, but also removes all linked attributes from the tree.
+ ///
+ /// We have to iterate over all document attributes which can be very expensive.
///
/// # 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 doc = Document::from_str(
+ /// "<svg>
+ /// <rect id='rect1'/>
+ /// <use xlink:href='#rect1'/>
+ /// </svg>").unwrap();
+ ///
+ /// let rect_elem = doc.descendants().filter(|n| *n.id() == "rect1").next().unwrap();
+ /// let use_elem = doc.descendants().filter(|n| n.is_tag_name(ElementId::Use)).next().unwrap();
+ ///
+ /// assert_eq!(use_elem.has_attribute(AttributeId::XlinkHref), 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.
+ /// rect_elem.remove();
+ ///
+ /// assert_eq!(use_elem.has_attribute(AttributeId::XlinkHref), false);
+ /// ```
pub fn remove(&self) {
- Node::_remove(self);
- self.detach();
- }
+ let rm_nodes: Vec<Node> = self.descendants().svg().collect();
- fn _remove(node: &Node) {
- // remove link attributes, which will trigger nodes unlink
- let mut ids: Vec<AttributeId> = node.attributes().iter_svg()
- .filter(|&(_, a)| a.is_link() || a.is_func_link())
- .map(|(id, _)| id)
- .collect();
- for id in &ids {
- node.remove_attribute(*id);
- }
-
- // remove all attributes that linked to this node
- for linked in node.linked_nodes().collect::<Vec<Node>>() {
- ids.clear();
-
- for (aid, attr) in linked.attributes().iter_svg() {
+ for n in self.document().descendants() {
+ let mut attrs = n.attributes_mut();
+ attrs.retain(|attr| {
match attr.value {
- AttributeValue::Link(ref link) | AttributeValue::FuncLink(ref link) => {
- if link == node {
- ids.push(aid);
- }
+ AttributeValue::Link(ref link) |
+ AttributeValue::FuncLink(ref link) => {
+ !rm_nodes.contains(link)
}
- _ => {}
+ _ => true,
}
- }
-
- for id in &ids {
- linked.remove_attribute(*id);
- }
+ });
}
- // repeat for children
- for child in node.children().svg() {
- Node::_remove(&child);
- }
+ self.detach();
}
/// Removes only the children nodes specified by the predicate.
///
+ /// Uses `remove()`, not `detach()` internally.
+ ///
/// Current node ignored.
pub fn drain<P>(&self, f: P) -> usize
where P: Fn(&Node) -> bool
@@ -528,6 +532,7 @@ impl Node {
Ref::map(self.0.borrow(), |n| &n.id)
}
+ // TODO: is used/needed?
/// Returns `true` if node has a not empty ID.
///
/// # Panics
@@ -637,25 +642,21 @@ impl Node {
/// Use it to insert/create new attributes.
/// For existing attributes use `Node::set_attribute_object()`.
///
- /// You can't use this method to set referenced attributes.
- /// Use `Node::set_link_attribute()` instead.
- ///
/// # Panics
///
/// Panics if the node is currently borrowed.
pub fn set_attribute<'a, N, T>(&self, name: N, value: T)
where AttributeNameRef<'a>: From<N>, N: Copy, AttributeValue: From<T>
{
- debug_assert!(self.node_type() == NodeType::Element);
+ // TODO: allow Attribute
- // we must remove existing attribute to prevent dangling links
- self.remove_attribute(name);
+ debug_assert!(self.node_type() == NodeType::Element);
- let a = Attribute::new(name, value);
let mut attrs = self.attributes_mut();
- attrs.insert(a);
+ attrs.insert_from(name, value);
}
+ // TODO: remove
/// Inserts a new SVG attribute into the attributes list.
///
/// This method will overwrite an existing attribute with the same id.
@@ -665,128 +666,13 @@ impl Node {
/// - Panics if the node is currently borrowed.
/// - Panics if the attribute cause an ElementCrosslink error.
pub fn set_attribute_object(&self, attr: Attribute) {
- // TODO: fix stupid name
-
debug_assert!(self.node_type() == NodeType::Element);
- // we must remove existing attribute to prevent dangling links
- self.remove_attribute(attr.name.into_ref());
-
- if attr.is_svg() {
- match attr.value {
- AttributeValue::Link(ref iri) | AttributeValue::FuncLink(ref iri) => {
- let aid = attr.id().unwrap();
- self.set_link_attribute(aid, iri.clone()).unwrap();
- return;
- }
- _ => {}
- }
- }
-
let mut attrs = self.attributes_mut();
attrs.insert(attr);
}
- /// Inserts a new referenced SVG attribute into the attributes list.
- ///
- /// This method will overwrite an existing attribute with the same id.
- ///
- /// # Panics
- ///
- /// Panics if the node is currently borrowed.
- ///
- /// # Examples
- /// ```
- /// use svgdom::{Document, ValueId};
- /// use svgdom::AttributeId as AId;
- /// use svgdom::ElementId as EId;
- ///
- /// // Create a simple document.
- /// let doc = Document::new();
- /// let gradient = doc.create_element(EId::LinearGradient);
- /// let rect = doc.create_element(EId::Rect);
- ///
- /// doc.append(&gradient);
- /// doc.append(&rect);
- ///
- /// gradient.set_id("lg1");
- /// rect.set_id("rect1");
- ///
- /// // Set a `fill` attribute value to the `none`.
- /// // For now everything like in any other XML DOM library.
- /// rect.set_attribute(AId::Fill, ValueId::None);
- ///
- /// // Now we want to fill our rect with a gradient.
- /// // To do this we need to set a link attribute:
- /// rect.set_link_attribute(AId::Fill, gradient.clone()).unwrap();
- ///
- /// // Now our fill attribute has a link to the `gradient` node.
- /// // Not as text, aka `url(#lg1)`, but an actual reference.
- ///
- /// // This adds support for fast checking that the element is used. Which is very useful.
- ///
- /// // `gradient` is now used, since we link it.
- /// assert_eq!(gradient.is_used(), true);
- /// // Also, we can check how many elements are uses this `gradient`.
- /// assert_eq!(gradient.uses_count(), 1);
- /// // And even get this elements:
- /// assert_eq!(gradient.linked_nodes().next().unwrap(), rect);
- ///
- /// // `rect` is unused, because no one has referenced attribute that has link to it.
- /// assert_eq!(rect.is_used(), false);
- ///
- /// // Now, if we set other attribute value, `gradient` will be automatically unlinked.
- /// rect.set_attribute(AId::Fill, ValueId::None);
- /// // No one uses it anymore.
- /// assert_eq!(gradient.is_used(), false);
- /// ```
- pub fn set_link_attribute(&self, id: AttributeId, node: Node) -> Result<(), Error> {
- // TODO: rewrite to template specialization when it will be available
- // TODO: check that node is element
-
- debug_assert!(self.node_type() == NodeType::Element);
-
- if node.id().is_empty() {
- return Err(Error::ElementMustHaveAnId);
- }
-
- // check for recursion
- if *self.id() == *node.id() {
- return Err(Error::ElementCrosslink);
- }
-
- // check for recursion 2
- {
- let self_borrow = self.0.borrow();
- let v = &self_borrow.linked_nodes;
-
- if v.iter().any(|n| Node(n.upgrade().unwrap()) == node) {
- return Err(Error::ElementCrosslink);
- }
- }
-
- // we must remove existing attribute to prevent dangling links
- self.remove_attribute(id);
-
- {
- let a = if id == AttributeId::XlinkHref {
- Attribute::new(id, AttributeValue::Link(node.clone()))
- } else {
- Attribute::new(id, AttributeValue::FuncLink(node.clone()))
- };
-
- let mut attributes = self.attributes_mut();
- attributes.insert(a);
- }
-
- {
- let mut value_borrow = node.0.borrow_mut();
- value_borrow.linked_nodes.push(Rc::downgrade(&self.0));
- }
-
- Ok(())
- }
-
+ // TODO: remove
/// Returns a copy of the attribute value by `id`.
///
/// Use it only for simple `AttributeValue` types, and not for `String` and `Path`,
@@ -801,6 +687,7 @@ impl Node {
self.attributes().get_value(id).cloned()
}
+ // TODO: remove
/// Returns a copy of the attribute by `id`.
///
/// Use it only for attributes with simple `AttributeValue` types,
@@ -851,7 +738,11 @@ impl Node {
///
/// Panics if the node is currently mutability borrowed.
pub fn has_visible_attribute(&self, id: AttributeId) -> bool {
- self.has_attribute(id) && self.attributes().get(id).unwrap().visible
+ if let Some(attr) = self.attributes().get(id) {
+ attr.visible
+ } else {
+ false
+ }
}
/// Returns `true` if the node has any of provided attributes.
@@ -895,29 +786,7 @@ impl Node {
pub fn remove_attribute<'a, N>(&self, name: N)
where AttributeNameRef<'a>: From<N>, N: Copy
{
- if !self.has_attribute(name) {
- return;
- }
-
- let mut attrs = self.attributes_mut();
-
- // we must unlink referenced attributes
- if let Some(value) = attrs.get_value(name) {
- match *value {
- AttributeValue::Link(ref node) | AttributeValue::FuncLink(ref node) => {
- let mut self_borrow = node.0.borrow_mut();
- let ln = &mut self_borrow.linked_nodes;
- // this code can't panic, because we know that such node exist
- let index = ln.iter().position(|x| {
- same_rc(&x.upgrade().unwrap(), &self.0)
- }).unwrap();
- ln.remove(index);
- }
- _ => {}
- }
- }
-
- attrs.remove(name);
+ self.attributes_mut().remove(name);
}
/// Removes attributes from the node.
@@ -931,39 +800,6 @@ impl Node {
self.remove_attribute(*id);
}
}
-
- /// Returns an iterator over linked nodes.
- ///
- /// # Panics
- ///
- /// Panics if the node is currently mutability borrowed.
- pub fn linked_nodes(&self) -> LinkedNodes {
- LinkedNodes::new(Ref::map(self.0.borrow(), |n| &n.linked_nodes))
- }
-
- /// Returns `true` if the current node is linked to any of the DOM nodes.
- ///
- /// See `Node::set_link_attribute()` for details.
- ///
- /// # Panics
- ///
- /// Panics if the node is currently mutability borrowed.
- pub fn is_used(&self) -> bool {
- let self_borrow = self.0.borrow();
- !self_borrow.linked_nodes.is_empty()
- }
-
- /// Returns a number of nodes, which is linked to this node.
- ///
- /// See `Node::set_link_attribute()` for details.
- ///
- /// # Panics
- ///
- /// Panics if the node is currently mutability borrowed.
- pub fn uses_count(&self) -> usize {
- let self_borrow = self.0.borrow();
- self_borrow.linked_nodes.len()
- }
}
// TODO: move to Rc::ptr_eq (since 1.17) when we drop 1.13 version support
diff --git a/src/dom/node_data.rs b/src/dom/node_data.rs
index b329803..b26f803 100644
@@ -25,7 +25,6 @@ pub struct NodeData {
pub tag_name: Option<TagName>,
pub id: String,
pub attributes: Attributes,
- pub linked_nodes: Vec<WeakLink>,
pub text: String,
}
@@ -33,6 +32,7 @@ impl NodeData {
/// Detach a node from its parent and siblings. Children are not affected.
pub fn detach(&mut self) {
// TODO: trim names
+ // TODO: detach doc
let parent_weak = self.parent.take();
let previous_sibling_weak = self.previous_sibling.take();
diff --git a/src/error.rs b/src/error.rs
index 0ae2e2f..bb8a192 100644
@@ -17,7 +17,7 @@ use simplecss::Error as CssParseError;
pub enum Error {
/// If you want to use referenced element inside link attribute,
/// such element must have a non-empty ID.
- ElementMustHaveAnId,
+ ElementMustHaveAnId, // TODO: currently unused
/// A linked nodes can't reference each other.
///
/// Example:
diff --git a/src/parser.rs b/src/parser.rs
index 6312db1..1b7c947 100644
@@ -3,6 +3,7 @@
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// TODO: implement xml escape
+// TODO: split to submodules
use std::str;
use std::collections::HashMap;
@@ -163,8 +164,8 @@ pub fn parse_svg(text: &str, opt: &ParseOptions) -> Result<Document, Error> {
}
resolve_links(&post_data.links)?;
-
prepare_text(&doc);
+ crosslink_check(&doc)?;
Ok(doc)
}
@@ -801,7 +802,13 @@ fn resolve_links(links: &Links) -> Result<(), Error> {
let s = d.iri.to_string();
return Err(Error::UnsupportedPaintFallback(s))
}
- None => d.node.set_link_attribute(d.attr_id, node.clone())?,
+ None => {
+ if d.attr_id == AttributeId::XlinkHref {
+ d.node.set_attribute(d.attr_id, AttributeValue::Link(node.clone()))
+ } else {
+ d.node.set_attribute(d.attr_id, AttributeValue::FuncLink(node.clone()))
+ }
+ }
}
}
None => {
@@ -1167,3 +1174,46 @@ fn trim_text(text: &mut String, xmlspace: XmlSpace) {
}
}
}
+
+// TODO: simplify
+fn crosslink_check(dom: &Document) -> Result<(), Error> {
+ // Check that element doesn't have links to itself.
+ for node in dom.descendants().svg() {
+ for attr in node.attributes().iter() {
+ match attr.value {
+ AttributeValue::Link(ref link) |
+ AttributeValue::FuncLink(ref link) => {
+ if node == *link {
+ return Err(Error::ElementCrosslink);
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ // Check that two elements doesn't linked to each other.
+ for node1 in dom.descendants().svg() {
+ for attr1 in node1.attributes().iter() {
+ match attr1.value {
+ AttributeValue::Link(ref link1) |
+ AttributeValue::FuncLink(ref link1) => {
+ for attr2 in link1.attributes().iter() {
+ match attr2.value {
+ AttributeValue::Link(ref link2) |
+ AttributeValue::FuncLink(ref link2) => {
+ if *link2 == node1 {
+ return Err(Error::ElementCrosslink);
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ Ok(())
+}
diff --git a/src/postproc/gradients.rs b/src/postproc/gradients.rs
index 23d0176..dc20219 100644
@@ -123,23 +123,35 @@ pub fn resolve_stop_attributes(doc: &Document) -> Result<(), Error> {
Ok(())
}
+// TODO: explain algorithm
fn gen_order(doc: &Document, eid: ElementId) -> Vec<Node> {
- let nodes = doc.descendants().svg().filter(|n| n.is_tag_name(eid))
- .collect::<Vec<Node>>();
+ let nodes: Vec<Node> = doc.descendants().svg().filter(|n| n.is_tag_name(eid)).collect();
+
+ let mut linked_nodes = Vec::with_capacity(nodes.len());
+ for node in &nodes {
+ let attrs = node.attributes();
+ if let Some(&AttributeValue::Link(ref link)) = attrs.get_value(AttributeId::XlinkHref) {
+ linked_nodes.push((node.clone(), link.clone()));
+ }
+ }
let mut order = Vec::with_capacity(nodes.len());
while order.len() != nodes.len() {
for node in &nodes {
- if order.iter().any(|on| on == node) {
+ if order.contains(node) {
continue;
}
- let c = node.linked_nodes().filter(|n| {
- n.is_tag_name(eid) && !order.iter().any(|on| on == n)
- }).count();
+ let mut is_any = false;
+
+ if let Some(v) = linked_nodes.iter().filter(|v| v.0 != *node).find(|v| *node == v.1) {
+ if !order.contains(&v.0) {
+ is_any = true;
+ }
+ }
- if c == 0 {
+ if !is_any {
order.push(node.clone());
}
}
diff --git a/src/postproc/mod.rs b/src/postproc/mod.rs
index 525825f..32a317f 100644
@@ -17,6 +17,6 @@ pub use self::resolve_inherit::resolve_inherit;
#[macro_use]
mod macros;
+mod fix_attrs;
mod gradients;
mod resolve_inherit;
-mod fix_attrs;
diff --git a/tests/domapi.rs b/tests/domapi.rs
index 12cd4fb..fb5666e 100644
@@ -4,138 +4,27 @@
#[macro_use]
extern crate svgdom;
-
-use svgdom::{Document, AttributeValue, Error, WriteToString, WriteOptions};
-use svgdom::AttributeId as AId;
-use svgdom::ElementId as EId;
-
-#[test]
-fn linked_attributes_1() {
- let doc = Document::new();
- let n1 = doc.create_element(EId::Svg);
- let n2 = doc.create_element(EId::Svg);
-
- doc.root().append(&n1);
- doc.root().append(&n2);
-
- n2.set_id("2");
-
- n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
- assert_eq!(n1.is_used(), false);
- assert_eq!(n2.is_used(), true);
-
- assert_eq!(n2.linked_nodes().next().unwrap(), n1);
-}
-
-#[test]
-fn linked_attributes_2() {
- let doc = Document::new();
- let n1 = doc.create_element(EId::Svg);
- let n2 = doc.create_element(EId::Svg);
-
- n1.set_id("1");
- n2.set_id("2");
-
- doc.root().append(&n1);
- doc.root().append(&n2);
-
- n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
- // recursion error
- assert_eq!(n2.set_link_attribute(AId::XlinkHref, n1.clone()).unwrap_err(),
- Error::ElementCrosslink);
-}
-
-#[test]
-fn linked_attributes_3() {
- let doc = Document::new();
-
- {
- let n1 = doc.create_element(EId::Svg);
- let n2 = doc.create_element(EId::Svg);
-
- doc.root().append(&n1);
- doc.root().append(&n2);
-
- n1.set_id("1");
- n2.set_id("2");
-
- n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
- assert_eq!(n1.is_used(), false);
- assert_eq!(n2.is_used(), true);
- }
-
- {
- // remove n1
- let n = doc.descendants().next().unwrap();
- n.remove();
- }
-
- {
- // n2 should became unused
- let n = doc.descendants().next().unwrap();
- assert_eq!(n.is_used(), false);
- }
-}
-
-#[test]
-fn linked_attributes_4() {
- let doc = Document::new();
-
- {
- let n1 = doc.create_element(EId::Svg);
- let n2 = doc.create_element(EId::Svg);
-
- doc.root().append(&n1);
- doc.root().append(&n2);
-
- n1.set_id("1");
- n2.set_id("2");
-
- n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
- assert_eq!(n1.is_used(), false);
- assert_eq!(n2.is_used(), true);
- }
-
- {
- // remove n2
- let n = doc.descendants().nth(1).unwrap();
- n.remove();
- }
-
- {
- // xlink:href attribute from n1 should be removed
- let n = doc.descendants().next().unwrap();
- assert_eq!(n.has_attribute(AId::XlinkHref), false);
- }
-}
-
-#[test]
-fn linked_attributes_5() {
- let doc = Document::new();
- let n1 = doc.create_element(EId::Svg);
- let n2 = doc.create_element(EId::Svg);
-
- doc.root().append(&n1);
- doc.root().append(&n2);
-
- n1.set_id("1");
- n2.set_id("2");
-
- // no matter how many times we insert/clone/link same node,
- // amount of linked nodes in n1 must be 1
- n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
- n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
- n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
- n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
-
- assert_eq!(n1.is_used(), true);
- assert_eq!(n2.is_used(), false);
-
- assert_eq!(n1.uses_count(), 1);
+extern crate unindent;
+
+use unindent::unindent;
+
+use svgdom::{
+ AttributeId as AId,
+ AttributeValue,
+ Document,
+ ElementId as EId,
+ WriteOptions,
+ WriteToString,
+};
+
+macro_rules! write_opt_for_tests {
+ () => ({
+ use WriteOptions;
+ let mut opt = WriteOptions::default();
+ opt.use_single_quote = true;
+ opt.simplify_transform_matrices = true;
+ opt
+ })
}
#[test]
@@ -416,3 +305,97 @@ fn deep_copy_3() {
</svg>
");
}
+
+#[test]
+fn node_remove_1() {
+ let in_text =
+ "<svg>
+ <rect id='r1'/>
+ <use xlink:href='#r1'/>
+ </svg>";
+
+ let doc = Document::from_str(in_text).unwrap();
+
+ let rect = doc.descendants().find(|n| *n.id() == "r1").unwrap();
+ rect.remove();
+
+ let out_text = unindent(
+ "<svg>
+ <use/>
+ </svg>
+ ");
+
+ assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
+
+#[test]
+fn node_remove_2() {
+ let in_text =
+ "<svg>
+ <linearGradient id='lg1'/>
+ <rect id='r1' fill='url(#lg1)'/>
+ </svg>";
+
+ let doc = Document::from_str(in_text).unwrap();
+
+ let lg = doc.descendants().find(|n| *n.id() == "lg1").unwrap();
+ lg.remove();
+
+ let out_text = unindent(
+ "<svg>
+ <rect id='r1'/>
+ </svg>
+ ");
+
+ assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
+
+#[test]
+fn node_remove_3() {
+ let in_text =
+ "<svg>
+ <rect id='r1' fill='url(#lg1)'/>
+ <linearGradient id='lg1'/>
+ <rect id='r2' fill='url(#lg1)'/>
+ <rect id='r3' fill='url(#lg1)'/>
+ </svg>";
+
+ let doc = Document::from_str(in_text).unwrap();
+
+ let lg = doc.descendants().find(|n| *n.id() == "lg1").unwrap();
+ lg.remove();
+
+ let out_text = unindent(
+ "<svg>
+ <rect id='r1'/>
+ <rect id='r2'/>
+ <rect id='r3'/>
+ </svg>
+ ");
+
+ assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
+
+#[test]
+fn node_remove_4() {
+ let in_text =
+ "<svg>
+ <defs id='defs1'>
+ <linearGradient id='lg1'/>
+ </defs>
+ <rect id='r1' fill='url(#lg1)'/>
+ </svg>";
+
+ let doc = Document::from_str(in_text).unwrap();
+
+ let defs = doc.descendants().find(|n| *n.id() == "defs1").unwrap();
+ defs.remove();
+
+ let out_text = unindent(
+ "<svg>
+ <rect id='r1'/>
+ </svg>
+ ");
+
+ assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
diff --git a/tests/generator.rs b/tests/generator.rs
index ccaa8c4..ee29314 100644
@@ -5,7 +5,7 @@
#[macro_use]
extern crate svgdom;
-use svgdom::{Document, WriteOptions, WriteToString, NodeType, Indent};
+use svgdom::{Document, WriteOptions, WriteToString, NodeType, Indent, AttributeValue};
use svgdom::AttributeId as AId;
use svgdom::ElementId as EId;
use svgdom::types::{Transform, Length, LengthUnit, Color};
@@ -96,7 +96,7 @@ fn links_1() {
doc.append(&svg_n);
svg_n.append(&use_n);
- use_n.set_link_attribute(AId::XlinkHref, svg_n).unwrap();
+ use_n.set_attribute(AId::XlinkHref, AttributeValue::Link(svg_n));
assert_eq_text!(doc.to_string(),
"<svg id=\"svg1\">
@@ -118,7 +118,7 @@ fn links_2() {
svg_n.append(&lg_n);
svg_n.append(&rect_n);
- rect_n.set_link_attribute(AId::Fill, lg_n).unwrap();
+ rect_n.set_attribute(AId::Fill, AttributeValue::FuncLink(lg_n));
assert_eq_text!(doc.to_string(),
"<svg>
diff --git a/tests/parser.rs b/tests/parser.rs
index 9275081..ca2e3b8 100644
@@ -7,29 +7,27 @@ extern crate svgdom;
extern crate simplecss;
use svgdom::{
+ AttributeId as AId,
+ AttributeValue,
Document,
- ParseOptions,
+ ElementId as EId,
Error,
ErrorPos,
Name,
NodeType,
+ ParseOptions,
ValueId,
- WriteToString
+ WriteOptions,
+ WriteToString,
};
use svgdom::types::Color;
-use svgdom::AttributeValue;
-use svgdom::AttributeId as AId;
-use svgdom::ElementId as EId;
use simplecss::Error as CssParseError;
-macro_rules! write_opt_for_tests {
- () => ({
- use svgdom::WriteOptions;
- let mut opt = WriteOptions::default();
- opt.use_single_quote = true;
- opt
- })
+fn write_options() -> WriteOptions {
+ let mut opt = WriteOptions::default();
+ opt.use_single_quote = true;
+ opt
}
macro_rules! test_resave {
@@ -37,7 +35,7 @@ macro_rules! test_resave {
#[test]
fn $name() {
let doc = Document::from_str($in_text).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text);
+ assert_eq_text!(doc.to_string_with_opt(&write_options()), $out_text);
}
)
}
@@ -537,7 +535,6 @@ fn parse_iri_1() {
let rg = child.children().nth(0).unwrap();
let rect = child.children().nth(1).unwrap();
- assert_eq!(rg.is_used(), true);
assert_eq!(rect.attribute_value(AId::Fill).unwrap(), AttributeValue::FuncLink(rg));
}
@@ -555,7 +552,6 @@ fn parse_iri_2() {
let rect = child.children().nth(0).unwrap();
let rg = child.children().nth(1).unwrap();
- assert_eq!(rg.is_used(), true);
assert_eq!(rect.attribute_value(AId::Fill).unwrap(), AttributeValue::FuncLink(rg));
}
@@ -754,7 +750,7 @@ fn skip_comments_1() {
"<!--comment-->
<svg/>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg/>
");
}
@@ -767,7 +763,7 @@ fn skip_declaration_1() {
"<?xml version='1.0'?>
<svg/>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg/>
");
}
@@ -782,7 +778,7 @@ fn skip_unknown_elements_1() {
<rect/>
</svg>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg>
<rect/>
</svg>
@@ -803,7 +799,7 @@ fn skip_unknown_elements_2() {
<rect/>
</svg>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg>
<rect/>
</svg>
@@ -824,7 +820,7 @@ fn skip_unknown_elements_3() {
<rect/>
</svg>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg>
<rect/>
</svg>
@@ -842,7 +838,7 @@ fn skip_unknown_elements_4() {
<rect/>
</svg>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg>
<rect/>
</svg>
@@ -857,7 +853,7 @@ fn skip_unknown_attributes_1() {
"<svg fill='#ff0000' test='1' qwe='zzz' xmlns='http://www.w3.org/2000/svg' \
xmlns:xlink='http://www.w3.org/1999/xlink'/>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg fill='#ff0000' xmlns='http://www.w3.org/2000/svg' \
xmlns:xlink='http://www.w3.org/1999/xlink'/>
");
@@ -868,7 +864,7 @@ fn parse_px_unit_on_1() {
let mut opt = ParseOptions::default();
opt.parse_px_unit = true;
let doc = Document::from_str_with_opt("<svg x='10px'/>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), "<svg x='10px'/>\n");
+ assert_eq_text!(doc.to_string_with_opt(&write_options()), "<svg x='10px'/>\n");
}
#[test]
@@ -876,7 +872,7 @@ fn parse_px_unit_off_1() {
let mut opt = ParseOptions::default();
opt.parse_px_unit = false;
let doc = Document::from_str_with_opt("<svg x='10px'/>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), "<svg x='10'/>\n");
+ assert_eq_text!(doc.to_string_with_opt(&write_options()), "<svg x='10'/>\n");
}
#[test]
@@ -884,7 +880,7 @@ fn parse_px_unit_off_2() {
let mut opt = ParseOptions::default();
opt.parse_px_unit = false;
let doc = Document::from_str_with_opt("<svg stroke-dasharray='10px 20px'/>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg stroke-dasharray='10 20'/>\n");
}
@@ -902,7 +898,7 @@ fn skip_unresolved_classes_1() {
<g class='fil1 fil4 str1 fil5'/>
</svg>", &opt).unwrap();
- assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+ assert_eq_text!(doc.to_string_with_opt(&write_options()),
"<svg>
<g class='fil3' fill='#0000ff'/>
<g class='fil4 fil5' fill='#0000ff' stroke='#0000ff'/>
@@ -910,5 +906,28 @@ fn skip_unresolved_classes_1() {
");
}
+#[test]
+fn crosslink_1() {
+ let doc = Document::from_str(
+ "<svg>
+ <linearGradient id='lg1' xlink:href='#lg1'/>
+ </svg>
+ "
+ );
+ assert_eq!(doc.err().unwrap(), Error::ElementCrosslink);
+}
+
+#[test]
+fn crosslink_2() {
+ let doc = Document::from_str(
+ "<svg>
+ <linearGradient id='lg1' xlink:href='#lg2'/>
+ <linearGradient id='lg2' xlink:href='#lg1'/>
+ </svg>
+ "
+ );
+ assert_eq!(doc.err().unwrap(), Error::ElementCrosslink);
+}
+
// TODO: this
// p { font-family: "Font 1", "Font 2", Georgia, Times, serif; }