aboutsummaryrefslogtreecommitdiffstatsci
path: root/src/GraphicObjects/GraphicObject.cs
blob: aa108e22f3fe42cb4e9f68375b684a2247dde647 (plain)
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//using OpenTK.Graphics.OpenGL;
using System.Drawing.Imaging;
using System.Diagnostics;
using OpenTK.Input;

using Cairo;

using System.Xml.Serialization;
using System.Reflection;
using System.ComponentModel;
using System.IO;
//using System.Xml;
using System.Xml;

namespace go
{
	public class GraphicObject : IXmlSerializable, ILayoutable
	{
		#region CTOR
		public GraphicObject ()
		{
			loadDefaultValues ();
			registerForGraphicUpdate ();
		}
		public GraphicObject (Rectangle _bounds)
		{
			loadDefaultValues ();
			Bounds = _bounds;
			registerForGraphicUpdate ();
		}
		#endregion

		#region private fields
		ILayoutable _parent;
		string _name;
		Color _background;
		Color _foreground;
		double _cornerRadius;
		int _margin;
		bool _focusable = false;
		bool _hasFocus = false;
		protected bool _isVisible = true;
		VerticalAlignment _verticalAlignment;
		HorizontalAlignment _horizontalAlignment;

		bool hIsValid = false;
		bool wIsValid = false;
		bool xIsValid = false;
		bool yIsValid = false;
		#endregion

		public static int TabSize = 4;
		public static string LineBreak = "\r\n";
		public static bool ReplaceTabsWithSpace = false;
		public static bool DesignerMode = false;

		#region public fields
		public Rectangle Bounds;
		public Rectangle Slot = new Rectangle ();
		public object Tag;
		public byte[] bmp;
		#endregion

		#region ILayoutable
		[XmlIgnore]public ILayoutable Parent { 
			get { return _parent; }
			set { _parent = value; }
		}
		[XmlIgnore]public virtual bool SizeIsValid {
			get { return hIsValid & wIsValid; }
			set {
				hIsValid = value;
				wIsValid = value;
			}
		}
		[XmlIgnore]public virtual bool WIsValid {
			get { return wIsValid; }
			set { wIsValid = value; }
		}
		[XmlIgnore]public virtual bool HIsValid {
			get { return hIsValid; }
			set { hIsValid = value; }
		}
		[XmlIgnore]public virtual bool XIsValid {
			get { return xIsValid; }
			set { xIsValid = value; }
		}
		[XmlIgnore]public virtual bool YIsValid {
			get { return yIsValid; }
			set { yIsValid = value; }
		}
		[XmlIgnore]public virtual bool PositionIsValid {
			get { return xIsValid & yIsValid; }
			set {
				xIsValid = value;
				yIsValid = value;
			}
		}
		[XmlIgnore]public virtual bool LayoutIsValid {
			get { return SizeIsValid & PositionIsValid; }
			set {
				if (value == SizeIsValid & PositionIsValid)
					return;

				SizeIsValid = value;
				PositionIsValid = value;

				//if (!layoutIsValid && Parent != null)
				//    Parent.layoutIsValid = false;
			}
		}
		[XmlIgnore]public virtual Rectangle ClientRectangle {
			get {
				Rectangle cb = Slot.Size;
				cb.Inflate ( - Margin);
				return cb;
			}
		}
		[XmlIgnore]public virtual IGOLibHost TopContainer {
			get { return Parent.TopContainer; }
		}
		public virtual void InvalidateLayout ()
		{
			bmp = null;
			LayoutIsValid = false;
		}
		public virtual Rectangle ContextCoordinates(Rectangle r){
			return
				Parent.ContextCoordinates (r);// + ClientRectangle.Position;
		}			
		public virtual Rectangle ScreenCoordinates (Rectangle r){
			//r += Slot.Position;

			return 
				Parent.ScreenCoordinates(r) + Parent.getSlot().Position + Parent.ClientRectangle.Position;
		}
		public virtual Rectangle getSlot()
		{
			return Slot;
		}
		public virtual Rectangle getBounds()
		{
			return Bounds;
		}
		#endregion

		#region EVENT HANDLERS
		public event EventHandler<MouseWheelEventArgs> MouseWheelChanged = delegate { };
		public event EventHandler<MouseButtonEventArgs> MouseButtonUp = delegate { };
		public event EventHandler<MouseButtonEventArgs> MouseButtonDown = delegate { };
		public event EventHandler<MouseButtonEventArgs> MouseClick = delegate { };
		public event EventHandler<MouseMoveEventArgs> MouseMove = delegate { };
		public event EventHandler<MouseMoveEventArgs> MouseEnter = delegate { };
		public event EventHandler<MouseMoveEventArgs> MouseLeave = delegate { };
		public event EventHandler<KeyboardKeyEventArgs> KeyDown = delegate { };
		public event EventHandler<KeyboardKeyEventArgs> KeyUp = delegate { };
		public event EventHandler Focused = delegate { };
		public event EventHandler Unfocused = delegate { };
		#endregion

		#region public properties
		[XmlAttributeAttribute()][DefaultValue("unamed")]
		public virtual string Name {
			get { return _name; }
			set { _name = value; }
		}
		[XmlAttributeAttribute()][DefaultValue(VerticalAlignment.Center)]
		public virtual VerticalAlignment VerticalAlignment {
			get { return _verticalAlignment; }
			set { 
				if (_verticalAlignment == value)
					return;

				_verticalAlignment = value; 

//				if (Top > 0)
			}
		}
		[XmlAttributeAttribute()][DefaultValue(HorizontalAlignment.Center)]
		public virtual HorizontalAlignment HorizontalAlignment {
			get { return _horizontalAlignment; }
			set { _horizontalAlignment = value; }
		}
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Left {
			get { return Bounds.X; }
			set {
				if (Bounds.X == value)
					return;

				Bounds.X = value;

				LayoutIsValid = false;
				registerForGraphicUpdate ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Top {
			get { return Bounds.Y; }
			set {
				if (Bounds.Y == value)
					return;

				Bounds.Y = value;

				LayoutIsValid = false;
				registerForGraphicUpdate ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Width {
			get { return Bounds.Width; }
			set {
				if (Bounds.Width == value)
					return;

				Bounds.Width = value;

				InvalidateLayout ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Height {
			get { return Bounds.Height; }
			set {
				if (Bounds.Height == value)
					return;

				Bounds.Height = value;

				InvalidateLayout ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(false)]
		public virtual bool Fit {
			get { return Bounds.Width < 0 && Bounds.Height < 0 ? true : false; }
			set {
				if (value == Fit)
					return;

				Bounds.Width = Bounds.Height = -1;
				InvalidateLayout ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(false)]
		public virtual bool Focusable {
			get { return _focusable | DesignerMode; }
			set { _focusable = value; }
		}        
		[XmlAttributeAttribute()][DefaultValue("Transparent")]
		public virtual Color Background {
			get { return _background; }
			set {
				_background = value;
				registerForGraphicUpdate ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue("White")]
		public virtual Color Foreground {
			get { return _foreground; }
			set {
				_foreground = value;
				registerForGraphicUpdate ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(5)]
		public virtual double CornerRadius {
			get { return _cornerRadius; }
			set {
				_cornerRadius = value;
				registerForGraphicUpdate ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Margin {
			get { return _margin; }
			set {
				_margin = value;
				registerForGraphicUpdate ();
			}
		}
		[XmlAttributeAttribute()][DefaultValue(true)]
		public virtual bool Visible {
			get { return _isVisible; }
			set {
				if (value == _isVisible)
					return;

				_isVisible = value;

				//add slot to clipping to redraw
				TopContainer.gobjsToRedraw.Add (this);

				//ensure main win doesn't keep hidden childrens ref
				if (this.Contains (TopContainer.hoverWidget))
					TopContainer.hoverWidget = null;
//				if (Parent != null)
//					Parent.InvalidateLayout ();
				//else
				//    registerForRedraw();
			}
		}
		[XmlIgnore]public virtual bool HasFocus {
			get { return _hasFocus; }
			set { _hasFocus = value; }
		}
		[XmlIgnore]public virtual bool DrawingIsValid
		{ get { return bmp == null ? 
				false : 
				true; } }
		#endregion

		/// <summary>
		/// Loads the default values from XML attributes default
		/// </summary>
		void loadDefaultValues()
		{
			foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
				if (pi.GetSetMethod () == null)
					continue;

				bool isAttribute = false;
				string name = "";
				Type valueType = null;

				MemberInfo mi = pi.GetGetMethod ();

				object[] att = pi.GetCustomAttributes (false);

				foreach (object o in att) {
					XmlAttributeAttribute xaa = o as XmlAttributeAttribute;
					if (xaa != null) {
						isAttribute = true;
						if (string.IsNullOrEmpty (xaa.AttributeName))
							name = pi.Name;
						else
							name = xaa.AttributeName;
						continue;
					}

					XmlIgnoreAttribute xia = o as XmlIgnoreAttribute;
					if (xia != null)
						continue;

					DefaultValueAttribute dv = o as DefaultValueAttribute;
					if (dv != null) {
						if (pi.PropertyType == typeof(Color))
							pi.SetValue (this, Color.Parse ((string)dv.Value), null);
						else if (pi.PropertyType == typeof(Font))
							pi.SetValue (this, Font.Parse ((string)dv.Value), null);
						else
							pi.SetValue (this, dv.Value, null);
						continue;
					}

					//Debug.WriteLine (o.ToString ());
				}
			}

		}

		public virtual GraphicObject FindByName(string nameToFind){
			return nameToFind == _name ? this : null;
		}
		public virtual bool Contains(GraphicObject goToFind){
			return false;
		}


		/// <summary>
		/// Clear chached object and add clipping region in redraw list of interface
		/// </summary>
		public virtual void registerForGraphicUpdate ()
		{
			bmp = null;
			registerForRedraw ();
			//Interface.registerForGraphicUpdate(this);
		}
		/// <summary>
		/// Add clipping region in redraw list of interface, dont update cached object content
		/// </summary>
		public virtual void registerForRedraw ()
		{
			if (LayoutIsValid && Visible)
				TopContainer.gobjsToRedraw.Add (this);
		}
		public virtual void registerClipRect()
		{
			TopContainer.redrawClip.AddRectangle (ScreenCoordinates(Slot));
		}
		protected virtual Size measureRawSize ()
		{
			return Bounds.Size;
		}

		protected virtual void ComputeSize()
		{
			Size rawSize = measureRawSize ();

			if (!wIsValid) {
				wIsValid = true;
				if (Width > 0)
					Slot.Width = Width;
				else if (Width < 0) {
					if (rawSize.Width > 0)
						Slot.Width = rawSize.Width;
					else
						wIsValid = false;
				} else if (Parent.WIsValid)
					Slot.Width = Parent.ClientRectangle.Width;
				else
					wIsValid = false;				
			}

			if (!hIsValid) {
				hIsValid = true;
				if (Height > 0)
					Slot.Height = Height;
				else if (Height < 0) {
					if (rawSize.Height > 0)
						Slot.Height = rawSize.Height;
					else
						hIsValid = false;
				} else if (Parent.HIsValid)
					Slot.Height = Parent.ClientRectangle.Height;
				else
					hIsValid = false;				
			}
		}
		protected virtual void ComputePosition()
		{
			if (!xIsValid) {
				xIsValid = true;
				if (Width == 0)
					Slot.X = 0;
				else if (Left != 0)
					Slot.X = Left;
				else if (Parent.WIsValid && WIsValid) {
					switch (HorizontalAlignment) {
					case HorizontalAlignment.Left:
						Slot.X = 0;
						break;
					case HorizontalAlignment.Right:
						Slot.X = Parent.ClientRectangle.Width - Slot.Width;
						break;
					case HorizontalAlignment.Center:
						Slot.X = Parent.ClientRectangle.Width / 2 - Slot.Width / 2;
						break;
					}
				} else// if (Parent.getBounds().Width>=0)
					xIsValid = false;
			}

			if (!yIsValid) {
				yIsValid = true;
				if (Height== 0)
					Slot.Y = 0;
				else if (Top != 0)
					Slot.Y = Top;
				else if (Parent.HIsValid && HIsValid) {
					switch (VerticalAlignment) {
					case VerticalAlignment.Top:
						Slot.Y = 0;
						break;
					case VerticalAlignment.Bottom:
						Slot.Y = Parent.ClientRectangle.Height - Slot.Height;
						break;
					case VerticalAlignment.Center:
						Slot.Y = Parent.ClientRectangle.Height / 2 - Slot.Height / 2;
						break;
					}
				} else// if (Parent.getBounds().Height>=0)
					yIsValid = false;
			}
		}
		public virtual void UpdateLayout ()
		{
			if (!SizeIsValid)
				ComputeSize ();
			if (!PositionIsValid)
				ComputePosition ();				
			if (LayoutIsValid)
				registerForRedraw ();

		}
		protected virtual void onDraw(Context gr)
		{
			Rectangle rBack = new Rectangle (Slot.Size);

			gr.Color = Background;
			CairoHelpers.CairoRectangle(gr,rBack,_cornerRadius);
			gr.Fill ();
		}
		protected virtual void UpdateGraphic ()
		{
			int stride = 4 * Slot.Width;

			int bmpSize = Math.Abs (stride) * Slot.Height;
			bmp = new byte[bmpSize];

			using (ImageSurface draw =
                new ImageSurface(bmp, Format.Argb32, Slot.Width, Slot.Height, stride)) {
				using (Context gr = new Context (draw)) {
					gr.Antialias = Antialias.Subpixel;
					onDraw (gr);
				}
				draw.Flush ();
			}
		}
			
		public virtual void Paint (ref Context ctx, Rectangles clip = null)
		{
			if (!Visible)
				return;

			if (bmp == null)
				UpdateGraphic ();

			Rectangle rb = Parent.ContextCoordinates(Slot);

			using (ImageSurface source = new ImageSurface(bmp, Format.Argb32, rb.Width, rb.Height, 4 * Slot.Width)) {
				ctx.SetSourceSurface (source, rb.X, rb.Y);
				ctx.Paint ();
			}
		}

        #region Keyboard handling
		public virtual void onKeyDown(object sender, KeyboardKeyEventArgs e){
			if (KeyDown != null)
				KeyDown (sender, e);
		}
        #endregion

		#region Mouse handling
		public virtual bool MouseIsIn(Point m)
		{
			return Visible & Focusable ? ScreenCoordinates(Slot).ContainsOrIsEqual (m) : false; 
		}
		public virtual void onMouseMove(object sender, MouseMoveEventArgs e)
		{
			//ILayoutable w = sender as ILayoutable;

			if (TopContainer.hoverWidget != this) {
				TopContainer.hoverWidget = this;
				onMouseEnter (sender, e);
			}
				
			MouseMove (this, e);
		}
		public virtual void onMouseButtonUp(object sender, MouseButtonEventArgs e){
			if (MouseIsIn (e.Position))
				onMouseClick (sender, e);

			MouseButtonUp (this, e);
		}
		public virtual void onMouseButtonDown(object sender, MouseButtonEventArgs e){
			TopContainer.FocusedWidget = this;

			MouseButtonDown (this, e);
		}
		public virtual void onMouseClick(object sender, MouseButtonEventArgs e){	
			MouseClick(this,e);
		}
		public virtual void onMouseWheel(object sender, MouseWheelEventArgs e){
			GraphicObject p = Parent as GraphicObject;
			if (p != null)
				p.onMouseWheel(this,e);
				
			MouseWheelChanged (this, e);
		}
		public virtual void onFocused(object sender, EventArgs e){
			Focused (this, e);
			this.HasFocus = true;
		}
		public virtual void onUnfocused(object sender, EventArgs e){
			Unfocused (this, e);
			this.HasFocus = false;
		}
		public virtual void onMouseEnter(object sender, MouseMoveEventArgs e)
		{
			Debug.WriteLine ("Mouse enter: " + this.Name);
			MouseEnter (this, e);
		}
		public virtual void onMouseLeave(object sender, MouseMoveEventArgs e)
		{
			Debug.WriteLine ("Mouse leave: " + this.Name);
			MouseLeave (this, e);
		}
		#endregion

		#region Load/Save

		internal static List<EventSource> EventsToResolve;

		public static void Save<T>(string file, T graphicObject)
		{            
			XmlSerializerNamespaces xn = new XmlSerializerNamespaces();
			xn.Add("", "");
			XmlSerializer xs = new XmlSerializer(typeof(T));

			xs = new XmlSerializer(typeof(T));
			using (Stream s = new FileStream(file, FileMode.Create))
			{
				xs.Serialize(s, graphicObject, xn);
			}
		}
		public static GraphicObject Load(string path)
		{
			string root = "Object";
			using (Stream s = new FileStream (path, FileMode.Open)) {
				using (XmlReader reader = XmlReader.Create (s)) {
					while (reader.Read()) {
						// first element is the root element
						if (reader.NodeType == XmlNodeType.Element) {
							root = reader.Name;
							break;
						}
					}
				}
			}
			Type t = Type.GetType("go." + root);
			var go = Activator.CreateInstance(t);
			return Load(path, t);
		}
		public static void Load<T>(string file, out T result, object ClassContainingHandlers = null)
		{
			EventsToResolve = new List<EventSource>();

			XmlSerializerNamespaces xn = new XmlSerializerNamespaces();
			xn.Add("", "");
			XmlSerializer xs = new XmlSerializer(typeof(T));            

			using (Stream s = new FileStream(file, FileMode.Open))
			{
				result = (T)xs.Deserialize(s);
			}

			if (ClassContainingHandlers == null)
				return;

			foreach (EventSource es in EventsToResolve)
			{
				if (string.IsNullOrEmpty(es.Handler))
					continue;

				if (es.Handler.StartsWith ("{")) {
					CompilerServices.CompileEventSource (es);
				} else {					
					MethodInfo mi = ClassContainingHandlers.GetType ().GetMethod (es.Handler, BindingFlags.NonPublic | BindingFlags.Public
					               | BindingFlags.Instance);

					if (mi == null) {
						Debug.WriteLine ("Handler Method not found: " + es.Handler);
						continue;
					}

					FieldInfo fi = CompilerServices.getEventHandlerField (es.Source.GetType (), es.EventName);
					Delegate del = Delegate.CreateDelegate(fi.FieldType, ClassContainingHandlers, mi);
					fi.SetValue(es.Source, del);
				}
			}
		}

		public static GraphicObject Load(string file, Type type, object ClassContainingHandlers = null)
		{
			GraphicObject result;
			EventsToResolve = new List<EventSource>();

			XmlSerializerNamespaces xn = new XmlSerializerNamespaces();
			xn.Add("", "");
			XmlSerializer xs = new XmlSerializer(type);            

			using (Stream s = new FileStream(file, FileMode.Open))
			{
				result = (GraphicObject)xs.Deserialize(s);
			}

			if (ClassContainingHandlers == null)
				return result;

			foreach (EventSource es in EventsToResolve)
			{
				if (string.IsNullOrEmpty(es.Handler))
					continue;

				if (es.Handler.StartsWith ("{")) {
					CompilerServices.CompileEventSource (es);
				} else {					
					MethodInfo mi = ClassContainingHandlers.GetType ().GetMethod (es.Handler, BindingFlags.NonPublic | BindingFlags.Public
						| BindingFlags.Instance);

					if (mi == null) {
						Debug.WriteLine ("Handler Method not found: " + es.Handler);
						continue;
					}

					FieldInfo fi = CompilerServices.getEventHandlerField (es.Source.GetType (), es.EventName);
					Delegate del = Delegate.CreateDelegate(fi.FieldType, ClassContainingHandlers, mi);
					fi.SetValue(es.Source, del);
				}
			}
			return result;
		}

		#endregion

		public override string ToString ()
		{
			return Name == "unamed" ? this.GetType ().ToString() : Name;
		}
			
		#region IXmlSerializable

		public virtual System.Xml.Schema.XmlSchema GetSchema ()
		{
			return null;
		}
		//TODO: allert or inform when unknow attribute name in XML, very confusing...
		public virtual void ReadXml (System.Xml.XmlReader reader)
		{
			foreach (EventInfo ei in this.GetType().GetEvents()) {
//				FieldInfo fi = this.GetType().GetField(ei.Name,
//					BindingFlags.NonPublic |
//					BindingFlags.Instance |
//					BindingFlags.GetField);
				string handler = reader.GetAttribute(ei.Name);
				if (string.IsNullOrEmpty (handler))
					continue;
					
				GraphicObject.EventsToResolve.Add(new EventSource 
					{ 
						Source = this, 
						Handler = handler,
						EventName = ei.Name
					});
			}
			foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
				if (pi.GetSetMethod () == null)
					continue;

				bool isAttribute = false;

				string name = "";
				object value = null;
				object defaultValue = null;

				Type valueType = null;


				MemberInfo mi = pi.GetGetMethod ();

				//if (mi.MemberType == MemberTypes.Property)
				//{
				//    PropertyInfo pi = mi as PropertyInfo;
				//    value = pi.GetValue(this, null);
				//    valueType = pi.PropertyType;
				//}
				//else if (mi.MemberType == MemberTypes.Field)
				//{
				//    FieldInfo fi = mi as FieldInfo;
				//    value = fi.GetValue(this);
				//    valueType = fi.FieldType;
				//}

				object[] att = pi.GetCustomAttributes (false);

				foreach (object o in att) {
					XmlAttributeAttribute xaa = o as XmlAttributeAttribute;
					if (xaa != null) {
						isAttribute = true;
						if (string.IsNullOrEmpty (xaa.AttributeName))
							name = pi.Name;
						else
							name = xaa.AttributeName;
						continue;
					}

					XmlIgnoreAttribute xia = o as XmlIgnoreAttribute;
					if (xia != null)
						continue;

					DefaultValueAttribute dv = o as DefaultValueAttribute;
					if (dv != null) {
						defaultValue = dv.Value;
						continue;
					}
				}


				if (isAttribute) {
					string v = reader.GetAttribute (name);

					if (string.IsNullOrEmpty (v)) {
						//TODO: maybe find another way to convert correctely colors default values
						if (pi.PropertyType == typeof(Color))
							pi.SetValue (this, Color.Parse ((string)defaultValue), null);
						else if (pi.PropertyType == typeof(Font))
							pi.SetValue (this, Font.Parse ((string)defaultValue), null);
						else
							pi.SetValue (this, defaultValue, null);
					} else {
						if (pi.PropertyType == typeof(string)) {
							pi.SetValue (this, v, null);
							continue;
						}

						object o = null;

						if (pi.PropertyType.IsEnum) {
							o = Enum.Parse (pi.PropertyType, v);
						} else {
							MethodInfo me = pi.PropertyType.GetMethod ("Parse", new Type[] { typeof(string) });
							o = me.Invoke (null, new string[] { v });
						}

						pi.SetValue (this, o, null);
					}
				} else {
					////if member type is not serializable, cancel
					//if (valueType.GetInterface("IXmlSerializable") == null)
					//    continue;

					//(pi.GetValue(this, null) as IXmlSerializable).WriteXml(writer);
				}
			}

		}

		public virtual void WriteXml (System.Xml.XmlWriter writer)
		{
			foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
				if (pi.GetSetMethod () == null)
					continue;

				bool isAttribute = false;
				bool hasDefaultValue = false;
				bool ignore = false;
				string name = "";
				object value = null;
				Type valueType = null;


				MemberInfo mi = pi.GetGetMethod ();

				if (mi == null)
					continue;

				value = pi.GetValue (this, null);
				valueType = pi.PropertyType;
				name = pi.Name;



				object[] att = pi.GetCustomAttributes (false);

				foreach (object o in att) {
					XmlAttributeAttribute xaa = o as XmlAttributeAttribute;
					if (xaa != null) {
						isAttribute = true;
						if (string.IsNullOrEmpty (xaa.AttributeName))
							name = pi.Name;
						else
							name = xaa.AttributeName;
						continue;
					}

					XmlIgnoreAttribute xia = o as XmlIgnoreAttribute;
					if (xia != null) {
						ignore = true;
						continue;
					}

					DefaultValueAttribute dv = o as DefaultValueAttribute;
					if (dv != null) {
						if (dv.Value.Equals (value))
							hasDefaultValue = true;
						if (dv.Value.ToString () == value.ToString ())
							hasDefaultValue = true;

						continue;
					}


				}

				if (hasDefaultValue || ignore || value==null)
					continue;

				if (isAttribute)
					writer.WriteAttributeString (name, value.ToString ());
				else {
					if (valueType.GetInterface ("IXmlSerializable") == null)
						continue;

					(pi.GetValue (this, null) as IXmlSerializable).WriteXml (writer);
				}
			}
			foreach (EventInfo ei in this.GetType().GetEvents()) {
				FieldInfo fi = this.GetType().GetField(ei.Name,
					BindingFlags.NonPublic |
					BindingFlags.Instance |
					BindingFlags.GetField);

				Delegate dg = (System.Delegate)fi.GetValue (this);

				if (dg == null)
					continue;

				foreach (Delegate d in dg.GetInvocationList()) {
					if (!d.Method.Name.StartsWith ("<"))//Skipping empty handler, not clear it's trikky					
						writer.WriteAttributeString (ei.Name, d.Method.Name);
				} 
			}
		}

		#endregion	
	}
}