aboutsummaryrefslogtreecommitdiffstatsci
path: root/src/GraphicObjects/GraphicObject.cs
blob: 15730905e6193e8eb7d86edebbded0283e32c9a3 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
//
// GraphicObject.cs
//
// Author:
//       Jean-Philippe Bruyère <jp.bruyere@hotmail.com>
//
// Copyright (c) 2013-2017 Jean-Philippe Bruyère
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using Cairo;
using System.Diagnostics;
using Crow.IML;

namespace Crow
{
	/// <summary>
	/// The base class for all the graphic tree elements.
	/// </summary>
	public class GraphicObject : ILayoutable, IValueChange, IDisposable
	{
		#region IDisposable implementation
		protected bool disposed = false;

		public void Dispose(){  
			Dispose(true);  
			GC.SuppressFinalize(this);  
		}  
		~GraphicObject(){
			Dispose(false);
		}
		protected virtual void Dispose(bool disposing){
			if (disposed){
				#if DEBUG_DISPOSE
				Debug.WriteLine ("Trying to dispose already disposed obj: {0}", this.ToString());
				#endif
				return;
			}

			if (disposing) {
				#if DEBUG_DISPOSE
				Debug.WriteLine ("Disposing: {0}", this.ToString());
				if (IsQueueForRedraw)
				throw new Exception("Trying to dispose an object queued for Redraw: " + this.ToString());
				#endif
				if (CurrentInterface.HoverWidget != null) {
					if (CurrentInterface.HoverWidget.IsOrIsInside(this))
						CurrentInterface.HoverWidget = null;
				}
				if (CurrentInterface.ActiveWidget != null) {
					if (CurrentInterface.ActiveWidget.IsOrIsInside (this))
						CurrentInterface.ActiveWidget = null;
				}
				if (CurrentInterface.FocusedWidget != null) {
					if (CurrentInterface.FocusedWidget.IsOrIsInside (this))
						CurrentInterface.FocusedWidget = null;
				}
				if (!localDataSourceIsNull)
					DataSource = null;
				parent = null;
			} else
				Debug.WriteLine ("!!! Finalized by GC: {0}", this.ToString ());
			Clipping?.Dispose ();
			bmp?.Dispose ();
			disposed = true;

		}  
		#endregion

		internal static ulong currentUid = 0;
		internal ulong uid = 0;

		internal bool isPopup = false;
		internal GraphicObject focusParent {
			get { return (isPopup ? LogicalParent : parent) as GraphicObject; }
		}

		/// <summary>
		/// interface this widget is bound to, this should not be changed once the instance is created
		/// </summary>
		public Interface CurrentInterface = null;

		/// <summary>
		/// contains the dirty rectangles in the coordinate system of the cache. those dirty zones
		/// are repeated at each cached levels of the tree with correspondig coordinate system. This is done
		/// in a dedicated step of the update between layouting and drawing.
		/// </summary>
		public Region Clipping;

		#region IValueChange implementation
		/// <summary>
		/// Raise to notify that the value of a property has changed, the binding system
		/// rely mainly on this event. the member name may not be present in the class, this is 
		/// used in **propertyless** bindings, this allow to raise custom named events without needing
		/// to create an new one in the class or a new property.
		/// </summary>
		public event EventHandler<ValueChangeEventArgs> ValueChanged;
		/// <summary>
		/// Helper function to raise the value changed event
		/// </summary>
		public virtual void NotifyValueChanged(string MemberName, object _value)
		{
			//Debug.WriteLine ("Value changed: {0}->{1} = {2}", this, MemberName, _value);
			ValueChanged.Raise(this, new ValueChangeEventArgs(MemberName, _value));
		}
		#endregion

		#region CTOR
		/// <summary>
		/// default private parameter less constructor use in instantiators, it should not be used
		/// when creating widget from code because widgets has to be bound to an interface before any other
		/// action.
		/// </summary>
		protected GraphicObject () {
			Clipping = new Region ();
			#if DEBUG
			uid = currentUid;
			currentUid++;
			#endif			
		}
		/// <summary>
		/// This constructor **must** be used when creating widget from code.
		///
		/// When creating new widgets derived from GraphicObject, both parameterless and this constructors are
		/// facultatives, the compiler will create the parameterless one automaticaly if no other one exists.
		/// But if you intend to be able to create instances of the new widget in code and override the constructor
		/// with the Interface parameter, you **must** also provide the override of the parameterless constructor because
		/// compiler will not create it automatically because of the presence of the other one.
		/// </summary>
		/// <param name="iface">Iface.</param>
		public GraphicObject (Interface iface) : this()
		{
			CurrentInterface = iface;
			Initialize ();
		}
		#endregion
		internal bool initialized = false;
		/// <summary>
		/// Initialize this Graphic object instance by setting style and default values and loading template if required
		/// </summary>
		public virtual void Initialize(){
			loadDefaultValues ();
			initialized = true;
		}
		#region private fields
		LayoutingType registeredLayoutings = LayoutingType.All;
		ILayoutable logicalParent;
		ILayoutable parent;
		string name;
		Fill background = Color.Transparent;
		Fill foreground = Color.White;
		Font font = "droid, 10";
		Measure width, height;
		int left, top;
		double cornerRadius = 0;
		int margin = 0;
		bool focusable = false;
		bool hasFocus = false;
		bool isActive = false;
		bool mouseRepeat;
		protected bool isVisible = true;
		bool isEnabled = true;
		VerticalAlignment verticalAlignment = VerticalAlignment.Center;
		HorizontalAlignment horizontalAlignment = HorizontalAlignment.Center;
		Size maximumSize = "0,0";
		Size minimumSize = "0,0";
		bool cacheEnabled = false;
		bool clipToClientRect = true;
		protected object dataSource;
		string style;
		object tag;
		bool isDragged;
		bool allowDrag;
		bool allowDrop;
		string tooltip;
		IList<Command> contextCommands;
		#endregion

		#region public fields
		/// <summary>
		/// Current size and position computed during layouting pass
		/// </summary>
		public Rectangle Slot = new Rectangle ();
		/// <summary>
		/// keep last slot components for each layouting pass to track
		/// changes and trigger update of other component accordingly
		/// </summary>
		public Rectangle LastSlots;
		/// <summary>
		/// keep last slot painted on screen to clear traces if moved or resized
		/// version to clear effective oldslot if parents have been moved or resized.
		/// IDEA is to add a ScreenCoordinates function that use only lastPaintedSlots
		/// </summary>
		//TODO: we should ensure the whole parsed widget tree is the last painted
		public Rectangle LastPaintedSlot;
		/// <summary>Prevent requeuing multiple times the same widget</summary>
		public bool IsQueueForRedraw = false;
		/// <summary>drawing Cache, if null, a redraw is done, cached or not</summary>
		public Surface bmp;
		public bool IsDirty = true;
		/// <summary>
		/// This size is computed on each child' layout changes.
		/// In stacking widget, it is used to compute the remaining space for the stretched
		/// widget inside the stack, which is never added to the contentSize, instead, its size
		/// is deducted from (parent.ClientRectangle - contentSize)
		/// </summary>
		internal Size contentSize;
		#endregion

		#region ILayoutable
		[XmlIgnore]public LayoutingType RegisteredLayoutings { get { return registeredLayoutings; } set { registeredLayoutings = value; } }
		//TODO: it would save the recurent cost of a cast in event bubbling if parent type was GraphicObject
		//		or we could add to the interface the mouse events
		/// <summary>
		/// Parent in the graphic tree, used for rendering and layouting
		/// </summary>
		[XmlIgnore]public virtual ILayoutable Parent {
			get { return parent; }
			set {
				if (parent == value)
					return;
				DataSourceChangeEventArgs e = new DataSourceChangeEventArgs (parent, value);
				lock (this)
					parent = value;

				onParentChanged (this, e);
			}
		}
		[XmlIgnore]public ILayoutable LogicalParent {
			get { return logicalParent == null ? Parent : logicalParent; }
			set {
				if (logicalParent == value)
					return;
				if (logicalParent != null)
					(logicalParent as GraphicObject).DataSourceChanged -= onLogicalParentDataSourceChanged;
				DataSourceChangeEventArgs dsce = new DataSourceChangeEventArgs (LogicalParent, null);
				logicalParent = value;
				dsce.NewDataSource = LogicalParent;
				if (logicalParent != null)
					(logicalParent as GraphicObject).DataSourceChanged += onLogicalParentDataSourceChanged;
				onLogicalParentChanged (this, dsce);
			}
		}
		[XmlIgnore]public virtual Rectangle ClientRectangle {
			get {
				Rectangle cb = Slot.Size;
				cb.Inflate ( - Margin);
				return cb;
			}
		}
		public virtual Rectangle ContextCoordinates(Rectangle r){
			GraphicObject go = Parent as GraphicObject;
			if (go == null)
				return r + Parent.ClientRectangle.Position;
			return go.CacheEnabled ?
				r + Parent.ClientRectangle.Position :
				Parent.ContextCoordinates (r);
		}
		public virtual Rectangle ScreenCoordinates (Rectangle r){
			return
				Parent.ScreenCoordinates(r) + Parent.getSlot().Position + Parent.ClientRectangle.Position;
		}
		public virtual Rectangle getSlot () { return Slot;}
		#endregion

		#region EVENT HANDLERS
		/// <summary>Occurs when mouse wheel is rolled in this object. It bubbles to the root</summary>
		public event EventHandler<MouseWheelEventArgs> MouseWheelChanged;
		/// <summary>Occurs when mouse button is released in this object. It bubbles to the root</summary>
		public event EventHandler<MouseButtonEventArgs> MouseUp;
		/// <summary>Occurs when mouse button is pressed in this object. It bubbles to the root</summary>
		public event EventHandler<MouseButtonEventArgs> MouseDown;
		/// <summary>Occurs when mouse button has been pressed then relesed in this object. It bubbles to the root</summary>
		public event EventHandler<MouseButtonEventArgs> MouseClick;
		/// <summary>Occurs when mouse button has been pressed then relesed 2 times in this object. It bubbles to the root</summary>
		public event EventHandler<MouseButtonEventArgs> MouseDoubleClick;
		/// <summary>Occurs when mouse mouve in this object. It bubbles to the root</summary>
		public event EventHandler<MouseMoveEventArgs> MouseMove;
		/// <summary>Occurs when mouse enter this object</summary>
		public event EventHandler<MouseMoveEventArgs> MouseEnter;
		/// <summary>Occurs when mouse leave this object</summary>
		public event EventHandler<MouseMoveEventArgs> MouseLeave;
		/// <summary>Occurs when key is pressed when this object is active</summary>
		public event EventHandler<KeyboardKeyEventArgs> KeyDown;
		/// <summary>Occurs when key is released when this object is active</summary>
		public event EventHandler<KeyboardKeyEventArgs> KeyUp;
		/// <summary>Occurs when translated key event occurs in the host when this object is active</summary>
		public event EventHandler<KeyPressEventArgs> KeyPress;
		/// <summary>Occurs when this object received focus</summary>
		public event EventHandler Focused;
		/// <summary>Occurs when this object loose focus</summary>
		public event EventHandler Unfocused;
		/// <summary>Occurs when the enabled state this object is set to true</summary>
		public event EventHandler Enabled;
		/// <summary>Occurs when the enabled state this object is set to false</summary>
		public event EventHandler Disabled;
		public event EventHandler Dragged;
		public event EventHandler Dropped;
		/// <summary>Occurs when one part of the rendering slot changed</summary>
		public event EventHandler<LayoutingEventArgs> LayoutChanged;
		/// <summary>Occurs when DataSource changed</summary>
		public event EventHandler<DataSourceChangeEventArgs> DataSourceChanged;
		/// <summary>Occurs when the parent has changed</summary>
		public event EventHandler<DataSourceChangeEventArgs> ParentChanged;
		/// <summary>Occurs when the logical parent has changed</summary>
		public event EventHandler<DataSourceChangeEventArgs> LogicalParentChanged;
		#endregion

		#region public properties
		/// <summary>Random value placeholder</summary>
		[XmlAttributeAttribute]
		public object Tag {
			get { return tag; }
			set {
				if (tag == value)
					return;
				tag = value;
				NotifyValueChanged ("Tag", tag);
			}
		}
		/// <summary>
		/// If enabled, resulting bitmap of graphic object is cached
		/// speeding up rendering of complex object. Default is enabled.
		/// </summary>
		[XmlAttributeAttribute][DefaultValue(true)]
		public virtual bool CacheEnabled {
			get { return cacheEnabled; }
			set {
				if (cacheEnabled == value)
					return;
				cacheEnabled = value;
				NotifyValueChanged ("CacheEnabled", cacheEnabled);
			}
		}
		/// <summary>
		/// If true, rendering of GraphicObject is clipped inside client rectangle
		/// </summary>
		[XmlAttributeAttribute][DefaultValue(true)]
		public virtual bool ClipToClientRect {
			get { return clipToClientRect; }
			set {
				if (clipToClientRect == value)
					return;
				clipToClientRect = value;
				NotifyValueChanged ("ClipToClientRect", clipToClientRect);
				this.RegisterForRedraw ();
			}
		}
		#if DEBUG
		[XmlIgnore]public string TreePath {
			get { return this.GetType().Name + uid.ToString ();	}
		}
		#endif
		/// <summary>
		/// Name is used in binding to reference other GraphicObjects inside the graphic tree
		/// and by template controls to find special element in their template implementation such
		/// as a container or a group to put children in.
		/// </summary>
		[XmlAttributeAttribute][DefaultValue(null)]
		public virtual string Name {
			get {
				#if DEBUG
				return string.IsNullOrEmpty(name) ? this.GetType().Name + uid.ToString () : name;
				#else
				return name;
				#endif
			}
			set {
				if (name == value)
					return;
				name = value;
				NotifyValueChanged("Name", name);
			}
		}
		/// <summary>
		/// Vertical alignment inside parent, disabled if height is stretched
		/// or top coordinate is not null
		/// </summary>
		[XmlAttributeAttribute	()][DefaultValue(VerticalAlignment.Center)]
		public virtual VerticalAlignment VerticalAlignment {
			get { return verticalAlignment; }
			set {
				if (verticalAlignment == value)
					return;

				verticalAlignment = value;
				NotifyValueChanged("VerticalAlignment", verticalAlignment);
				RegisterForLayouting (LayoutingType.Y);
			}
		}
		/// <summary>
		/// Horizontal alignment inside parent, disabled if width is stretched
		/// or left coordinate is not null
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(HorizontalAlignment.Center)]
		public virtual HorizontalAlignment HorizontalAlignment {
			get { return horizontalAlignment; }
			set {
				if (horizontalAlignment == value)
					return;
				horizontalAlignment = value;
				NotifyValueChanged("HorizontalAlignment", horizontalAlignment);
				RegisterForLayouting (LayoutingType.X);
			}
		}
		/// <summary>
		/// x position inside parent
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Left {
			get { return left; }
			set {
				if (left == value)
					return;
				left = value;
				NotifyValueChanged ("Left", left);
				this.RegisterForLayouting (LayoutingType.X);
			}
		}
		/// <summary>
		/// y position inside parent
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Top {
			get { return top; }
			set {
				if (top == value)
					return;
				top = value;
				NotifyValueChanged ("Top", top);
				this.RegisterForLayouting (LayoutingType.Y);
			}
		}
		/// <summary>
		/// Helper property used to set width and height to fit in one call
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(false)]
		public virtual bool Fit {
			get { return Width == Measure.Fit && Height == Measure.Fit ? true : false; }
			set {
				if (value == Fit)
					return;

				Width = Height = Measure.Fit;
			}
		}
		/// <summary>
		/// Width of this control, by default inherited from parent. May have special values
		/// such as Stretched or Fit. It may be proportionnal or absolute.
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("Inherit")]
		public virtual Measure Width {
			get {
				return width.Units == Unit.Inherit ?
					Parent is GraphicObject ? (Parent as GraphicObject).WidthPolicy :
					Measure.Stretched : width;
			}
			set {
				if (width == value)
					return;
				if (value.IsFixed) {
					if (value < MinimumSize.Width || (value > MaximumSize.Width && MaximumSize.Width > 0))
						return;
				}
				Measure lastWP = WidthPolicy;
				width = value;
				NotifyValueChanged ("Width", width);
				if (WidthPolicy != lastWP) {
					NotifyValueChanged ("WidthPolicy", WidthPolicy);
					//contentSize in Stacks are only update on childLayoutChange, and the single stretched
					//child of the stack is not counted in contentSize, so when changing size policy of a child
					//we should adapt contentSize
					//TODO:check case when child become stretched, and another stretched item already exists.
					if (parent is GenericStack) {//TODO:check if I should test Group instead
						if ((parent as GenericStack).Orientation == Orientation.Horizontal) {
							if (lastWP == Measure.Fit)
								(parent as GenericStack).contentSize.Width -= this.LastSlots.Width;
							else
								(parent as GenericStack).contentSize.Width += this.LastSlots.Width;
						}
					}
				}

				this.RegisterForLayouting (LayoutingType.Width);
			}
		}
		/// <summary>
		/// Height of this control, by default inherited from parent. May have special values
		/// such as Stretched or Fit. It may be proportionnal or absolute.
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("Inherit")]
		public virtual Measure Height {
			get {
				return height.Units == Unit.Inherit ?
					Parent is GraphicObject ? (Parent as GraphicObject).HeightPolicy :
					Measure.Stretched : height;
			}
			set {
				if (height == value)
					return;
				if (value.IsFixed) {
					if (value < MinimumSize.Height || (value > MaximumSize.Height && MaximumSize.Height > 0))
						return;
				}
				Measure lastHP = HeightPolicy;
				height = value;
				NotifyValueChanged ("Height", height);
				if (HeightPolicy != lastHP) {
					NotifyValueChanged ("HeightPolicy", HeightPolicy);
					if (parent is GenericStack) {
						if ((parent as GenericStack).Orientation == Orientation.Vertical) {
							if (lastHP == Measure.Fit)
								(parent as GenericStack).contentSize.Height -= this.LastSlots.Height;
							else
								(parent as GenericStack).contentSize.Height += this.LastSlots.Height;
						}
					}
				}

				this.RegisterForLayouting (LayoutingType.Height);
			}
		}
		/// <summary>
		/// Used for binding on dimensions, this property will never hold fixed size, but instead only
		/// Fit or Stretched, **with inherited state implementation, it is not longer used in binding**
		/// </summary>
		[XmlIgnore]public virtual Measure WidthPolicy { get {
				return Width.IsFit ? Measure.Fit : Measure.Stretched; } }
		/// <summary>
		/// Used for binding on dimensions, this property will never hold fixed size, but instead only
		/// Fit or Stretched, **with inherited state implementation, it is not longer used in binding**
		/// </summary>
		[XmlIgnore]public virtual Measure HeightPolicy { get {
				return Height.IsFit ? Measure.Fit : Measure.Stretched; } }
		/// <summary>
		/// Indicate that this object may received focus or not, if not focusable all the descendants are 
		/// affected.
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(false)]
		public virtual bool Focusable {
			get { return focusable; }
			set {
				if (focusable == value)
					return;
				focusable = value;
				NotifyValueChanged ("Focusable", focusable);
			}
		}
		/// <summary>
		/// True when this control has the focus, only one control per interface may have it.
		/// </summary>
		[XmlIgnore]public virtual bool HasFocus {
			get { return hasFocus; }
			set {
				if (value == hasFocus)
					return;

				hasFocus = value;
				if (hasFocus)
					onFocused (this, null);
				else
					onUnfocused (this, null);
				NotifyValueChanged ("HasFocus", hasFocus);
			}
		}
		/// <summary>
		/// true if this control is active, this means that mouse has been pressed in it and not yet released. It could 
		/// be used for other two states periferic action.
		/// </summary>
		[XmlIgnore]public virtual bool IsActive {
			get { return isActive; }
			set {
				if (value == isActive)
					return;

				isActive = value;
				NotifyValueChanged ("IsActive", isActive);
			}
		}
		/// <summary>
		/// true if holding mouse button down should trigger multiple click events
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(false)]
		public virtual bool MouseRepeat {
			get { return mouseRepeat; }
			set {
				if (mouseRepeat == value)
					return;
				mouseRepeat = value;
				NotifyValueChanged ("MouseRepeat", mouseRepeat);
			}
		}
		bool clearBackground = false;
		/// <summary>
		/// background fill of the control, maybe solid color, gradient, image, or svg
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("Transparent")]
		public virtual Fill Background {
			get { return background; }
			set {
				if (background == value)
					return;
				clearBackground = false;
				if (value == null)
					return;
				background = value;
				NotifyValueChanged ("Background", background);
				RegisterForRedraw ();
				if (background is SolidColor) {
					if ((Background as SolidColor).Equals (Color.Clear))
						clearBackground = true;
				}
			}
		}
		/// <summary>
		/// Foreground fill of the control, usage may be different among derived controls
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("White")]
		public virtual Fill Foreground {
			get { return foreground; }
			set {
				if (foreground == value)
					return;
				foreground = value;
				NotifyValueChanged ("Foreground", foreground);
				RegisterForRedraw ();
			}
		}
		/// <summary>
		/// Font being used in many controls, it is defined in the base GraphicObject class.
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("sans,10")]
		public virtual Font Font {
			get { return font; }
			set {
				if (value == font)
					return;
				font = value;
				NotifyValueChanged ("Font", font);
				RegisterForGraphicUpdate ();
			}
		}
		/// <summary>
		/// to get rounded corners
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(0.0)]
		public virtual double CornerRadius {
			get { return cornerRadius; }
			set {
				if (value == cornerRadius)
					return;
				cornerRadius = value;
				NotifyValueChanged ("CornerRadius", cornerRadius);
				RegisterForRedraw ();
			}
		}
		/// <summary>
		/// This is a single integer for the 4 direction, a gap between the control and it's container,
		/// by default it is filled with the background.
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue(0)]
		public virtual int Margin {
			get { return margin; }
			set {
				if (value == margin)
					return;
				margin = value;
				NotifyValueChanged ("Margin", margin);
				RegisterForGraphicUpdate ();
			}
		}
		/// <summary>
		/// set the visible state of the control, invisible controls does reserve space in the layouting system.
		/// </summary>
		[XmlAttributeAttribute][DefaultValue(true)]
		public virtual bool Visible {
			get { return isVisible; }
			set {
				if (value == isVisible)
					return;

				isVisible = value;

				RegisterForLayouting (LayoutingType.Sizing);

				//trigger a mouse to handle possible hover changes
				//CurrentInterface.ProcessMouseMove (CurrentInterface.Mouse.X, CurrentInterface.Mouse.Y);

				NotifyValueChanged ("Visible", isVisible);
			}
		}
		/// <summary>
		/// get or set the enabled state, disabling a control will affect focuability and
		/// also it's rendering which will be grayed
		/// </summary>
		[XmlAttributeAttribute][DefaultValue(true)]
		public virtual bool IsEnabled {
			get { return isEnabled; }
			set {
				if (value == isEnabled)
					return;

				isEnabled = value;

				if (isEnabled)
					onEnable (this, null);
				else
					onDisable (this, null);

				NotifyValueChanged ("IsEnabled", isEnabled);
				RegisterForRedraw ();
			}
		}
		/// <summary>
		/// Minimal width and  height for this control
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("1,1")]
		public virtual Size MinimumSize {
			get { return minimumSize; }
			set {
				if (value == minimumSize)
					return;

				minimumSize = value;

				NotifyValueChanged ("MinimumSize", minimumSize);
				RegisterForLayouting (LayoutingType.Sizing);
			}
		}
		/// <summary>
		/// Maximum width and  height for this control, unlimited if null.
		/// </summary>
		[XmlAttributeAttribute()][DefaultValue("0,0")]
		public virtual Size MaximumSize {
			get { return maximumSize; }
			set {
				if (value == maximumSize)
					return;

				maximumSize = value;

				NotifyValueChanged ("MaximumSize", maximumSize);
				RegisterForLayouting (LayoutingType.Sizing);
			}
		}
		/// <summary>
		/// Seek first logical tree upward if logicalParent is set, or seek graphic tree for
		/// a not null dataSource that will be active for all descendants having dataSource=null
		/// </summary>
		[XmlAttributeAttribute]//[DefaultValue(null)]
		public virtual object DataSource {
			set {
				if (DataSource == value)
					return;

				DataSourceChangeEventArgs dse = new DataSourceChangeEventArgs (DataSource, null);
				dataSource = value;
				dse.NewDataSource = DataSource;

				//prevent setting null causing stack overflow in specific case
				if (dse.NewDataSource == dse.OldDataSource)
					return;

				OnDataSourceChanged (this, dse);

				NotifyValueChanged ("DataSource", DataSource);
			}
			get {
				return dataSource == null ?
					LogicalParent == null ? null :
					LogicalParent is GraphicObject ? (LogicalParent as GraphicObject).DataSource : null :
					dataSource;
			}
		}
		protected virtual void onLogicalParentDataSourceChanged(object sender, DataSourceChangeEventArgs e){
			if (localDataSourceIsNull)
				OnDataSourceChanged (this, e);
		}
		internal bool localDataSourceIsNull { get { return dataSource == null; } }
		public bool localLogicalParentIsNull { get { return logicalParent == null; } }

		public virtual void OnDataSourceChanged(object sender, DataSourceChangeEventArgs e){
			DataSourceChanged.Raise (this, e);
			#if DEBUG_BINDING
			Debug.WriteLine("New DataSource for => {0} \n\t{1}=>{2}", this.ToString(),e.OldDataSource,e.NewDataSource);
			#endif
		}
		/// <summary>
		/// Style key to use for this control
		/// </summary>
		[XmlAttributeAttribute]
		public virtual string Style {
			get { return style; }
			set {
				if (value == style)
					return;

				style = value;

				NotifyValueChanged ("Style", style);
			}
		}
		[XmlAttributeAttribute]
		public virtual string Tooltip {
			get { return tooltip; }
			set {
				if (tooltip == value)
					return;
				tooltip = value;
				NotifyValueChanged("Tooltip", tooltip);
			}
		}
		[XmlAttributeAttribute]
		public IList<Command> ContextCommands {
			get { return contextCommands; }
			set {
				if (contextCommands == value)
					return;
				contextCommands = value;
				NotifyValueChanged("ContextCommands", contextCommands);
			}
		}
		#endregion

		#region Default and Style Values loading
		/// <summary> Loads the default values from XML attributes default </summary>
		public void loadDefaultValues()
		{
			#if DEBUG_LOAD
			Debug.WriteLine ("LoadDefValues for " + this.ToString ());
			#endif

			Type thisType = this.GetType ();

			if (!string.IsNullOrEmpty (Style)) {
				if (CurrentInterface.DefaultValuesLoader.ContainsKey (Style)) {
					CurrentInterface.DefaultValuesLoader [Style] (this);
					return;
				}
			} else {
				if (CurrentInterface.DefaultValuesLoader.ContainsKey (thisType.FullName)) {
					CurrentInterface.DefaultValuesLoader [thisType.FullName] (this);
					return;
				} else if (!CurrentInterface.Styling.ContainsKey (thisType.FullName)) {
					if (CurrentInterface.DefaultValuesLoader.ContainsKey (thisType.Name)) {
						CurrentInterface.DefaultValuesLoader [thisType.Name] (this);
						return;
					}
				}
			}

			List<Style> styling = new List<Style>();

			//Search for a style matching :
			//1: Full class name, with full namespace
			//2: class name
			//3: style may have been registered with their ressource ID minus .style extention
			//   those files being placed in a Styles folder
			string styleKey = Style;
			if (!string.IsNullOrEmpty (Style)) {
				if (CurrentInterface.Styling.ContainsKey (Style)) {
					styling.Add (CurrentInterface.Styling [Style]);
				}
			}
			if (CurrentInterface.Styling.ContainsKey (thisType.FullName)) {
				styling.Add (CurrentInterface.Styling [thisType.FullName]);
				if (string.IsNullOrEmpty (styleKey))
					styleKey = thisType.FullName;
			}
			if (CurrentInterface.Styling.ContainsKey (thisType.Name)) {
				styling.Add (CurrentInterface.Styling [thisType.Name]);
				if (string.IsNullOrEmpty (styleKey))
					styleKey = thisType.Name;
			}

			if (string.IsNullOrEmpty (styleKey))
				styleKey = thisType.FullName;


			//Reflexion being very slow compared to dyn method or delegates,
			//I compile the initial values coded in the CustomAttribs of the class,
			//all other instance of this type would not longer use reflexion to init properly
			//but will fetch the  dynamic initialisation method compiled for this precise type
			//TODO:measure speed gain.
			#region Delfault values Loading dynamic compilation
			DynamicMethod dm = null;
			ILGenerator il = null;

			dm = new DynamicMethod("dyn_loadDefValues",
				MethodAttributes.Family | MethodAttributes.FamANDAssem | MethodAttributes.NewSlot,
				CallingConventions.Standard,
				typeof(void),new Type[] {CompilerServices.TObject},thisType,true);

			il = dm.GetILGenerator(256);
			il.DeclareLocal(CompilerServices.TObject);
			il.Emit(OpCodes.Nop);
			//set local GraphicObject to root object passed as 1st argument
			il.Emit (OpCodes.Ldarg_0);
			il.Emit (OpCodes.Stloc_0);

			foreach (EventInfo ei in thisType.GetEvents(BindingFlags.Public | BindingFlags.Instance)) {
				string expression;
				if (!getDefaultEvent(ei, styling, out expression))
					continue;
				//TODO:dynEventHandler could be cached somewhere, maybe a style instanciator class holding the styling delegate and bound to it.
				foreach (string exp in CompilerServices.splitOnSemiColumnOutsideAccolades(expression)) {
					string trimed = exp.Trim();
					if (trimed.StartsWith ("{", StringComparison.OrdinalIgnoreCase)){
						il.Emit (OpCodes.Ldloc_0);//load this as 1st arg of event Add

						//push eventInfo as 1st arg of compile
						il.Emit (OpCodes.Ldloc_0);
						il.Emit (OpCodes.Call, CompilerServices.miGetType);
						il.Emit (OpCodes.Ldstr, ei.Name);//push event name
						il.Emit (OpCodes.Call, CompilerServices.miGetEvent);
						//push expression as 2nd arg of compile
						il.Emit (OpCodes.Ldstr, trimed.Substring (1, trimed.Length - 2));
						//push null as 3rd arg, currentNode, not known when instanciing
						il.Emit (OpCodes.Ldnull);
						il.Emit (OpCodes.Callvirt, CompilerServices.miCompileDynEventHandler);
						il.Emit (OpCodes.Castclass, ei.EventHandlerType);
						il.Emit (OpCodes.Callvirt, ei.AddMethod);
					}else
						Debug.WriteLine("error in styling, event not handled : " + trimed);
				}
			}

			foreach (PropertyInfo pi in thisType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
				if (pi.GetSetMethod () == null)
					continue;
				object defaultValue;
				if (!getDefaultValue (pi, styling, out defaultValue))
					continue;

				CompilerServices.EmitSetValue (il, pi, defaultValue);
			}
			il.Emit(OpCodes.Ret);
			#endregion

			try {
				CurrentInterface.DefaultValuesLoader[styleKey] = (Interface.LoaderInvoker)dm.CreateDelegate(typeof(Interface.LoaderInvoker));
				CurrentInterface.DefaultValuesLoader[styleKey] (this);
			} catch (Exception ex) {
				throw new Exception ("Error applying style <" + styleKey + ">:", ex);
			}
		}
		bool getDefaultEvent(EventInfo ei, List<Style> styling,
			out string expression){
			expression = "";
			if (styling.Count > 0){
				for (int i = 0; i < styling.Count; i++) {
					if (styling[i].ContainsKey (ei.Name)){
						expression = (string)styling[i] [ei.Name];
						return true;
					}
				}
			}
			return false;
		}
		/// <summary>
		/// Gets the default value of the widget's property from either the style, or from xml default
		/// </summary>
		/// <returns><c>true</c>, if default value is defined, <c>false</c> otherwise.</returns>
		/// <param name="pi">PropertyInfo</param>
		/// <param name="styling">Styling informations</param>
		/// <param name="defaultValue">output of Default value, null if not found</param>
		bool getDefaultValue(PropertyInfo pi, List<Style> styling,
			out object defaultValue){
			defaultValue = null;
			string name = "";

			XmlIgnoreAttribute xia = (XmlIgnoreAttribute)pi.GetCustomAttribute (typeof(XmlIgnoreAttribute));
			if (xia != null)
				return false;
			XmlAttributeAttribute xaa = (XmlAttributeAttribute)pi.GetCustomAttribute (typeof(XmlAttributeAttribute));
			if (xaa != null) {
				if (string.IsNullOrEmpty (xaa.AttributeName))
					name = pi.Name;
				else
					name = xaa.AttributeName;
			}

			int styleIndex = -1;
			if (styling.Count > 0){
				for (int i = 0; i < styling.Count; i++) {
					if (styling[i].ContainsKey (name)){
						styleIndex = i;
						break;
					}
				}
			}
			if (styleIndex >= 0){
				if (pi.PropertyType.IsEnum)//maybe should be in parser..
					defaultValue = Enum.Parse(pi.PropertyType, (string)styling[styleIndex] [name], true);
				else
					defaultValue = styling[styleIndex] [name];
			}else {
				DefaultValueAttribute dv = (DefaultValueAttribute)pi.GetCustomAttribute (typeof (DefaultValueAttribute));
				if (dv == null)
					return false;
				defaultValue = dv.Value;
			}
			return true;
		}
		#endregion

		public virtual GraphicObject FindByName(string nameToFind){
			return string.Equals(nameToFind, name, StringComparison.Ordinal) ? this : null;
		}
		public virtual bool Contains(GraphicObject goToFind){
			return false;
		}
		/// <summary>
		/// return true if this is contained inside go
		/// </summary>
		public bool IsOrIsInside(GraphicObject go){
			if (this == go)
				return true;
			ILayoutable p = this.Parent;
			while (p != null) {
				if (p == go)
					return true;
				p = p.Parent;
			}
			return false;
		}

		#region Drag&Drop
		[XmlAttributeAttribute][DefaultValue(false)]
		public virtual bool AllowDrag {
			get { return allowDrag; }
			set {
				if (allowDrag == value)
					return;
				allowDrag = value;
				NotifyValueChanged ("AllowDrag", allowDrag);
			}
		}
		[XmlAttributeAttribute][DefaultValue(false)]
		public virtual bool AllowDrop {
			get { return allowDrop; }
			set {
				if (allowDrop == value)
					return;
				allowDrop = value;
				NotifyValueChanged ("AllowDrop", allowDrop);
			}
		}

//		public List<Type> AllowedDroppedTypes;
//		public void AddAllowedDroppedType (Type newType){
//			if (AllowedDroppedTypes == null)
//				AllowedDroppedTypes = new List<Type> ();
//			AllowedDroppedTypes.Add (newType);
//			NotifyValueChanged ("AllowDrop", AllowDrop);
//		}
//		[XmlIgnore]public virtual bool AllowDrop {
//			get { return AllowedDroppedTypes?.Count>0; }
//		}
		[XmlIgnore]public virtual bool IsDragged {
			get { return isDragged; }
			set {
				if (isDragged == value)
					return;
				isDragged = value;

				if (isDragged) {
					CurrentInterface.HoverWidget = null;
					onStartDrag (this, null);
				}

				NotifyValueChanged ("IsDrag", IsDragged);
			}
		}
		/// <summary>
		/// start dragging
		/// </summary>
		protected virtual void onStartDrag (object sender, EventArgs e){
			Debug.WriteLine("DRAG => " + this.ToString());
			Dragged.Raise (this, null);
		}
		/// <summary>
		///  Occured when dragging ends without dropping
		/// </summary>
		protected virtual void onEndDrag (object sender, EventArgs e){
			IsDragged = false;
			Debug.WriteLine("END DRAG => " + this.ToString());
		}
		/// <summary>
		/// Dragging end with a dropping
		/// </summary>
		protected virtual void onDrop (object sender, EventArgs e){
			IsDragged = false;
			Debug.WriteLine("DROPPED => " + this.ToString());
			Dropped.Raise (this, null);
		}
		#endregion

		#region Queuing
		/// <summary>
		/// Register old and new slot for clipping
		/// </summary>
		public virtual void ClippingRegistration(){
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("ClippingRegistration -> {0}", this.ToString ()));
			#endif
			IsQueueForRedraw = false;
			if (Parent == null)
				return;
			Parent.RegisterClip (LastPaintedSlot);
			Parent.RegisterClip (Slot);
		}
		/// <summary>
		/// Add clip rectangle to this.clipping and propagate up to root
		/// </summary>
		/// <param name="clip">Clip rectangle</param>
		public virtual void RegisterClip(Rectangle clip){
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("RegisterClip -> {1}:{0}", clip, this.ToString ()));
			#endif
			Rectangle  r = clip + ClientRectangle.Position;
			if (CacheEnabled && !IsDirty)
				Clipping.UnionRectangle (r);
			if (Parent == null)
				return;
			GraphicObject p = Parent as GraphicObject;
			if (p?.IsDirty == true && p?.CacheEnabled == true)
				return;
			Parent.RegisterClip (r + Slot.Position);
		}
		/// <summary> Full update, taking care of sizing policy </summary>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void RegisterForGraphicUpdate ()
		{
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("RegisterForGraphicUpdate (IsDirty set)-> {0}", this.ToString ()));
			#endif
			IsDirty = true;
			if (Width.IsFit || Height.IsFit)
				RegisterForLayouting (LayoutingType.Sizing);
			else if (RegisteredLayoutings == LayoutingType.None)
				CurrentInterface.EnqueueForRepaint (this);
		}
		/// <summary> query an update of the content, a redraw </summary>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void RegisterForRedraw ()
		{
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("RegisterForRedraw (IsDirty set)-> {0}", this.ToString ()));
			#endif
			IsDirty = true;
			if (RegisteredLayoutings == LayoutingType.None)
				CurrentInterface.EnqueueForRepaint (this);
		}
		#endregion

		#region Layouting

		/// <summary> return size of content + margins </summary>
		protected virtual int measureRawSize (LayoutingType lt) {
			return lt == LayoutingType.Width ?
				contentSize.Width + 2 * Margin: contentSize.Height + 2 * Margin;
		}
		/// <summary> By default in groups, LayoutingType.ArrangeChildren is reset </summary>
		public virtual void ChildrenLayoutingConstraints(ref LayoutingType layoutType){
		}
		public virtual bool ArrangeChildren { get { return false; } }
		public virtual void RegisterForLayouting(LayoutingType layoutType){
			if (Parent == null)
				return;
			lock (CurrentInterface.LayoutMutex) {
				//prevent queueing same LayoutingType for this
				layoutType &= (~RegisteredLayoutings);

				if (layoutType == LayoutingType.None)
					return;
				//dont set position for stretched item
				if (Width == Measure.Stretched)
					layoutType &= (~LayoutingType.X);
				if (Height == Measure.Stretched)
					layoutType &= (~LayoutingType.Y);

				if (!ArrangeChildren)
					layoutType &= (~LayoutingType.ArrangeChildren);

				//apply constraints depending on parent type
				if (Parent is GraphicObject)
					(Parent as GraphicObject).ChildrenLayoutingConstraints (ref layoutType);

//				//prevent queueing same LayoutingType for this
//				layoutType &= (~RegisteredLayoutings);

				if (layoutType == LayoutingType.None)
					return;

				//enqueue LQI LayoutingTypes separately
				if (layoutType.HasFlag (LayoutingType.Width))
					CurrentInterface.LayoutingQueue.Enqueue (new LayoutingQueueItem (LayoutingType.Width, this));
				if (layoutType.HasFlag (LayoutingType.Height))
					CurrentInterface.LayoutingQueue.Enqueue (new LayoutingQueueItem (LayoutingType.Height, this));
				if (layoutType.HasFlag (LayoutingType.X))
					CurrentInterface.LayoutingQueue.Enqueue (new LayoutingQueueItem (LayoutingType.X, this));
				if (layoutType.HasFlag (LayoutingType.Y))
					CurrentInterface.LayoutingQueue.Enqueue (new LayoutingQueueItem (LayoutingType.Y, this));
				if (layoutType.HasFlag (LayoutingType.ArrangeChildren))
					CurrentInterface.LayoutingQueue.Enqueue (new LayoutingQueueItem (LayoutingType.ArrangeChildren, this));
			}
		}

		/// <summary> trigger dependant sizing component update </summary>
		public virtual void OnLayoutChanges(LayoutingType  layoutType)
		{
			#if DEBUG_LAYOUTING
			CurrentInterface.currentLQI.Slot = LastSlots;
			CurrentInterface.currentLQI.NewSlot = Slot;
			Debug.WriteLine ("\t\t{0} => {1}",LastSlots,Slot);
			#endif

			switch (layoutType) {
			case LayoutingType.Width:
				RegisterForLayouting (LayoutingType.X);
				break;
			case LayoutingType.Height:
				RegisterForLayouting (LayoutingType.Y);
				break;
			}
			LayoutChanged.Raise (this, new LayoutingEventArgs (layoutType));
		}
		internal protected void raiseLayoutChanged(LayoutingEventArgs e){
			LayoutChanged.Raise (this, e);
		}
		/// <summary> Update layout component only one at a time, this is where the computation of alignement
		/// and size take place.
		/// The redrawing will only be triggered if final slot size has changed </summary>
		/// <returns><c>true</c>, if layouting was possible, <c>false</c> if conditions were not
		/// met and LQI has to be re-queued</returns>
		public virtual bool UpdateLayout (LayoutingType layoutType)
		{
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("UpdateLayout ({1})-> {0}", this.ToString (), layoutType));
			#endif
			//unset bit, it would be reset if LQI is re-queued
			registeredLayoutings &= (~layoutType);

			switch (layoutType) {
			case LayoutingType.X:
				if (Left == 0) {

					if (Parent.RegisteredLayoutings.HasFlag (LayoutingType.Width) ||
					    RegisteredLayoutings.HasFlag (LayoutingType.Width))
						return false;

					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
					Slot.X = Left;

				if (LastSlots.X == Slot.X)
					break;

				IsDirty = true;

				OnLayoutChanges (layoutType);

				LastSlots.X = Slot.X;
				break;
			case LayoutingType.Y:
				if (Top == 0) {

					if (Parent.RegisteredLayoutings.HasFlag (LayoutingType.Height) ||
					    RegisteredLayoutings.HasFlag (LayoutingType.Height))
						return false;

					switch (VerticalAlignment) {
					case VerticalAlignment.Top://this could be processed even if parent Height is not known
						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
					Slot.Y = Top;

				if (LastSlots.Y == Slot.Y)
					break;

				IsDirty = true;

				OnLayoutChanges (layoutType);

				LastSlots.Y = Slot.Y;
				break;
			case LayoutingType.Width:
				if (Visible) {
					if (Width.IsFixed)
						Slot.Width = Width;
					else if (Width == Measure.Fit) {
						Slot.Width = measureRawSize (LayoutingType.Width);
					} else if (Parent.RegisteredLayoutings.HasFlag (LayoutingType.Width))
						return false;
					else if (Width == Measure.Stretched)
						Slot.Width = Parent.ClientRectangle.Width;
					else
						Slot.Width = (int)Math.Round ((double)(Parent.ClientRectangle.Width * Width) / 100.0);

					if (Slot.Width < 0)
						return false;

					//size constrain
					if (Slot.Width < MinimumSize.Width) {
						Slot.Width = MinimumSize.Width;
						//NotifyValueChanged ("WidthPolicy", Measure.Stretched);
					} else if (Slot.Width > MaximumSize.Width && MaximumSize.Width > 0) {
						Slot.Width = MaximumSize.Width;
						//NotifyValueChanged ("WidthPolicy", Measure.Stretched);
					}
				} else
					Slot.Width = 0;

				if (LastSlots.Width == Slot.Width)
					break;

				IsDirty = true;

				OnLayoutChanges (layoutType);

				LastSlots.Width = Slot.Width;
				break;
			case LayoutingType.Height:
				if (Visible) {
					if (Height.IsFixed)
						Slot.Height = Height;
					else if (Height == Measure.Fit) {
						Slot.Height = measureRawSize (LayoutingType.Height);
					} else if (Parent.RegisteredLayoutings.HasFlag (LayoutingType.Height))
						return false;
					else if (Height == Measure.Stretched)
						Slot.Height = Parent.ClientRectangle.Height;
					else
						Slot.Height = (int)Math.Round ((double)(Parent.ClientRectangle.Height * Height) / 100.0);

					if (Slot.Height < 0)
						return false;

					//size constrain
					if (Slot.Height < MinimumSize.Height) {
						Slot.Height = MinimumSize.Height;
						//NotifyValueChanged ("HeightPolicy", Measure.Stretched);
					} else if (Slot.Height > MaximumSize.Height && MaximumSize.Height > 0) {
						Slot.Height = MaximumSize.Height;
						//NotifyValueChanged ("HeightPolicy", Measure.Stretched);
					}
				} else
					Slot.Height = 0;

				if (LastSlots.Height == Slot.Height)
					break;

				IsDirty = true;

				OnLayoutChanges (layoutType);

				LastSlots.Height = Slot.Height;
				break;
			}

			//if no layouting remains in queue for item, registre for redraw
			if (this.registeredLayoutings == LayoutingType.None && IsDirty)
				CurrentInterface.EnqueueForRepaint (this);

			return true;
		}
		#endregion

		#region Rendering
		/// <summary> This is the common overridable drawing routine to create new widget </summary>
		protected virtual void onDraw(Context gr)
		{
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("OnDraw -> {0}", this.ToString ()));
			#endif

			Rectangle rBack = new Rectangle (Slot.Size);

			Background.SetAsSource (gr, rBack);
			CairoHelpers.CairoRectangle (gr, rBack, cornerRadius);
			gr.Fill ();
		}

		/// <summary>
		/// Internal drawing context creation on a cached surface limited to slot size
		/// this trigger the effective drawing routine </summary>
		protected virtual void RecreateCache ()
		{
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("RecreateCache -> {0}", this.ToString ()));
			#endif
			IsDirty = false;
			if (bmp != null)
				bmp.Dispose ();
			bmp = new ImageSurface (Format.Argb32, Slot.Width, Slot.Height);
			using (Context gr = new Context (bmp)) {
				gr.Antialias = Interface.Antialias;
				onDraw (gr);
			}
			bmp.Flush ();
		}
		protected virtual void UpdateCache(Context ctx){
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("UpdateCache -> {0}", this.ToString ()));
			#endif
			Rectangle rb = Slot + Parent.ClientRectangle.Position;
			if (clearBackground) {
					ctx.Save ();
					ctx.Operator = Operator.Clear;
					ctx.Rectangle (rb);
					ctx.Fill ();
					ctx.Restore ();
			}
			ctx.SetSourceSurface (bmp, rb.X, rb.Y);
			ctx.Paint ();
			Clipping.Dispose ();
			Clipping = new Region ();
		}
		/// <summary> Chained painting routine on the parent context of the actual cached version
		/// of the widget </summary>
		public virtual void Paint (ref Context ctx)
		{
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("Paint -> {0}", this.ToString ()));
			#endif
			//TODO:this test should not be necessary
			if (Slot.Height < 0 || Slot.Width < 0 || parent == null)
				return;
			lock (this) {
				if (cacheEnabled) {
					if (Slot.Width > Interface.MaxCacheSize || Slot.Height > Interface.MaxCacheSize)
						cacheEnabled = false;
				}

				if (cacheEnabled) {
					if (IsDirty)
						RecreateCache ();

					UpdateCache (ctx);
					if (!isEnabled)
						paintDisabled (ctx, Slot + Parent.ClientRectangle.Position);
				} else {
					Rectangle rb = Slot + Parent.ClientRectangle.Position;
					ctx.Save ();

					ctx.Translate (rb.X, rb.Y);

					onDraw (ctx);
					if (!isEnabled)
						paintDisabled (ctx, Slot);

					ctx.Restore ();
				}
				LastPaintedSlot = Slot;
			}
		}
		void paintDisabled(Context gr, Rectangle rb){
			gr.Operator = Operator.Xor;
			gr.SetSourceRGBA (0.6, 0.6, 0.6, 0.3);
			gr.Rectangle (rb);
			gr.Fill ();
			gr.Operator = Operator.Over;
		}
		#endregion

        #region Keyboard handling
		public virtual void onKeyDown(object sender, KeyboardKeyEventArgs e){
			KeyDown.Raise (sender, e);
		}
		public virtual void onKeyUp(object sender, KeyboardKeyEventArgs e){
			KeyUp.Raise (sender, e);
		}
		public virtual void onKeyPress(object sender, KeyPressEventArgs e){
			KeyPress.Raise (sender, e);
		}
        #endregion

		#region Mouse handling
		public virtual bool PointIsIn(ref Point m)
		{			
			if (!(Visible & isEnabled)||IsDragged)
				return false;
			if (!parent.PointIsIn(ref m))
				return false;
			m -= (parent.getSlot().Position + parent.ClientRectangle.Position) ;
			return Slot.ContainsOrIsEqual (m);					
		}
		public virtual bool MouseIsIn(Point m)
		{			
			return (!(Visible & isEnabled)||IsDragged) ? false : PointIsIn (ref m);
		}
		public virtual void checkHoverWidget(MouseMoveEventArgs e)
		{
			if (CurrentInterface.HoverWidget != this) {
				CurrentInterface.HoverWidget = this;
				onMouseEnter (this, e);
			}

			//this.onMouseMove (this, e);//without this, window border doesn't work, should be removed
		}
		public virtual void onMouseMove(object sender, MouseMoveEventArgs e)
		{
			if (AllowDrag & !IsDragged & IsActive)
				IsDragged = true;

			//bubble event to the top
			GraphicObject p = focusParent;
			if (p != null)
				p.onMouseMove(sender,e);

			MouseMove.Raise (this, e);
		}
		public virtual void onMouseDown(object sender, MouseButtonEventArgs e){
			if (CurrentInterface.eligibleForDoubleClick == this && CurrentInterface.clickTimer.ElapsedMilliseconds < Interface.DoubleClick)
				onMouseDoubleClick (this, e);
			else
				CurrentInterface.clickTimer.Restart();
			CurrentInterface.eligibleForDoubleClick = null;

			if (CurrentInterface.ActiveWidget == null)
				CurrentInterface.ActiveWidget = this;
			if (this.Focusable && !Interface.FocusOnHover) {
				BubblingMouseButtonEventArg be = e as BubblingMouseButtonEventArg;
				if (be.Focused == null) {
					be.Focused = this;
					CurrentInterface.FocusedWidget = this;
					if (e.Button == MouseButton.Right && this.ContextCommands != null)
						CurrentInterface.ShowContextMenu (this);					
				}
			}
			//bubble event to the top
			GraphicObject p = focusParent;
			if (p != null)
				p.onMouseDown(sender,e);

			MouseDown.Raise (this, e);
		}
		public virtual void onMouseUp(object sender, MouseButtonEventArgs e){
			if (IsDragged){
				bool dropOK = false;
				if (CurrentInterface.HoverWidget!=null) {
					if (CurrentInterface.HoverWidget.AllowDrop)
						dropOK = true;
				}
				if (dropOK)
					onDrop (this, null);
				else
					onEndDrag (this, null);
			}

			//bubble event to the top
			GraphicObject p = focusParent;
			if (p != null)
				p.onMouseUp(sender,e);

			MouseUp.Raise (this, e);

			if (MouseIsIn (e.Position) && IsActive) {
				if (CurrentInterface.clickTimer.ElapsedMilliseconds < Interface.DoubleClick)
					CurrentInterface.eligibleForDoubleClick = this;
				onMouseClick (this, e);
			}
		}
		public virtual void onMouseClick(object sender, MouseButtonEventArgs e){
			GraphicObject p = focusParent;
			if (p != null)
				p.onMouseClick(sender,e);
			MouseClick.Raise (this, e);
		}
		public virtual void onMouseDoubleClick(object sender, MouseButtonEventArgs e){
			GraphicObject p = focusParent;
			if (p != null)
				p.onMouseDoubleClick(sender,e);
			MouseDoubleClick.Raise (this, e);
		}
		public virtual void onMouseWheel(object sender, MouseWheelEventArgs e){
			GraphicObject p = focusParent;
			if (p != null)
				p.onMouseWheel(sender,e);

			MouseWheelChanged.Raise (this, e);
		}
		public virtual void onMouseEnter(object sender, MouseMoveEventArgs e)
		{
			#if DEBUG_FOCUS
			Debug.WriteLine("MouseEnter => " + this.ToString());
			#endif
			MouseEnter.Raise (this, e);
		}
		public virtual void onMouseLeave(object sender, MouseMoveEventArgs e)
		{
			#if DEBUG_FOCUS
			Debug.WriteLine("MouseLeave => " + this.ToString());
			#endif
			MouseLeave.Raise (this, e);
		}
		#endregion

		protected virtual void onFocused(object sender, EventArgs e){
			#if DEBUG_FOCUS
			Debug.WriteLine("Focused => " + this.ToString());
			#endif
			Focused.Raise (this, e);
		}
		protected virtual void onUnfocused(object sender, EventArgs e){
			#if DEBUG_FOCUS
			Debug.WriteLine("UnFocused => " + this.ToString());
			#endif
			Unfocused.Raise (this, e);
		}
		public virtual void onEnable(object sender, EventArgs e){
			Enabled.Raise (this, e);
		}
		public virtual void onDisable(object sender, EventArgs e){
			Disabled.Raise (this, e);
		}
		protected virtual void onParentChanged(object sender, DataSourceChangeEventArgs e) {
			ParentChanged.Raise (this, e);
			if (logicalParent == null)
				LogicalParentChanged.Raise (this, e);
		}
		protected virtual void onLogicalParentChanged(object sender, DataSourceChangeEventArgs e) {
			LogicalParentChanged.Raise (this, e);
		}
		internal void ClearTemplateBinding(){
			#if DEBUG_UPDATE
			Debug.WriteLine (string.Format("ClearTemplateBinding: {0}", this.ToString()));
			#endif
			if (ValueChanged == null)
				return;
			EventInfo eiEvt = this.GetType().GetEvent ("ValueChanged");
			foreach (Delegate d in ValueChanged.GetInvocationList()) {
				if (d.Method.Name == "dyn_tmpValueChanged") {
					eiEvt.RemoveEventHandler (this, d);
					#if DEBUG_BINDING
					Debug.WriteLine ("\t{0} template binding handler removed in {1} for: {2}", d.Method.Name, this, "ValueChanged");
					#endif
				}
			}
		}
		public override string ToString ()
		{
			string tmp ="";

			if (Parent != null)
				tmp = Parent.ToString () + tmp;
			#if DEBUG_LAYOUTING
			return Name == "unamed" ? tmp + "." + this.GetType ().Name + uid.ToString(): tmp + "." + Name;
			#else
			return Name == "unamed" ? tmp + "." + this.GetType ().Name : tmp + "." + Name;
			#endif
		}
	}
}