SvgElement.cs 21 KB
Newer Older
davescriven's avatar
davescriven committed
1
2
3
4
5
6
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml;
7
using System.Linq;
davescriven's avatar
davescriven committed
8
using Svg.Transforms;
9
using System.Reflection;
davescriven's avatar
davescriven committed
10
11
12
13
14
15
16
17

namespace Svg
{
    /// <summary>
    /// The base class of which all SVG elements are derived from.
    /// </summary>
    public abstract class SvgElement : ISvgElement, ISvgTransformable, ICloneable
    {
18
19
20
        //optimization
        protected class AttributeTuple
        {
Tebjan Halm's avatar
Tebjan Halm committed
21
            public MemberDescriptor Property;
22
23
24
25
26
            public SvgAttributeAttribute Attribute;
        }
        protected IEnumerable<AttributeTuple> _svgAttributes;


davescriven's avatar
davescriven committed
27
28
29
30
31
32
33
        internal SvgElement _parent;
        private string _elementName;
        private SvgAttributeCollection _attributes;
        private EventHandlerList _eventHandlers;
        private SvgElementCollection _children;
        private static readonly object _loadEventKey = new object();
        private Matrix _graphicsMatrix;
34
        private Dictionary<string, string> _customAttributes;
davescriven's avatar
davescriven committed
35
36
37
38

        /// <summary>
        /// Gets the name of the element.
        /// </summary>
39
        protected internal string ElementName
davescriven's avatar
davescriven committed
40
        {
41
42
43
44
45
46
47
48
49
50
51
52
53
54
            get
            {
                if (string.IsNullOrEmpty(this._elementName))
                {
                    var attr = TypeDescriptor.GetAttributes(this).OfType<SvgElementAttribute>().SingleOrDefault();

                    if (attr != null)
                    {
                        this._elementName = attr.ElementName;
                    }
                }

                return this._elementName;
            }
55
            internal set { this._elementName = value; }
davescriven's avatar
davescriven committed
56
57
58
59
60
61
62
        }

        /// <summary>
        /// Gets or sets the content of the element.
        /// </summary>
        public virtual string Content
        {
63
64
            get;
            set;
davescriven's avatar
davescriven committed
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
        }

        /// <summary>
        /// Gets an <see cref="EventHandlerList"/> of all events belonging to the element.
        /// </summary>
        protected virtual EventHandlerList Events
        {
            get { return this._eventHandlers; }
        }

        /// <summary>
        /// Occurs when the element is loaded.
        /// </summary>
        public event EventHandler Load
        {
            add { this.Events.AddHandler(_loadEventKey, value); }
            remove { this.Events.RemoveHandler(_loadEventKey, value); }
        }

        /// <summary>
        /// Gets a collection of all child <see cref="SvgElements"/>.
        /// </summary>
        public virtual SvgElementCollection Children
        {
            get { return this._children; }
        }

        /// <summary>
        /// Gets a value to determine whether the element has children.
        /// </summary>
        public virtual bool HasChildren()
        {
            return (this.Children.Count > 0);
        }

        /// <summary>
        /// Gets the parent <see cref="SvgElement"/>.
        /// </summary>
        /// <value>An <see cref="SvgElement"/> if one exists; otherwise null.</value>
        public virtual SvgElement Parent
        {
            get { return this._parent; }
        }

        /// <summary>
        /// Gets the owner <see cref="SvgDocument"/>.
        /// </summary>
        public virtual SvgDocument OwnerDocument
        {
            get
            {
                if (Parent == null)
                {
                    if (this is SvgDocument)
119
                    {
davescriven's avatar
davescriven committed
120
                        return (SvgDocument)this;
121
                    }
davescriven's avatar
davescriven committed
122
                    else
123
                    {
davescriven's avatar
davescriven committed
124
                        return null;
125
                    }
davescriven's avatar
davescriven committed
126
127
                }
                else
128
                {
davescriven's avatar
davescriven committed
129
                    return Parent.OwnerDocument;
130
                }
davescriven's avatar
davescriven committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
            }
        }

        /// <summary>
        /// Gets a collection of element attributes.
        /// </summary>
        protected internal virtual SvgAttributeCollection Attributes
        {
            get
            {
                if (this._attributes == null)
                {
                    this._attributes = new SvgAttributeCollection(this);
                }

                return this._attributes;
            }
        }

150
151
152
153
154
        public Dictionary<string, string> CustomAttributes
        {
            get { return this._customAttributes; }
        }

155
156
157
158
159
        /// <summary>
        /// Applies the required transforms to <see cref="SvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> to be transformed.</param>
        protected internal virtual void PushTransforms(SvgRenderer renderer)
davescriven's avatar
davescriven committed
160
        {
161
            _graphicsMatrix = renderer.Transform;
162

davescriven's avatar
davescriven committed
163
164
165
166
167
168
            // Return if there are no transforms
            if (this.Transforms == null || this.Transforms.Count == 0)
            {
                return;
            }

169
            Matrix transformMatrix = renderer.Transform;
davescriven's avatar
davescriven committed
170
171
172

            foreach (SvgTransform transformation in this.Transforms)
            {
Matt Bowers's avatar
Matt Bowers committed
173
                transformMatrix.Multiply(transformation.Matrix, MatrixOrder.Append);
davescriven's avatar
davescriven committed
174
175
            }

176
            renderer.Transform = transformMatrix;
davescriven's avatar
davescriven committed
177
178
        }

179
180
181
182
183
        /// <summary>
        /// Removes any previously applied transforms from the specified <see cref="SvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> that should have transforms removed.</param>
        protected internal virtual void PopTransforms(SvgRenderer renderer)
davescriven's avatar
davescriven committed
184
        {
185
            renderer.Transform = _graphicsMatrix;
davescriven's avatar
davescriven committed
186
187
188
            _graphicsMatrix = null;
        }

189
190
191
192
193
        /// <summary>
        /// Applies the required transforms to <see cref="SvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> to be transformed.</param>
        void ISvgTransformable.PushTransforms(SvgRenderer renderer)
davescriven's avatar
davescriven committed
194
        {
195
            this.PushTransforms(renderer);
davescriven's avatar
davescriven committed
196
197
        }

198
199
200
201
202
        /// <summary>
        /// Removes any previously applied transforms from the specified <see cref="SvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> that should have transforms removed.</param>
        void ISvgTransformable.PopTransforms(SvgRenderer renderer)
davescriven's avatar
davescriven committed
203
        {
204
            this.PopTransforms(renderer);
davescriven's avatar
davescriven committed
205
206
207
208
209
210
211
212
213
        }

        /// <summary>
        /// Gets or sets the element transforms.
        /// </summary>
        /// <value>The transforms.</value>
        [SvgAttribute("transform")]
        public SvgTransformCollection Transforms
        {
214
            get { return (this.Attributes.GetAttribute<SvgTransformCollection>("Transforms") ?? new SvgTransformCollection()); }
davescriven's avatar
davescriven committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
            set { this.Attributes["Transforms"] = value; }
        }

        /// <summary>
        /// Gets or sets the ID of the element.
        /// </summary>
        /// <exception cref="SvgException">The ID is already used within the <see cref="SvgDocument"/>.</exception>
        [SvgAttribute("id")]
        public string ID
        {
            get { return this.Attributes.GetAttribute<string>("ID"); }
            set
            {
                // Don't do anything if it hasn't changed
                if (string.Compare(this.ID, value) == 0)
230
                {
davescriven's avatar
davescriven committed
231
                    return;
232
                }
davescriven's avatar
davescriven committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

                if (this.OwnerDocument != null)
                {
                    this.OwnerDocument.IdManager.Remove(this);
                }

                this.Attributes["ID"] = value;

                if (this.OwnerDocument != null)
                {
                    this.OwnerDocument.IdManager.Add(this);
                }
            }
        }

248
249
250
251
252
253
        /// <summary>
        /// Called by the underlying <see cref="SvgElement"/> when an element has been added to the
        /// <see cref="Children"/> collection.
        /// </summary>
        /// <param name="child">The <see cref="SvgElement"/> that has been added.</param>
        /// <param name="index">An <see cref="int"/> representing the index where the element was added to the collection.</param>
254
        protected virtual void AddElement(SvgElement child, int index)
davescriven's avatar
davescriven committed
255
256
257
        {
        }

258
259
260
261
262
        /// <summary>
        /// Calls the <see cref="AddElement"/> method with the specified parameters.
        /// </summary>
        /// <param name="child">The <see cref="SvgElement"/> that has been added.</param>
        /// <param name="index">An <see cref="int"/> representing the index where the element was added to the collection.</param>
davescriven's avatar
davescriven committed
263
264
        internal void OnElementAdded(SvgElement child, int index)
        {
265
            this.AddElement(child, index);
davescriven's avatar
davescriven committed
266
267
        }

268
269
270
271
272
        /// <summary>
        /// Called by the underlying <see cref="SvgElement"/> when an element has been removed from the
        /// <see cref="Children"/> collection.
        /// </summary>
        /// <param name="child">The <see cref="SvgElement"/> that has been removed.</param>
273
        protected virtual void RemoveElement(SvgElement child)
davescriven's avatar
davescriven committed
274
275
276
        {
        }

277
278
279
280
        /// <summary>
        /// Calls the <see cref="RemoveElement"/> method with the specified <see cref="SvgElement"/> as the parameter.
        /// </summary>
        /// <param name="child">The <see cref="SvgElement"/> that has been removed.</param>
davescriven's avatar
davescriven committed
281
282
        internal void OnElementRemoved(SvgElement child)
        {
283
            this.RemoveElement(child);
davescriven's avatar
davescriven committed
284
285
286
287
288
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SvgElement"/> class.
        /// </summary>
289
        public SvgElement()
davescriven's avatar
davescriven committed
290
291
292
293
        {
            this._children = new SvgElementCollection(this);
            this._eventHandlers = new EventHandlerList();
            this._elementName = string.Empty;
294
            this._customAttributes = new Dictionary<string, string>();
295
296

            //fill svg attribute description
Tebjan Halm's avatar
Tebjan Halm committed
297
298
299
300
301
302

            var search = TypeDescriptor.GetProperties(this).Cast<MemberDescriptor>()
               .Concat(TypeDescriptor.GetEvents(this).Cast<MemberDescriptor>());


            _svgAttributes = from MemberDescriptor c in search
303
304
305
                            let attribute = a.Attributes[typeof(SvgAttributeAttribute)] as SvgAttributeAttribute
                            where attribute != null
                            select new AttributeTuple { Property = a, Attribute = attribute };
davescriven's avatar
davescriven committed
306
307
        }

308
309
310

		public virtual void InitialiseFromXML(XmlTextReader reader, SvgDocument document)
		{
311
            throw new NotImplementedException();
312
313
314
		}


315
316
317
318
319
        /// <summary>
        /// Renders this element to the <see cref="SvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> that the element should use to render itself.</param>
        public void RenderElement(SvgRenderer renderer)
davescriven's avatar
davescriven committed
320
        {
321
            this.Render(renderer);
davescriven's avatar
davescriven committed
322
323
324
325
326
327
328
329
330
331
332
333
        }

        public void WriteElement(XmlTextWriter writer)
        {
            this.Write(writer);
        }

        protected virtual void WriteStartElement(XmlTextWriter writer)
        {
            if (this.ElementName != String.Empty)
            {
                writer.WriteStartElement(this.ElementName);
Tebjan Halm's avatar
Tebjan Halm committed
334
335
                if (this.ElementName == "svg")
                {
336
337
338
339
340
341
342
343
344
					foreach (var ns in SvgAttributeAttribute.Namespaces)
					{
						if (string.IsNullOrEmpty(ns.Key))
							writer.WriteAttributeString("xmlns", ns.Value);
						else
							writer.WriteAttributeString("xmlns:" + ns.Key, ns.Value);
					}
					writer.WriteAttributeString("version", "1.1");
				}
davescriven's avatar
davescriven committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
            }
            this.WriteAttributes(writer);
        }

        protected virtual void WriteEndElement(XmlTextWriter writer)
        {
            if (this.ElementName != String.Empty)
            {
                writer.WriteEndElement();
            }
        }

        protected virtual void WriteAttributes(XmlTextWriter writer)
        {
359
            foreach (var attr in _svgAttributes)
360
361
362
363
364
            {
                if (attr.Property.Converter.CanConvertTo(typeof(string)))
                {
                    object propertyValue = attr.Property.GetValue(this);

365
366
367
                    var forceWrite = false;
                    if ((attr.Attribute.Name == "fill") && (Parent != null))
                    {
368
369
                        object parentValue;
                        if (TryResolveParentAttributeValue(attr.Attribute.Name, out parentValue))
370
                        {
371
372
                            if ((parentValue == propertyValue) 
                                || ((parentValue != null) &&  parentValue.Equals(propertyValue)))
373
                                continue;
374
                            
375
376
377
378
                            forceWrite = true;
                        }
                    }

379
380
                    if (propertyValue != null)
                    {
Tebjan Halm's avatar
Tebjan Halm committed
381
                        var type = propertyValue.GetType();
382
                        string value = (string)attr.Property.Converter.ConvertTo(propertyValue, typeof(string));
Tebjan Halm's avatar
Tebjan Halm committed
383

384
                        if (!SvgDefaults.IsDefault(attr.Attribute.Name, value) || forceWrite)
Tebjan Halm's avatar
Tebjan Halm committed
385
                        {
386
                            writer.WriteAttributeString(attr.Attribute.NamespaceAndName, value);
Tebjan Halm's avatar
Tebjan Halm committed
387
388
389
390
                        }
                    }
                    else if(attr.Attribute.Name == "fill") //if fill equals null, write 'none'
                    {
391
392
                        string value = (string)attr.Property.Converter.ConvertTo(propertyValue, typeof(string));
                        writer.WriteAttributeString(attr.Attribute.NamespaceAndName, value);
393
394
395
                    }
                }
            }
396
397
398
399
400
401

            //add the custom attributes
            foreach (var item in this._customAttributes)
            {
                writer.WriteAttributeString(item.Key, item.Value);
            }
402
403
        }

404
        private bool TryResolveParentAttributeValue(string attributeKey, out object parentAttributeValue)
405
        {
406
            parentAttributeValue = null;
407

408
            attributeKey = char.ToUpper(attributeKey[0]) + attributeKey.Substring(1);
409
410

            var currentParent = Parent;
411
            var resolved = false;
412
413
414
415
            while (currentParent != null)
            {
                if (currentParent.Attributes.ContainsKey(attributeKey))
                {
416
417
418
                    resolved = true;
                    parentAttributeValue = currentParent.Attributes[attributeKey];
                    if (parentAttributeValue != null)
419
420
421
422
                        break;
                }
                currentParent = currentParent.Parent;
            }
423

424
            return resolved;
davescriven's avatar
davescriven committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        }

        protected virtual void Write(XmlTextWriter writer)
        {
            if (this.ElementName != String.Empty)
            {
                this.WriteStartElement(writer);
                this.WriteChildren(writer);
                this.WriteEndElement(writer);
            }
        }

        protected virtual void WriteChildren(XmlTextWriter writer)
        {
Tebjan Halm's avatar
Tebjan Halm committed
439
440
441
442
443
            //write the content
            if(!String.IsNullOrEmpty(this.Content))
                writer.WriteString(this.Content);

            //write all children
davescriven's avatar
davescriven committed
444
445
446
447
448
449
450
            foreach (SvgElement child in this.Children)
            {
                child.Write(writer);
            }
        }

        /// <summary>
451
        /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="SvgRenderer"/> object.
davescriven's avatar
davescriven committed
452
        /// </summary>
453
454
        /// <param name="renderer">The <see cref="SvgRenderer"/> object to render to.</param>
        protected virtual void Render(SvgRenderer renderer)
davescriven's avatar
davescriven committed
455
        {
456
457
458
            this.PushTransforms(renderer);
            this.RenderChildren(renderer);
            this.PopTransforms(renderer);
davescriven's avatar
davescriven committed
459
460
        }

461
462
463
464
465
        /// <summary>
        /// Renders the children of this <see cref="SvgElement"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> to render the child <see cref="SvgElement"/>s to.</param>
        protected virtual void RenderChildren(SvgRenderer renderer)
davescriven's avatar
davescriven committed
466
467
468
        {
            foreach (SvgElement element in this.Children)
            {
469
                element.Render(renderer);
davescriven's avatar
davescriven committed
470
471
472
            }
        }

473
474
475
476
477
        /// <summary>
        /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="SvgRenderer"/> object.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> object to render to.</param>
        void ISvgElement.Render(SvgRenderer renderer)
davescriven's avatar
davescriven committed
478
        {
479
            this.Render(renderer);
davescriven's avatar
davescriven committed
480
        }
Tebjan Halm's avatar
Tebjan Halm committed
481
482
483
484
485
486
487
488
        
        /// <summary>
        /// Recursive method to add up the paths of all children
        /// </summary>
        /// <param name="elem"></param>
        /// <param name="path"></param>
        protected void AddPaths(SvgElement elem, GraphicsPath path)
        {
Tebjan Halm's avatar
Tebjan Halm committed
489
        	foreach(var child in elem.Children)
Tebjan Halm's avatar
Tebjan Halm committed
490
        	{
Tebjan Halm's avatar
Tebjan Halm committed
491
        		if (child is SvgVisualElement)
Tebjan Halm's avatar
Tebjan Halm committed
492
        		{
Tebjan Halm's avatar
Tebjan Halm committed
493
        			if(!(child is SvgGroup))
494
        			{
Tebjan Halm's avatar
Tebjan Halm committed
495
        				var childPath = ((SvgVisualElement)child).Path;
496
        				
Tebjan Halm's avatar
Tebjan Halm committed
497
498
499
500
501
502
503
504
        				if (childPath != null)
        				{
        					childPath = (GraphicsPath)childPath.Clone();
        					if(child.Transforms != null)
        						childPath.Transform(child.Transforms.GetMatrix());
        					
        					path.AddPath(childPath, false);
        				}
505
        			}
Tebjan Halm's avatar
Tebjan Halm committed
506
        		}
Tebjan Halm's avatar
Tebjan Halm committed
507
        			
Tebjan Halm's avatar
Tebjan Halm committed
508
        		AddPaths(child, path);
Tebjan Halm's avatar
Tebjan Halm committed
509
        	}
Tebjan Halm's avatar
Tebjan Halm committed
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
        }
        
        /// <summary>
        /// Recursive method to add up the paths of all children
        /// </summary>
        /// <param name="elem"></param>
        /// <param name="path"></param>
        protected GraphicsPath GetPaths(SvgElement elem)
        {
        	var ret = new GraphicsPath();
        	
        	foreach(var child in elem.Children)
        	{
        		if (child is SvgVisualElement)
        		{
        			if(!(child is SvgGroup))
        			{
        				var childPath = ((SvgVisualElement)child).Path;
        				
        				if (childPath != null)
        				{
        					childPath = (GraphicsPath)childPath.Clone();
        					if(child.Transforms != null)
        						childPath.Transform(child.Transforms.GetMatrix());
        					
        					ret.AddPath(childPath, false);
        				}
        			}
        			else
        			{
        				var childPath = GetPaths(child);
        				if(child.Transforms != null)
        					childPath.Transform(child.Transforms.GetMatrix());
        			}
        		}
        			
        	}
Tebjan Halm's avatar
Tebjan Halm committed
547
        	
Tebjan Halm's avatar
Tebjan Halm committed
548
        	return ret;
Tebjan Halm's avatar
Tebjan Halm committed
549
        }
davescriven's avatar
davescriven committed
550

551
552
553
554
555
556
        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
davescriven's avatar
davescriven committed
557
558
559
560
        public virtual object Clone()
        {
            return this.MemberwiseClone();
        }
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585

    	public abstract SvgElement DeepCopy();

		public virtual SvgElement DeepCopy<T>() where T : SvgElement, new()
		{
			var newObj = new T();
			newObj.Content = this.Content;
			newObj.ElementName = this.ElementName;
//			if (this.Parent != null)
	//			this.Parent.Children.Add(newObj);

			if (this.Transforms != null)
			{
				newObj.Transforms = new SvgTransformCollection();
				foreach (var transform in this.Transforms)
					newObj.Transforms.Add(transform.Clone() as SvgTransform);
			}

			foreach (var child in this.Children)
			{
				newObj.Children.Add(child.DeepCopy());
			}
				

			return newObj;
Tebjan Halm's avatar
Tebjan Halm committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
        }

        #region graphical EVENTS

        /*  
            onfocusin = "<anything>"
            onfocusout = "<anything>"
            onactivate = "<anything>"
            onclick = "<anything>"
            onmousedown = "<anything>"
            onmouseup = "<anything>"
            onmouseover = "<anything>"
            onmousemove = "<anything>"
            onmouseout = "<anything>" 
         */

        [SvgAttribute("onclick")]
        public event EventHandler<MouseArg> Click;

        protected void OnClick(float x, float y, int button)
        {
            var handler = Click;
            if(handler != null)
            {
                handler(this, new MouseArg { x=x, y=y, button=button});
            }
        }



        #endregion graphical EVENTS

    }

    /// <summary>
    /// Represents the state of the mouse at the moment the event occured.
    /// </summary>
    public class MouseArg : EventArgs
    {
        public float x;
        public float y;

        /// <summary>
        /// 0 = left, 1 = middle, 2 = right
        /// </summary>
        public int button;
davescriven's avatar
davescriven committed
632
633
634
635
    }

    internal interface ISvgElement
    {
636
637
638
		SvgElement Parent {get;}
		SvgElementCollection Children { get; }

639
        void Render(SvgRenderer renderer);
davescriven's avatar
davescriven committed
640
641
    }
}