summaryrefslogtreecommitdiffstats
path: root/part/kxmleditorpart.cpp
blob: ab60676d5d5b054acada9787ebaa900336e011f7 (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
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
/***************************************************************************
                          kxmleditorpart.cpp  -  description
                             -------------------
    begin                : Wed Sep 19 2001
    copyright            : (C) 2001, 2002, 2003 by The KXMLEditor Team
    email                : [email protected]
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kxmleditorpart.h"
#include "kxmleditorfactory.h"

#include "kxedocument.h"

#include "kxeconfiguration.h"
#include "kxenewfilesettings.h"
#include "kxearchiveextssettings.h"
#include "kxeprintsettings.h"
#include "kxetextviewsettings.h"

#include "commands_edit.h"
#include "commands_insert.h"

#include "kxe_viewelement.h"
#include "kxe_treeviewitem.h"

#include "kxesearchdialog.h"
#include "kxechoosestringdialog.h"
#include "kxeelementdialog.h"
#include "kxeattributedialog.h"
#include "kxeprocinstrdialog.h"
#include "kxespecprocinstrdialog.h"
#include "kxefilenewdialog.h"
#include "kxechardatadialog.h"
#include "kxeattachdialogbase.h"
#include "kxetexteditordialog.h"

#include "actions.h"
#include "qdom_add.h"

#include <kinstance.h>
#include <kdebug.h>
#include <klocale.h>
#include <kaction.h>
#include <kstdaction.h>
#include <kpopupmenu.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kprinter.h>
#include <ktar.h>
#include <kzip.h>
#include <ktempfile.h>
#include <kconfig.h>
#include <kurlrequester.h>
#include <kcommand.h>
#include <ktoolbar.h>
#include <kfiledialog.h>

#include <qregexp.h>
#include <qtextcodec.h>
#include <qstringlist.h>
#include <qsplitter.h>
#include <qtabwidget.h>
#include <qtextedit.h>
#include <qcombobox.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qclipboard.h>
#include <qdragobject.h>
#include <qapplication.h>
#include <qbuffer.h>
#include <qlabel.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qevent.h>

#include "dcopiface_part_ro.h" // DCOP Iface

#define CONFIG_MAIN_SPLITTER_SIZES "Main splitter sizes"


KXMLEditorPart::KXMLEditorPart( bool fReadWrite, KXEDocument* pDocument, QWidget * pParent, const char * pszName )
	: KParts::ReadWritePart(pParent,pszName),
	m_pDlgSearch(0),
	m_pDocument(0)
{
	//////////////////////////////
	// INIT PART
	//////////////////////////////

	setInstance(KXMLEditorFactory::instance());

	if(fReadWrite)
		m_pBrowserExt = 0L; // Create Browser extension only for read-only part
	else
		m_pBrowserExt = new KXMLEditorBrowserExtension( this, "KXMLEditorPart browser extension" );
	
	m_pPrinter = 0L;

	m_bAlreadyModified = false;

	//////////////////////////////
	// CREATE ACTIONS
	//////////////////////////////

	// file actions
	if(fReadWrite)
		{
			KStdAction::save(this, SLOT(save()), actionCollection());
			KStdAction::saveAs(this, SLOT(slotFileSaveAs()), actionCollection());
		}
		
	// edit actions
	m_pActEditFind = KStdAction::find( this, SLOT(slotEditFind()), actionCollection());
	m_pActEditFindNext = KStdAction::findNext( this, SLOT(slotEditFindNext()), actionCollection());
	m_pActEditDeselect = new KAction( i18n("D&eselect Node"), CTRL+Key_E, this,
	                                SLOT(slotEditDeselect()), actionCollection(), "deselect" );

	// view actions
	m_pActViewNodeUp = new KAction( i18n("To &Parent Node"), "up", 0, this,
	                                SLOT(slotViewNodeUp()), actionCollection(), "treeitem_up" );

	m_pActViewExpNode = new KToolBarPopupAction( i18n("&Expand Node"), "expand_node", CTRL+Key_Plus, this,
	                                             SLOT(slotViewExpNode()), actionCollection(), "treeitem_expand" );
	KPopupMenu * pMenuExpNode = m_pActViewExpNode->popupMenu();
	connect( pMenuExpNode, SIGNAL(activated(int)), this, SLOT(slotViewExpNode(int)) );
	for ( uint i = 1; i <= 8; i++ )
		pMenuExpNode->insertItem( i18n("Expand To Level %1").arg(i), i-1 );

	m_pActViewColNode = new KToolBarPopupAction( i18n("&Collapse Node"), "collapse_node", CTRL+Key_Minus, this,
	                                             SLOT(slotViewColNode()), actionCollection(), "treeitem_collapse" );
	KPopupMenu * pMenuColNode = m_pActViewColNode->popupMenu();
	connect( pMenuColNode, SIGNAL(activated(int)), this, SLOT(slotViewColNode(int)) );
	for ( uint i = 0; i <= 7; i++ )
		pMenuColNode->insertItem( i18n("Collapse To Level %1").arg(i), i );

	// bookmark actions
	m_pActBookmarksToggle = new KAction( i18n("&Toggle Bookmark"), "bookmark_add", CTRL+Key_B, this,
	                                   SLOT(slotBookmarksToggle()), actionCollection(), "bookmark_toggle" );
	m_pActBookmarksPrev = new KAction( i18n("&Previous Bookmark"), "bookmark_prev", SHIFT+Key_F5, this,
	                                   SLOT(slotBookmarksPrev()), actionCollection(), "bookmark_prev" );
	m_pActBookmarksNext = new KAction( i18n("&Next Bookmark"), "bookmark_next", Key_F5, this,
	                                   SLOT(slotBookmarksNext()), actionCollection(), "bookmark_next" );

	// settings actions
	new KAction( i18n("&Configure KXMLEditor..."), "configure", 0, this,
	             SLOT (slotConfigure()), actionCollection(), "configure" );

	// path toolbar
	m_pActPathCombo = new KXmlEditorComboAction( i18n("Path Bar"), 0, this,
	                                             SLOT(slotPathSelected(const QString &)), actionCollection(), "path_combo" );
	new KAction( i18n("Clear Path Bar"), BarIcon("locationbar_erase", 16), 0, this,
	             SLOT(slotPathClear()), actionCollection(), "path_clear" );
	QLabel *m_locationLabel = new ToolbarLabel( i18n("Path: ") );
	new KWidgetAction( m_locationLabel, i18n("Path: "), 0, this, 0, actionCollection(), "path_label" );
	m_locationLabel->setBuddy( m_pActPathCombo->comboBox());

	if ( ! fReadWrite )
		{
			setXMLFile( "kxmleditorpartBrowseUI.rc", true );
			
			KStdAction::cut( m_pBrowserExt, SLOT(slotEditCut()), actionCollection(), "cut" );
			KStdAction::copy( m_pBrowserExt, SLOT(slotEditCopy()), actionCollection(), "copy" );
			KStdAction::paste( m_pBrowserExt, SLOT(slotEditPaste()), actionCollection(), "paste");
			
			m_pCmdHistory = 0L;
			
			m_pActVersionEncoding =  0L;
			m_pActAttachSchema =  0L;
			m_pActDetachSchema =  0L;
			m_pActAttachStylesheet =  0L;
			m_pActDetachStylesheet =  0L;
		}
	else
	{
		// document specific actions here
		m_pActVersionEncoding = new KAction( i18n("&Version && Encoding..."), 0, 0, this, SLOT(slotActVersionEncoding()), actionCollection(), "xml_ins_spec_procins" );
		m_pActAttachSchema = new KAction(i18n("Attach Schema..."),0,0,this,SLOT(slotActAttachSchema()), actionCollection(), "xml_attach_schema");
		m_pActDetachSchema = new KAction(i18n("Detach Schema"),0,0,this,SLOT(slotActDetachSchema()), actionCollection(), "xml_detach_schema");
		m_pActAttachStylesheet = new KAction(i18n("Attach Stylesheet..."),0,0,this,SLOT(slotActAttachStylesheet()), actionCollection(), "xml_attach_stylesheet");
		m_pActDetachStylesheet = new KAction(i18n("Detach Stylesheet"),0,0,this,SLOT(slotActDetachStylesheet()), actionCollection(), "xml_detach_stylesheet");
		
		KStdAction::print( this, SLOT(slotActPrint()), actionCollection(), "print" );
		
		m_pActAttachSchema->setEnabled(false);
		m_pActDetachSchema->setEnabled(false);
		m_pActDetachStylesheet->setEnabled(false);
	
	
		// undo & redo
    KStdAction::undo(this, SLOT(slotActUndo()), actionCollection());
    KStdAction::redo(this, SLOT(slotActRedo()), actionCollection());
		
		m_pCmdHistory = new KCommandHistory(actionCollection());
		
		m_pActEditCut = KStdAction::cut( this, SLOT(slotEditCut()), actionCollection());
		m_pActEditCopy = KStdAction::copy( this, SLOT(slotEditCopy()), actionCollection());
		m_pActEditPaste = KStdAction::paste( this, SLOT(slotEditPaste()), actionCollection());

		// Move node Up & Down
		m_pActXmlMoveNodeUp = new KAction( i18n("&Move Up"), "xml_move_item_up", CTRL+Key_U, this, SLOT(slotXmlMoveNodeUp()), actionCollection(), "xml_move_item_up" );
		m_pActXmlMoveNodeDown = new KAction( i18n("Move &Down"), "xml_move_item_down", CTRL+Key_D, this, SLOT(slotXmlMoveNodeDown()), actionCollection(), "xml_move_item_down" );

		// Insert actions
		m_pActXmlElementInsert = new KAction( i18n("&Element..."), "xml_insert_element", CTRL+SHIFT+Key_E, this, SLOT(slotXmlElementInsert()), actionCollection(), "xml_ins_element" );
		m_pActXmlAttributesAdd = new KAction( i18n("&Attribute..."), "xml_insert_attribute", CTRL+SHIFT+Key_A, this, SLOT(slotXmlAttributesAdd()), actionCollection(), "xml_add_attribute" );
		m_pActInsertText = new KAction( i18n("&Text..."), "xml_text", CTRL+SHIFT+Key_T, this, SLOT(slotActInsertText()), actionCollection(), "insert_text" );
		m_pActInsertCDATA = new KAction( i18n("C&DATA..."), "xml_cdata", CTRL+SHIFT+Key_D, this, SLOT(slotActInsertCDATA()), actionCollection(), "insert_cdata" );
		m_pActInsertComment = new KAction( i18n("&Comment..."), "xml_comment", CTRL+SHIFT+Key_C, this, SLOT(slotActInsertComment()), actionCollection(), "insert_comment" );
		m_pActXmlProcInstrInsert = new KAction( i18n("&Processing Instruction..."), "xml_insert_procins", CTRL+SHIFT+Key_P, this, SLOT(slotXmlProcInstrInsert()), actionCollection(), "xml_ins_procins" );

		// Edit node properties
		m_pActProperties = new KAction(i18n("&Properties..."),"edit",0,this,SLOT(slotActProperties()),actionCollection(),"edit_properties");
		m_pActEditRawXml = new KAction(i18n("Edit &raw XML..."), 0, 0, this, SLOT(slotActEditRawXml()),actionCollection(),"edit_as_raw_xml");

		// delete actions
		m_pActXmlAttributeDel = new KAction( i18n("&Delete"), "editdelete", 0, this, SLOT(slotXmlAttributeDel()), actionCollection(), "xml_del_attribute" );
		m_pActXmlAttributesDel = new KAction( i18n("Delete all Attributes..."), 0, 0, this, SLOT(slotXmlAttributesDel()), actionCollection(), "xml_del_attributes" );
		m_pActDelete = new KAction(i18n("&Delete"),"editdelete",0,this,SLOT(slotActDelete()),actionCollection(),"edit_delete");

		setXMLFile( "kxmleditorpartEditUI.rc", true );
		
		// we are not modified since we haven't done anything yet
    setModified(false);
	}

	//////////////////////////////
	// CREATE WIDGETS
	//////////////////////////////

	pSplitter = new QSplitter( pParent, "KXMLEditorPart main widget (Splitter)" );
	pSplitter->setFocusPolicy( QWidget::NoFocus );
	pSplitter->setOpaqueResize(true);
	setWidget( pSplitter );

	// create the tree view -------------------
	m_pViewTree = new KXE_TreeView( this, pSplitter, "KXMLEditorPart treeview" );

	connect( m_pViewTree, SIGNAL(sigSelectionCleared(bool)), this, SLOT(slotSelectionCleared(bool)) );
	connect( m_pViewTree, SIGNAL(sigSelectionChanged(const QDomElement &)), this, SLOT(slotSelectionChanged(const QDomElement &)) );
	connect( m_pViewTree, SIGNAL(sigSelectionChanged(const QDomCharacterData &)), this, SLOT(slotSelectionChanged(const QDomCharacterData &)) );
	connect( m_pViewTree, SIGNAL(sigSelectionChanged(const QDomProcessingInstruction &)), this, SLOT(slotSelectionChanged(const QDomProcessingInstruction &)) );
	connect( m_pViewTree, SIGNAL(sigContextMenuRequested(const QString&,const QPoint&)), this, SLOT(slotContextMenuRequested(const QString&,const QPoint&)) );
	connect( m_pViewTree, SIGNAL(itemRenamed(QListViewItem *)), this, SLOT(slotItemRenamedInplace(QListViewItem *)) );
	connect( m_pViewTree, SIGNAL(sigKeyPressed(QKeyEvent* )),this,SLOT(slotTreeViewKeyPressed(QKeyEvent*)));

	// create tab widget ----------------------
	m_pTabWidget = new QTabWidget( pSplitter, "KXMLEditorPart tabwidget");
	m_pTabWidget->setFocusPolicy( QWidget::NoFocus );

	// create element view
	m_pViewElement = new KXE_ViewElement( m_pTabWidget, instance()->config(), "KXMLEditorPart element view" );
	m_pTabWidget->addTab( m_pViewElement, g_iconElement, i18n("Element") );
	connect( m_pViewElement, SIGNAL(sigContextMenuRequested(const QString&,const QPoint&)), this, SLOT(slotContextMenuRequested(const QString&,const QPoint&)) );
	connect( m_pViewElement, SIGNAL(sigAttributeNameChangedInplace(const QDomAttr&, const QString)), this, SLOT(slotAttributeNameChangedInplace(const QDomAttr&, const QString)) );
	connect( m_pViewElement, SIGNAL(sigAttributeValueChangedInplace(const QDomAttr&, const QString)), this, SLOT(slotAttributeValueChangedInplace(const QDomAttr&, const QString)) );

	// create edit widget, that display XML character data contents
	m_pViewContents = new QTextEdit( m_pTabWidget, "KXMLEditorPart contents view" );
	m_pTabWidget->addTab( m_pViewContents, g_iconText, i18n("Contents") );
	m_pViewContents->setReadOnly( true );
	m_pViewContents->setWordWrap( QTextEdit::NoWrap );
	m_pViewContents->setTextFormat(QTextEdit::PlainText);

	// create proc.instr. view
	m_pViewProcInstr = new QTextEdit( m_pTabWidget, "KXMLEditorPart proc.instr. view" );
	m_pTabWidget->addTab( m_pViewProcInstr, g_iconProcessingInstruction, i18n("Proc.Instruction") );
	m_pViewProcInstr->setReadOnly( true );
	m_pViewProcInstr->setWordWrap( QTextEdit::NoWrap );

	connect( this, SIGNAL(started(KIO::Job*)), this, SLOT(started()) );
	connect( this, SIGNAL(completed()), this, SLOT(completed()) );
	connect( this, SIGNAL(canceled(const QString &)), this, SLOT(canceled()) );

	//////////////////////////////
	// INIT BEGIN STATE
	//////////////////////////////

	// Disable actions
	if(m_pBrowserExt)
		m_pBrowserExt->emit enableAction("copy", false);
	else
		m_pActEditCopy->setEnabled(false);

	m_pActEditFindNext->setEnabled(false);
	m_pActEditDeselect->setEnabled(false);
	m_pActViewNodeUp->setEnabled(false);
	m_pActViewExpNode->setEnabled(false);
	m_pActViewColNode->setEnabled(false);
	m_pActBookmarksToggle->setEnabled(false);
	m_pActBookmarksPrev->setEnabled(false);
	m_pActBookmarksNext->setEnabled(false);

	if ( fReadWrite )
	{
		m_pActEditCut->setEnabled(false);
		m_pActEditPaste->setEnabled(true);

		m_pActXmlElementInsert->setEnabled(true);
		m_pActXmlAttributesAdd->setEnabled(false);
		m_pActXmlAttributesDel->setEnabled(false);
		m_pActXmlProcInstrInsert->setEnabled(true);
		m_pActInsertText->setEnabled(false);
		m_pActInsertCDATA->setEnabled(false);
		m_pActInsertComment->setEnabled(false);
		m_pActXmlMoveNodeUp->setEnabled(false);
		m_pActXmlMoveNodeDown->setEnabled(false);
		m_pActDelete->setEnabled(false);
		m_pActProperties->setEnabled(false);
		m_pActEditRawXml->setEnabled(false);
	}

	m_pTabWidget->setTabEnabled( m_pViewElement, false );
	m_pTabWidget->setTabEnabled( m_pViewContents, false );
	m_pTabWidget->setTabEnabled( m_pViewProcInstr, false );

	setReadWrite(fReadWrite);

	// configuring splitter sizes
	QValueList<int> list = instance()->config()->readIntListEntry(CONFIG_MAIN_SPLITTER_SIZES);
	if (!list.isEmpty())
		pSplitter->setSizes(list);

	//////////////////////////////
	// INIT DCOP object (if any)
	//////////////////////////////
	//m_pDCOPIface = NULL;
	//m_pDCOPIface = new KXMLEditorPartIfaceReadOnly(this);
	m_pDCOPIface = new KXMLEditorPartIfaceReadWrite(this); // temporarly to test openUrl

	setDocument(pDocument);

}

KXMLEditorPart::~KXMLEditorPart()
{
	// saving splitter configuration
	KConfig *pConfig = instance()->config();
	pConfig->writeEntry( CONFIG_MAIN_SPLITTER_SIZES, pSplitter->sizes() );

	if (m_pDCOPIface)
		delete m_pDCOPIface;

	if (m_pDlgSearch)
		delete m_pDlgSearch;

	if (m_pPrinter)
		delete m_pPrinter;

	if (document())
		delete document();
		
	delete m_pCmdHistory;
}


/////////////////////////////////////////////////////////////////////
//                   KPART FUNCTIONALITY
/////////////////////////////////////////////////////////////////////

bool KXMLEditorPart::openFile()
{
	if( isModified() )
		kdError() << "KXMLEditorPart::openFile the current document is modified." << endl;

	document()->setURL(m_url);
	bool bResult = document()->open(m_file);
	updateActions();
	return bResult;
}

bool KXMLEditorPart::saveFile()
{
  emit setStatusBarText( i18n("Saving file...") );
	
	if( url().isEmpty() )
		{	
			return slotFileSaveAs();
		}
		
	// delegate this operation to underlying document object
	document()->setURL(m_url);
	bool bRetVal = document()->save(m_file);

	emit setStatusBarText( i18n("Ready.") );
	return bRetVal;	
}

void KXMLEditorPart::setModified( bool bModified )
{
	KParts::ReadWritePart::setModified( bModified ); // base functionality

	if ( m_bAlreadyModified != bModified )
	{
		m_bAlreadyModified = bModified;

		QString szNewCaption = m_url.prettyURL();
		emit setWindowCaption( szNewCaption );
	}
			
	// get a handle on our Save action and make sure it is valid
  KAction *pActFileSave = actionCollection()->action(KStdAction::stdName(KStdAction::Save));
  if(!pActFileSave)
        return;

  // if so, we either enable or disable it based on the current state
  pActFileSave->setEnabled(bModified);
	
	// Update others actions
	updateActions();
}

void KXMLEditorPart::setReadWrite( bool fReadWrite )
{
	m_pViewTree->setReadWrite(fReadWrite);
	m_pViewElement->setReadWrite(fReadWrite);

	KParts::ReadWritePart::setReadWrite( fReadWrite ); // base functionality
}

void KXMLEditorPart::started()
{
	kdDebug() << "KXMLEditorPart::started" << endl;
}
void KXMLEditorPart::completed()
{
	kdDebug() << "KXMLEditorPart::completed" << endl;
}
void KXMLEditorPart::canceled()
{
	kdDebug() << "KXMLEditorPart::canceled" << endl;
}


/////////////////////////////////////////////////////////////////////
//                     ACTION SLOTS
/////////////////////////////////////////////////////////////////////

void KXMLEditorPart::slotActPrint()
{
	// this slot is called whenever the File->Print menu is selected,
	// the Print shortcut is pressed (usually CTRL+P) or the Print toolbar
	// button is clicked
	if (!m_pPrinter)
		m_pPrinter = new KPrinter;

	if (m_pPrinter->setup(widget()))
		print(m_pPrinter);
}

void KXMLEditorPart::slotActProperties()
{
	QDomNode* pNode = m_pViewTree->getSelectedNode();
	if (pNode)
	{
		if (pNode->isElement())
			slotXmlElementEdit();
		else if (pNode->isCharacterData())
			slotXmlCharDataEdit();
		else if (pNode->isProcessingInstruction())
			slotXmlProcInstrEdit();
		else
			kdError() << "Unknown node selected.";
	}
}

void KXMLEditorPart::slotActDelete()
{
	QDomNode* pNode = m_pViewTree->getSelectedNode();

	if (!m_pViewElement->hasFocus())
	{
		// delete nodes selected there
		if (pNode)
		{
			KCommand *pCmd = new KXEDeleteNodeCommand(document(), *pNode);
			m_pCmdHistory->addCommand(pCmd);
		}
	}
	else
	{
		// we can have also delete attribute selected on a element view
		QDomAttr domAttr = m_pViewElement->getSelectedAttribute();
		if (!domAttr.isNull())
		{
			QDomElement domElement = pNode->toElement();
			QDomAttr domAttr = m_pViewElement->getSelectedAttribute();

			KCommand *pCmd = new KXEDeleteAttrCommand(document(), domElement, domAttr);
			m_pCmdHistory->addCommand(pCmd);
		}
	}
}

void KXMLEditorPart::slotEditCut()
{
	kdDebug() << "KXMLEditor " << k_funcinfo << endl;

	if(! isReadWrite())
	{
		kdError() << "KXMLEditorPart::slotEditCut called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();

	if(pNode)
	{ // copy to clipboard
		slotEditCopy();

		// and cut it
		KCommand *pCmd = new KXECutCommand(document(), *pNode);
		m_pCmdHistory->addCommand(pCmd);
	}
}

void KXMLEditorPart::slotEditCopy()
{
	kdDebug() << "KXMLEditor " << k_funcinfo << endl;

	QDomNode * pNode = m_pViewTree->getSelectedNode();

	if(pNode)
	{
		QTextDrag *pDrag = copyNode(m_pViewTree->getSelectedNode());
		if(pDrag)
			QApplication::clipboard()->setData(pDrag);
	}
	else
		kdError() << "KXMLEditorPart::slotEditCopy no element selected." << endl;
}

void KXMLEditorPart::slotEditPaste()
{
	kdDebug() << "KXMLEditor " << k_funcinfo << endl;

	if(!isReadWrite())
	{
		kdError() << "KXMLEditorPart::slotEditPaste called in readonly mode." << endl;
		return;
	}

	if (document()->documentElement().isNull())
	{
		pasteNode(0, QApplication::clipboard()->data());
	}
	else
	{
		pasteNode(m_pViewTree->getSelectedNode(), QApplication::clipboard()->data());
	}
}

void KXMLEditorPart::slotEditFind()
{
	emit setStatusBarText( i18n("Search in XML tree ...") );

	if ( ! m_pDlgSearch )
	{
		m_pDlgSearch = new KXESearchDialog( widget(), "search dialog", true );
	}

	if ( m_pDlgSearch->exec() == KXESearchDialog::Accepted )
		slotEditFindNext();

	m_pActEditFindNext->setEnabled(true);

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotEditFindNext()
{
	emit setStatusBarText( i18n("Search in XML tree ...") );

	if ( ! m_pDlgSearch )
	{
		kdDebug() << "KXMLEditorPart::slotEditFindNext implementation error - no search dialog" << endl;
		emit setStatusBarText( i18n("Ready.") );
		return;
	}

	// get node to start with (either the next node of the item selected at the tree view or documents root node)
	QDomNode node = ( (m_pViewTree->getSelectedNode()) && (! m_pViewTree->getSelectedNode()->isNull()) ) ? domTool_nextNode(* m_pViewTree->getSelectedNode()) : document()->documentElement();

	// start testing til the last node
	while( ! node.isNull() )
	{
		if ( domTool_match( node, m_pDlgSearch ) )
		{
			m_pViewTree->selectNode(node);
			emit setStatusBarText( i18n("Ready.") );
			return;
		}
		
		node = domTool_nextNode(node);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlElementInsert()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlElementInsert called in readonly mode." << endl;
		return;
	}

	emit setStatusBarText( i18n("Inserting XML element into document...") );

	KXEElementDialog dlg( widget(), "XML element dialog" );
	
	if ( document()->documentElement().isNull() ) // the document doesn't
	{                                         // have a root element yet
		if ( dlg.exec( false, true, false ) == QDialog::Accepted )
		{
			KCommand *pCmd = new KXEElementCommand(document(), document(), dlg.nsURI(), dlg.prefix(), dlg.name());
			m_pCmdHistory->addCommand(pCmd);
		}
	}
	else  // the document seems to
	{     // have a root element
		QDomNode * pParentNode = m_pViewTree->getSelectedNode();

		if ( (pParentNode) && (pParentNode->isElement()) )
		{
			QDomElement domParentElement = pParentNode->toElement();
			
			if ( dlg.exec( false, false, false ) == QDialog::Accepted )
			{
				KCommand *pCmd = new KXEElementCommand(document(), domParentElement, dlg.nsURI(), dlg.prefix(), dlg.name(), dlg.atTop());
				m_pCmdHistory->addCommand(pCmd);
			}
		}
		else
			kdError() << "KXMLEditorPart::slotXmlElementInsert no element selected." << endl;
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlElementEdit()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlElementEdit called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotXmlElementEdit no node selected or selected node is no XML element." << endl;
		return;
	}

	emit setStatusBarText( i18n("Editing XML element...") );

	QDomElement domElement = pNode->toElement();

	KXEElementDialog dlg( widget(), "XML element dialog" );

	dlg.setPrefix(domElement.prefix());
	dlg.setName(domElement.tagName());
	if(!domElement.namespaceURI().isNull())
		dlg.setNsURI(domElement.namespaceURI() );

	if ( dlg.exec( true, false, domElement.namespaceURI().isNull() ) == QDialog::Accepted )
	{
		KCommand *pCmd = new KXEEditElementCommand(document(), domElement, dlg.prefix(), dlg.name());
		m_pCmdHistory->addCommand(pCmd);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotActEditRawXml()
{
  if ( ! isReadWrite() )
	{
	  kdError() << "KXMLEditorPart::slotActEditRawXml called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotActEditRawXml no node selected or selected node is no XML element." << endl;
		return;
	}

	emit setStatusBarText( i18n("Editing raw XML...") );

	QDomElement domElement = pNode->toElement();

	QString strXML;

	QTextStream streamXML(&strXML, IO_WriteOnly);
	int iIndent = KXMLEditorFactory::configuration()->textview()->indentSteps();
	pNode->save(streamXML, iIndent);

	KXETextEditorDialog dlg(0, "Text dialog");
	dlg.setEditorText(strXML);
	if((dlg.exec() == QDialog::Accepted) && (strXML != dlg.editorText()))
	{
		QString strXML = "<root>" + dlg.editorText()  + "</root>";

		// create XML documemt from text
		QString strErrorMsg;
		int iErrorLine, iErrorColumn;
		QDomDocument doc;

 		if(!doc.setContent(strXML, true, &strErrorMsg, &iErrorLine, &iErrorColumn) )
 		{
			kdDebug() << "KXMLEditorPart::slotActEditRawXml: Failed parsing the file." << endl;

			KMessageBox::error(m_pViewTree,
											 		i18n("%1 in line %2, column %3").arg(strErrorMsg).arg(iErrorLine).arg(iErrorColumn),
											 		i18n("Parsing error !"));

			return;
		}

    // check if root item already exists
		if(!doc.firstChild().firstChild().isElement())
			{
				KMessageBox::sorry(m_pViewTree, i18n("You are changed root element to another node type, while editing !"));
				return;
			}

		QDomElement domNewElement = doc.firstChild().firstChild().toElement();
		KCommand *pCmd = new KXEEditRawXmlCommand(document(), domElement, domNewElement);
		m_pCmdHistory->addCommand(pCmd);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlAttributesAdd()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlAttributesAdd called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotXmlAttributesAdd no node selected or selected node is no XML element." << endl;
		return;
	}

	emit setStatusBarText( i18n("Add attribute...") );

	KXEAttributeDialog dlg( widget(), "attribute dialog" );

	QDomElement domOwnerElement = pNode->toElement();
	if ( dlg.exec( ) == QDialog::Accepted )
	{
		KCommand *pCmd = new KXEAttributeCommand(document(), domOwnerElement, dlg.attributeNamespace(), dlg.QName(), dlg.Value());
		m_pCmdHistory->addCommand(pCmd);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlAttributesDel()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlAttributesDel called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotXmlAttributesDel no node selected or selected node is no XML element." << endl;
		return;
	}

	if(KMessageBox::questionYesNo(0, i18n("Remove all attributes from selected node ?")) != KMessageBox::Yes)
		return;

	emit setStatusBarText( i18n("Delete all attributes...") );

	QDomElement domOwnerElement = pNode->toElement();

	KCommand *pCmd = new KXEDeleteAllAttribCommand(document(), domOwnerElement);
	m_pCmdHistory->addCommand(pCmd);

	emit setStatusBarText( i18n("Ready.") );
}


void KXMLEditorPart::slotXmlAttributeDel()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlAttributeDel called in readonly mode." << endl;

		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotXmlAttributeDel no node selected or selected node is no XML element." << endl;
		return;
	}

	emit setStatusBarText( i18n("Delete attribute...") );

	QDomElement domElement = pNode->toElement();
	QDomAttr domAttr = m_pViewElement->getSelectedAttribute();

	KCommand *pCmd = new KXEDeleteAttrCommand(document(), domElement, domAttr);
	m_pCmdHistory->addCommand(pCmd);

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlProcInstrInsert()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlProcInstrInsert called in readonly mode." << endl;
		return;
	}

	KXEProcInstrDialog dlg( widget(), "proc. instr. dialog" );

	QDomNode * pParentNode = m_pViewTree->getSelectedNode();
	if ( (pParentNode) && (!pParentNode->isElement()) )
	{
		kdError() << k_funcinfo << " The selected node is no XML element." << endl;
		return;
	}
	else
  {
    if ( ! pParentNode )  // no node selected -> the new node should be a direct child of the document
    {
      if ( dlg.exec( false, true ) == QDialog::Accepted )
      {
        KCommand *pCmd = new KXEProcInstrCommand(document(), document(), dlg.atTop(), dlg.target(), dlg.data());
        m_pCmdHistory->addCommand(pCmd);
      }
    }
    else
    {
      if ( dlg.exec( false, false ) == QDialog::Accepted )
      {
        QDomElement domParentElement = pParentNode->toElement();

        KCommand *pCmd = new KXEProcInstrCommand(document(), domParentElement, dlg.atTop(), dlg.target(), dlg.data());
        m_pCmdHistory->addCommand(pCmd);
      }
    }
   }

	emit setStatusBarText( i18n("Inserting processing instruction into document...") );

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlProcInstrEdit()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlProcInstrEdit called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isProcessingInstruction()) )
	{
		kdError() << "KXMLEditorPart::slotXmlProcInstrEdit no node selected or selected node is no processing instruction." << endl;
		return;
	}

	emit setStatusBarText( i18n("Editing processing instruction...") );

	QDomProcessingInstruction domProcInstr = pNode->toProcessingInstruction();

	// We have two different kinds of processing instructions:
	// - a special one - defining the documents XML version and encoding
	// - others
	// and both cases require different dialogs.
	if( domProcInstr.target() == "xml" ) // 1st case (special proc.instr.)
		document()->actVersionEncoding();
	else                                 // 2nd case (others)
	{
		KXEProcInstrDialog dlg( widget(), "proc. instr. dialog" );

		dlg.setTarget(domProcInstr.target());
		dlg.setData(domProcInstr.data());

		if ( dlg.exec( true, false ) == QDialog::Accepted )
		{
			KCommand *pCmd = new KXEEditProcInstrCommand(document(), domProcInstr, dlg.data());
			m_pCmdHistory->addCommand(pCmd);
		}
	}
	
	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotActInsertText()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotActInsertText called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotActInsertText no element selected." << endl;
		return;
	}

	emit setStatusBarText( i18n("Inserting text into document...") );

	KXECharDataDialog dlg( widget());
	dlg.setCaption(i18n("Insert text"));

	QDomElement domParentElement = pNode->toElement();

	if ( dlg.exec( false ) == QDialog::Accepted )
	{
		KCommand *pCmd = new KXECharDataCommand(document(), domParentElement, dlg.atTop(), CharDataTextNode, dlg.contents());
		m_pCmdHistory->addCommand(pCmd);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotActInsertCDATA()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotActInsertCDATA called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotActInsertCDATA no element selected." << endl;
		return;
	}

	emit setStatusBarText( i18n("Inserting CDATA into document...") );

	KXECharDataDialog dlg( widget());
        dlg.setCaption(i18n("Insert CDATA"));

	QDomElement domParentElement = pNode->toElement();

	if ( dlg.exec( false ) == QDialog::Accepted )
	{
		KCommand *pCmd = new KXECharDataCommand(document(), domParentElement, dlg.atTop(), CharDataCDATASection, dlg.contents());
		m_pCmdHistory->addCommand(pCmd);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotActInsertComment()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotActInsertComment called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isElement()) )
	{
		kdError() << "KXMLEditorPart::slotActInsertComment no element selected." << endl;
		return;
	}

	emit setStatusBarText( i18n("Inserting comment into document...") );

	KXECharDataDialog dlg( widget());
	dlg.setCaption(i18n("Insert comment"));

	QDomElement domParentElement = pNode->toElement();

	if ( dlg.exec( false ) == QDialog::Accepted )
	{
		KCommand *pCmd = new KXECharDataCommand(document(), domParentElement, dlg.atTop(), CharDataComment, dlg.contents());
		m_pCmdHistory->addCommand(pCmd);
	}
	emit setStatusBarText( i18n("Ready.") );
}



void KXMLEditorPart::slotXmlCharDataEdit()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlCharDataEdit called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( (!pNode) || (!pNode->isCharacterData()) )
	{
		kdError() << "KXMLEditorPart::slotXmlCharDataEdit no node selected or selected node is no character data." << endl;
		return;
	}

	emit setStatusBarText( i18n("Editing character data...") );

	QDomCharacterData domCharData = pNode->toCharacterData();

	KXECharDataDialog dlg( widget() );

	CharDataKind eCharDataKind;
	if(domCharData.isText())
		eCharDataKind = CharDataTextNode;
	else
	{
		if(domCharData.isCDATASection())
			eCharDataKind = CharDataCDATASection;
		else
			eCharDataKind = CharDataComment;
	}

	//  dlg.setCharDataKind(eCharDataKind);
	dlg.setContents(domCharData.data());

	if ( dlg.exec( true ) == QDialog::Accepted )
	{
		KCommand *pCmd = new KXEEditCharDataCommand(document(), domCharData, dlg.contents());
		m_pCmdHistory->addCommand(pCmd);
	}

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlMoveNodeUp()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlMoveNodeUp called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( ! pNode )
	{
		kdError() << "KXMLEditorPart::slotXmlMoveNodeUp no node selected." << endl;
		return;
	}

	emit setStatusBarText( i18n("Moving node up...") );

	KCommand *pCmd = new KXEUpCommand(document(), * pNode);
	m_pCmdHistory->addCommand(pCmd);

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotXmlMoveNodeDown()
{
	if ( ! isReadWrite() )
	{
		kdError() << "KXMLEditorPart::slotXmlMoveNodeDown called in readonly mode." << endl;
		return;
	}

	QDomNode * pNode = m_pViewTree->getSelectedNode();
	if ( ! pNode )
	{
		kdError() << "KXMLEditorPart::slotXmlMoveNodeDown no node selected." << endl;
		return;
	}

	emit setStatusBarText( i18n("Moving node down...") );

	KCommand *pCmd = new KXEDownCommand(document(), * pNode);
	m_pCmdHistory->addCommand(pCmd);

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotBookmarksToggle()
{
	m_pViewTree->bookmarksToggle();
	m_pActBookmarksPrev->setEnabled(m_pViewTree->containsBookmarkedItems());
	m_pActBookmarksNext->setEnabled(m_pViewTree->containsBookmarkedItems());
}

void KXMLEditorPart::slotConfigure()
{
	emit setStatusBarText( i18n("Configure KXML Editor ...") );

	KXMLEditorFactory::configuration()->showDialog();

	emit setStatusBarText( i18n("Ready.") );
}

void KXMLEditorPart::slotPathSelected(  )
{

}

void KXMLEditorPart::slotPathSelected( const QString & strPath )
{
	QDomNode node = domTool_matchingNode( document()->toDocument(), strPath );
	if(node.isNull())
	  { // node don't exists, remove item from combo
		m_pActPathCombo->removeItem(strPath);
		m_pActPathCombo->slotClearEdit();
		return;
	  }

	if(!m_pViewTree->selectNode(node))
	{ // node not found, remove item from combo
		m_pActPathCombo->removeItem(strPath);
		m_pActPathCombo->slotClearEdit();
	}
}

void KXMLEditorPart::slotPathClear()
{
	slotEditDeselect();
	m_pActPathCombo->slotFocusEdit();
}

void KXMLEditorPart::slotItemRenamedInplace( QListViewItem * pItem )
{
	KXE_TreeViewItem * pXMLItem = static_cast <KXE_TreeViewItem*> (pItem);

	if ( ! pXMLItem->xmlNode()->isElement() ) // check, if it really represents an XML element
	{
		kdFatal() << "KXMLEditorPart " << k_funcinfo << " the given item doesn't represent an XML element." << endl;
		return;
	}

	QDomElement domElement = pXMLItem->xmlNode()->toElement();

	if ( domElement.nodeName() != pItem->text(0) ) // if really something was changed
	{
		// else the element is "namespaced"
 		int nPosColon = pItem->text(0).find(':');

		if ( nPosColon == -1 )   // if no namespace prefix was entered,
		{
			// check name
			QString strMessage = KXEElementDialog::checkName(pItem->text(0));
			if(strMessage.length() > 0)
			{
				// restore old name
				m_pViewTree->updateNodeChanged(domElement);
				KMessageBox::sorry(m_pViewTree, strMessage);
				return;
			}

						// clear the elements namespace prefix
						// and set the entered text as its tag name
			KCommand *pCmd = new KXEEditElementCommand(document(), domElement, QString::null, pItem->text(0));
			m_pCmdHistory->addCommand(pCmd);
		}
		else
		{
			// otherwise split up the entered text by the first colon and
			QString strPrefix(pItem->text(0).left(nPosColon));
			QString strName(pItem->text(0).right( pItem->text(0).length() - nPosColon - 1 ));

			// check name
			QString strMessage = KXEElementDialog::checkName(strName);
			if(strMessage.length() > 0)
			{
				// restore old name
				m_pViewTree->updateNodeChanged(domElement);
				KMessageBox::sorry(m_pViewTree, strMessage);
				return;
			}

			KCommand *pCmd = new KXEEditElementCommand(
				document(),
				domElement,
				strPrefix,
				strName
				);

			m_pCmdHistory->addCommand(pCmd);
		}


		if ( m_pViewTree->selectedItem() == pItem )                       // and if the item is still selected
		{
			m_pActPathCombo->insertItem( domTool_getIconForNodeType(pXMLItem->xmlNode()->nodeType(), false),
			                             domTool_getPath(*pXMLItem->xmlNode()) ); // the path combo
		}
	}
}

void KXMLEditorPart::slotAttributeNameChangedInplace( const QDomAttr & domAttr, const QString strNewName )
{
	if ( *m_pViewTree->getSelectedNode() == domAttr.ownerElement() ) // if the corresponding element
	{                                                               // is still selected
		KCommand *pCmd = new KXEEditAttrNameCommand(document(), domAttr, strNewName);
		m_pCmdHistory->addCommand(pCmd);
	}
}

void KXMLEditorPart::slotAttributeValueChangedInplace( const QDomAttr & domAttr, const QString strNewValue )
{
	if ( *m_pViewTree->getSelectedNode() == domAttr.ownerElement() ) // if the corresponding element
	{                                                               // is still selected
		KCommand *pCmd = new KXEEditAttrValueCommand(document(), domAttr, strNewValue);
		m_pCmdHistory->addCommand(pCmd);
	}
}

/////////////////////////////////////////////////////////////////////
//                     MISC FUNCTIONS
/////////////////////////////////////////////////////////////////////

/** Copy XML node into clipboard */
QTextDrag * KXMLEditorPart::copyNode(QDomNode * pNode)
{
	QTextDrag *pDrag = 0;
	QString strXML;

	QTextStream streamXML(&strXML, IO_WriteOnly);
	int iIndent = KXMLEditorFactory::configuration()->textview()->indentSteps();
	pNode->save(streamXML, iIndent);
	pDrag = new QTextDrag(strXML, m_pViewTree);

	/*if(pNode->isElement())
		pDrag->setSubtype(KXE_TreeViewItem::m_strSubtypeXML);

	if(pNode->isProcessingInstruction())
		pDrag->setSubtype(KXE_TreeViewItem::m_strSubtypeXML_procins);

	if(pNode->isText())
		pDrag->setSubtype(KXE_TreeViewItem::m_strSubtypeXML_text);

	if(pNode->isCDATASection())
		pDrag->setSubtype(KXE_TreeViewItem::m_strSubtypeXML_cdata);

	if(pNode->isComment())
		pDrag->setSubtype(KXE_TreeViewItem::m_strSubtypeXML_comment);		*/

	return pDrag;
}

//-----------------------------------------------------------------------------
//
// Paste XML node from clipboard into document
//
// pTargetNode    - target node
// data           - data to pasted
//
//-----------------------------------------------------------------------------
bool KXMLEditorPart::pasteNode(QDomNode * pTargetNode, QMimeSource *data)
{
	QString strText;

	// Drop XML Processing Instruction
  if(QTextDrag::decode(data, strText))
		{ if(strText.find("<?xml ") == 0)
      {
        KMessageBox::sorry(0, i18n("This processing instruction cannot be pasted here !"));
        return false;
      }

      //---

      QString strXML = "<root>" + strText  + "</root>";

			// Paste clipboard contents as XML element
			QString strErrorMsg;
  		int iErrorLine, iErrorColumn;
			QDomDocument doc;

 		  if(!doc.setContent(strXML, true, &strErrorMsg, &iErrorLine, &iErrorColumn) )
 				{ kdDebug() << "KXMLEditorPart::pasteNode: Failed parsing the file." << endl;

					KMessageBox::error(m_pViewTree,
												 		i18n("%1 in line %2, column %3").arg(strErrorMsg).arg(iErrorLine).arg(iErrorColumn),
												 		i18n("Parsing error !"));

					return false;
				}

			// Import parsed document to main document
			if(doc.hasChildNodes())
				{ if(pTargetNode == 0)
						{ // check if root item already exists
              if(!document()->documentElement().isNull() /*(this->documentElement().isElement())*/ && (doc.firstChild().firstChild().isElement()) )
              { KMessageBox::sorry(m_pViewTree, i18n("Root element already exists !"));
                return false;
              }

              if(doc.documentElement().firstChild().isElement() == false)
              {
                KMessageBox::sorry(m_pViewTree, i18n("Node pasted to document must be element !"));
                return false;
              }

              // Append it as root node
              QDomElement newNode = doc.documentElement().firstChild().cloneNode(true).toElement();

              KCommand *pCmd = new KXEPasteToDocumentCommand(document(), document(), newNode);
              m_pCmdHistory->addCommand(pCmd);
		}
		else
		{ QDomNode sourceNode = doc.firstChild().firstChild().cloneNode(true);
		
			/*
			L.V.
			
			TESTING CODE FOR [ 925668 ] Attribute values in a copied element can't be changed.
						
			if(sourceNode.isElement())
			{
				QDomElement domSourceElement = sourceNode.toElement();
				
				QDomNamedNodeMap list = domSourceElement.attributes();
				unsigned int iLength = list.length();
				

				for ( unsigned int iRow = 0; iRow < iLength; iRow++ )
				{
					QDomAttr a = list.item(iRow).toAttr();
					
					QDomElement domOwnerElement = a.ownerElement();
					if(domOwnerElement.isNull())
						KMessageBox::sorry(m_pViewTree, i18n("Cloned owner is null !"));
				}*/
              //---

              if(pTargetNode->isElement())
          		{
                QDomElement domTargetElement = pTargetNode->toElement();
                KCommand *pCmd = new KXEPasteToElementCommand(document(), domTargetElement, sourceNode);
                m_pCmdHistory->addCommand(pCmd);
                return true;
          		}

          		if(pTargetNode->isProcessingInstruction() && sourceNode.isProcessingInstruction())
          		{ // Replace contents of selected node
                QDomProcessingInstruction domTargetProcInstr = pTargetNode->toProcessingInstruction();
                QDomProcessingInstruction domSourceProcInstr = sourceNode.toProcessingInstruction();

          			KCommand *pCmd = new KXEPasteToProcInstrCommand(document(), domTargetProcInstr, domSourceProcInstr);
                m_pCmdHistory->addCommand(pCmd);
                return true;
          		}

          		if(pTargetNode->isCharacterData() && sourceNode.isCharacterData())
          		{ // Replace contents of selected node
                QDomCharacterData domTargetCharData = pTargetNode->toCharacterData();
                QDomCharacterData domSourceCharData = sourceNode.toCharacterData();

          			KCommand *pCmd = new KXEPasteToCharDataCommand(document(), domTargetCharData, domSourceCharData);
                m_pCmdHistory->addCommand(pCmd);
                return true;
          		}

              KMessageBox::sorry(m_pViewTree, i18n("Incompactible node types for drag&drop !"));
              return false;
						}
				}
			return true;
		}
	return false;
}

//-----------------------------------------------------------------------------
//
// Drag & Drop MOVE operation
//
// domTrgetElement    - target element
// domSourceNode      - source node
//
//-----------------------------------------------------------------------------
bool KXMLEditorPart::dropMoveNode(QDomElement & domTargetElement, QDomNode & domSourceNode)
{
  KCommand *pCmd = new KXEDragDropMoveCommand(document(), domTargetElement, domSourceNode);
  m_pCmdHistory->addCommand(pCmd);
  return true;
}

/////////////////////////////////////////////////////////////////////
//                          PRINTING
/////////////////////////////////////////////////////////////////////

// these defines should rather stay fixed and not configurable by the user.
#define headerMargin 30;
#define footerMargin 50;
#define m_printLinespace 0.4			// percent of font size used to make line indent

int headerHeight, footerHeight;	// used in few functions, nevertheless temporary...

void KXMLEditorPart::print(KPrinter* pPrinter)
{
	// setup the printer.  with Qt, you always "print" to a
	// QPainter.. whether the output medium is a pixmap, a screen, or paper
	QPainter p;
	QPainter *painter = &p;
	QFont font( KXMLEditorFactory::configuration()->print()->fontFamily(),
	            KXMLEditorFactory::configuration()->print()->fontSize() );

	QPaintDeviceMetrics metrics((QPrinter*)pPrinter);		// determining
	int width = metrics.width();						// width and
	int height = metrics.height();						// height of the page

	footerHeight = font.pointSize()+footerMargin;
	headerHeight = font.pointSize()+headerMargin;

	int pageNumber = 0;

	painter->begin(pPrinter);						// start print job
	painter->setFont(font);							// set up fonts for printout
	printHeader(painter,pageNumber,0,width);			// draw header on a first page
	while (printPage	(painter,pageNumber,
				headerHeight,width,
				height-headerHeight-footerHeight))	// and start printing loop
	{
		printFooter(painter, pageNumber, height-footerHeight,width);	// draw footer at the end of that page
		pageNumber++;
		pPrinter->newPage();
		printHeader(painter,pageNumber,0,width);				// draw header on new page
	}
	printFooter(painter,pageNumber,height-footerHeight,width);		// draw footer on last page
	painter->end();								// finish print job
}

void KXMLEditorPart::printHeader(QPainter* painter,int pageNumber, int ypos, int width)
{
	pageNumber = pageNumber;
	if ( KXMLEditorFactory::configuration()->print()->hasHeader() )
	{
		painter->drawText(0,ypos,m_url.prettyURL());
		painter->drawLine(0,ypos,width,ypos);
	}
}

bool KXMLEditorPart::printPage(QPainter* painter,int pageNumber, int top, int width, int height)
{
	width = width;
	if (pageNumber==0)
	{
		// initialization of working variables is done when
		// first page is about to be printed
		m_printLineNumber = 0;
		m_printLines = QStringList::split( "\n", document()->toString(KXMLEditorFactory::configuration()->print()->indentSteps()) );
	}
	int lineHeight = (int)(painter->font().pointSize()*(1+m_printLinespace));
	int y = top;
	while ( y <= height )
	{
		painter->drawText(0,y,m_printLines[m_printLineNumber]);
		if (m_printLineNumber++==m_printLines.size())
			return false;	// no more pages to print
		y += lineHeight;
	}
	return true;			// there are still some pages to print
}

void KXMLEditorPart::printFooter(QPainter* painter,int pageNumber, int ypos, int width)
{
	if ( KXMLEditorFactory::configuration()->print()->hasFooter() )
	{
		int fh = painter->font().pointSize();
		painter->drawText(0,ypos,i18n("Page %1").arg(pageNumber+1));
		painter->drawLine(0,ypos-fh,width,ypos-fh);
	}
}


/////////////////////////////////////////////////////////////////////
//                           OTHER SLOTS
/////////////////////////////////////////////////////////////////////

void KXMLEditorPart::slotTreeViewKeyPressed(QKeyEvent *e)
{
	// few keypresses are recognized and proper actions
	// are executed.
	switch (e->key())
	{
		case Qt::Key_Delete	: slotActDelete(); break;
		case Qt::Key_Return	:
		case Qt::Key_Enter	: slotActProperties(); break;
	}
}

void KXMLEditorPart::slotSelectionCleared(bool bRootElementExists)
{
	// Enable/Disable actions
	if(m_pBrowserExt)
		m_pBrowserExt->emit enableAction( "copy", false );
	else
		m_pActEditCopy->setEnabled(false);
		
	m_pActEditDeselect->setEnabled(false);
	m_pActViewNodeUp->setEnabled(false);
	m_pActViewExpNode->setEnabled(false);
	m_pActViewColNode->setEnabled(false);
	m_pActBookmarksToggle->setEnabled(false);
  
	if ( isReadWrite() )
	{
		m_pActEditCut->setEnabled(false );
		m_pActEditPaste->setEnabled(true );

		m_pActXmlElementInsert->setEnabled(!bRootElementExists);
		m_pActXmlAttributesAdd->setEnabled(false);
		m_pActXmlAttributesDel->setEnabled(false);
		m_pActXmlProcInstrInsert->setEnabled(true);
		m_pActInsertText->setEnabled(false);
		m_pActInsertCDATA->setEnabled(false);
		m_pActInsertComment->setEnabled(false);
		m_pActXmlMoveNodeUp->setEnabled(false);
		m_pActXmlMoveNodeDown->setEnabled(false);
		m_pActDelete->setEnabled(false);
		m_pActProperties->setEnabled(false);
		m_pActEditRawXml->setEnabled(false);
	}

	m_pActPathCombo->slotClearEdit();

	// change views
	m_pViewContents->clear();

	m_pTabWidget->setTabEnabled( m_pViewElement, false );
	m_pTabWidget->setTabEnabled( m_pViewContents, false );
	m_pTabWidget->setTabEnabled( m_pViewProcInstr, false );

	m_pTabWidget->showPage( m_pViewContents );

	// change path combo
	m_pActPathCombo->slotClearEdit();
}

void KXMLEditorPart::slotSelectionChanged( const QDomElement & selectedNode)
{
	// Enable/Disable actions
	if(m_pBrowserExt)
		m_pBrowserExt->emit enableAction( "copy", true );
	else
		m_pActEditCopy->setEnabled(true);
		
	m_pActEditDeselect->setEnabled(true);
	m_pActViewNodeUp->setEnabled( ! selectedNode.parentNode().isNull() ); // disable if it's a root item
	m_pActViewExpNode->setEnabled( ! selectedNode.firstChild().isNull() ); // no childs -> disable
	m_pActViewColNode->setEnabled( ! selectedNode.firstChild().isNull() ); // no childs -> disable
	m_pActBookmarksToggle->setEnabled(true);

	if ( isReadWrite() )
	{
		m_pActEditCut->setEnabled(true);
		m_pActEditPaste->setEnabled(true);

		m_pActXmlElementInsert->setEnabled(true);
		m_pActXmlAttributesAdd->setEnabled(true);
		m_pActXmlAttributesDel->setEnabled( (selectedNode.attributes().count() != 0) );
		m_pActXmlProcInstrInsert->setEnabled(true);
//		m_pActXmlCharDataInsert->setEnabled(true);
		m_pActInsertText->setEnabled(true);
		m_pActInsertCDATA->setEnabled(true);
		m_pActInsertComment->setEnabled(true);
		m_pActDelete->setEnabled(true);
		m_pActProperties->setEnabled(true);
		m_pActEditRawXml->setEnabled(true);

		if ( selectedNode.parentNode().isDocument() )
		{
			m_pActXmlMoveNodeUp->setEnabled(false);
			m_pActXmlMoveNodeDown->setEnabled(false);
		}
		else
		{
			m_pActXmlMoveNodeUp->setEnabled( ! selectedNode.previousSibling().isNull() );
			m_pActXmlMoveNodeDown->setEnabled( ! selectedNode.nextSibling().isNull() );
		}
	}

	// change views
	m_pViewElement->slotChange(selectedNode);

	m_pTabWidget->setTabEnabled( m_pViewElement, true );
	m_pTabWidget->setTabEnabled( m_pViewContents, false );
	m_pTabWidget->setTabEnabled( m_pViewProcInstr, false );

	m_pTabWidget->showPage(m_pViewElement);

	// change path combo
	m_pActPathCombo->insertItem( domTool_getIconForNodeType(selectedNode.nodeType(), false), domTool_getPath(selectedNode) );
}

void KXMLEditorPart::slotSelectionChanged( const QDomCharacterData & selectedNode )
{
	// Enable/Disable actions
	if(m_pBrowserExt)
		m_pBrowserExt->emit enableAction( "copy", true );
	else
		m_pActEditCopy->setEnabled(true);

	m_pActEditDeselect->setEnabled(true);
	m_pActViewNodeUp->setEnabled( ! selectedNode.parentNode().isNull() ); // disable if it's a root item
	m_pActViewExpNode->setEnabled(false);
	m_pActViewColNode->setEnabled(false);
	m_pActBookmarksToggle->setEnabled(true);

	if ( isReadWrite() )
	{
		m_pActEditCut->setEnabled(true);
		m_pActEditPaste->setEnabled(true);

		m_pActXmlElementInsert->setEnabled(false);
		m_pActXmlAttributesAdd->setEnabled(false);
		m_pActXmlAttributesDel->setEnabled(false);
		m_pActXmlProcInstrInsert->setEnabled(false);
		m_pActInsertText->setEnabled(false);
		m_pActInsertCDATA->setEnabled(false);
		m_pActInsertComment->setEnabled(false);
		m_pActXmlMoveNodeUp->setEnabled( ! selectedNode.previousSibling().isNull() );
		m_pActXmlMoveNodeDown->setEnabled( ! selectedNode.nextSibling().isNull() );
		m_pActDelete->setEnabled(true);
		m_pActProperties->setEnabled(true);
		m_pActEditRawXml->setEnabled(false);
	}

	// change views
	m_pViewContents->setText( selectedNode.data() );

	m_pTabWidget->setTabEnabled( m_pViewElement, false );
	m_pTabWidget->setTabEnabled( m_pViewContents, true );
	m_pTabWidget->setTabEnabled( m_pViewProcInstr, false );

	m_pTabWidget->showPage( m_pViewContents );

	// change path combo
	m_pActPathCombo->insertItem( domTool_getIconForNodeType(selectedNode.nodeType(), false), domTool_getPath(selectedNode) );
}

void KXMLEditorPart::slotSelectionChanged( const QDomProcessingInstruction & selectedNode )
{
	// Enable/Disable actions
	if(m_pBrowserExt)
		m_pBrowserExt->emit enableAction( "copy", true );
	else
		m_pActEditCopy->setEnabled(true);

	m_pActEditDeselect->setEnabled(true);
	m_pActViewNodeUp->setEnabled( ! selectedNode.parentNode().isNull() ); // disable if it's a root item
	m_pActViewExpNode->setEnabled(false);
	m_pActViewColNode->setEnabled(false);
	m_pActBookmarksToggle->setEnabled(true);

	if ( isReadWrite() )
	{
		m_pActEditCut->setEnabled(true);
		m_pActEditPaste->setEnabled(true);

		m_pActXmlAttributesAdd->setEnabled(false);
		m_pActXmlAttributesDel->setEnabled(false);
		m_pActXmlProcInstrInsert->setEnabled(false);
		m_pActInsertText->setEnabled(false);
		m_pActInsertCDATA->setEnabled(false);
		m_pActInsertComment->setEnabled(false);
		m_pActDelete->setEnabled(true);
		m_pActProperties->setEnabled(true);
		m_pActEditRawXml->setEnabled(false);
		m_pActXmlElementInsert->setEnabled(selectedNode.parentNode().isDocument() &&
									document()->documentElement().isNull());

		if ( selectedNode.parentNode().isDocument() )
		{
			m_pActXmlMoveNodeUp->setEnabled(false);
			m_pActXmlMoveNodeDown->setEnabled(false);
		}
		else
		{
			m_pActXmlMoveNodeUp->setEnabled( ! selectedNode.previousSibling().isNull() );
			m_pActXmlMoveNodeDown->setEnabled( ! selectedNode.nextSibling().isNull() );
		}
	}

	// change views
	m_pViewProcInstr->setText( selectedNode.data() );

	m_pTabWidget->setTabEnabled( m_pViewElement, false );
	m_pTabWidget->setTabEnabled( m_pViewContents, false );
	m_pTabWidget->setTabEnabled( m_pViewProcInstr, true );

	m_pTabWidget->showPage( m_pViewProcInstr );

	// change path combo
	m_pActPathCombo->insertItem( domTool_getIconForNodeType(selectedNode.nodeType(), false), domTool_getPath(selectedNode) );
}

void KXMLEditorPart::slotContextMenuRequested( const QString & szMenuName, const QPoint & pos )
{
	QWidget * pContainer = hostContainer(szMenuName);

	if ( ! pContainer )
	{
		kdError() << "KXMLEditor " << k_funcinfo << " Couldn't get a container widget for the given menu name (" << szMenuName << ")" << endl;
		return;
	}

	if ( ! pContainer->inherits("KPopupMenu") )
	{
		kdError() << "KXMLEditor " << k_funcinfo << " Wrong container widget" << endl;
		return;
	}

	KPopupMenu * pMenu = static_cast <KPopupMenu*> (pContainer);
	pMenu->popup( pos );
}


/////////////////////////////////////////////////////////////////////
//        FUNCTIONS CALLED FROM KXECommand CHILD CLASSES
/////////////////////////////////////////////////////////////////////

void KXMLEditorPart::updateNodeCreated(const QDomNode & node)
{
	m_pViewTree->updateNodeCreated(node);
}

void KXMLEditorPart::updateNodeDeleted( const QDomNode & node )
{
	m_pViewTree->updateNodeDeleted(node);

	// if root element deleted, enable Insert Element
	if(node.isElement() && (m_pViewTree->firstChild() == 0) && (isReadWrite()))
	m_pActXmlElementInsert->setEnabled(true);
}

void KXMLEditorPart::updateNodeChanged( const QDomElement & domElement )
{
	m_pViewTree->updateNodeChanged(domElement);
	m_pViewElement->slotChange(domElement);
}

void KXMLEditorPart::updateNodeChanged( const QDomCharacterData & domCharData )
{
	m_pViewTree->updateNodeChanged(domCharData);
	m_pViewContents->setText( domCharData.data() );
}

void KXMLEditorPart::updateNodeChanged( const QDomProcessingInstruction &domProcInstr )
{
	m_pViewTree->updateNodeChanged(domProcInstr);
	m_pViewProcInstr->setText( domProcInstr.data() );
}

void KXMLEditorPart::updateNodeMoved( const QDomNode & domNode )
{
	m_pViewTree->updateNodeMoved(domNode);
}


bool KXMLEditorPart::slotFileSaveAs()
{
	emit setStatusBarText( i18n("Saving file with a new filename...") );

	KFileDialog dlg( QDir::currentDirPath(),   // start dir.
	                 i18n(FILE_DIALOG_FILTER), // filter
	                 widget(),                 // parent
	                 "file dialog for saving", // name
	                 true );                   // modal
	dlg.setCaption( i18n("Save as...") );
	dlg.setOperationMode( KFileDialog::Saving );
	dlg.exec();

	KURL url = dlg.selectedURL();
	bool bRetVal = false;
	
	if(!url.isEmpty())
	{
    // append filetype if necessary
    if(dlg.currentFilter() != "*.*")
    { QString strExtension = dlg.currentFilter();
      strExtension.remove('*');

      if(strExtension != url.fileName().right(strExtension.length()))
        url.setFileName(url.fileName() + strExtension );
    }
				
		if((bRetVal = saveAs(url)))	// something may go wrong
		{
			emit sigAddRecentURL(url);
			setModified(false);
		}
	}

	emit setStatusBarText( i18n("Ready.") );
	return bRetVal;
}

void KXMLEditorPart::slotDocOpened()
{
// I temporary introduced code to measure the loading time using
// the different tree view item initialization modes.
// Simply open a document, remember the measured time difference,
// change the mode (in the configuration dialog), load the
// same document again and compare the measurements.
//                                                     Olaf
//
// TODO: the three lines operating with the QTime objects
//       can be removed later

	// update the view
	m_pViewTree->updateClear();
	int i = document()->childNodes().length();
	//QTime t1 = QTime::currentTime(); //TODO: remove this line later (Olaf)
	while ( i > 0  )
	{
		i--;
		m_pViewTree->updateNodeCreated( document()->childNodes().item(i) );
	}
	
	//QTime t2 = QTime::currentTime(); //TODO: remove this and the next line later (Olaf)
	//kdDebug() << "KXMLEditorPart::slotDocOpened()   time difference: " << t1.msecsTo(t2) << " msecs" << endl;
	
	m_pActPathCombo->slotClear();
}

void KXMLEditorPart::setDocument(KXEDocument *pDocument)
{
	// detach previously used document
	if (m_pDocument)
	{
		disconnect (m_pDocument,0,this,0);
	}
	m_pDocument = pDocument;
	if (pDocument)
	{
		// open document notification
		connect(pDocument,SIGNAL(sigOpened()),this,SLOT(slotDocOpened()));
		// document modification is also dispatched
		connect(pDocument,SIGNAL(sigModified(bool)),this,SLOT(setModified(bool)));
		// update notifications
		connect(pDocument,SIGNAL(sigNodeChanged(const QDomElement&)),this,SLOT(updateNodeChanged(const QDomElement&)));
		connect(pDocument,SIGNAL(sigNodeChanged(const QDomProcessingInstruction&)),this,SLOT(updateNodeChanged(const QDomProcessingInstruction&)));
		connect(pDocument,SIGNAL(sigNodeChanged(const QDomCharacterData&)),this,SLOT(updateNodeChanged(const QDomCharacterData&)));
		connect(pDocument,SIGNAL(sigNodeCreated(const QDomNode&)),this,SLOT(updateNodeCreated(const QDomNode&)));
		connect(pDocument,SIGNAL(sigNodeDeleted(const QDomNode&)),this,SLOT(updateNodeDeleted(const QDomNode&)));
		connect(pDocument,SIGNAL(sigNodeMoved(const QDomNode&)),this,SLOT(updateNodeMoved(const QDomNode&)));
		// merging document action collection
		insertChildClient(pDocument);
	}
}

void KXMLEditorPart::slotActRedo()
{
	m_pCmdHistory->redo();
}

void KXMLEditorPart::slotActUndo()
{
	m_pCmdHistory->undo();
}

void KXMLEditorPart::slotActDetachStylesheet()
{
	KCommand *pCmd = m_pDocument->actDetachStylesheet();
	if(pCmd) m_pCmdHistory->addCommand(pCmd);
}

void KXMLEditorPart::slotActAttachStylesheet()
{
	KCommand *pCmd = m_pDocument->actAttachStylesheet();
	if(pCmd) m_pCmdHistory->addCommand(pCmd);
}

void KXMLEditorPart::slotActDetachSchema()
{
	KCommand *pCmd = m_pDocument->actDetachSchema();
	if(pCmd) m_pCmdHistory->addCommand(pCmd);
}

void KXMLEditorPart::slotActAttachSchema()
{
	KCommand *pCmd = m_pDocument->actAttachSchema();
	if(pCmd) m_pCmdHistory->addCommand(pCmd);
}

// Instert or edit special processing instruction <?xml ... ?>
void KXMLEditorPart::slotActVersionEncoding()
{
	KCommand *pCmd = m_pDocument->actVersionEncoding();
	if(pCmd) m_pCmdHistory->addCommand(pCmd);
}

void KXMLEditorPart::updateActions()
{
	if(!m_pDocument) return;
	if(!m_pActAttachSchema) return; // not in read-write mode
	
	// Schema
	bool bSchemaExists = !m_pDocument->documentElement().isNull() &&
						// that's a question why it works with negated condition ??????
						!m_pDocument->documentElement().hasAttributeNS(SCHEMA_NAMESPACE,SCHEMA_ATTRIBUTE);

	m_pActAttachSchema->setEnabled(!m_pDocument->documentElement().isNull() && !bSchemaExists);
	m_pActDetachSchema->setEnabled(bSchemaExists);

	// Stylesheet
	m_pActDetachStylesheet->setEnabled(!m_pDocument->getSpecProcInstr("xml-stylesheet").isNull());
}

#include "kxmleditorpart.moc"