1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.vectomatic.svg.edit.client.model;
19
20 import org.vectomatic.dom.svg.impl.Attr;
21 import org.vectomatic.dom.svg.impl.SVGElement;
22 import org.vectomatic.dom.svg.utils.DOMHelper;
23 import org.vectomatic.dom.svg.utils.SVGPrefixResolver;
24 import org.vectomatic.svg.edit.client.command.IFactoryInstantiator;
25
26 import com.google.gwt.dom.client.Node;
27 import com.google.gwt.dom.client.Text;
28
29
30
31
32
33
34
35 public class XPathMetadata<T> extends MetadataBase<T, SVGElement> {
36 private String xpath;
37 public XPathMetadata(String propertyName, String description, IFieldFactory fieldFactory, String xpath, IFactoryInstantiator<?> factory, IValidator<T, SVGElement> validator) {
38 super(propertyName, description, fieldFactory, factory, validator);
39 this.xpath = xpath;
40 }
41
42 public String getXPath() {
43 return xpath;
44 }
45
46 @Override
47 public T get(SVGElement element) {
48 Node node = DOMHelper.evaluateNodeXPath(element, xpath, SVGPrefixResolver.INSTANCE);
49 if (node != null) {
50 switch(node.getNodeType()) {
51 case Node.TEXT_NODE:
52 return (T)((Text)node.cast()).getData();
53 case 2:
54 return (T)((Attr)node.cast()).getValue();
55 default:
56 assert(false);
57 }
58 }
59 return null;
60 }
61
62 @Override
63 public T set(SVGElement element, T value) {
64 T oldValue = null;
65 Node node = DOMHelper.evaluateNodeXPath(element, xpath, SVGPrefixResolver.INSTANCE);
66 if (node != null) {
67 switch(node.getNodeType()) {
68 case Node.TEXT_NODE:
69 {
70 Text text = node.cast();
71 oldValue = (T)text.getData();
72 text.setData((String)value);
73 }
74 break;
75 case 2:
76 {
77 Attr attr = node.cast();
78 oldValue = (T)attr.getValue();
79 attr.setValue((String)value);
80 }
81 break;
82 default:
83 assert(false);
84 }
85 }
86 return oldValue;
87 }
88
89 @Override
90 public T remove(SVGElement element) {
91 T oldValue = null;
92 Node node = DOMHelper.evaluateNodeXPath(element, xpath, SVGPrefixResolver.INSTANCE);
93 if (node != null) {
94 switch(node.getNodeType()) {
95 case Node.TEXT_NODE:
96 {
97 Text text = node.cast();
98 oldValue = (T)text.getData();
99 text.getParentElement().removeChild(text);
100 }
101 break;
102 case 2:
103 {
104 Attr attr = node.cast();
105 oldValue = (T)attr.getValue();
106 attr.getOwnerElement().removeAttribute(attr.getName());
107 }
108 break;
109 default:
110 assert(false);
111 }
112 }
113 return oldValue;
114 }
115 @Override
116 public String toString() {
117 StringBuilder builder = new StringBuilder("XPathMetadata(");
118 builder.append(propertyName);
119 builder.append(", ");
120 builder.append(xpath);
121 builder.append(")");
122 return builder.toString();
123 }
124 }