File: MainForm.cs

package info (click to toggle)
xsddiagram 1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,188 kB
  • sloc: cs: 9,274; sh: 42; makefile: 26; xml: 3
file content (1953 lines) | stat: -rw-r--r-- 79,250 bytes parent folder | download | duplicates (2)
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
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
//    XSDDiagram - A XML Schema Definition file viewer
//    Copyright (C) 2006-2016  Regis COSNIER
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program; if not, write to the Free Software
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

// To generate the XMLSchema.cs file:
// > xsd.exe XMLSchema.xsd /classes /l:cs /n:XMLSchema /order

using XSDDiagram.Rendering;
using System.Xml.Schema;
using System.Diagnostics;

using System.Security.Principal;

namespace XSDDiagram
{
	public partial class MainForm : Form
	{
        private DiagramPrinter _diagramPrinter;
        private DiagramGdiRenderer _diagramGdiRenderer;
        private Rectangle _renderingClipRectangle = new Rectangle();

        private Diagram diagram = new Diagram();
        private Schema schema = new Schema();
        private Dictionary<string, TabPage> hashtableTabPageByFilename = new Dictionary<string, TabPage>();
		private string originalTitle = "";
		private DiagramItem contextualMenuPointedElement = null;
        //private string currentLoadedSchemaFilename = "";

        private TextBox textBoxAnnotation;
        private WebBrowser webBrowserDocumentation;
		private bool webBrowserSupported = true;
        private string backupUsername = "", backupPassword = "";

        private MRUManager mruManager;

        public MainForm()
		{
			InitializeComponent();

            bool isElevated = false;
            WindowsIdentity identity = null;
            try
            {
                identity = WindowsIdentity.GetCurrent();
                if (identity != null)
                {
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    if (principal != null)
                        isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
                }
            }
            catch (UnauthorizedAccessException)
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                if (identity != null)
                    identity.Dispose();
            }
            this.toolsToolStripMenuItem.Visible = isElevated && !Options.IsRunningOnMono;
            this.diagram.ShowDocumentation = this.toolStripButtonShowDocumentation.Checked = Options.ShowDocumentation;

            this.originalTitle = Text;

			this.toolStripComboBoxSchemaElement.Sorted = true;
			this.toolStripComboBoxSchemaElement.Items.Add("");

			this.diagram.RequestAnyElement += new Diagram.RequestAnyElementEventHandler(diagram_RequestAnyElement);
            this.panelDiagram.VirtualSize = new Size(0, 0);
            this.panelDiagram.DiagramControl.ContextMenuStrip = this.contextMenuStripDiagram;
			this.panelDiagram.DiagramControl.MouseWheel += new MouseEventHandler(DiagramControl_MouseWheel);
			this.panelDiagram.DiagramControl.MouseClick += new MouseEventHandler(DiagramControl_MouseClick);
			this.panelDiagram.DiagramControl.MouseHover += new EventHandler(DiagramControl_MouseHover);
            this.panelDiagram.DiagramControl.MouseMove += new MouseEventHandler(DiagramControl_MouseMove);
            //this.panelDiagram.DiagramControl.KeyDown += DiagramControl_KeyDown;
            this.panelDiagram.DiagramControl.KeyDown += new KeyEventHandler(DiagramControl_KeyDown);
            this.panelDiagram.DiagramControl.Paint += new PaintEventHandler(DiagramControl_Paint);

            this.schema.RequestCredential += schema_RequestCredential;
            this.backupUsername = Options.Username;
            this.backupPassword = Options.Password;
			if (Options.IsRunningOnMono)
			{
				try
				{
					new WebBrowser().Navigate("about:blank");
				}
				catch
				{
					webBrowserSupported = false;
				}
			}

            UpdateActionsState();
        }

        bool schema_RequestCredential(string url, string realm, int attemptCount, out string username, out string password)
        {
            string label = "The file '" + url + "' requires a username and password.";
            LoginPromptForm dlg = new LoginPromptForm(label);
            dlg.Username = backupUsername;
            dlg.Password = backupPassword;
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                backupUsername = username = dlg.Username;
                backupPassword = password = dlg.Password;
                return true;
            }
            username = password = "";
            return false;
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (Options.IsRunningOnMono)
            {
                // Prevent exception with Linux on Mono
                object[] toolStripMenuItems = new object[] { this.fileToolStripMenuItem, this.fileToolStripMenuItem, this.openToolStripMenuItem, this.openToolStripMenuItem, this.openURLToolStripMenuItem, this.openURLToolStripMenuItem, this.saveDiagramToolStripMenuItem, this.saveDiagramToolStripMenuItem, this.validateXMLFileToolStripMenuItem, this.validateXMLFileToolStripMenuItem, this.recentFilesToolStripMenuItem, this.recentFilesToolStripMenuItem, this.closeToolStripMenuItem, this.closeToolStripMenuItem, this.toolStripMenuItem2, this.pageToolStripMenuItem, this.pageToolStripMenuItem, this.printPreviewToolStripMenuItem, this.printPreviewToolStripMenuItem, this.printToolStripMenuItem, this.printToolStripMenuItem, this.toolStripMenuItem1, this.exitToolStripMenuItem, this.exitToolStripMenuItem, this.toolsToolStripMenuItem, this.toolsToolStripMenuItem, this.windowsExplorerRegistrationToolStripMenuItem, this.windowsExplorerRegistrationToolStripMenuItem, this.registerToolStripMenuItem, this.registerToolStripMenuItem, this.unregisterToolStripMenuItem, this.unregisterToolStripMenuItem, this.windowToolStripMenuItem, this.windowToolStripMenuItem, this.nextTabToolStripMenuItem, this.nextTabToolStripMenuItem, this.previousTabToolStripMenuItem, this.previousTabToolStripMenuItem, this.helpToolStripMenuItem, this.helpToolStripMenuItem, this.aboutToolStripMenuItem, this.aboutToolStripMenuItem, this.toolStripMenuItemAttributesCopyLine, this.toolStripMenuItemAttributesCopyLine, this.toolStripMenuItemAttributesCopyList, this.toolStripMenuItemAttributesCopyList, this.toolStripMenuItemEnumerateCopyLine, this.toolStripMenuItemEnumerateCopyLine, this.toolStripMenuItemEnumerateCopyList, this.toolStripMenuItemEnumerateCopyList, this.addToDiagrammToolStripMenuItem, this.addToDiagrammToolStripMenuItem, this.toolStripMenuItem4, this.toolStripMenuItemElementsCopyLine, this.toolStripMenuItemElementsCopyLine, this.toolStripMenuItemElementsCopyList, this.toolStripMenuItemElementsCopyList, this.gotoXSDFileToolStripMenuItem, this.gotoXSDFileToolStripMenuItem, this.expandToolStripMenuItem, this.expandToolStripMenuItem, this.removeFromDiagramToolStripMenuItem, this.removeFromDiagramToolStripMenuItem, this.toolStripMenuItem3, this.addAllToolStripMenuItem, this.addAllToolStripMenuItem, this.removeAllToolStripMenuItem, this.removeAllToolStripMenuItem, this.expandOneLevelToolStripMenuItem, this.expandOneLevelToolStripMenuItem };
                foreach (var toolStripMenuItem in toolStripMenuItems)
                    GC.SuppressFinalize(toolStripMenuItem);
            }

            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                    components = null;
                }

                if (_diagramPrinter != null)
                {
                    _diagramPrinter.Dispose();
                    _diagramPrinter = null;
                }
            }

            base.Dispose(disposing);
        }

		private void MainForm_Load(object sender, EventArgs e)
		{
            this.mruManager = new MRUManager(this.recentFilesToolStripMenuItem, "xsddiagram", this.recentFilesToolStripMenuSubItemFile_Click, this.recentFilesToolStripMenuSubItemClearAll_Click);


            this.toolStripComboBoxZoom.SelectedIndex = 8;
			this.toolStripComboBoxAlignement.SelectedIndex = 1;

			if (!string.IsNullOrEmpty(Options.InputFile))
			{
				LoadSchema(Options.InputFile);
				foreach (var rootElement in Options.RootElements)
				{
					foreach (var element in schema.Elements)
					{
						if (element.Name == rootElement)
						{
							diagram.Add(element.Tag, element.NameSpace);
						}
					}
				}
				for (int i = 0; i < Options.ExpandLevel; i++)
				{
					diagram.ExpandOneLevel();
				}
				UpdateDiagram();
			}
		}

		private void openToolStripMenuItem_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "xsd files (*.xsd)|*.xsd|All files (*.*)|*.*";
			openFileDialog.FilterIndex = 1;
			openFileDialog.RestoreDirectory = true;
			if (openFileDialog.ShowDialog() == DialogResult.OK)
				LoadSchema(openFileDialog.FileName);
		}

        private void openURLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenURLForm openURLForm = new OpenURLForm("");
            if (openURLForm.ShowDialog() == DialogResult.OK)
                LoadSchema(openURLForm.URL);
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CleanupUserInterface(true);
        }

        private void recentFilesToolStripMenuSubItemFile_Click(object sender, EventArgs evt)
        {
            string filenameOrURL = (sender as ToolStripItem).Text;
            LoadSchema(filenameOrURL);
            //this.mruManager.RemoveRecentFile(filenameOrURL);
        }

        private void recentFilesToolStripMenuSubItemClearAll_Click(object sender, EventArgs evt)
        {
        }

        private void MainForm_DragDrop(object sender, DragEventArgs e)
		{
            if (e.Data.GetDataPresent("UniformResourceLocator"))
            {
                string url = e.Data.GetData(DataFormats.Text, true) as string;
                if (!string.IsNullOrEmpty(url))
                    LoadSchema(url.Trim());
            }
            else if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if(files != null && files.Length > 0)
                    LoadSchema(files[0]);
            }
		}

		private void MainForm_DragEnter(object sender, DragEventArgs e)
		{
            if (e.Data.GetDataPresent(DataFormats.FileDrop)
                || e.Data.GetDataPresent("UniformResourceLocator")
                )
				e.Effect = DragDropEffects.Move;
			else
				e.Effect = DragDropEffects.None;
		}

		private void saveDiagramToolStripMenuItem_Click(object sender, EventArgs e)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "SVG files (*.svg)|*.svg" + (Options.IsRunningOnMono ? "" : "|EMF files (*.emf)|*.emf") + "|PNG files (*.png)|*.png|JPG files (*.jpg)|*.jpg|TXT files (*.txt)|*.txt|CSV files (*.csv)|*.csv|All files (*.*)|*.*";
			saveFileDialog.FilterIndex = 1;
			saveFileDialog.RestoreDirectory = true;
			if (saveFileDialog.ShowDialog() == DialogResult.OK)
			{
                string outputFilename = saveFileDialog.FileName;
				try
				{
                    DiagramExporter exporter = new DiagramExporter(diagram);
                    Graphics g1 = this.panelDiagram.DiagramControl.CreateGraphics();
                    exporter.Export(outputFilename, g1, new DiagramAlertHandler(SaveAlert), new Dictionary<string, object>() 
                            { 
                                { "TextOutputFields", Options.TextOutputFields }
                                //For future parameters, {}
                            });
                    g1.Dispose();
				}
                catch (System.ArgumentException ex)
                {
                    MessageBox.Show("You have reach the system limit.\r\nPlease remove some element from the diagram to make it smaller.");
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                }
                catch (System.Runtime.InteropServices.ExternalException ex)
                {
                    MessageBox.Show("You have reach the system limit.\r\nPlease remove some element from the diagram to make it smaller.");
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                }
                catch (Exception ex)
				{
                    MessageBox.Show(ex.Message);
					System.Diagnostics.Trace.WriteLine(ex.ToString());
				}
			}
		}

        bool SaveAlert(string title, string message)
        {
            return MessageBox.Show(this, message, title, MessageBoxButtons.YesNo) == DialogResult.Yes;
        }

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AboutForm aboutForm = new AboutForm();
			aboutForm.ShowDialog(this);
		}

		private void toolStripComboBoxSchemaElement_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (this.toolStripComboBoxSchemaElement.SelectedItem != null)
			{
				XSDObject xsdObject = this.toolStripComboBoxSchemaElement.SelectedItem as XSDObject;
				if (xsdObject != null)
					SelectSchemaElement(xsdObject);
			}
		}

		private void toolStripButtonAddToDiagram_Click(object sender, EventArgs e)
		{
			if (this.toolStripComboBoxSchemaElement.SelectedItem != null)
            {
                XSDObject xsdObject = this.toolStripComboBoxSchemaElement.SelectedItem as XSDObject;
                if (xsdObject != null)
                {
                    DiagramItem diagramItem = this.diagram.Add(xsdObject.Tag, xsdObject.NameSpace);
                    if(diagramItem != null)
                        SelectDiagramElement(diagramItem, true);
                    else
                        UpdateDiagram();
                }
            }
        }

        private void toolStripButtonAddAllToDiagram_Click(object sender, EventArgs e)
		{
            DiagramItem firstDiagramItem = null;
            foreach (XSDObject xsdObject in this.schema.ElementsByName.Values)
                if (xsdObject != null)
                {
                    DiagramItem diagramItem = this.diagram.Add(xsdObject.Tag, xsdObject.NameSpace);
                    if (firstDiagramItem == null && diagramItem != null)
                        firstDiagramItem = diagramItem;
                }
            if(firstDiagramItem != null)
                SelectDiagramElement(firstDiagramItem, true);
            else
                UpdateDiagram();
        }

		void DiagramControl_Paint(object sender, PaintEventArgs e)
		{
            if (_diagramGdiRenderer == null)
                _diagramGdiRenderer = new DiagramGdiRenderer(e.Graphics);
            else if (e.Graphics != _diagramGdiRenderer.Graphics)
                _diagramGdiRenderer.Graphics = e.Graphics;
            if (_diagramGdiRenderer != null)
            {
                Point virtualPoint = this.panelDiagram.VirtualPoint;
                e.Graphics.TranslateTransform(-(float)virtualPoint.X, -(float)virtualPoint.Y);
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                _renderingClipRectangle.Location = virtualPoint;
                _renderingClipRectangle.Size = this.panelDiagram.DiagramControl.ClientRectangle.Size;

                _diagramGdiRenderer.Render(diagram, _renderingClipRectangle);
            }
		}

		private void UpdateDiagram()
		{
			if (this.diagram.RootElements.Count != 0)
			{
				Graphics g = this.panelDiagram.DiagramControl.CreateGraphics();
				this.diagram.Layout(g);
				g.Dispose();
				Size bbSize = this.diagram.BoundingBox.Size + this.diagram.Padding + this.diagram.Padding;
				this.panelDiagram.VirtualSize = new Size((int)(bbSize.Width * this.diagram.Scale), (int)(bbSize.Height * this.diagram.Scale));
			}
			else
				this.panelDiagram.VirtualSize = new Size(0, 0);
		}

		private void UpdateTitle(string filename)
		{
			if (filename.Length > 0)
				Text = this.originalTitle + " - " + filename;
			else
				Text = this.originalTitle;
		}

		private void LoadSchema(string schemaFilename)
        {
            Cursor = Cursors.WaitCursor;

            this.mruManager.AddRecentFile(schemaFilename);

            CleanupUserInterface(false);

            UpdateTitle(schemaFilename);

            schema.LoadSchema(schemaFilename);

            UpdateActionsState();

            foreach (XSDObject xsdObject in schema.Elements)
            {
                this.listViewElements.Items.Add(new ListViewItem(new string[] { xsdObject.Name, xsdObject.Type, xsdObject.NameSpace })).Tag = xsdObject;
                this.toolStripComboBoxSchemaElement.Items.Add(xsdObject);
            }

            Cursor = Cursors.Default;

            if (this.schema.LoadError.Count > 0)
            {
                ErrorReportForm errorReportForm = new ErrorReportForm();
                errorReportForm.Errors = this.schema.LoadError;
                errorReportForm.ShowDialog(this);
            }

            this.diagram.ElementsByName = this.schema.ElementsByName;
            if (this.schema.FirstElement != null)
                this.toolStripComboBoxSchemaElement.SelectedItem = this.schema.FirstElement;
            else
                this.toolStripComboBoxSchemaElement.SelectedIndex = 0;

            tabControlView_Selected(null, null);

            this.tabControlView.SuspendLayout();
            foreach (string filename in this.schema.XsdFilenames)
            {
                string fullPath = filename;
                Control browser = null;
                if (webBrowserSupported)
                    browser = new WebBrowser();
                else
                    browser = new System.Windows.Forms.TextBox() { Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Both };
                browser.Dock = DockStyle.Fill;
                browser.TabIndex = 0;
                try
                {
                    new Uri(filename);
                }
                catch
                {
                    fullPath = Path.GetFullPath(filename);
                }
                TabPage tabPage = new TabPage(Path.GetFileNameWithoutExtension(filename));
                tabPage.Tag = fullPath;
                tabPage.ToolTipText = fullPath;
                tabPage.Controls.Add(browser);
                tabPage.UseVisualStyleBackColor = true;

                this.tabControlView.TabPages.Add(tabPage);
                this.hashtableTabPageByFilename[filename] = tabPage;

            }
            this.tabControlView.ResumeLayout();

            //currentLoadedSchemaFilename = schemaFilename;
        }

        private void UpdateActionsState()
        {
            bool isSchemaLoaded = schema.IsLoaded();
            toolStripButtonSaveDiagram.Enabled = isSchemaLoaded;
            toolStripButtonPrint.Enabled = isSchemaLoaded;
            toolStripButtonAddToDiagram.Enabled = isSchemaLoaded;
            toolStripButtonAddAllToDiagram.Enabled = isSchemaLoaded;
            toolStripButtonRemoveAllFromDiagram.Enabled = isSchemaLoaded;
            toolStripButtonExpandOneLevel.Enabled = isSchemaLoaded;
            closeToolStripMenuItem.Enabled = isSchemaLoaded;
            saveDiagramToolStripMenuItem.Enabled = isSchemaLoaded;
            validateXMLFileToolStripMenuItem.Enabled = isSchemaLoaded;
            printPreviewToolStripMenuItem.Enabled = isSchemaLoaded;
            printToolStripMenuItem.Enabled = isSchemaLoaded;
        }

        private void CleanupUserInterface(bool fullCleanup)
        {
            this.diagram.Clear();
            this.panelDiagram.VirtualSize = new Size(0, 0);
            this.panelDiagram.VirtualPoint = new Point(0, 0);
            this.panelDiagram.Clear();
            this.hashtableTabPageByFilename.Clear();
            this.listViewElements.Items.Clear();
            this.listViewAttributes.Items.Clear();
            this.toolStripComboBoxSchemaElement.SelectedItem = "";
            this.toolStripComboBoxSchemaElement.Items.Clear();
            this.toolStripComboBoxSchemaElement.Items.Add("");
            this.propertyGridSchemaObject.SelectedObject = null;
            this.textBoxElementPath.Text = "";

            while (this.tabControlView.TabCount > 1)
                this.tabControlView.TabPages.RemoveAt(1);

            ShowDocumentation(null);

            if (fullCleanup)
            {
                UpdateTitle("");
                schema.Cleanup();
                UpdateActionsState();
            }
        }

        void DiagramControl_MouseClick(object sender, MouseEventArgs e)
		{
			Point location = e.Location;
			location.Offset(this.panelDiagram.VirtualPoint);

			DiagramItem resultElement;
			DiagramHitTestRegion resultRegion;
			this.diagram.HitTest(location, out resultElement, out resultRegion);
			if (resultRegion != DiagramHitTestRegion.None)
			{
				if (resultRegion == DiagramHitTestRegion.ChildExpandButton)
				{
					if (resultElement.HasChildElements)
					{
						if (resultElement.ChildElements.Count == 0)
						{
							this.diagram.ExpandChildren(resultElement);
							resultElement.ShowChildElements = true;
						}
						else
							resultElement.ShowChildElements ^= true;

                        //UpdateDiagram();
                        //this.panelDiagram.ScrollTo(this.diagram.ScalePoint(resultElement.Location), true);
                        SelectDiagramElement(resultElement, true);
                    }
				}
				else if (resultRegion == DiagramHitTestRegion.Element)
				{
					if ((ModifierKeys & (Keys.Control | Keys.Shift)) == (Keys.Control | Keys.Shift)) // For Debug
					{
						this.toolStripComboBoxSchemaElement.SelectedItem = "";
						this.propertyGridSchemaObject.SelectedObject = resultElement;
					}
					else
						SelectDiagramElement(resultElement);
				}
				else
					SelectDiagramElement(null);
			}
		}

		private void SelectDiagramElement(DiagramItem element)
		{
			SelectDiagramElement(element, false);
		}

        private void SelectDiagramElement(DiagramItem element, bool scrollToElement)
		{
			this.textBoxElementPath.Text = "";

            if (element == null)
			{
				this.toolStripComboBoxSchemaElement.SelectedItem = "";
				this.propertyGridSchemaObject.SelectedObject = null;
				this.listViewAttributes.Items.Clear();
			}
            else
			{
                XSDObject xsdObject;
                if (this.schema.ElementsByName.TryGetValue(element.FullName, out xsdObject) && xsdObject != null)
                    this.toolStripComboBoxSchemaElement.SelectedItem = xsdObject;
				else
					this.toolStripComboBoxSchemaElement.SelectedItem = null;

				SelectSchemaElement(element);

				string path = '/' + element.Name;
				DiagramItem parentElement = element.Parent;
				while (parentElement != null)
				{
					if (parentElement.ItemType == DiagramItemType.element && !string.IsNullOrEmpty(parentElement.Name))
						path = '/' + parentElement.Name + path;
					parentElement = parentElement.Parent;
				}
				this.textBoxElementPath.Text = path;
			}

            this.diagram.SelectElement(element);
            UpdateDiagram();
            if (scrollToElement)
                this.panelDiagram.ScrollTo(this.diagram.ScalePoint(element.Location), true);
        }

        private void SelectSchemaElement(XSDObject xsdObject)
		{
			SelectSchemaElement(xsdObject.Tag, xsdObject.NameSpace);
		}

		private void SelectSchemaElement(DiagramItem diagramBase)
		{
			SelectSchemaElement(diagramBase.TabSchema, diagramBase.NameSpace);
		}

		private void SelectSchemaElement(XMLSchema.openAttrs openAttrs, string nameSpace)
		{
			this.propertyGridSchemaObject.SelectedObject = openAttrs;
			ShowDocumentation(null);

			XMLSchema.annotated annotated = openAttrs as XMLSchema.annotated;
			if (annotated != null)
			{
				// Element documentation
				if (annotated.annotation != null)
					ShowDocumentation(annotated.annotation);

				// Show the enumeration
				ShowEnumerate(annotated);

				// Attributes enumeration
				List<XSDAttribute> listAttributes = new List<XSDAttribute>();
				if (annotated is XMLSchema.element)
				{
					XMLSchema.element element = annotated as XMLSchema.element;

					if (element.Item is XMLSchema.complexType)
					{
						XMLSchema.complexType complexType = element.Item as XMLSchema.complexType;
						listAttributes.AddRange(ShowAttributes(complexType, nameSpace));
					}
					else if (element.type != null)
					{
                        //XSDObject xsdObject = this.schema.ElementsByName[QualifiedNameToFullName("type", element.type)] as XSDObject;
                        //if (xsdObject != null)
                        XSDObject xsdObject;
                        if (this.schema.ElementsByName.TryGetValue(QualifiedNameToFullName("type", element.type), out xsdObject) && xsdObject != null)
						{
							XMLSchema.annotated annotatedElement = xsdObject.Tag as XMLSchema.annotated;
							if (annotatedElement is XMLSchema.complexType)
							{
								XMLSchema.complexType complexType = annotatedElement as XMLSchema.complexType;
								listAttributes.AddRange(ShowAttributes(complexType, nameSpace));
							}
							else
							{
							}
						}
						else
						{
						}
					}
					else
					{
					}
				}
				else if (annotated is XMLSchema.complexType)
				{
					XMLSchema.complexType complexType = annotated as XMLSchema.complexType;
					listAttributes.AddRange(ShowAttributes(complexType, nameSpace));
				}
                //RC++ Original code
                //else
                //{
                //}

                //this.listViewAttributes.Items.Clear();
                //foreach (XSDAttribute attribute in listAttributes)
                //    this.listViewAttributes.Items.Add(new ListViewItem(new string[] { attribute.Name, attribute.Type, attribute.Use, attribute.DefaultValue })).Tag = attribute;
                //RC--

                //Adrian++
                //This part i modify
                else if (annotated is XMLSchema.simpleType)
                {
                    XMLSchema.attribute attr = new XMLSchema.attribute();
                    XMLSchema.localSimpleType def = new XMLSchema.localSimpleType();
                    def.Item = (annotated as XMLSchema.simpleType).Item;
                    attr.simpleType = def;
                    string type = "";
                    if (def.Item is XMLSchema.restriction) type = (def.Item as XMLSchema.restriction).@base.Name;
                    XSDAttribute XSDattr = new XSDAttribute("filename", (annotated as XMLSchema.simpleType).name, "namespace", type, false, "", "", attr);
                    listAttributes.Add(XSDattr);

                }
                //This part i modify
                this.listViewAttributes.Items.Clear();
                listAttributes.Reverse();
                foreach (XSDAttribute attribute in listAttributes)
                {
                    string s = "";
                    //dgis fix github issue 2 (attribute.Tag == null ???)
                    if (attribute.Tag != null && attribute.Tag.simpleType != null && attribute.Tag.simpleType.Item is XMLSchema.restriction)
                    {
                        XMLSchema.restriction r = attribute.Tag.simpleType.Item as XMLSchema.restriction;
                        if (r.Items != null)
                        {
                            for (int i = 0; i < r.Items.Length; i++)
                            {
                                s += r.ItemsElementName[i].ToString() + "(" + r.Items[i].id + " " + r.Items[i].value + ");";
                            }
                        }
                    }

                    this.listViewAttributes.Items.Add(new ListViewItem(new string[] { attribute.Name, attribute.Type, attribute.Use, attribute.DefaultValue, s })).Tag = attribute;
                }
                //Adrian--
			}
		}

		private List<XSDAttribute> ShowAttributes(XMLSchema.complexType complexType, string nameSpace)
		{
			List<XSDAttribute> listAttributes = new List<XSDAttribute>();
			ParseComplexTypeAttributes(nameSpace, listAttributes, complexType, false);
			return listAttributes;
		}

		private void ParseComplexTypeAttributes(string nameSpace, List<XSDAttribute> listAttributes, XMLSchema.complexType complexType, bool isRestriction)
		{
			if (complexType.ItemsElementName != null)
			{
				for (int i = 0; i < complexType.ItemsElementName.Length; i++)
				{
					switch (complexType.ItemsElementName[i])
					{
						case XMLSchema.ItemsChoiceType4.attribute:
							{
								XMLSchema.attribute attribute = complexType.Items[i] as XMLSchema.attribute;
								ParseAttribute(nameSpace, listAttributes, attribute, false);
							}
							break;
						case XMLSchema.ItemsChoiceType4.attributeGroup:
							{
								XMLSchema.attributeGroup attributeGroup = complexType.Items[i] as XMLSchema.attributeGroup;
								ParseAttributeGroup(nameSpace, listAttributes, attributeGroup, false);
							}
							break;
						case XMLSchema.ItemsChoiceType4.anyAttribute:
							XMLSchema.wildcard wildcard = complexType.Items[i] as XMLSchema.wildcard;
							XSDAttribute xsdAttribute = new XSDAttribute("", "*", wildcard.@namespace, "", false, null, null, null);
							listAttributes.Add(xsdAttribute);
							break;
						case XMLSchema.ItemsChoiceType4.simpleContent:
						case XMLSchema.ItemsChoiceType4.complexContent:
							XMLSchema.annotated annotatedContent = null;
							if (complexType.Items[i] is XMLSchema.complexContent)
							{
								XMLSchema.complexContent complexContent = complexType.Items[i] as XMLSchema.complexContent;
								annotatedContent = complexContent.Item;
							}
							else if (complexType.Items[i] is XMLSchema.simpleContent)
							{
								XMLSchema.simpleContent simpleContent = complexType.Items[i] as XMLSchema.simpleContent;
								annotatedContent = simpleContent.Item;
							}
							if (annotatedContent is XMLSchema.extensionType)
							{
								XMLSchema.extensionType extensionType = annotatedContent as XMLSchema.extensionType;
                                //XSDObject xsdExtensionType = this.schema.ElementsByName[QualifiedNameToFullName("type", extensionType.@base)] as XSDObject;
                                //if (xsdExtensionType != null)
                                XSDObject xsdExtensionType;
                                if (this.schema.ElementsByName.TryGetValue(QualifiedNameToFullName("type", extensionType.@base), out xsdExtensionType) && xsdExtensionType != null)
                                {
									XMLSchema.annotated annotatedExtension = xsdExtensionType.Tag as XMLSchema.annotated;
									if (annotatedExtension != null)
									{
										if (annotatedExtension is XMLSchema.complexType)
											ParseComplexTypeAttributes(extensionType.@base.Namespace, listAttributes, annotatedExtension as XMLSchema.complexType, false);
									}
								}
								if (extensionType.Items != null)
								{
									foreach (XMLSchema.annotated annotated in extensionType.Items)
									{
										if (annotated is XMLSchema.attribute)
										{
											ParseAttribute(nameSpace, listAttributes, annotated as XMLSchema.attribute, false);
										}
										else if (annotated is XMLSchema.attributeGroup)
										{
											ParseAttributeGroup(nameSpace, listAttributes, annotated as XMLSchema.attributeGroup, false);
										}
									}
								}
							}
							else if (annotatedContent is XMLSchema.restrictionType)
							{
								XMLSchema.restrictionType restrictionType = annotatedContent as XMLSchema.restrictionType;
                                //XSDObject xsdRestrictionType = this.schema.ElementsByName[QualifiedNameToFullName("type", restrictionType.@base)] as XSDObject;
                                //if (xsdRestrictionType != null)
                                XSDObject xsdRestrictionType;
                                if (this.schema.ElementsByName.TryGetValue(QualifiedNameToFullName("type", restrictionType.@base), out xsdRestrictionType) && xsdRestrictionType != null)
                                {
									XMLSchema.annotated annotatedRestriction = xsdRestrictionType.Tag as XMLSchema.annotated;
									if (annotatedRestriction != null)
									{
										if (annotatedRestriction is XMLSchema.complexType)
											ParseComplexTypeAttributes(restrictionType.@base.Namespace, listAttributes, annotatedRestriction as XMLSchema.complexType, false);
									}
								}
								if (restrictionType.Items1 != null)
								{
									foreach (XMLSchema.annotated annotated in restrictionType.Items1)
									{
										if (annotated is XMLSchema.attribute)
										{
											ParseAttribute(nameSpace, listAttributes, annotated as XMLSchema.attribute, true);
										}
										else if (annotated is XMLSchema.attributeGroup)
										{
											ParseAttributeGroup(nameSpace, listAttributes, annotated as XMLSchema.attributeGroup, true);
										}
									}
								}
							}
							break;
					}
				}
			}
			else
			{
			}
		}

		private void ParseAttribute(string nameSpace, List<XSDAttribute> listAttributes, XMLSchema.attribute attribute, bool isRestriction)
		{
			bool isReference = false;
			string filename = "";
			string name = attribute.name;
			string type = "";
			if (attribute.@ref != null)
			{
                object o = null;
                this.schema.AttributesByName.TryGetValue(QualifiedNameToFullName("attribute", attribute.@ref), out o);
                if (o is XSDAttribute)
				{
					XSDAttribute xsdAttributeInstance = o as XSDAttribute;
					ParseAttribute(nameSpace, listAttributes, xsdAttributeInstance.Tag, isRestriction);
					return;
				}
				else // Reference not found!
				{
					type = QualifiedNameToAttributeTypeName(attribute.@ref);
					name = attribute.@ref.Name;
					nameSpace = attribute.@ref.Namespace;
					isReference = true;
				}
			}
			else if (attribute.type != null)
			{
				type = QualifiedNameToAttributeTypeName(attribute.type);
				nameSpace = attribute.type.Namespace;
			}
			else if (attribute.simpleType != null)
			{
				XMLSchema.simpleType simpleType = attribute.simpleType as XMLSchema.simpleType;
				if (simpleType.Item is XMLSchema.restriction)
				{
					XMLSchema.restriction restriction = simpleType.Item as XMLSchema.restriction;
					type = QualifiedNameToAttributeTypeName(restriction.@base);
					nameSpace = restriction.@base.Namespace;
				}
				else if (simpleType.Item is XMLSchema.list)
				{
					XMLSchema.list list = simpleType.Item as XMLSchema.list;
					type = QualifiedNameToAttributeTypeName(list.itemType);
					nameSpace = list.itemType.Namespace;
				}
				else
				{
				}
			}
			else
			{

			}
			if (string.IsNullOrEmpty(attribute.name) && string.IsNullOrEmpty(name))
			{
			}
			if (isRestriction)
			{
				if (attribute.use == XMLSchema.attributeUse.prohibited)
				{
					foreach (XSDAttribute xsdAttribute in listAttributes)
					{
						if (xsdAttribute.Name == name)
						{
							//listAttributes.Remove(xsdAttribute);
							xsdAttribute.Use = attribute.use.ToString();
							break;
						}
					}
				}
			}
			else
			{
				XSDAttribute xsdAttribute = new XSDAttribute(filename, name, nameSpace, type, isReference, attribute.@default, attribute.use.ToString(), attribute);
				listAttributes.Insert(0, xsdAttribute);
			}
		}

		private void ParseAttributeGroup(string nameSpace, List<XSDAttribute> listAttributes, XMLSchema.attributeGroup attributeGroup, bool isRestriction)
		{
			if (attributeGroup is XMLSchema.attributeGroupRef && attributeGroup.@ref != null)
			{
                object o = null;
                this.schema.AttributesByName.TryGetValue(QualifiedNameToFullName("attributeGroup", attributeGroup.@ref), out o);
                if (o is XSDAttributeGroup)
				{
					XSDAttributeGroup xsdAttributeGroup = o as XSDAttributeGroup;
					XMLSchema.attributeGroup attributeGroupInstance = xsdAttributeGroup.Tag;

					foreach (XMLSchema.annotated annotated in attributeGroupInstance.Items)
					{
						if (annotated is XMLSchema.attribute)
						{
							ParseAttribute(nameSpace, listAttributes, annotated as XMLSchema.attribute, isRestriction);
						}
						else if (annotated is XMLSchema.attributeGroup)
						{
							ParseAttributeGroup(nameSpace, listAttributes, annotated as XMLSchema.attributeGroup, isRestriction);
						}
					}
				}
			}
			else
			{

			}
		}

		private static string QualifiedNameToFullName(string type, System.Xml.XmlQualifiedName xmlQualifiedName)
		{
			return xmlQualifiedName.Namespace + ':' + type + ':' + xmlQualifiedName.Name;
		}

		private static string QualifiedNameToAttributeTypeName(System.Xml.XmlQualifiedName xmlQualifiedName)
		{
			return xmlQualifiedName.Name + "  : " + xmlQualifiedName.Namespace;
		}

		private void ShowEnumerate(XMLSchema.attribute attribute)
		{
			this.listViewEnumerate.Items.Clear();
			if (attribute != null)
			{
				if (attribute.type != null)
				{
                    //XSDObject xsdObject = this.schema.ElementsByName[QualifiedNameToFullName("type", attribute.type)] as XSDObject;
                    //if (xsdObject != null)
                    XSDObject xsdObject;
                    if (this.schema.ElementsByName.TryGetValue(QualifiedNameToFullName("type", attribute.type), out xsdObject) && xsdObject != null)
                    {
						XMLSchema.annotated annotatedElement = xsdObject.Tag as XMLSchema.annotated;
						if (annotatedElement is XMLSchema.simpleType)
							ShowEnumerate(annotatedElement as XMLSchema.simpleType);
					}
				}
				else if (attribute.simpleType != null)
				{
					ShowEnumerate(attribute.simpleType);
				}
			}
		}

		private void ShowEnumerate(XMLSchema.annotated annotated)
		{
			this.listViewEnumerate.Items.Clear();

			if (annotated != null)
			{
				XMLSchema.element element = annotated as XMLSchema.element;
				if (element != null && element.type != null)
				{
                    //XSDObject xsdObject = this.schema.ElementsByName[QualifiedNameToFullName("type", element.type)] as XSDObject;
                    //if (xsdObject != null)
                    XSDObject xsdObject;
                    if (this.schema.ElementsByName.TryGetValue(QualifiedNameToFullName("type", element.type), out xsdObject) && xsdObject != null)
                    {
						XMLSchema.annotated annotatedElement = xsdObject.Tag as XMLSchema.annotated;
						if (annotatedElement is XMLSchema.simpleType)
							ShowEnumerate(annotatedElement as XMLSchema.simpleType);
					}
				}
			}
		}

		private void ShowEnumerate(XMLSchema.simpleType simpleType)
		{
			if (simpleType != null)
			{
				if (simpleType.Item != null)
				{
					XMLSchema.restriction restriction = simpleType.Item as XMLSchema.restriction;
					if (restriction != null && restriction.ItemsElementName != null)
					{
						for (int i = 0; i < restriction.ItemsElementName.Length; i++)
						{
							if (restriction.ItemsElementName[i] == XMLSchema.ItemsChoiceType.enumeration)
							{
								XMLSchema.facet facet = restriction.Items[i] as XMLSchema.facet;
								if (facet != null)
                                    this.listViewEnumerate.Items.Add(facet.value).Tag = facet;
							}
						}

						if (this.listViewEnumerate.Items.Count != 0)
							this.listViewEnumerate.Columns[0].Width = -1;
					}
				}
			}
		}


		private void ShowDocumentation(XMLSchema.annotation annotation)
		{
            if (this.textBoxAnnotation == null)
            {
                // 
                // webBrowserDocumentation
                // 
                if(webBrowserSupported)
                {
                    this.webBrowserDocumentation = new System.Windows.Forms.WebBrowser();
                    this.webBrowserDocumentation.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.webBrowserDocumentation.Location = new System.Drawing.Point(0, 0);
                    this.webBrowserDocumentation.MinimumSize = new System.Drawing.Size(20, 20);
                    this.webBrowserDocumentation.Name = "webBrowserDocumentation";
                    this.webBrowserDocumentation.Size = new System.Drawing.Size(214, 117);
                    this.webBrowserDocumentation.TabIndex = 1;
                    this.splitContainerDiagramElement.Panel2.Controls.Add(this.webBrowserDocumentation);
                }
                else
                    this.webBrowserDocumentation = null;
                // 
                // textBoxAnnotation
                // 
                this.textBoxAnnotation = new System.Windows.Forms.TextBox();
                this.textBoxAnnotation.Dock = System.Windows.Forms.DockStyle.Fill;
                this.textBoxAnnotation.Location = new System.Drawing.Point(0, 0);
                this.textBoxAnnotation.Multiline = true;
                this.textBoxAnnotation.Name = "textBoxAnnotation";
                this.textBoxAnnotation.ReadOnly = true;
                this.textBoxAnnotation.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
                this.textBoxAnnotation.Size = new System.Drawing.Size(214, 117);
                this.textBoxAnnotation.TabIndex = 0;
                this.splitContainerDiagramElement.Panel2.Controls.Add(this.textBoxAnnotation);
            }
			if (annotation == null)
			{
				this.textBoxAnnotation.Text = "";
				this.textBoxAnnotation.Visible = true;
                if (this.webBrowserDocumentation != null)
    				this.webBrowserDocumentation.Visible = false;

				return;
			}

			foreach (object o in annotation.Items)
			{
				if (o is XMLSchema.documentation)
				{
					XMLSchema.documentation documentation = o as XMLSchema.documentation;
					if (documentation.Any != null && documentation.Any.Length > 0)
					{
						string text = documentation.Any[0].Value;
						text = text.Replace("\n", " ");
						text = text.Replace("\t", " ");
						text = text.Replace("\r", "");
						text = Regex.Replace(text, " +", " ");
						text = text.Trim();

						//text = text.Replace(, " ");

						//text = text.Trim('\n', '\t', '\r', ' ');
						//string[] textLines = text.Split(new char[] { '\n' });
						//for (int i = 0; i < textLines.Length; i++)
						//    textLines[i] = textLines[i].Trim('\n', '\t', '\r', ' ');
						//text = string.Join("\r\n", textLines);
						this.textBoxAnnotation.Text = text;
						this.textBoxAnnotation.Visible = true;
                        if (this.webBrowserDocumentation != null)
                            this.webBrowserDocumentation.Visible = false;
					}
					else if (documentation.source != null)
					{
                        if (this.webBrowserDocumentation != null)
                        {
                            this.textBoxAnnotation.Visible = false;
                            this.webBrowserDocumentation.Visible = true;
                            this.webBrowserDocumentation.Navigate(documentation.source);
                        }
                        else
                        {
                            this.textBoxAnnotation.Text = documentation.source;
                            this.textBoxAnnotation.Visible = true;
                        }
					}
					break;
				}
			}
		}

		private void listViewAttributes_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (this.listViewAttributes.SelectedItems.Count > 0)
			{
				XSDAttribute xsdAttribute = this.listViewAttributes.SelectedItems[0].Tag as XSDAttribute;
				XMLSchema.attribute attribute = xsdAttribute.Tag;
				if (attribute != null && attribute.annotation != null)
					ShowDocumentation(attribute.annotation);
				else
					ShowDocumentation(null);
				ShowEnumerate(attribute);
			}
		}

        private void listViewEnumerate_SelectedIndexChanged(object sender, EventArgs e)
		{
            if (this.listViewEnumerate.SelectedItems.Count > 0)
			{
				XMLSchema.facet facet = this.listViewEnumerate.SelectedItems[0].Tag as XMLSchema.facet;
				if (facet != null && facet.annotation != null)
					ShowDocumentation(facet.annotation);
				else
					ShowDocumentation(null);
			}
		}

		private void toolStripComboBoxZoom_SelectedIndexChanged(object sender, EventArgs e)
		{
			try
			{
				string zoomString = this.toolStripComboBoxZoom.SelectedItem as string;
				zoomString = zoomString.Replace("%", "");

				float zoom = (float)int.Parse(zoomString) / 100.0f;
				if (zoom >= 0.10 && zoom <= 10)
				{
					//Point virtualCenter = this.panelDiagram.VirtualPoint;
					//virtualCenter.Offset(this.panelDiagram.DiagramControl.Width / 2, this.panelDiagram.DiagramControl.Height / 2);
					//Size oldSize = this.panelDiagram.VirtualSize;
					//this.diagram.Scale = zoom;
					//UpdateDiagram();
					//Size newSize = this.panelDiagram.VirtualSize;
					//virtualCenter.X = (int)((float)newSize.Width / (float)oldSize.Width * (float)virtualCenter.X);
					//virtualCenter.Y = (int)((float)newSize.Height / (float)oldSize.Height * (float)virtualCenter.Y);
					//if (virtualCenter.X > this.diagram.BoundingBox.Right)
					//    virtualCenter.X = this.diagram.BoundingBox.Right;
					//if (virtualCenter.Y > this.diagram.BoundingBox.Bottom)
					//    virtualCenter.Y = this.diagram.BoundingBox.Bottom;
					//this.panelDiagram.ScrollTo(virtualCenter, true);

					Point virtualCenter = this.panelDiagram.VirtualPoint;
					virtualCenter.Offset(this.panelDiagram.DiagramControl.Width / 2, this.panelDiagram.DiagramControl.Height / 2);
					Size oldSize = this.panelDiagram.VirtualSize;
					this.diagram.Scale = zoom;
					UpdateDiagram();
					Size newSize = this.panelDiagram.VirtualSize;
					Point newVirtualCenter = new Point();
					newVirtualCenter.X = (int)((float)newSize.Width / (float)oldSize.Width * (float)virtualCenter.X);
					newVirtualCenter.Y = (int)((float)newSize.Height / (float)oldSize.Height * (float)virtualCenter.Y);
					if (newVirtualCenter.X > this.diagram.BoundingBox.Right)
						newVirtualCenter.X = this.diagram.BoundingBox.Right;
					if (newVirtualCenter.Y > this.diagram.BoundingBox.Bottom)
						newVirtualCenter.Y = this.diagram.BoundingBox.Bottom;
					this.panelDiagram.ScrollTo(newVirtualCenter, true);
				}
			}
			catch { }
		}

		private void toolStripComboBoxZoom_TextChanged(object sender, EventArgs e)
		{
			//try
			//{
			//    string zoomString = this.toolStripComboBoxZoom.SelectedItem as string;
			//    zoomString = zoomString.Replace("%", "");

			//    float zoom = (float)int.Parse(zoomString) / 100.0f;
			//    if (zoom >= 0.10 && zoom <= 10)
			//    {
			//        this.diagram.Scale = zoom;
			//        UpdateDiagram();
			//    }
			//}
			//catch { }
		}

		void DiagramControl_MouseWheel(object sender, MouseEventArgs e)
		{
			if ((ModifierKeys & Keys.Control) == Keys.Control)
			{
				if (e.Delta > 0)
				{
					if (this.toolStripComboBoxZoom.SelectedIndex < this.toolStripComboBoxZoom.Items.Count - 1)
						this.toolStripComboBoxZoom.SelectedIndex++;
				}
				else
				{
					if (this.toolStripComboBoxZoom.SelectedIndex > 0)
						this.toolStripComboBoxZoom.SelectedIndex--;
				}
			}
		}

		private void pageToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
                if (_diagramPrinter == null)
                {
                    _diagramPrinter = new DiagramPrinter();
                }
                _diagramPrinter.Diagram = diagram;

                _diagramPrinter.PageSetup();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
                if (_diagramPrinter == null)
                {
                    _diagramPrinter = new DiagramPrinter();
                }
                _diagramPrinter.Diagram = diagram;

                _diagramPrinter.PrintPreview();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void printToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
                if (_diagramPrinter == null)
                {
                    _diagramPrinter = new DiagramPrinter();
                }
                _diagramPrinter.Diagram = diagram;

                _diagramPrinter.Print(true, Options.IsRunningOnMono);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void toolStripButtonTogglePanel_Click(object sender, EventArgs e)
		{
			this.splitContainerMain.Panel2Collapsed = !this.toolStripButtonTogglePanel.Checked;
		}

		private void contextMenuStripDiagram_Opened(object sender, EventArgs e)
		{
			this.gotoXSDFileToolStripMenuItem.Enabled = false;
            this.expandToolStripMenuItem.Enabled = false;
            this.removeFromDiagramToolStripMenuItem.Enabled = false;

			Point contextualMenuMousePosition = this.panelDiagram.DiagramControl.PointToClient(MousePosition);
			contextualMenuMousePosition.Offset(this.panelDiagram.VirtualPoint);
			DiagramItem resultElement;
			DiagramHitTestRegion resultRegion;
			this.diagram.HitTest(contextualMenuMousePosition, out resultElement, out resultRegion);
			if (resultRegion != DiagramHitTestRegion.None)
			{
				if (resultRegion == DiagramHitTestRegion.Element) // && resultElement.Parent == null)
				{
					this.contextualMenuPointedElement = resultElement;
                    this.gotoXSDFileToolStripMenuItem.Enabled = this.schema.ElementsByName.ContainsKey(this.contextualMenuPointedElement.FullName);
                    this.expandToolStripMenuItem.Enabled = true;
                    this.removeFromDiagramToolStripMenuItem.Enabled = true;
				}
			}
		}

		private void gotoXSDFileToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (this.contextualMenuPointedElement != null)
			{
				//XSDObject xsdObject = this.schema.ElementsByName[this.contextualMenuPointedElement.FullName] as XSDObject;
                //if (xsdObject != null)
				XSDObject xsdObject;
                if (this.schema.ElementsByName.TryGetValue(this.contextualMenuPointedElement.FullName, out xsdObject) && xsdObject != null)
				{
                    TabPage tabPage = null;
                    if (this.hashtableTabPageByFilename.TryGetValue(xsdObject.Filename, out tabPage) && tabPage != null)
						this.tabControlView.SelectedTab = tabPage;
				}
			}
			this.contextualMenuPointedElement = null;
		}

        private void expandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExpandCollapseElement(this.contextualMenuPointedElement, false);
            this.contextualMenuPointedElement = null;
        }

        private void removeFromDiagramToolStripMenuItem_Click(object sender, EventArgs e)
		{
            RemoveElement(this.contextualMenuPointedElement);
            this.contextualMenuPointedElement = null;
		}

        private void RemoveElement(DiagramItem element)
        {
            DiagramItem parentDiagram = element.Parent;
            this.diagram.Remove(element);
            UpdateDiagram();
            if (parentDiagram != null)
                this.panelDiagram.ScrollTo(this.diagram.ScalePoint(parentDiagram.Location), true);
            else
                this.panelDiagram.ScrollTo(new Point(0, 0));
        }

        private void tabControlView_Selected(object sender, TabControlEventArgs e)
		{
			if (tabControlView.SelectedTab.Tag != null)
			{
				WebBrowser webBrowser = tabControlView.SelectedTab.Controls[0] as WebBrowser;
                if (webBrowser != null)
                {
                    string url = tabControlView.SelectedTab.Tag as string;
                    //if (webBrowser.Url == null || webBrowser.Url != new Uri(url))
                    if (webBrowser.Document == null)
                        webBrowser.Navigate(url);
                    webBrowser.Select();
                }
                else
                {
                    TextBox textBrowser = tabControlView.SelectedTab.Controls[0] as TextBox;
                    if (textBrowser != null)
                    {
                        string url = tabControlView.SelectedTab.Tag as string;
                        if (string.IsNullOrEmpty(textBrowser.Text))
                        {
                            try
                            {
                                //HttpWebRequest webRequestObject = (HttpWebRequest)WebRequest.Create(url);
                                ////WebRequestObject.UserAgent = ".NET Framework/2.0";
                                ////WebRequestObject.Referer = "http://www.example.com/";
                                //WebResponse response = webRequestObject.GetResponse();
                                //Stream webStream = response.GetResponseStream();
                                //StreamReader reader = new StreamReader(webStream);
                                //textBrowser.Text = reader.ReadToEnd();
                                //reader.Close();
                                //webStream.Close();
                                //response.Close();

                                WebClient client = new WebClient();
                                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                                Stream data = client.OpenRead(url);
                                StreamReader reader = new StreamReader(data);
                                textBrowser.Text = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n", "\r\n");
                                data.Close();
                                reader.Close();
                            }
                            catch (Exception ex)
                            {
                                textBrowser.Text = ex.Message;
                            }
                        }
                        textBrowser.Select();
                    }
                }
			}
		}

		private void tabControlView_Click(object sender, EventArgs e)
		{
			if (tabControlView.SelectedTab.Tag != null)
			{
                Control webBrowser = tabControlView.SelectedTab.Controls[0] as Control;
				if (webBrowser != null)
					webBrowser.Select();
			}
		}

		private void tabControlView_Enter(object sender, EventArgs e)
		{
            if (tabControlView.SelectedTab != null && tabControlView.SelectedTab.Tag != null)
			{
                Control webBrowser = tabControlView.SelectedTab.Controls[0] as Control;
				if (webBrowser != null)
					webBrowser.Focus();
			}
			else
				this.panelDiagram.Focus();
		}

		private void registerToolStripMenuItem_Click(object sender, EventArgs e)
		{
			FileShellExtension.Register(Microsoft.Win32.Registry.GetValue("HKEY_CLASSES_ROOT\\.xsd", null, "xsdfile") as string, "XSDDiagram", "XSD Diagram", string.Format("\"{0}\" \"%L\"", Application.ExecutablePath));
		}

		private void unregisterToolStripMenuItem_Click(object sender, EventArgs e)
		{
			FileShellExtension.Unregister(Microsoft.Win32.Registry.GetValue("HKEY_CLASSES_ROOT\\.xsd", null, "xsdfile") as string, "XSDDiagram");
		}

		private void toolStripButtonShowReferenceBoundingBox_Click(object sender, EventArgs e)
		{
			this.diagram.ShowBoundingBox = this.toolStripButtonShowReferenceBoundingBox.Checked;
			UpdateDiagram();
		}

		private void toolStripComboBoxAlignement_SelectedIndexChanged(object sender, EventArgs e)
		{
			switch (this.toolStripComboBoxAlignement.SelectedItem as string)
			{
				case "Top": this.diagram.Alignement = DiagramAlignement.Near; break;
				case "Center": this.diagram.Alignement = DiagramAlignement.Center; break;
				case "Bottom": this.diagram.Alignement = DiagramAlignement.Far; break;
			}
			UpdateDiagram();
		}

		void diagram_RequestAnyElement(DiagramItem diagramElement, out XMLSchema.element element, out string nameSpace)
		{
			element = null;
			nameSpace = "";

			//ElementsForm elementsForm = new ElementsForm();
			//elementsForm.Location = MousePosition; //diagramElement.Location //MousePosition;
			//elementsForm.ListBoxElements.Items.Clear();
			//elementsForm.ListBoxElements.Items.Insert(0, "(Cancel)");
			//foreach (XSDObject xsdObject in this.schema.ElementsByName.Values)
			//    if (xsdObject != null && xsdObject.Type == "element")
			//        elementsForm.ListBoxElements.Items.Add(xsdObject);
			//if (elementsForm.ShowDialog(this.diagramControl) == DialogResult.OK && (elementsForm.ListBoxElements.SelectedItem as XSDObject) != null)
			//{
			//    XSDObject xsdObject = elementsForm.ListBoxElements.SelectedItem as XSDObject;
			//    element = xsdObject.Tag as XMLSchema.element;
			//    nameSpace = xsdObject.NameSpace;
			//}
		}

		private void listViewElement_Click(object sender, EventArgs e)
		{
			if (this.listViewElements.SelectedItems.Count > 0)
				SelectSchemaElement(this.listViewElements.SelectedItems[0].Tag as XSDObject);
		}

		private void listViewElement_DoubleClick(object sender, EventArgs e)
		{
			if (this.listViewElements.SelectedItems.Count > 0)
			{
                DiagramItem firstDiagramItem = null;

                foreach (ListViewItem lvi in this.listViewElements.SelectedItems)
				{
					XSDObject xsdObject = lvi.Tag as XSDObject;
                    DiagramItem diagramItem = this.diagram.Add(xsdObject.Tag as XMLSchema.openAttrs, xsdObject.NameSpace);
                    if (firstDiagramItem == null && diagramItem != null)
                        firstDiagramItem = diagramItem;

                    //switch (xsdObject.Type)
                    //{
                    //    case "element":
                    //        this.diagram.AddElement(xsdObject.Tag as XMLSchema.element, xsdObject.NameSpace);
                    //        break;
                    //    case "group":
                    //        this.diagram.AddCompositors(xsdObject.Tag as XMLSchema.group, xsdObject.NameSpace);
                    //        break;
                    //    case "complexType":
                    //        this.diagram.AddComplexType(xsdObject.Tag as XMLSchema.complexType, xsdObject.NameSpace);
                    //        break;
                    //    case "simpleType":
                    //        this.diagram.Add(xsdObject.Tag as XMLSchema.simpleType, xsdObject.NameSpace);
                    //        break;
                    //}
                }
                if (firstDiagramItem != null)
                    SelectDiagramElement(firstDiagramItem, true);
                else
    				UpdateDiagram();
			}
		}

		private void expandOneLevelToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.diagram.ExpandOneLevel();
			UpdateDiagram();
		}

		// Implements the manual sorting of items by columns.
		class ListViewItemComparer : IComparer
		{
			private int column;
			private ListView listView;
			public ListViewItemComparer(int column, ListView listView)
			{
				this.column = column;
				this.listView = listView;

				switch (this.listView.Sorting)
				{
					case SortOrder.None: this.listView.Sorting = SortOrder.Ascending; break;
					case SortOrder.Ascending: this.listView.Sorting = SortOrder.Descending; break;
					case SortOrder.Descending: this.listView.Sorting = SortOrder.Ascending; break;
				}
			}
			public int Compare(object x, object y)
			{
				int result = 0;
				if (this.listView.Sorting == SortOrder.Ascending)
					result = String.Compare(((ListViewItem)x).SubItems[this.column].Text, ((ListViewItem)y).SubItems[column].Text);
				if (this.listView.Sorting == SortOrder.Descending)
					result = -String.Compare(((ListViewItem)x).SubItems[this.column].Text, ((ListViewItem)y).SubItems[column].Text);

				return result;
			}
		}

		private void listViewElement_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			this.listViewElements.ListViewItemSorter = new ListViewItemComparer(e.Column, this.listViewElements);
		}

		private void listViewAttributes_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			this.listViewAttributes.ListViewItemSorter = new ListViewItemComparer(e.Column, this.listViewAttributes);
		}

		private void toolStripButtonRemoveAllFromDiagram_Click(object sender, EventArgs e)
		{
            DialogResult dialogResult = MessageBox.Show("Are you sure to remove everything?", "Remove All", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                this.diagram.RemoveAll();
                UpdateDiagram();
                this.panelDiagram.VirtualPoint = new Point(0, 0);
                this.panelDiagram.Clear();
            }
        }

		private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e)
		{
			e.CancelEdit = true;
		}

		private void nextTabToolStripMenuItem_Click(object sender, EventArgs e)
		{
			int index = this.tabControlView.SelectedIndex;
			++index;
			this.tabControlView.SelectedIndex = index % this.tabControlView.TabCount;
		}

		private void previousTabToolStripMenuItem_Click(object sender, EventArgs e)
		{
			int index = this.tabControlView.SelectedIndex;
			--index;
			if (index < 0) index = this.tabControlView.TabCount - 1;
			this.tabControlView.SelectedIndex = index;
		}

		private void ListViewToString(ListView listView, bool selectedLineOnly)
		{
			string result = "";
			if (selectedLineOnly)
			{
				if (listView.SelectedItems.Count > 0)
				{
					foreach (ColumnHeader columnHeader in listView.Columns)
					{
						if (columnHeader.Index > 0) result += "\t";
						result += listView.SelectedItems[0].SubItems[columnHeader.Index].Text;
					}
				}
			}
			else
			{
				foreach (ListViewItem lvi in listView.Items)
				{
					foreach (ColumnHeader columnHeader in listView.Columns)
					{
						if (columnHeader.Index > 0) result += "\t";
						result += lvi.SubItems[columnHeader.Index].Text;
					}
					result += "\r\n";
				}
			}
			if (result.Length > 0)
				Clipboard.SetText(result);
		}

		private void toolStripMenuItemAttributesCopyLine_Click(object sender, EventArgs e)
		{
			ListViewToString(this.listViewAttributes, true);
		}

		private void toolStripMenuItemAttributesCopyList_Click(object sender, EventArgs e)
		{
			ListViewToString(this.listViewAttributes, false);
		}

		private void contextMenuStripAttributes_Opening(object sender, CancelEventArgs e)
		{
			this.toolStripMenuItemAttributesCopyLine.Enabled = (this.listViewAttributes.SelectedItems.Count == 1);
			this.toolStripMenuItemAttributesCopyList.Enabled = (this.listViewAttributes.Items.Count > 0);
		}

		private void toolStripMenuItemEnumerateCopyLine_Click(object sender, EventArgs e)
		{
			ListViewToString(this.listViewEnumerate, true);
		}

		private void toolStripMenuItemEnumerateCopyList_Click(object sender, EventArgs e)
		{
			ListViewToString(this.listViewEnumerate, false);
		}

		private void contextMenuStripEnumerate_Opening(object sender, CancelEventArgs e)
		{
			this.toolStripMenuItemEnumerateCopyLine.Enabled = (this.listViewEnumerate.SelectedItems.Count == 1);
			this.toolStripMenuItemEnumerateCopyList.Enabled = (this.listViewEnumerate.Items.Count > 0);
		}

		private void toolStripMenuItemElementsCopyLine_Click(object sender, EventArgs e)
		{
			ListViewToString(this.listViewElements, true);
		}

		private void toolStripMenuItemElementsCopyList_Click(object sender, EventArgs e)
		{
			ListViewToString(this.listViewElements, false);
		}

		private void contextMenuStripElements_Opening(object sender, CancelEventArgs e)
		{
			this.toolStripMenuItemElementsCopyLine.Enabled = (this.listViewElements.SelectedItems.Count == 1);
			this.toolStripMenuItemElementsCopyList.Enabled = (this.listViewElements.Items.Count > 0);
		}

		private void listViewElements_ItemDrag(object sender, ItemDragEventArgs e)
		{
			listViewElements.DoDragDrop(e.Item, DragDropEffects.Copy);
		}

		private void panelDiagram_DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(typeof(ListViewItem)))
			{
				ListViewItem lvi = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
				if (lvi != null)
				{
					XSDObject xsdObject = lvi.Tag as XSDObject;
					switch (xsdObject.Type)
					{
						case "element":
						case "group":
						case "complexType":
							e.Effect = DragDropEffects.Copy;
							break;
					}
				}
			}
			else if (e.Data.GetDataPresent(DataFormats.FileDrop))
				e.Effect = DragDropEffects.Move;
		}

		private void panelDiagram_DragDrop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(typeof(ListViewItem)))
			{
				ListViewItem lvi = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
				if (lvi != null)
				{
					listViewElement_DoubleClick(sender, e);
				}
			}
			else if (e.Data.GetDataPresent(DataFormats.FileDrop))
				MainForm_DragDrop(sender, e);
		}

		void DiagramControl_MouseMove(object sender, MouseEventArgs e)
		{
			//toolTip.Show("Coucou", panelDiagram.DiagramControl, 200);
		}

		void DiagramControl_MouseHover(object sender, EventArgs e)
		{
		}

        //private void toolTip_Popup(object sender, PopupEventArgs e)
        //{
        //    //toolTip.SetToolTip(e.AssociatedControl, "AAAAAAAAAA");
        //}

        private void DiagramControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.diagram.RootElements.Count > 0)
            {
                if (e.KeyCode == Keys.Space || e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter)
                    ExpandCollapseElement(this.diagram.SelectedElement, true);
                if (e.KeyCode == Keys.Delete)
                {
                    DiagramItem parentElement = this.diagram.SelectedElement.Parent;
                    RemoveElement(this.diagram.SelectedElement);
                    if (parentElement != null)
                        SelectDiagramElement(this.diagram.SelectedElement.Parent, true);
                    else
                        SelectDiagramElement(null);
                }
                else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Left
                    || e.KeyCode == Keys.Down || e.KeyCode == Keys.Up
                    || e.KeyCode == Keys.PageDown || e.KeyCode == Keys.PageUp
                    || e.KeyCode == Keys.Home || e.KeyCode == Keys.End
                    )
                {
                    DiagramItem element = this.diagram.SelectedElement;
                    if (element == null)
                        SelectDiagramElement(this.diagram.RootElements[0], true);
                    else
                    {
                        switch (e.KeyCode)
                        {
                            case Keys.Right:
                                if (element.HasChildElements)
                                {
                                    if (element.ChildElements.Count == 0)
                                        this.diagram.ExpandChildren(element);
                                    element.ShowChildElements = true;
                                    SelectDiagramElement(element.ChildElements[0], true);
                                }
                                break;
                            case Keys.Left:
                                if (element.Parent != null)
                                    SelectDiagramElement(element.Parent, true);
                                break;
                            case Keys.Down:
                                {
                                    IList<DiagramItem> children = element.Parent == null ? this.diagram.RootElements : element.Parent.ChildElements;
                                    if (children != null)
                                    {
                                        var pos = children.IndexOf(element);
                                        if (pos + 1 < children.Count)
                                            SelectDiagramElement(children[pos + 1], true);
                                    }
                                }
                                break;
                            case Keys.Up:
                                {
                                    IList<DiagramItem> children = element.Parent == null ? this.diagram.RootElements : element.Parent.ChildElements;
                                    if (children != null)
                                    {
                                        var pos = children.IndexOf(element);
                                        if (pos - 1 >= 0)
                                            SelectDiagramElement(children[pos - 1], true);
                                    }
                                }
                                break;
                        }
                    }
                }
            }
        }

		private void ExpandCollapseElement(DiagramItem element)
		{
			ExpandCollapseElement(element, false);
		}

        private void ExpandCollapseElement(DiagramItem element, bool scrollToElement)
        {
            if (element != null && element.HasChildElements)
            {
                if (element.ChildElements.Count == 0)
                {
                    this.diagram.ExpandChildren(element);
                    element.ShowChildElements = true;
                }
                else
                    element.ShowChildElements ^= true;
                UpdateDiagram();
                this.panelDiagram.ScrollTo(this.diagram.ScalePoint(element.Location), true);
            }
        }

        private void toolTip_Draw(object sender, DrawToolTipEventArgs e)
		{
			Point diagramMousePosition = e.AssociatedControl.PointToClient(MousePosition);
			string text = string.Format("AAAA {0} {1}\nA Que\n\nCoucou", diagramMousePosition.X, diagramMousePosition.Y);

			Size textSize = TextRenderer.MeasureText(text, e.Font);
			Rectangle newBound = new Rectangle(e.Bounds.X + 20, e.Bounds.Y - 20, textSize.Width + 10, textSize.Height + 10);

			DrawToolTipEventArgs newArgs = new DrawToolTipEventArgs(e.Graphics,
				e.AssociatedWindow, e.AssociatedControl, newBound, text,
				this.BackColor, this.ForeColor, e.Font);
			newArgs.DrawBackground();
			newArgs.DrawBorder();
			newArgs.DrawText(TextFormatFlags.TextBoxControl);

			//e.DrawBackground();
			//e.DrawBorder();
			//using (StringFormat sf = new StringFormat())
			//{
			//    sf.Alignment = StringAlignment.Center;
			//    sf.LineAlignment = StringAlignment.Center;
			//    sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
			//    sf.FormatFlags = StringFormatFlags.NoWrap;
			//    using (Font f = new Font("Tahoma", 9))
			//    {
			//        e.Graphics.DrawString(text, f,
			//            SystemBrushes.ActiveCaptionText, e.Bounds, sf);
			//    }
			//}
			//e.DrawText();
		}

        private void validateXMLFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Cursor = Cursors.WaitCursor;

                    validationErrorMessages.Clear();

                    StreamReader streamReader = new StreamReader(openFileDialog.FileName);
                    string xmlSource = streamReader.ReadToEnd();
                    streamReader.Close();

					//XmlDocument x = new XmlDocument();
					//x.LoadXml(xmlSource);

                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.CloseInput = true;
                    settings.ValidationType = ValidationType.Schema;
                    settings.ProhibitDtd = false;
					settings.XmlResolver = null;
                    settings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
                    settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |
                                                XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                                XmlSchemaValidationFlags.ProcessInlineSchema |
                                                XmlSchemaValidationFlags.ProcessSchemaLocation
												; //| XmlSchemaValidationFlags.AllowXmlAttributes;
                    //settings.Schemas.Add("http://www.collada.org/2005/11/COLLADASchema", currentLoadedSchemaFilename);
                    //settings.Schemas.Add(null, currentLoadedSchemaFilename); // = sc;
                    List<string> schemas = new List<string>(schema.XsdFilenames);
                    schemas.Reverse();
					foreach (string schemaFilename in schemas)
					{
						try
						{
							settings.Schemas.Add(null, schemaFilename);
						}
						catch (Exception ex)
						{
							validationErrorMessages.Add(string.Format("Error while parsing {0}, Message: {1}",
								schemaFilename, ex.Message));
						}
					}

                    StringReader r = new StringReader(xmlSource);
                    using (XmlReader validatingReader = XmlReader.Create(r, settings))
                    {
                        while (validatingReader.Read()) { /* just loop through document */ }
                    }

                    Cursor = Cursors.Default;

                    ErrorReportForm errorReportForm = new ErrorReportForm();
                    errorReportForm.Errors = validationErrorMessages;
                    errorReportForm.ShowDialog(this);
                }
                catch (Exception ex)
                {
					Cursor = Cursors.Default;

					validationErrorMessages.Add(string.Format("Error while validating {0}, Message: {1}",
						openFileDialog.FileName, ex.Message));
					//MessageBox.Show("Cannot validate: " + ex.Message);
					ErrorReportForm errorReportForm = new ErrorReportForm();
					errorReportForm.Errors = validationErrorMessages;
					errorReportForm.ShowDialog(this);
                }
				Cursor = Cursors.Default;

				if (validationErrorMessages.Count == 0)
					MessageBox.Show("No issue found");
			}
        }

        static List<string> validationErrorMessages = new List<string>();

        public static void ValidationHandler(object sender, ValidationEventArgs e)
        {
            //if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            validationErrorMessages.Add(string.Format("{4}: [{3}] Line: {0}, Position: {1} \"{2}\"",
                e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message, validationErrorMessages.Count, e.Severity));
        }

        private void toolStripButtonShowDocumentation_Click(object sender, EventArgs e)
        {
            this.diagram.ShowDocumentation = this.toolStripButtonShowDocumentation.Checked;
            UpdateDiagram();
        }

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.Control && (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0))
			{
				this.toolStripComboBoxZoom.SelectedIndex = 8;
			}
		}



		//void DiagramControl_MouseMove(object sender, MouseEventArgs e)
		//{
		//System.Diagnostics.Trace.WriteLine("toolTipDiagramElement_Popup");
		//Point contextualMenuMousePosition = this.panelDiagram.DiagramControl.PointToClient(MousePosition);
		//contextualMenuMousePosition.Offset(this.panelDiagram.VirtualPoint);
		//DiagramBase resultElement;
		//DiagramBase.HitTestRegion resultRegion;
		//this.diagram.HitTest(contextualMenuMousePosition, out resultElement, out resultRegion);
		//if (resultRegion != DiagramBase.HitTestRegion.None)
		//{
		//    if (resultRegion == DiagramBase.HitTestRegion.Element) // && resultElement.Parent == null)
		//    {
		//        //this.contextualMenuPointedElement = resultElement;
		//        //toolTipDiagramElement.SetToolTip(this.panelDiagram.DiagramControl, "coucou");
		//        e.Cancel = true;
		//        toolTipElement.Show("Coucou", this);
		//    }
		//}
		//}
	}
}