SvgElementFactory.cs 13.8 KB
Newer Older
davescriven's avatar
davescriven committed
1
2
3
4
5
6
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.ComponentModel;
using System.Diagnostics;
7
using System.Linq;
Eric Domke's avatar
Eric Domke committed
8
using ExCSS;
davescriven's avatar
davescriven committed
9
10
11

namespace Svg
{
12
13
14
    /// <summary>
    /// Provides the methods required in order to parse and create <see cref="SvgElement"/> instances from XML.
    /// </summary>
davescriven's avatar
davescriven committed
15
16
    internal class SvgElementFactory
    {
Eric Domke's avatar
Eric Domke committed
17
        private static Dictionary<string, ElementInfo> availableElements;
Eric Domke's avatar
Eric Domke committed
18
        private static Parser cssParser = new Parser();
19

20
21
22
        /// <summary>
        /// Gets a list of available types that can be used when creating an <see cref="SvgElement"/>.
        /// </summary>
Eric Domke's avatar
Eric Domke committed
23
        public static Dictionary<string, ElementInfo> AvailableElements
24
25
26
27
28
29
30
        {
            get
            {
                if (availableElements == null)
                {
                    var svgTypes = from t in typeof(SvgDocument).Assembly.GetExportedTypes()
                                   where t.GetCustomAttributes(typeof(SvgElementAttribute), true).Length > 0
31
                                   && t.IsSubclassOf(typeof(SvgElement))
32
33
                                   select new ElementInfo { ElementName = ((SvgElementAttribute)t.GetCustomAttributes(typeof(SvgElementAttribute), true)[0]).ElementName, ElementType = t };

Eric Domke's avatar
Eric Domke committed
34
35
36
37
                    availableElements = (from t in svgTypes
                                         where t.ElementName != "svg"
                                         group t by t.ElementName into types
                                         select types).ToDictionary(e => e.Key, e => e.SingleOrDefault());
38
39
40
41
42
43
                }

                return availableElements;
            }
        }

44
45
46
47
48
49
        /// <summary>
        /// Creates an <see cref="SvgDocument"/> from the current node in the specified <see cref="XmlTextReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="XmlTextReader"/> containing the node to parse into an <see cref="SvgDocument"/>.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="reader"/> parameter cannot be <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException">The CreateDocument method can only be used to parse root &lt;svg&gt; elements.</exception>
Eric Domke's avatar
Eric Domke committed
50
        public static T CreateDocument<T>(XmlReader reader) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
51
        {
52
53
54
55
56
57
58
59
60
61
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.LocalName != "svg")
            {
                throw new InvalidOperationException("The CreateDocument method can only be used to parse root <svg> elements.");
            }

62
            return (T)CreateElement<T>(reader, true, null);
davescriven's avatar
davescriven committed
63
64
        }

65
66
67
68
69
70
        /// <summary>
        /// Creates an <see cref="SvgElement"/> from the current node in the specified <see cref="XmlTextReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="XmlTextReader"/> containing the node to parse into a subclass of <see cref="SvgElement"/>.</param>
        /// <param name="document">The <see cref="SvgDocument"/> that the created element belongs to.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="reader"/> and <paramref name="document"/> parameters cannot be <c>null</c>.</exception>
Eric Domke's avatar
Eric Domke committed
71
        public static SvgElement CreateElement(XmlReader reader, SvgDocument document)
davescriven's avatar
davescriven committed
72
        {
73
74
75
76
77
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

78
            return CreateElement<SvgDocument>(reader, false, document);
davescriven's avatar
davescriven committed
79
80
        }

Eric Domke's avatar
Eric Domke committed
81
        private static SvgElement CreateElement<T>(XmlReader reader, bool fragmentIsDocument, SvgDocument document) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
82
83
84
        {
            SvgElement createdElement = null;
            string elementName = reader.LocalName;
Tibor Peluch's avatar
Tibor Peluch committed
85
            string elementNS = reader.NamespaceURI;
davescriven's avatar
davescriven committed
86

87
            //Trace.TraceInformation("Begin CreateElement: {0}", elementName);
88

Eric Domke's avatar
Eric Domke committed
89
            if (elementNS == SvgAttributeAttribute.SvgNamespace || string.IsNullOrEmpty(elementNS))
davescriven's avatar
davescriven committed
90
            {
Tibor Peluch's avatar
Tibor Peluch committed
91
                if (elementName == "svg")
92
                {
Tibor Peluch's avatar
Tibor Peluch committed
93
94
95
96
                    createdElement = (fragmentIsDocument) ? new T() : new SvgFragment();
                }
                else
                {
Eric Domke's avatar
Eric Domke committed
97
98
                    ElementInfo validType = null;
                    if (AvailableElements.TryGetValue(elementName, out validType))
Tibor Peluch's avatar
Tibor Peluch committed
99
                    {
100
101
102
103
104
                        createdElement = (SvgElement) Activator.CreateInstance(validType.ElementType);
                    }
                    else
                    {
                        createdElement = new SvgUnknownElement(elementName);
Tibor Peluch's avatar
Tibor Peluch committed
105
                    }
106
                }
davescriven's avatar
davescriven committed
107

Tibor Peluch's avatar
Tibor Peluch committed
108
109
110
111
                if (createdElement != null)
                {
                    SetAttributes(createdElement, reader, document);
                }
112
            }
113
114
115
116
117
118
            else
            {
                // All non svg element (html, ...)
                createdElement = new NonSvgElement(elementName);
                SetAttributes(createdElement, reader, document);
            }
119

120
            //Trace.TraceInformation("End CreateElement");
davescriven's avatar
davescriven committed
121
122
123
124

            return createdElement;
        }

Eric Domke's avatar
Eric Domke committed
125
        private static void SetAttributes(SvgElement element, XmlReader reader, SvgDocument document)
davescriven's avatar
davescriven committed
126
        {
127
            //Trace.TraceInformation("Begin SetAttributes");
128

Eric Domke's avatar
Eric Domke committed
129
130
131
            //string[] styles = null;
            //string[] style = null;
            //int i = 0;
davescriven's avatar
davescriven committed
132
133
134

            while (reader.MoveToNextAttribute())
            {
Eric Domke's avatar
Eric Domke committed
135
136
137
138
                if (reader.LocalName.Equals("style") && !(element is NonSvgElement)) 
                {
                    var inlineSheet = cssParser.Parse("#a{" + reader.Value + "}");
                    foreach (var rule in inlineSheet.StyleRules)
davescriven's avatar
davescriven committed
139
                    {
Eric Domke's avatar
Eric Domke committed
140
                        foreach (var decl in rule.Declarations)
davescriven's avatar
davescriven committed
141
                        {
Eric Domke's avatar
Eric Domke committed
142
                            element.AddStyle(decl.Name, decl.Term.ToString(), SvgElement.StyleSpecificity_InlineStyle);
davescriven's avatar
davescriven committed
143
144
145
                        }
                    }
                }
146
                else if (IsStyleAttribute(reader.LocalName))
Eric Domke's avatar
Eric Domke committed
147
                {
Eric Domke's avatar
Eric Domke committed
148
                    element.AddStyle(reader.LocalName, reader.Value, SvgElement.StyleSpecificity_PresAttribute);
Eric Domke's avatar
Eric Domke committed
149
                }
150
151
152
153
                else
                {
                    SetPropertyValue(element, reader.LocalName, reader.Value, document);
                }
davescriven's avatar
davescriven committed
154
            }
155

156
            //Trace.TraceInformation("End SetAttributes");
davescriven's avatar
davescriven committed
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
        private static bool IsStyleAttribute(string name)
        {
            switch (name)
            {
                case "alignment-baseline":
                case "baseline-shift":
                case "clip":
                case "clip-path":
                case "clip-rule":
                case "color":
                case "color-interpolation":
                case "color-interpolation-filters":
                case "color-profile":
                case "color-rendering":
                case "cursor":
                case "direction":
                case "display":
                case "dominant-baseline":
                case "enable-background":
                case "fill":
                case "fill-opacity":
                case "fill-rule":
                case "filter":
                case "flood-color":
                case "flood-opacity":
                case "font":
                case "font-family":
                case "font-size":
                case "font-size-adjust":
                case "font-stretch":
                case "font-style":
                case "font-variant":
                case "font-weight":
                case "glyph-orientation-horizontal":
                case "glyph-orientation-vertical":
                case "image-rendering":
                case "kerning":
                case "letter-spacing":
                case "lighting-color":
                case "marker":
                case "marker-end":
                case "marker-mid":
                case "marker-start":
                case "mask":
                case "opacity":
                case "overflow":
                case "pointer-events":
                case "shape-rendering":
                case "stop-color":
                case "stop-opacity":
                case "stroke":
                case "stroke-dasharray":
                case "stroke-dashoffset":
                case "stroke-linecap":
                case "stroke-linejoin":
                case "stroke-miterlimit":
                case "stroke-opacity":
                case "stroke-width":
                case "text-anchor":
                case "text-decoration":
                case "text-rendering":
                case "unicode-bidi":
                case "visibility":
                case "word-spacing":
                case "writing-mode":
                    return true;
            }
            return false;
        }

ddpruitt's avatar
ddpruitt committed
229
        private static Dictionary<Type, Dictionary<string, PropertyDescriptorCollection>> _propertyDescriptors = new Dictionary<Type, Dictionary<string, PropertyDescriptorCollection>>();
230
        private static object syncLock = new object();
ddpruitt's avatar
ddpruitt committed
231

Eric Domke's avatar
Eric Domke committed
232
        internal static void SetPropertyValue(SvgElement element, string attributeName, string attributeValue, SvgDocument document)
davescriven's avatar
davescriven committed
233
        {
ddpruitt's avatar
ddpruitt committed
234
235
236
            var elementType = element.GetType();

            PropertyDescriptorCollection properties;
237
            lock (syncLock)
ddpruitt's avatar
ddpruitt committed
238
            {
239
                if (_propertyDescriptors.Keys.Contains(elementType))
ddpruitt's avatar
ddpruitt committed
240
                {
241
242
243
244
245
246
247
248
249
                    if (_propertyDescriptors[elementType].Keys.Contains(attributeName))
                    {
                        properties = _propertyDescriptors[elementType][attributeName];
                    }
                    else
                    {
                        properties = TypeDescriptor.GetProperties(elementType, new[] { new SvgAttributeAttribute(attributeName) });
                        _propertyDescriptors[elementType].Add(attributeName, properties);
                    }
ddpruitt's avatar
ddpruitt committed
250
251
252
253
                }
                else
                {
                    properties = TypeDescriptor.GetProperties(elementType, new[] { new SvgAttributeAttribute(attributeName) });
254
                    _propertyDescriptors.Add(elementType, new Dictionary<string, PropertyDescriptorCollection>());
ddpruitt's avatar
ddpruitt committed
255

256
257
                    _propertyDescriptors[elementType].Add(attributeName, properties);
                } 
ddpruitt's avatar
ddpruitt committed
258
            }
davescriven's avatar
davescriven committed
259
260
261

            if (properties.Count > 0)
            {
262
                PropertyDescriptor descriptor = properties[0];
davescriven's avatar
davescriven committed
263
264
265

                try
                {
Mark Johnson's avatar
Mark Johnson committed
266
267
268
269
270
271
272
273
					if (attributeName == "opacity" && attributeValue == "undefined")
					{
						attributeValue = "1";
					}

					descriptor.SetValue(element, descriptor.Converter.ConvertFrom(document, CultureInfo.InvariantCulture, attributeValue));
					

davescriven's avatar
davescriven committed
274
275
276
277
278
279
                }
                catch
                {
                    Trace.TraceWarning(string.Format("Attribute '{0}' cannot be set - type '{1}' cannot convert from string '{2}'.", attributeName, descriptor.PropertyType.FullName, attributeValue));
                }
            }
280
281
            else
            {
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
                //check for namespace declaration in svg element
                if (string.Equals(element.ElementName, "svg", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.Equals(attributeName, "xmlns", StringComparison.OrdinalIgnoreCase)
                        || string.Equals(attributeName, "xlink", StringComparison.OrdinalIgnoreCase)
                        || string.Equals(attributeName, "xmlns:xlink", StringComparison.OrdinalIgnoreCase)
                        || string.Equals(attributeName, "version", StringComparison.OrdinalIgnoreCase))
                    {
                        //nothing to do
                    }
                    else
                    {
                        //attribute is not a svg attribute, store it in custom attributes
                        element.CustomAttributes[attributeName] = attributeValue;
                    }
                }
                else
                {
                    //attribute is not a svg attribute, store it in custom attributes
                    element.CustomAttributes[attributeName] = attributeValue;
                }
303
            }
davescriven's avatar
davescriven committed
304
        }
305

306
307
308
        /// <summary>
        /// Contains information about a type inheriting from <see cref="SvgElement"/>.
        /// </summary>
309
310
        [DebuggerDisplay("{ElementName}, {ElementType}")]
        internal sealed class ElementInfo
311
        {
312
313
314
            /// <summary>
            /// Gets the SVG name of the <see cref="SvgElement"/>.
            /// </summary>
315
            public string ElementName { get; set; }
316
317
318
            /// <summary>
            /// Gets the <see cref="Type"/> of the <see cref="SvgElement"/> subclass.
            /// </summary>
319
320
            public Type ElementType { get; set; }

321
322
323
324
325
            /// <summary>
            /// Initializes a new instance of the <see cref="ElementInfo"/> struct.
            /// </summary>
            /// <param name="elementName">Name of the element.</param>
            /// <param name="elementType">Type of the element.</param>
326
327
328
329
330
            public ElementInfo(string elementName, Type elementType)
            {
                this.ElementName = elementName;
                this.ElementType = elementType;
            }
331
332
333
334
335
336
337

            /// <summary>
            /// Initializes a new instance of the <see cref="ElementInfo"/> class.
            /// </summary>
            public ElementInfo()
            {
            }
338
        }
davescriven's avatar
davescriven committed
339
340
    }
}