SvgElement.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.Drawing.Drawing2D;
  6. using System.Xml;
  7. using System.Linq;
  8. using Svg.Transforms;
  9. using System.Reflection;
  10. using System.Threading;
  11. using System.Globalization;
  12. #pragma warning disable
  13. namespace Svg
  14. {
  15. /// <summary>
  16. /// The base class of which all SVG elements are derived from.
  17. /// </summary>
  18. public abstract partial class SvgElement : ISvgElement, ISvgTransformable, ICloneable, ISvgNode
  19. {
  20. internal const int StyleSpecificity_PresAttribute = 0;
  21. internal const int StyleSpecificity_InlineStyle = 1 << 16;
  22. //optimization
  23. protected class PropertyAttributeTuple
  24. {
  25. public PropertyDescriptor Property;
  26. public SvgAttributeAttribute Attribute;
  27. }
  28. protected class EventAttributeTuple
  29. {
  30. public FieldInfo Event;
  31. public SvgAttributeAttribute Attribute;
  32. }
  33. //reflection cache
  34. private IEnumerable<PropertyAttributeTuple> _svgPropertyAttributes;
  35. private IEnumerable<EventAttributeTuple> _svgEventAttributes;
  36. internal SvgElement _parent;
  37. private string _elementName;
  38. private SvgAttributeCollection _attributes;
  39. private EventHandlerList _eventHandlers;
  40. private SvgElementCollection _children;
  41. private static readonly object _loadEventKey = new object();
  42. private Region _graphicsClip;
  43. private Matrix _graphicsMatrix;
  44. private SvgCustomAttributeCollection _customAttributes;
  45. private List<ISvgNode> _nodes = new List<ISvgNode>();
  46. private Dictionary<string, SortedDictionary<int, string>> _styles = new Dictionary<string, SortedDictionary<int, string>>();
  47. public void AddStyle(string name, string value, int specificity)
  48. {
  49. SortedDictionary<int, string> rules;
  50. if (!_styles.TryGetValue(name, out rules))
  51. {
  52. rules = new SortedDictionary<int, string>();
  53. _styles[name] = rules;
  54. }
  55. while (rules.ContainsKey(specificity)) specificity++;
  56. rules[specificity] = value;
  57. }
  58. public void FlushStyles()
  59. {
  60. foreach (var s in _styles)
  61. {
  62. SvgElementFactory.SetPropertyValue(this, s.Key, s.Value.Last().Value, this.OwnerDocument);
  63. }
  64. _styles = null;
  65. }
  66. public bool ContainsAttribute(string name)
  67. {
  68. SortedDictionary<int, string> rules;
  69. return (this.Attributes.ContainsKey(name) || this.CustomAttributes.ContainsKey(name) ||
  70. (_styles != null && _styles.TryGetValue(name, out rules)) && (rules.ContainsKey(StyleSpecificity_InlineStyle) || rules.ContainsKey(StyleSpecificity_PresAttribute)));
  71. }
  72. public bool TryGetAttribute(string name, out string value)
  73. {
  74. object objValue;
  75. if (this.Attributes.TryGetValue(name, out objValue))
  76. {
  77. value = objValue.ToString();
  78. return true;
  79. }
  80. if (this.CustomAttributes.TryGetValue(name, out value)) return true;
  81. SortedDictionary<int, string> rules;
  82. if (_styles != null && _styles.TryGetValue(name, out rules))
  83. {
  84. // Get staged styles that are
  85. if (rules.TryGetValue(StyleSpecificity_InlineStyle, out value)) return true;
  86. if (rules.TryGetValue(StyleSpecificity_PresAttribute, out value)) return true;
  87. }
  88. return false;
  89. }
  90. /// <summary>
  91. /// Gets the name of the element.
  92. /// </summary>
  93. protected internal string ElementName
  94. {
  95. get
  96. {
  97. if (string.IsNullOrEmpty(this._elementName))
  98. {
  99. var attr = TypeDescriptor.GetAttributes(this).OfType<SvgElementAttribute>().SingleOrDefault();
  100. if (attr != null)
  101. {
  102. this._elementName = attr.ElementName;
  103. }
  104. }
  105. return this._elementName;
  106. }
  107. internal set { this._elementName = value; }
  108. }
  109. /// <summary>
  110. /// Gets or sets the color <see cref="SvgPaintServer"/> of this element which drives the currentColor property.
  111. /// </summary>
  112. [SvgAttribute("color", true)]
  113. public virtual SvgPaintServer Color
  114. {
  115. get { return (this.Attributes["color"] == null) ? SvgColourServer.NotSet : (SvgPaintServer)this.Attributes["color"]; }
  116. set { this.Attributes["color"] = value; }
  117. }
  118. /// <summary>
  119. /// Gets or sets the content of the element.
  120. /// </summary>
  121. private string _content;
  122. public virtual string Content
  123. {
  124. get
  125. {
  126. return _content;
  127. }
  128. set
  129. {
  130. if (_content != null)
  131. {
  132. var oldVal = _content;
  133. _content = value;
  134. if (_content != oldVal)
  135. OnContentChanged(new ContentEventArgs { Content = value });
  136. }
  137. else
  138. {
  139. _content = value;
  140. OnContentChanged(new ContentEventArgs { Content = value });
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Gets an <see cref="EventHandlerList"/> of all events belonging to the element.
  146. /// </summary>
  147. protected virtual EventHandlerList Events
  148. {
  149. get { return this._eventHandlers; }
  150. }
  151. /// <summary>
  152. /// Occurs when the element is loaded.
  153. /// </summary>
  154. public event EventHandler Load
  155. {
  156. add { this.Events.AddHandler(_loadEventKey, value); }
  157. remove { this.Events.RemoveHandler(_loadEventKey, value); }
  158. }
  159. /// <summary>
  160. /// Gets a collection of all child <see cref="SvgElements"/>.
  161. /// </summary>
  162. public virtual SvgElementCollection Children
  163. {
  164. get { return this._children; }
  165. }
  166. public IList<ISvgNode> Nodes
  167. {
  168. get { return this._nodes; }
  169. }
  170. public IEnumerable<SvgElement> Descendants()
  171. {
  172. return this.AsEnumerable().Descendants();
  173. }
  174. private IEnumerable<SvgElement> AsEnumerable()
  175. {
  176. yield return this;
  177. }
  178. /// <summary>
  179. /// Gets a value to determine whether the element has children.
  180. /// </summary>
  181. public virtual bool HasChildren()
  182. {
  183. return (this.Children.Count > 0);
  184. }
  185. /// <summary>
  186. /// Gets the parent <see cref="SvgElement"/>.
  187. /// </summary>
  188. /// <value>An <see cref="SvgElement"/> if one exists; otherwise null.</value>
  189. public virtual SvgElement Parent
  190. {
  191. get { return this._parent; }
  192. }
  193. public IEnumerable<SvgElement> Parents
  194. {
  195. get
  196. {
  197. var curr = this;
  198. while (curr.Parent != null)
  199. {
  200. curr = curr.Parent;
  201. yield return curr;
  202. }
  203. }
  204. }
  205. public IEnumerable<SvgElement> ParentsAndSelf
  206. {
  207. get
  208. {
  209. var curr = this;
  210. yield return curr;
  211. while (curr.Parent != null)
  212. {
  213. curr = curr.Parent;
  214. yield return curr;
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// Gets the owner <see cref="SvgDocument"/>.
  220. /// </summary>
  221. public virtual SvgDocument OwnerDocument
  222. {
  223. get
  224. {
  225. if (this is SvgDocument)
  226. {
  227. return this as SvgDocument;
  228. }
  229. else
  230. {
  231. if (this.Parent != null)
  232. return Parent.OwnerDocument;
  233. else
  234. return null;
  235. }
  236. }
  237. }
  238. /// <summary>
  239. /// Gets a collection of element attributes.
  240. /// </summary>
  241. protected internal virtual SvgAttributeCollection Attributes
  242. {
  243. get
  244. {
  245. if (this._attributes == null)
  246. {
  247. this._attributes = new SvgAttributeCollection(this);
  248. }
  249. return this._attributes;
  250. }
  251. }
  252. /// <summary>
  253. /// Gets a collection of custom attributes
  254. /// </summary>
  255. public SvgCustomAttributeCollection CustomAttributes
  256. {
  257. get { return this._customAttributes; }
  258. }
  259. private readonly Matrix _zeroMatrix = new Matrix(0, 0, 0, 0, 0, 0);
  260. /// <summary>
  261. /// Applies the required transforms to <see cref="ISvgRenderer"/>.
  262. /// </summary>
  263. /// <param name="renderer">The <see cref="ISvgRenderer"/> to be transformed.</param>
  264. protected internal virtual bool PushTransforms(ISvgRenderer renderer)
  265. {
  266. _graphicsMatrix = renderer.Transform;
  267. _graphicsClip = renderer.GetClip();
  268. // Return if there are no transforms
  269. if (this.Transforms == null || this.Transforms.Count == 0)
  270. {
  271. return true;
  272. }
  273. if (this.Transforms.Count == 1 && this.Transforms[0].Matrix.Equals(_zeroMatrix)) return false;
  274. Matrix transformMatrix = renderer.Transform.Clone();
  275. foreach (SvgTransform transformation in this.Transforms)
  276. {
  277. transformMatrix.Multiply(transformation.Matrix);
  278. }
  279. renderer.Transform = transformMatrix;
  280. return true;
  281. }
  282. /// <summary>
  283. /// Removes any previously applied transforms from the specified <see cref="ISvgRenderer"/>.
  284. /// </summary>
  285. /// <param name="renderer">The <see cref="ISvgRenderer"/> that should have transforms removed.</param>
  286. protected internal virtual void PopTransforms(ISvgRenderer renderer)
  287. {
  288. renderer.Transform = _graphicsMatrix;
  289. _graphicsMatrix = null;
  290. renderer.SetClip(_graphicsClip);
  291. _graphicsClip = null;
  292. }
  293. /// <summary>
  294. /// Applies the required transforms to <see cref="ISvgRenderer"/>.
  295. /// </summary>
  296. /// <param name="renderer">The <see cref="ISvgRenderer"/> to be transformed.</param>
  297. void ISvgTransformable.PushTransforms(ISvgRenderer renderer)
  298. {
  299. this.PushTransforms(renderer);
  300. }
  301. /// <summary>
  302. /// Removes any previously applied transforms from the specified <see cref="ISvgRenderer"/>.
  303. /// </summary>
  304. /// <param name="renderer">The <see cref="ISvgRenderer"/> that should have transforms removed.</param>
  305. void ISvgTransformable.PopTransforms(ISvgRenderer renderer)
  306. {
  307. this.PopTransforms(renderer);
  308. }
  309. /// <summary>
  310. /// Gets or sets the element transforms.
  311. /// </summary>
  312. /// <value>The transforms.</value>
  313. [SvgAttribute("transform")]
  314. public SvgTransformCollection Transforms
  315. {
  316. get { return (this.Attributes.GetAttribute<SvgTransformCollection>("transform")); }
  317. set
  318. {
  319. var old = this.Transforms;
  320. if (old != null)
  321. old.TransformChanged -= Attributes_AttributeChanged;
  322. value.TransformChanged += Attributes_AttributeChanged;
  323. this.Attributes["transform"] = value;
  324. }
  325. }
  326. /// <summary>
  327. /// Gets or sets the ID of the element.
  328. /// </summary>
  329. /// <exception cref="SvgException">The ID is already used within the <see cref="SvgDocument"/>.</exception>
  330. [SvgAttribute("id")]
  331. public string ID
  332. {
  333. get { return this.Attributes.GetAttribute<string>("id"); }
  334. set
  335. {
  336. SetAndForceUniqueID(value, false);
  337. }
  338. }
  339. /// <summary>
  340. /// Gets or sets the space handling.
  341. /// </summary>
  342. /// <value>The space handling.</value>
  343. [SvgAttribute("space", SvgAttributeAttribute.XmlNamespace)]
  344. public virtual XmlSpaceHandling SpaceHandling
  345. {
  346. get { return (this.Attributes["space"] == null) ? XmlSpaceHandling.@default : (XmlSpaceHandling)this.Attributes["space"]; }
  347. set { this.Attributes["space"] = value; }
  348. }
  349. public void SetAndForceUniqueID(string value, bool autoForceUniqueID = true, Action<SvgElement, string, string> logElementOldIDNewID = null)
  350. {
  351. // Don't do anything if it hasn't changed
  352. if (string.Compare(this.ID, value) == 0)
  353. {
  354. return;
  355. }
  356. if (this.OwnerDocument != null)
  357. {
  358. this.OwnerDocument.IdManager.Remove(this);
  359. }
  360. this.Attributes["id"] = value;
  361. if (this.OwnerDocument != null)
  362. {
  363. this.OwnerDocument.IdManager.AddAndForceUniqueID(this, null, autoForceUniqueID, logElementOldIDNewID);
  364. }
  365. }
  366. /// <summary>
  367. /// Only used by the ID Manager
  368. /// </summary>
  369. /// <param name="newID"></param>
  370. internal void ForceUniqueID(string newID)
  371. {
  372. this.Attributes["id"] = newID;
  373. }
  374. /// <summary>
  375. /// Called by the underlying <see cref="SvgElement"/> when an element has been added to the
  376. /// <see cref="Children"/> collection.
  377. /// </summary>
  378. /// <param name="child">The <see cref="SvgElement"/> that has been added.</param>
  379. /// <param name="index">An <see cref="int"/> representing the index where the element was added to the collection.</param>
  380. protected virtual void AddElement(SvgElement child, int index)
  381. {
  382. }
  383. /// <summary>
  384. /// Fired when an Element was added to the children of this Element
  385. /// </summary>
  386. public event EventHandler<ChildAddedEventArgs> ChildAdded;
  387. /// <summary>
  388. /// Calls the <see cref="AddElement"/> method with the specified parameters.
  389. /// </summary>
  390. /// <param name="child">The <see cref="SvgElement"/> that has been added.</param>
  391. /// <param name="index">An <see cref="int"/> representing the index where the element was added to the collection.</param>
  392. internal void OnElementAdded(SvgElement child, int index)
  393. {
  394. this.AddElement(child, index);
  395. SvgElement sibling = null;
  396. if (index < (Children.Count - 1))
  397. {
  398. sibling = Children[index + 1];
  399. }
  400. var handler = ChildAdded;
  401. if (handler != null)
  402. {
  403. handler(this, new ChildAddedEventArgs { NewChild = child, BeforeSibling = sibling });
  404. }
  405. }
  406. /// <summary>
  407. /// Called by the underlying <see cref="SvgElement"/> when an element has been removed from the
  408. /// <see cref="Children"/> collection.
  409. /// </summary>
  410. /// <param name="child">The <see cref="SvgElement"/> that has been removed.</param>
  411. protected virtual void RemoveElement(SvgElement child)
  412. {
  413. }
  414. /// <summary>
  415. /// Calls the <see cref="RemoveElement"/> method with the specified <see cref="SvgElement"/> as the parameter.
  416. /// </summary>
  417. /// <param name="child">The <see cref="SvgElement"/> that has been removed.</param>
  418. internal void OnElementRemoved(SvgElement child)
  419. {
  420. this.RemoveElement(child);
  421. }
  422. /// <summary>
  423. /// Initializes a new instance of the <see cref="SvgElement"/> class.
  424. /// </summary>
  425. public SvgElement()
  426. {
  427. this._children = new SvgElementCollection(this);
  428. this._eventHandlers = new EventHandlerList();
  429. this._elementName = string.Empty;
  430. this._customAttributes = new SvgCustomAttributeCollection(this);
  431. Transforms = new SvgTransformCollection();
  432. //subscribe to attribute events
  433. Attributes.AttributeChanged += Attributes_AttributeChanged;
  434. CustomAttributes.AttributeChanged += Attributes_AttributeChanged;
  435. //find svg attribute descriptions
  436. _svgPropertyAttributes = from PropertyDescriptor a in TypeDescriptor.GetProperties(this)
  437. let attribute = a.Attributes[typeof(SvgAttributeAttribute)] as SvgAttributeAttribute
  438. where attribute != null
  439. select new PropertyAttributeTuple { Property = a, Attribute = attribute };
  440. _svgEventAttributes = from EventDescriptor a in TypeDescriptor.GetEvents(this)
  441. let attribute = a.Attributes[typeof(SvgAttributeAttribute)] as SvgAttributeAttribute
  442. where attribute != null
  443. select new EventAttributeTuple { Event = a.ComponentType.GetField(a.Name, BindingFlags.Instance | BindingFlags.NonPublic), Attribute = attribute };
  444. }
  445. //dispatch attribute event
  446. void Attributes_AttributeChanged(object sender, AttributeEventArgs e)
  447. {
  448. OnAttributeChanged(e);
  449. }
  450. public virtual void InitialiseFromXML(XmlTextReader reader, SvgDocument document)
  451. {
  452. throw new NotImplementedException();
  453. }
  454. /// <summary>
  455. /// Renders this element to the <see cref="ISvgRenderer"/>.
  456. /// </summary>
  457. /// <param name="renderer">The <see cref="ISvgRenderer"/> that the element should use to render itself.</param>
  458. public void RenderElement(ISvgRenderer renderer)
  459. {
  460. this.Render(renderer);
  461. }
  462. /// <summary>Derrived classes may decide that the element should not be written. For example, the text element shouldn't be written if it's empty.</summary>
  463. public virtual bool ShouldWriteElement()
  464. {
  465. //Write any element who has a name.
  466. return (this.ElementName != String.Empty);
  467. }
  468. protected virtual void WriteStartElement(XmlTextWriter writer)
  469. {
  470. if (this.ElementName != String.Empty)
  471. {
  472. writer.WriteStartElement(this.ElementName);
  473. }
  474. this.WriteAttributes(writer);
  475. }
  476. protected virtual void WriteEndElement(XmlTextWriter writer)
  477. {
  478. if (this.ElementName != String.Empty)
  479. {
  480. writer.WriteEndElement();
  481. }
  482. }
  483. protected virtual void WriteAttributes(XmlTextWriter writer)
  484. {
  485. var styles = new Dictionary<string, string>();
  486. bool writeStyle;
  487. bool forceWrite;
  488. //properties
  489. foreach (var attr in _svgPropertyAttributes)
  490. {
  491. if (attr.Property.Converter.CanConvertTo(typeof(string)) &&
  492. (!attr.Attribute.InAttributeDictionary || _attributes.ContainsKey(attr.Attribute.Name)))
  493. {
  494. object propertyValue = attr.Property.GetValue(this);
  495. forceWrite = false;
  496. writeStyle = (attr.Attribute.Name == "fill");
  497. if (writeStyle && (Parent != null))
  498. {
  499. if (propertyValue == SvgColourServer.NotSet) continue;
  500. object parentValue;
  501. if (TryResolveParentAttributeValue(attr.Attribute.Name, out parentValue))
  502. {
  503. if ((parentValue == propertyValue)
  504. || ((parentValue != null) && parentValue.Equals(propertyValue)))
  505. continue;
  506. forceWrite = true;
  507. }
  508. }
  509. string value = propertyValue != null ?
  510. (string)attr.Property.Converter.ConvertTo(propertyValue, typeof(string)) : null;
  511. if (propertyValue != null)
  512. {
  513. var type = propertyValue.GetType();
  514. //Only write the attribute's value if it is not the default value, not null/empty, or we're forcing the write.
  515. if ((!string.IsNullOrEmpty(value) && !SvgDefaults.IsDefault(attr.Attribute.Name, value)) || forceWrite)
  516. {
  517. if (writeStyle)
  518. {
  519. styles[attr.Attribute.Name] = value;
  520. }
  521. else
  522. {
  523. writer.WriteAttributeString(attr.Attribute.NamespaceAndName, value);
  524. }
  525. }
  526. }
  527. else if (attr.Attribute.Name == "fill") //if fill equals null, write 'none'
  528. {
  529. if (writeStyle)
  530. {
  531. styles[attr.Attribute.Name] = value;
  532. }
  533. else
  534. {
  535. writer.WriteAttributeString(attr.Attribute.NamespaceAndName, value);
  536. }
  537. }
  538. }
  539. }
  540. //events
  541. if (AutoPublishEvents)
  542. {
  543. foreach (var attr in _svgEventAttributes)
  544. {
  545. var evt = attr.Event.GetValue(this);
  546. //if someone has registered publish the attribute
  547. if (evt != null && !string.IsNullOrEmpty(this.ID))
  548. {
  549. writer.WriteAttributeString(attr.Attribute.Name, this.ID + "/" + attr.Attribute.Name);
  550. }
  551. }
  552. }
  553. //add the custom attributes
  554. foreach (var item in this._customAttributes)
  555. {
  556. writer.WriteAttributeString(item.Key, item.Value);
  557. }
  558. //write the style property
  559. if (styles.Any())
  560. {
  561. writer.WriteAttributeString("style", (from s in styles
  562. select s.Key + ":" + s.Value + ";").Aggregate((p, c) => p + c));
  563. }
  564. }
  565. public bool AutoPublishEvents = true;
  566. private bool TryResolveParentAttributeValue(string attributeKey, out object parentAttributeValue)
  567. {
  568. parentAttributeValue = null;
  569. //attributeKey = char.ToUpper(attributeKey[0]) + attributeKey.Substring(1);
  570. var currentParent = Parent;
  571. var resolved = false;
  572. while (currentParent != null)
  573. {
  574. if (currentParent.Attributes.ContainsKey(attributeKey))
  575. {
  576. resolved = true;
  577. parentAttributeValue = currentParent.Attributes[attributeKey];
  578. if (parentAttributeValue != null)
  579. break;
  580. }
  581. currentParent = currentParent.Parent;
  582. }
  583. return resolved;
  584. }
  585. public virtual void Write(XmlTextWriter writer)
  586. {
  587. if (ShouldWriteElement())
  588. {
  589. this.WriteStartElement(writer);
  590. this.WriteChildren(writer);
  591. this.WriteEndElement(writer);
  592. }
  593. }
  594. protected virtual void WriteChildren(XmlTextWriter writer)
  595. {
  596. if (this.Nodes.Any())
  597. {
  598. SvgContentNode content;
  599. foreach (var node in this.Nodes)
  600. {
  601. content = node as SvgContentNode;
  602. if (content == null)
  603. {
  604. ((SvgElement)node).Write(writer);
  605. }
  606. else if (!string.IsNullOrEmpty(content.Content))
  607. {
  608. writer.WriteString(content.Content);
  609. }
  610. }
  611. }
  612. else
  613. {
  614. //write the content
  615. if (!String.IsNullOrEmpty(this.Content))
  616. writer.WriteString(this.Content);
  617. //write all children
  618. foreach (SvgElement child in this.Children)
  619. {
  620. child.Write(writer);
  621. }
  622. }
  623. }
  624. /// <summary>
  625. /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="ISvgRenderer"/> object.
  626. /// </summary>
  627. /// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
  628. protected virtual void Render(ISvgRenderer renderer)
  629. {
  630. this.PushTransforms(renderer);
  631. this.RenderChildren(renderer);
  632. this.PopTransforms(renderer);
  633. }
  634. /// <summary>
  635. /// Renders the children of this <see cref="SvgElement"/>.
  636. /// </summary>
  637. /// <param name="renderer">The <see cref="ISvgRenderer"/> to render the child <see cref="SvgElement"/>s to.</param>
  638. protected virtual void RenderChildren(ISvgRenderer renderer)
  639. {
  640. foreach (SvgElement element in this.Children)
  641. {
  642. element.Render(renderer);
  643. }
  644. }
  645. /// <summary>
  646. /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="ISvgRenderer"/> object.
  647. /// </summary>
  648. /// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
  649. void ISvgElement.Render(ISvgRenderer renderer)
  650. {
  651. this.Render(renderer);
  652. }
  653. /// <summary>
  654. /// Recursive method to add up the paths of all children
  655. /// </summary>
  656. /// <param name="elem"></param>
  657. /// <param name="path"></param>
  658. protected void AddPaths(SvgElement elem, GraphicsPath path)
  659. {
  660. foreach (var child in elem.Children)
  661. {
  662. // Skip to avoid double calculate Symbol element
  663. // symbol element is only referenced by use element
  664. // So here we need to skip when it is directly considered
  665. if (child is Svg.Document_Structure.SvgSymbol)
  666. continue;
  667. if (child is SvgVisualElement)
  668. {
  669. if (!(child is SvgGroup))
  670. {
  671. var childPath = ((SvgVisualElement)child).Path(null);
  672. if (childPath != null)
  673. {
  674. childPath = (GraphicsPath)childPath.Clone();
  675. if (child.Transforms != null)
  676. childPath.Transform(child.Transforms.GetMatrix());
  677. if (childPath.PointCount > 0) path.AddPath(childPath, false);
  678. }
  679. }
  680. }
  681. if (!(child is SvgPaintServer)) AddPaths(child, path);
  682. }
  683. }
  684. /// <summary>
  685. /// Recursive method to add up the paths of all children
  686. /// </summary>
  687. /// <param name="elem"></param>
  688. /// <param name="path"></param>
  689. protected GraphicsPath GetPaths(SvgElement elem, ISvgRenderer renderer)
  690. {
  691. var ret = new GraphicsPath();
  692. foreach (var child in elem.Children)
  693. {
  694. if (child is SvgVisualElement)
  695. {
  696. if (!(child is SvgGroup))
  697. {
  698. var childPath = ((SvgVisualElement)child).Path(renderer);
  699. // Non-group element can have child element which we have to consider. i.e tspan in text element
  700. if (child.Children.Count > 0)
  701. childPath.AddPath(GetPaths(child, renderer), false);
  702. if (childPath != null && childPath.PointCount > 0)
  703. {
  704. childPath = (GraphicsPath)childPath.Clone();
  705. if (child.Transforms != null)
  706. childPath.Transform(child.Transforms.GetMatrix());
  707. ret.AddPath(childPath, false);
  708. }
  709. }
  710. else
  711. {
  712. var childPath = GetPaths(child, renderer);
  713. if (childPath != null && childPath.PointCount > 0)
  714. {
  715. if (child.Transforms != null)
  716. childPath.Transform(child.Transforms.GetMatrix());
  717. ret.AddPath(childPath, false);
  718. }
  719. }
  720. }
  721. }
  722. return ret;
  723. }
  724. /// <summary>
  725. /// Creates a new object that is a copy of the current instance.
  726. /// </summary>
  727. /// <returns>
  728. /// A new object that is a copy of this instance.
  729. /// </returns>
  730. public virtual object Clone()
  731. {
  732. return this.MemberwiseClone();
  733. }
  734. public abstract SvgElement DeepCopy();
  735. ISvgNode ISvgNode.DeepCopy()
  736. {
  737. return DeepCopy();
  738. }
  739. public virtual SvgElement DeepCopy<T>() where T : SvgElement, new()
  740. {
  741. var newObj = new T();
  742. newObj.ID = this.ID;
  743. newObj.Content = this.Content;
  744. newObj.ElementName = this.ElementName;
  745. // if (this.Parent != null)
  746. // this.Parent.Children.Add(newObj);
  747. if (this.Transforms != null)
  748. {
  749. newObj.Transforms = this.Transforms.Clone() as SvgTransformCollection;
  750. }
  751. foreach (var child in this.Children)
  752. {
  753. newObj.Children.Add(child.DeepCopy());
  754. }
  755. foreach (var attr in this._svgEventAttributes)
  756. {
  757. var evt = attr.Event.GetValue(this);
  758. //if someone has registered also register here
  759. if (evt != null)
  760. {
  761. if (attr.Event.Name == "MouseDown")
  762. newObj.MouseDown += delegate { };
  763. else if (attr.Event.Name == "MouseUp")
  764. newObj.MouseUp += delegate { };
  765. else if (attr.Event.Name == "MouseOver")
  766. newObj.MouseOver += delegate { };
  767. else if (attr.Event.Name == "MouseOut")
  768. newObj.MouseOut += delegate { };
  769. else if (attr.Event.Name == "MouseMove")
  770. newObj.MouseMove += delegate { };
  771. else if (attr.Event.Name == "MouseScroll")
  772. newObj.MouseScroll += delegate { };
  773. else if (attr.Event.Name == "Click")
  774. newObj.Click += delegate { };
  775. else if (attr.Event.Name == "Change") //text element
  776. (newObj as SvgText).Change += delegate { };
  777. }
  778. }
  779. if (this._customAttributes.Count > 0)
  780. {
  781. foreach (var element in _customAttributes)
  782. {
  783. newObj.CustomAttributes.Add(element.Key, element.Value);
  784. }
  785. }
  786. if (this._nodes.Count > 0)
  787. {
  788. foreach (var node in this._nodes)
  789. {
  790. newObj.Nodes.Add(node.DeepCopy());
  791. }
  792. }
  793. return newObj;
  794. }
  795. /// <summary>
  796. /// Fired when an Atrribute of this Element has changed
  797. /// </summary>
  798. public event EventHandler<AttributeEventArgs> AttributeChanged;
  799. protected void OnAttributeChanged(AttributeEventArgs args)
  800. {
  801. var handler = AttributeChanged;
  802. if (handler != null)
  803. {
  804. handler(this, args);
  805. }
  806. }
  807. /// <summary>
  808. /// Fired when an Atrribute of this Element has changed
  809. /// </summary>
  810. public event EventHandler<ContentEventArgs> ContentChanged;
  811. protected void OnContentChanged(ContentEventArgs args)
  812. {
  813. var handler = ContentChanged;
  814. if (handler != null)
  815. {
  816. handler(this, args);
  817. }
  818. }
  819. #region graphical EVENTS
  820. /*
  821. onfocusin = "<anything>"
  822. onfocusout = "<anything>"
  823. onactivate = "<anything>"
  824. onclick = "<anything>"
  825. onmousedown = "<anything>"
  826. onmouseup = "<anything>"
  827. onmouseover = "<anything>"
  828. onmousemove = "<anything>"
  829. onmouseout = "<anything>"
  830. */
  831. #if Net4
  832. /// <summary>
  833. /// Use this method to provide your implementation ISvgEventCaller which can register Actions
  834. /// and call them if one of the events occurs. Make sure, that your SvgElement has a unique ID.
  835. /// The SvgTextElement overwrites this and regsiters the Change event tor its text content.
  836. /// </summary>
  837. /// <param name="caller"></param>
  838. public virtual void RegisterEvents(ISvgEventCaller caller)
  839. {
  840. if (caller != null && !string.IsNullOrEmpty(this.ID))
  841. {
  842. var rpcID = this.ID + "/";
  843. caller.RegisterAction<float, float, int, int, bool, bool, bool, string>(rpcID + "onclick", CreateMouseEventAction(RaiseMouseClick));
  844. caller.RegisterAction<float, float, int, int, bool, bool, bool, string>(rpcID + "onmousedown", CreateMouseEventAction(RaiseMouseDown));
  845. caller.RegisterAction<float, float, int, int, bool, bool, bool, string>(rpcID + "onmouseup", CreateMouseEventAction(RaiseMouseUp));
  846. caller.RegisterAction<float, float, int, int, bool, bool, bool, string>(rpcID + "onmousemove", CreateMouseEventAction(RaiseMouseMove));
  847. caller.RegisterAction<float, float, int, int, bool, bool, bool, string>(rpcID + "onmouseover", CreateMouseEventAction(RaiseMouseOver));
  848. caller.RegisterAction<float, float, int, int, bool, bool, bool, string>(rpcID + "onmouseout", CreateMouseEventAction(RaiseMouseOut));
  849. caller.RegisterAction<int, bool, bool, bool, string>(rpcID + "onmousescroll", OnMouseScroll);
  850. }
  851. }
  852. /// <summary>
  853. /// Use this method to provide your implementation ISvgEventCaller to unregister Actions
  854. /// </summary>
  855. /// <param name="caller"></param>
  856. public virtual void UnregisterEvents(ISvgEventCaller caller)
  857. {
  858. if (caller != null && !string.IsNullOrEmpty(this.ID))
  859. {
  860. var rpcID = this.ID + "/";
  861. caller.UnregisterAction(rpcID + "onclick");
  862. caller.UnregisterAction(rpcID + "onmousedown");
  863. caller.UnregisterAction(rpcID + "onmouseup");
  864. caller.UnregisterAction(rpcID + "onmousemove");
  865. caller.UnregisterAction(rpcID + "onmousescroll");
  866. caller.UnregisterAction(rpcID + "onmouseover");
  867. caller.UnregisterAction(rpcID + "onmouseout");
  868. }
  869. }
  870. #endif
  871. [SvgAttribute("onclick")]
  872. public event EventHandler<MouseArg> Click;
  873. [SvgAttribute("onmousedown")]
  874. public event EventHandler<MouseArg> MouseDown;
  875. [SvgAttribute("onmouseup")]
  876. public event EventHandler<MouseArg> MouseUp;
  877. [SvgAttribute("onmousemove")]
  878. public event EventHandler<MouseArg> MouseMove;
  879. [SvgAttribute("onmousescroll")]
  880. public event EventHandler<MouseScrollArg> MouseScroll;
  881. [SvgAttribute("onmouseover")]
  882. public event EventHandler<MouseArg> MouseOver;
  883. [SvgAttribute("onmouseout")]
  884. public event EventHandler<MouseArg> MouseOut;
  885. #if Net4
  886. protected Action<float, float, int, int, bool, bool, bool, string> CreateMouseEventAction(Action<object, MouseArg> eventRaiser)
  887. {
  888. return (x, y, button, clickCount, altKey, shiftKey, ctrlKey, sessionID) =>
  889. eventRaiser(this, new MouseArg { x = x, y = y, Button = button, ClickCount = clickCount, AltKey = altKey, ShiftKey = shiftKey, CtrlKey = ctrlKey, SessionID = sessionID });
  890. }
  891. #endif
  892. //click
  893. protected void RaiseMouseClick(object sender, MouseArg e)
  894. {
  895. var handler = Click;
  896. if (handler != null)
  897. {
  898. handler(sender, e);
  899. }
  900. }
  901. //down
  902. protected void RaiseMouseDown(object sender, MouseArg e)
  903. {
  904. var handler = MouseDown;
  905. if (handler != null)
  906. {
  907. handler(sender, e);
  908. }
  909. }
  910. //up
  911. protected void RaiseMouseUp(object sender, MouseArg e)
  912. {
  913. var handler = MouseUp;
  914. if (handler != null)
  915. {
  916. handler(sender, e);
  917. }
  918. }
  919. protected void RaiseMouseMove(object sender, MouseArg e)
  920. {
  921. var handler = MouseMove;
  922. if (handler != null)
  923. {
  924. handler(sender, e);
  925. }
  926. }
  927. //over
  928. protected void RaiseMouseOver(object sender, MouseArg args)
  929. {
  930. var handler = MouseOver;
  931. if (handler != null)
  932. {
  933. handler(sender, args);
  934. }
  935. }
  936. //out
  937. protected void RaiseMouseOut(object sender, MouseArg args)
  938. {
  939. var handler = MouseOut;
  940. if (handler != null)
  941. {
  942. handler(sender, args);
  943. }
  944. }
  945. //scroll
  946. protected void OnMouseScroll(int scroll, bool ctrlKey, bool shiftKey, bool altKey, string sessionID)
  947. {
  948. RaiseMouseScroll(this, new MouseScrollArg { Scroll = scroll, AltKey = altKey, ShiftKey = shiftKey, CtrlKey = ctrlKey, SessionID = sessionID });
  949. }
  950. protected void RaiseMouseScroll(object sender, MouseScrollArg e)
  951. {
  952. var handler = MouseScroll;
  953. if (handler != null)
  954. {
  955. handler(sender, e);
  956. }
  957. }
  958. #endregion graphical EVENTS
  959. }
  960. public class SVGArg : EventArgs
  961. {
  962. public string SessionID;
  963. }
  964. /// <summary>
  965. /// Describes the Attribute which was set
  966. /// </summary>
  967. public class AttributeEventArgs : SVGArg
  968. {
  969. public string Attribute;
  970. public object Value;
  971. }
  972. /// <summary>
  973. /// Content of this whas was set
  974. /// </summary>
  975. public class ContentEventArgs : SVGArg
  976. {
  977. public string Content;
  978. }
  979. /// <summary>
  980. /// Describes the Attribute which was set
  981. /// </summary>
  982. public class ChildAddedEventArgs : SVGArg
  983. {
  984. public SvgElement NewChild;
  985. public SvgElement BeforeSibling;
  986. }
  987. #if Net4
  988. //deriving class registers event actions and calls the actions if the event occurs
  989. public interface ISvgEventCaller
  990. {
  991. void RegisterAction(string rpcID, Action action);
  992. void RegisterAction<T1>(string rpcID, Action<T1> action);
  993. void RegisterAction<T1, T2>(string rpcID, Action<T1, T2> action);
  994. void RegisterAction<T1, T2, T3>(string rpcID, Action<T1, T2, T3> action);
  995. void RegisterAction<T1, T2, T3, T4>(string rpcID, Action<T1, T2, T3, T4> action);
  996. void RegisterAction<T1, T2, T3, T4, T5>(string rpcID, Action<T1, T2, T3, T4, T5> action);
  997. void RegisterAction<T1, T2, T3, T4, T5, T6>(string rpcID, Action<T1, T2, T3, T4, T5, T6> action);
  998. void RegisterAction<T1, T2, T3, T4, T5, T6, T7>(string rpcID, Action<T1, T2, T3, T4, T5, T6, T7> action);
  999. void RegisterAction<T1, T2, T3, T4, T5, T6, T7, T8>(string rpcID, Action<T1, T2, T3, T4, T5, T6, T7, T8> action);
  1000. void UnregisterAction(string rpcID);
  1001. }
  1002. #endif
  1003. /// <summary>
  1004. /// Represents the state of the mouse at the moment the event occured.
  1005. /// </summary>
  1006. public class MouseArg : SVGArg
  1007. {
  1008. public float x;
  1009. public float y;
  1010. /// <summary>
  1011. /// 1 = left, 2 = middle, 3 = right
  1012. /// </summary>
  1013. public int Button;
  1014. /// <summary>
  1015. /// Amount of mouse clicks, e.g. 2 for double click
  1016. /// </summary>
  1017. public int ClickCount = -1;
  1018. /// <summary>
  1019. /// Alt modifier key pressed
  1020. /// </summary>
  1021. public bool AltKey;
  1022. /// <summary>
  1023. /// Shift modifier key pressed
  1024. /// </summary>
  1025. public bool ShiftKey;
  1026. /// <summary>
  1027. /// Control modifier key pressed
  1028. /// </summary>
  1029. public bool CtrlKey;
  1030. }
  1031. /// <summary>
  1032. /// Represents a string argument
  1033. /// </summary>
  1034. public class StringArg : SVGArg
  1035. {
  1036. public string s;
  1037. }
  1038. public class MouseScrollArg : SVGArg
  1039. {
  1040. public int Scroll;
  1041. /// <summary>
  1042. /// Alt modifier key pressed
  1043. /// </summary>
  1044. public bool AltKey;
  1045. /// <summary>
  1046. /// Shift modifier key pressed
  1047. /// </summary>
  1048. public bool ShiftKey;
  1049. /// <summary>
  1050. /// Control modifier key pressed
  1051. /// </summary>
  1052. public bool CtrlKey;
  1053. }
  1054. public interface ISvgNode
  1055. {
  1056. string Content { get; }
  1057. /// <summary>
  1058. /// Create a deep copy of this <see cref="ISvgNode"/>.
  1059. /// </summary>
  1060. /// <returns>A deep copy of this <see cref="ISvgNode"/></returns>
  1061. ISvgNode DeepCopy();
  1062. }
  1063. /// <summary>This interface mostly indicates that a node is not to be drawn when rendering the SVG.</summary>
  1064. public interface ISvgDescriptiveElement
  1065. {
  1066. }
  1067. internal interface ISvgElement
  1068. {
  1069. SvgElement Parent { get; }
  1070. SvgElementCollection Children { get; }
  1071. IList<ISvgNode> Nodes { get; }
  1072. void Render(ISvgRenderer renderer);
  1073. }
  1074. }
  1075. #pragma warning restore