forked from svg-net/SVG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSvgElement.cs
1191 lines (1056 loc) · 43.2 KB
/
SvgElement.cs
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Xml;
using Svg.Transforms;
namespace Svg
{
/// <summary>
/// The base class of which all SVG elements are derived from.
/// </summary>
public abstract partial class SvgElement : ISvgElement, ISvgTransformable, ICloneable, ISvgNode
{
internal const int StyleSpecificity_PresAttribute = 0;
internal const int StyleSpecificity_InlineStyle = 1 << 16;
internal SvgElement _parent;
private string _elementName;
private SvgAttributeCollection _attributes;
private EventHandlerList _eventHandlers;
private SvgElementCollection _children;
private static readonly object _loadEventKey = new object();
private SvgCustomAttributeCollection _customAttributes;
private List<ISvgNode> _nodes = new List<ISvgNode>();
private Dictionary<string, SortedDictionary<int, string>> _styles = new Dictionary<string, SortedDictionary<int, string>>();
/// <summary>
/// Add style.
/// </summary>
/// <param name="name">The style name.</param>
/// <param name="value">The style value.</param>
/// <param name="specificity">The specificity value.</param>
public void AddStyle(string name, string value, int specificity)
{
if (!_styles.TryGetValue(name, out SortedDictionary<int, string> rules))
{
rules = new SortedDictionary<int, string>();
_styles[name] = rules;
}
while (rules.ContainsKey(specificity)) ++specificity;
rules[specificity] = value;
}
/// <summary>
/// Flush styles.
/// </summary>
/// <param name="children">If true, flush styles to the children.</param>
public void FlushStyles(bool children = false)
{
FlushStyles();
if (children)
foreach (var child in Children)
child.FlushStyles(children);
}
private void FlushStyles()
{
if (_styles.Any())
{
var styles = new Dictionary<string, SortedDictionary<int, string>>();
foreach (var s in _styles)
if (!SvgElementFactory.SetPropertyValue(this, string.Empty, s.Key, s.Value.Last().Value, OwnerDocument, true))
styles.Add(s.Key, s.Value);
_styles = styles;
}
}
public bool ContainsAttribute(string name)
{
return (this.Attributes.ContainsKey(name) || this.CustomAttributes.ContainsKey(name) ||
(_styles.TryGetValue(name, out SortedDictionary<int, string> rules))
&& (rules.ContainsKey(StyleSpecificity_InlineStyle) || rules.ContainsKey(StyleSpecificity_PresAttribute)));
}
public bool TryGetAttribute(string name, out string value)
{
if (this.Attributes.TryGetValue(name, out object objValue))
{
value = objValue.ToString();
return true;
}
if (this.CustomAttributes.TryGetValue(name, out value)) return true;
if (_styles.TryGetValue(name, out SortedDictionary<int, string> rules))
{
// Get staged styles that are
if (rules.TryGetValue(StyleSpecificity_InlineStyle, out value)) return true;
if (rules.TryGetValue(StyleSpecificity_PresAttribute, out value)) return true;
}
return false;
}
protected internal static HttpClient HttpClient { get; } = new HttpClient();
/// <summary>
/// Gets the namespaces that element has.
/// </summary>
/// <value>Key is prefix and value is namespace.</value>
public Dictionary<string, string> Namespaces { get; } = new Dictionary<string, string>();
/// <summary>
/// Gets the elements namespace as a string.
/// </summary>
protected internal string ElementNamespace { get; protected set; } = SvgNamespaces.SvgNamespace;
/// <summary>
/// Gets the name of the element.
/// </summary>
protected internal string ElementName
{
get
{
if (string.IsNullOrEmpty(this._elementName))
{
// There is special case for SvgDocument as valid attribute is only set on SvgFragment.
if (SvgElements.ElementNames.TryGetValue(this.GetType(), out var elementName))
{
this._elementName = elementName;
}
else if (this is SvgDocument)
{
// The SvgDocument does not have SvgElement attribute set, instead the attitude is used on SvgFragment so there would be duplicate im dictionary.
// The SvgDocument is not valid Svg element (that is SvgFragment) and is mainly used as abstraction for document reading and writing.
// The ElementName for SvgDocument is set explicitly here as that is the exception to attribute convention used across the codebase.
this._elementName = "svg";
}
}
return this._elementName;
}
internal set { this._elementName = value; }
}
/// <summary>
/// Gets or sets the color <see cref="SvgPaintServer"/> of this element which drives the currentColor property.
/// </summary>
[SvgAttribute("color")]
public virtual SvgPaintServer Color
{
get { return GetAttribute("color", true, SvgPaintServer.NotSet); }
set { Attributes["color"] = value; }
}
/// <summary>
/// Gets or sets the content of the element.
/// </summary>
private string _content;
public virtual string Content
{
get
{
return _content;
}
set
{
if (_content != null)
{
var oldVal = _content;
_content = value;
if (_content != oldVal)
OnContentChanged(new ContentEventArgs { Content = value });
}
else
{
_content = value;
OnContentChanged(new ContentEventArgs { Content = value });
}
}
}
/// <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="SvgElement"/> objects.
/// </summary>
public virtual SvgElementCollection Children
{
get { return this._children; }
}
public IList<ISvgNode> Nodes
{
get { return this._nodes; }
}
public IEnumerable<SvgElement> Descendants()
{
return this.AsEnumerable().Descendants();
}
private IEnumerable<SvgElement> AsEnumerable()
{
yield return this;
}
/// <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; }
}
public IEnumerable<SvgElement> Parents
{
get
{
var curr = this;
while (curr.Parent != null)
{
curr = curr.Parent;
yield return curr;
}
}
}
public IEnumerable<SvgElement> ParentsAndSelf
{
get
{
var curr = this;
yield return curr;
while (curr.Parent != null)
{
curr = curr.Parent;
yield return curr;
}
}
}
/// <summary>
/// Gets the owner <see cref="SvgDocument"/>.
/// </summary>
public virtual SvgDocument OwnerDocument
{
get
{
if (this is SvgDocument)
{
return this as SvgDocument;
}
else
{
if (this.Parent != null)
return Parent.OwnerDocument;
else
return null;
}
}
}
/// <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;
}
}
protected bool Writing { get; set; }
protected internal TAttributeType GetAttribute<TAttributeType>(string attributeName, bool inherited, TAttributeType defaultValue = default(TAttributeType))
{
if (Writing)
return Attributes.GetAttribute(attributeName, defaultValue);
else
return Attributes.GetInheritedAttribute(attributeName, inherited, defaultValue);
}
/// <summary>
/// Gets a collection of custom attributes
/// </summary>
public SvgCustomAttributeCollection CustomAttributes
{
get { return this._customAttributes; }
}
/// <summary>
/// Gets or sets the element transforms.
/// </summary>
/// <value>The transforms.</value>
[SvgAttribute("transform")]
public SvgTransformCollection Transforms
{
get { return GetAttribute<SvgTransformCollection>("transform", false); }
set
{
var old = Transforms;
if (old != null)
old.TransformChanged -= Attributes_AttributeChanged;
value.TransformChanged += Attributes_AttributeChanged;
Attributes["transform"] = 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 GetAttribute<string>("id", false); }
set { SetAndForceUniqueID(value, false); }
}
/// <summary>
/// Gets or sets the space handling.
/// </summary>
/// <value>The space handling.</value>
[SvgAttribute("space", SvgAttributeAttribute.XmlNamespace)]
public virtual XmlSpaceHandling SpaceHandling
{
get { return GetAttribute("space", true, XmlSpaceHandling.Inherit); }
set { Attributes["space"] = value; }
}
public void SetAndForceUniqueID(string value, bool autoForceUniqueID = true, Action<SvgElement, string, string> logElementOldIDNewID = null)
{
// Don't do anything if it hasn't changed
if (string.Compare(ID, value) == 0)
{
return;
}
if (OwnerDocument != null)
{
OwnerDocument.IdManager.Remove(this);
}
Attributes["id"] = value;
if (OwnerDocument != null)
{
OwnerDocument.IdManager.AddAndForceUniqueID(this, null, autoForceUniqueID, logElementOldIDNewID);
}
}
/// <summary>
/// Only used by the ID Manager
/// </summary>
/// <param name="newID"></param>
internal void ForceUniqueID(string newID)
{
Attributes["id"] = newID;
}
/// <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>
protected virtual void AddElement(SvgElement child, int index)
{
}
/// <summary>
/// Fired when an Element was added to the children of this Element
/// </summary>
public event EventHandler<ChildAddedEventArgs> ChildAdded;
/// <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>
internal void OnElementAdded(SvgElement child, int index)
{
this.AddElement(child, index);
SvgElement sibling = null;
if (index < (Children.Count - 1))
{
sibling = Children[index + 1];
}
var handler = ChildAdded;
if (handler != null)
{
handler(this, new ChildAddedEventArgs { NewChild = child, BeforeSibling = sibling });
}
}
/// <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>
protected virtual void RemoveElement(SvgElement child)
{
}
/// <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>
internal void OnElementRemoved(SvgElement child)
{
this.RemoveElement(child);
}
/// <summary>
/// Initializes a new instance of the <see cref="SvgElement"/> class.
/// </summary>
public SvgElement()
{
this._children = new SvgElementCollection(this);
this._eventHandlers = new EventHandlerList();
this._elementName = string.Empty;
this._customAttributes = new SvgCustomAttributeCollection(this);
//subscribe to attribute events
Attributes.AttributeChanged += Attributes_AttributeChanged;
CustomAttributes.AttributeChanged += Attributes_AttributeChanged;
}
//dispatch attribute event
void Attributes_AttributeChanged(object sender, AttributeEventArgs e)
{
OnAttributeChanged(e);
}
public virtual void InitialiseFromXML(XmlReader reader, SvgDocument document)
{
throw new NotImplementedException();
}
/// <summary>Derived classes may decide that the element should not be written. For example, the text element shouldn't be written if it's empty.</summary>
public virtual bool ShouldWriteElement()
{
//Write any element who has a name.
return !string.IsNullOrEmpty(this.ElementName);
}
protected virtual void WriteStartElement(XmlWriter writer)
{
if (!string.IsNullOrEmpty(this.ElementName))
{
if (string.IsNullOrEmpty(this.ElementNamespace))
writer.WriteStartElement(this.ElementName);
else
{
var prefix = writer.LookupPrefix(this.ElementNamespace);
if (prefix == null && !this.ElementNamespace.Equals(SvgNamespaces.SvgNamespace))
{
foreach (var kvp in this.Namespaces)
{
if (kvp.Value.Equals(this.ElementNamespace) && !string.IsNullOrEmpty(kvp.Key))
{
prefix = kvp.Key;
break;
}
}
}
if (prefix == null)
writer.WriteStartElement(this.ElementName, this.ElementNamespace);
else
writer.WriteStartElement(prefix, this.ElementName, this.ElementNamespace);
}
}
this.WriteAttributes(writer);
}
protected virtual void WriteEndElement(XmlWriter writer)
{
if (!string.IsNullOrEmpty(this.ElementName))
{
writer.WriteEndElement();
}
}
protected virtual void WriteAttributes(XmlWriter writer)
{
// namespaces
foreach (var ns in Namespaces)
{
if (ns.Value.Equals(SvgNamespaces.SvgNamespace) && !string.IsNullOrEmpty(ns.Key))
continue;
writer.WriteAttributeString("xmlns", ns.Key, null, ns.Value);
}
// properties
var styles = WritePropertyAttributes(writer);
// events
if (AutoPublishEvents)
{
foreach (var property in this.GetProperties().Where(x => x.DescriptorType == DescriptorType.Event))
{
var evt = property.GetValue(this);
// if someone has registered publish the attribute
if (evt != null && !string.IsNullOrEmpty(this.ID))
{
string evtValue = this.ID + "/" + property.AttributeName;
WriteAttributeString(writer, property.AttributeName, null, evtValue);
}
}
}
// add the custom attributes
var additionalStyleValue = string.Empty;
foreach (var item in this._customAttributes)
{
if (item.Key.Equals("style") && styles.Any())
{
additionalStyleValue = item.Value;
continue;
}
var index = item.Key.LastIndexOf(":");
if (index >= 0)
{
var ns = item.Key.Substring(0, index);
var localName = item.Key.Substring(index + 1);
WriteAttributeString(writer, localName, ns, item.Value);
}
else
WriteAttributeString(writer, item.Key, null, item.Value);
}
// write the style property
if (styles.Any())
{
var styleValues = styles.Select(s => s.Key + ":" + s.Value)
.Concat(Enumerable.Repeat(additionalStyleValue, 1));
WriteAttributeString(writer, "style", null, string.Join(";", styleValues));
}
}
private Dictionary<string, string> WritePropertyAttributes(XmlWriter writer)
{
var styles = _styles.ToDictionary(_styles => _styles.Key, _styles => _styles.Value.Last().Value);
var opacityAttributes = new List<ISvgPropertyDescriptor>();
var opacityValues = new Dictionary<string, float>();
try
{
Writing = true;
foreach (var property in this.GetProperties())
{
if (property.Converter == null)
{
continue;
}
if (property.Converter.CanConvertTo(typeof(string)))
{
if (property.AttributeName == "fill-opacity" || property.AttributeName == "stroke-opacity")
{
opacityAttributes.Add(property);
continue;
}
if (Attributes.ContainsKey(property.AttributeName))
{
var propertyValue = property.GetValue(this);
var forceWrite = false;
var writeStyle = property.AttributeName == "fill" || property.AttributeName == "stroke";
if (Parent != null)
{
if (writeStyle && propertyValue == SvgPaintServer.NotSet)
continue;
if (TryResolveParentAttributeValue(property.AttributeName, out object parentValue))
{
if ((parentValue == propertyValue)
|| ((parentValue != null) && parentValue.Equals(propertyValue)))
{
if (writeStyle)
continue;
}
else
forceWrite = true;
}
}
var hasOpacity = writeStyle;
if (hasOpacity)
{
if (propertyValue is SvgColourServer && ((SvgColourServer)propertyValue).Colour.A < 255)
{
var opacity = ((SvgColourServer)propertyValue).Colour.A / 255f;
opacityValues.Add(property.AttributeName + "-opacity", opacity);
}
}
#if NETFULL
var value = (string)property.Converter.ConvertTo(propertyValue, typeof(string));
#else
// dotnetcore throws exception if input is null
var value = propertyValue == null ? null : (string)property.Converter.ConvertTo(propertyValue, typeof(string));
#endif
if (propertyValue != null)
{
//Only write the attribute's value if it is not the default value, not null/empty, or we're forcing the write.
if (forceWrite || !string.IsNullOrEmpty(value))
{
if (writeStyle)
{
styles[property.AttributeName] = value;
}
else
{
WriteAttributeString(writer, property.AttributeName, property.AttributeNamespace, value);
}
}
}
else if (property.AttributeName == "fill") //if fill equals null, write 'none'
{
if (writeStyle)
{
styles[property.AttributeName] = value;
}
else
{
WriteAttributeString(writer, property.AttributeName, property.AttributeNamespace, value);
}
}
}
}
}
foreach (var property in opacityAttributes)
{
var opacity = 1f;
var write = false;
var key = property.AttributeName;
if (opacityValues.ContainsKey(key))
{
opacity = opacityValues[key];
write = true;
}
if (Attributes.ContainsKey(key))
{
opacity *= (float)property.GetValue(this);
write = true;
}
if (write)
{
opacity = (float)Math.Round(opacity, 2, MidpointRounding.AwayFromZero);
var value = (string)property.Converter.ConvertTo(opacity, typeof(string));
if (!string.IsNullOrEmpty(value))
WriteAttributeString(writer, property.AttributeName, property.AttributeNamespace, value);
}
}
}
finally
{
Writing = false;
}
return styles;
}
private static void WriteAttributeString(XmlWriter writer, string name, string ns, string value)
{
if (string.IsNullOrEmpty(ns))
writer.WriteAttributeString(name, value);
else
{
var prefix = writer.LookupPrefix(ns);
if (prefix != null)
ns = null;
writer.WriteAttributeString(prefix, name, ns, value);
}
}
public bool AutoPublishEvents = true;
private bool TryResolveParentAttributeValue(string attributeKey, out object parentAttributeValue)
{
parentAttributeValue = null;
//attributeKey = char.ToUpper(attributeKey[0]) + attributeKey.Substring(1);
var currentParent = Parent;
var resolved = false;
while (currentParent != null)
{
if (currentParent.Attributes.ContainsKey(attributeKey))
{
resolved = true;
parentAttributeValue = currentParent.Attributes[attributeKey];
if (parentAttributeValue != null)
break;
}
currentParent = currentParent.Parent;
}
return resolved;
}
/// <summary>
/// Write this SvgElement out using a given XmlWriter.
/// </summary>
/// <param name="writer">The XmlWriter to use.</param>
/// <remarks>
/// Recommendation is to create an XmlWriter by calling a factory method,<br/>
/// e.g. <see cref="XmlWriter.Create(System.IO.Stream)"/>,
/// as per <a href="https://docs.microsoft.com/dotnet/api/system.xml.xmltextwriter#remarks">Microsoft documentation</a>.<br/>
/// <br/>
/// However, unlike an <see cref="XmlTextWriter"/> created via 'new XmlTextWriter()',<br/>
/// a factory-constructed XmlWriter will not flush output until it is closed<br/>
/// (normally via a using statement), or unless the client explicitly calls <see cref="XmlWriter.Flush()"/>.
/// </remarks>
public virtual void Write(XmlWriter writer)
{
if (ShouldWriteElement())
{
this.WriteStartElement(writer);
this.WriteChildren(writer);
this.WriteEndElement(writer);
}
}
protected virtual void WriteChildren(XmlWriter writer)
{
if (this.Nodes.Any())
{
SvgContentNode content;
foreach (var node in this.Nodes)
{
content = node as SvgContentNode;
if (content == null)
{
((SvgElement)node).Write(writer);
}
else if (!string.IsNullOrEmpty(content.Content))
{
writer.WriteString(content.Content);
}
}
}
else
{
//write the content
if (!String.IsNullOrEmpty(this.Content))
writer.WriteString(this.Content);
//write all children
foreach (SvgElement child in this.Children)
{
child.Write(writer);
}
}
}
/// <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>
public virtual object Clone()
{
return DeepCopy();
}
public abstract SvgElement DeepCopy();
ISvgNode ISvgNode.DeepCopy()
{
return DeepCopy();
}
public virtual SvgElement DeepCopy<T>() where T : SvgElement, new()
{
var newObj = new T
{
Content = Content,
ElementName = ElementName
};
//if (this.Parent != null)
// this.Parent.Children.Add(newObj);
foreach (var attribute in Attributes)
{
var value = attribute.Value is ICloneable ? ((ICloneable)attribute.Value).Clone() : attribute.Value;
newObj.Attributes.Add(attribute.Key, value);
}
foreach (var child in Children)
newObj.Children.Add(child.DeepCopy());
foreach (var property in this.GetProperties().Where(x => x.DescriptorType == DescriptorType.Event))
{
var evt = property.GetValue(this);
// if someone has registered also register here
if (evt != null)
{
if (property.AttributeName == "MouseDown")
newObj.MouseDown += delegate { };
else if (property.AttributeName == "MouseUp")
newObj.MouseUp += delegate { };
else if (property.AttributeName == "MouseOver")
newObj.MouseOver += delegate { };
else if (property.AttributeName == "MouseOut")
newObj.MouseOut += delegate { };
else if (property.AttributeName == "MouseMove")
newObj.MouseMove += delegate { };
else if (property.AttributeName == "MouseScroll")
newObj.MouseScroll += delegate { };
else if (property.AttributeName == "Click")
newObj.Click += delegate { };
else if (property.AttributeName == "Change") // text element
(newObj as SvgText).Change += delegate { };
}
}
foreach (var attribute in CustomAttributes)
newObj.CustomAttributes.Add(attribute.Key, attribute.Value);
foreach (var node in Nodes)
{
if (node is SvgElement)
{
var index = Children.IndexOf((SvgElement)node);
if (index >= 0)
{
newObj.Nodes.Add(newObj.Children[index]);
continue;
}
}
newObj.Nodes.Add(node.DeepCopy());
}
foreach (var style in _styles)
foreach (var pair in style.Value)
newObj.AddStyle(style.Key, pair.Value, pair.Key);
return newObj;
}
/// <summary>
/// Fired when an Attribute of this Element has changed
/// </summary>
public event EventHandler<AttributeEventArgs> AttributeChanged;
protected void OnAttributeChanged(AttributeEventArgs args)
{
var handler = AttributeChanged;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Fired when an Attribute of this Element has changed
/// </summary>
public event EventHandler<ContentEventArgs> ContentChanged;
protected void OnContentChanged(ContentEventArgs args)
{
var handler = ContentChanged;
if (handler != null)
{
handler(this, args);
}
}
#region graphical EVENTS
/*
onfocusin = "<anything>"
onfocusout = "<anything>"
onactivate = "<anything>"
onclick = "<anything>"
onmousedown = "<anything>"
onmouseup = "<anything>"
onmouseover = "<anything>"
onmousemove = "<anything>"
onmouseout = "<anything>"
*/
/// <summary>
/// Use this method to provide your implementation ISvgEventCaller which can register Actions
/// and call them if one of the events occurs. Make sure, that your SvgElement has a unique ID.
/// The SvgTextElement overwrites this and registers the Change event tor its text content.
/// </summary>
/// <param name="caller"></param>
public virtual void RegisterEvents(ISvgEventCaller caller)
{
if (caller != null && !string.IsNullOrEmpty(this.ID))
{
var rpcID = this.ID + "/";
caller.RegisterAction(rpcID + "onclick", CreateMouseEventAction(RaiseMouseClick));
caller.RegisterAction(rpcID + "onmousedown", CreateMouseEventAction(RaiseMouseDown));
caller.RegisterAction(rpcID + "onmouseup", CreateMouseEventAction(RaiseMouseUp));
caller.RegisterAction(rpcID + "onmousemove", CreateMouseEventAction(RaiseMouseMove));
caller.RegisterAction(rpcID + "onmouseover", CreateMouseEventAction(RaiseMouseOver));
caller.RegisterAction(rpcID + "onmouseout", CreateMouseEventAction(RaiseMouseOut));
caller.RegisterAction<int, bool, bool, bool, string>(rpcID + "onmousescroll", OnMouseScroll);
}
}
/// <summary>
/// Use this method to provide your implementation ISvgEventCaller to unregister Actions
/// </summary>
/// <param name="caller"></param>
public virtual void UnregisterEvents(ISvgEventCaller caller)
{
if (caller != null && !string.IsNullOrEmpty(this.ID))
{
var rpcID = this.ID + "/";
caller.UnregisterAction(rpcID + "onclick");
caller.UnregisterAction(rpcID + "onmousedown");
caller.UnregisterAction(rpcID + "onmouseup");
caller.UnregisterAction(rpcID + "onmousemove");
caller.UnregisterAction(rpcID + "onmousescroll");
caller.UnregisterAction(rpcID + "onmouseover");
caller.UnregisterAction(rpcID + "onmouseout");
}
}
[SvgAttribute("onclick")]
public event EventHandler<MouseArg> Click;
[SvgAttribute("onmousedown")]
public event EventHandler<MouseArg> MouseDown;
[SvgAttribute("onmouseup")]
public event EventHandler<MouseArg> MouseUp;
[SvgAttribute("onmousemove")]
public event EventHandler<MouseArg> MouseMove;
[SvgAttribute("onmousescroll")]
public event EventHandler<MouseScrollArg> MouseScroll;
[SvgAttribute("onmouseover")]
public event EventHandler<MouseArg> MouseOver;
[SvgAttribute("onmouseout")]
public event EventHandler<MouseArg> MouseOut;
protected Action<float, float, int, int, bool, bool, bool, string> CreateMouseEventAction(Action<object, MouseArg> eventRaiser)
{
return (x, y, button, clickCount, altKey, shiftKey, ctrlKey, sessionID) =>
eventRaiser(this, new MouseArg { x = x, y = y, Button = button, ClickCount = clickCount, AltKey = altKey, ShiftKey = shiftKey, CtrlKey = ctrlKey, SessionID = sessionID });
}
//click
protected void RaiseMouseClick(object sender, MouseArg e)
{
var handler = Click;
if (handler != null)
{
handler(sender, e);
}
}
//down
protected void RaiseMouseDown(object sender, MouseArg e)
{
var handler = MouseDown;
if (handler != null)
{
handler(sender, e);
}
}
//up