summaryrefslogtreecommitdiffstats
path: root/tdeui/kedittoolbar.cpp
blob: e57a641a7fad5c7228b5e8078db99947f3ffabea (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
// -*- mode: c++; c-basic-offset: 2 -*-
/* This file is part of the KDE libraries
   Copyright (C) 2000 Kurt Granroth <granroth@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/
#include <kedittoolbar.h>

#include <tqdom.h>
#include <tqlayout.h>
#include <tqdir.h>
#include <tqfile.h>
#include <tqheader.h>
#include <tqcombobox.h>
#include <tqdragobject.h>
#include <tqtoolbutton.h>
#include <tqlabel.h>
#include <tqvaluelist.h>
#include <tqapplication.h>
#include <tqtextstream.h>

#include <kaction.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kicontheme.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <kmessagebox.h>
#include <kxmlguifactory.h>
#include <kseparator.h>
#include <kconfig.h>
#include <klistview.h>
#include <kdebug.h>
#include <kpushbutton.h>
#include <kprocio.h>

static const char * const lineseparatorstring = I18N_NOOP("--- line separator ---");
static const char * const separatorstring = I18N_NOOP("--- separator ---");

#define LINESEPARATORSTRING i18n(lineseparatorstring)
#define SEPARATORSTRING i18n(separatorstring)

static void dump_xml(const TQDomDocument& doc)
{
    TQString str;
    TQTextStream ts(&str, IO_WriteOnly);
    ts << doc;
    kdDebug() << str << endl;
}

typedef TQValueList<TQDomElement> ToolbarList;

namespace
{
class XmlData
{
public:
  enum XmlType { Shell = 0, Part, Local, Merged };
  XmlData()
  {
    m_isModified = false;
    m_actionCollection = 0;
  }

  TQString      m_xmlFile;
  TQDomDocument m_document;
  XmlType      m_type;
  bool         m_isModified;
  KActionCollection* m_actionCollection;

  ToolbarList  m_barList;
};

typedef TQValueList<XmlData> XmlDataList;

class ToolbarItem : public TQListViewItem
{
public:
  ToolbarItem(KListView *parent, const TQString& tag = TQString::null, const TQString& name = TQString::null, const TQString& statusText = TQString::null)
    : TQListViewItem(parent),
      m_tag(tag),
      m_name(name),
      m_statusText(statusText)
  {
  }

  ToolbarItem(KListView *parent, TQListViewItem *item, const TQString &tag = TQString::null, const TQString& name = TQString::null, const TQString& statusText = TQString::null)
    : TQListViewItem(parent, item),
      m_tag(tag),
      m_name(name),
      m_statusText(statusText)
  {
  }

  virtual TQString key(int column, bool) const
  {
    TQString s = text( column );
    if ( s == LINESEPARATORSTRING )
      return "0";
    if ( s == SEPARATORSTRING )
      return "1";
    return "2" + s;
  }

  void setInternalTag(const TQString &tag) { m_tag = tag; }
  void setInternalName(const TQString &name) { m_name = name; }
  void setStatusText(const TQString &text) { m_statusText = text; }
  TQString internalTag() const { return m_tag; }
  TQString internalName() const { return m_name; }
  TQString statusText() const { return m_statusText; }
private:
  TQString m_tag;
  TQString m_name;
  TQString m_statusText;
};

#define TOOLBARITEMMIMETYPE "data/x-kde.toolbar.item"
class ToolbarItemDrag : public TQStoredDrag
{
public:
  ToolbarItemDrag(ToolbarItem *toolbarItem,
                    TQWidget *dragSource = 0, const char *name = 0)
    : TQStoredDrag( TOOLBARITEMMIMETYPE, dragSource, name )
  {
    if (toolbarItem) {
      TQByteArray data;
      TQDataStream out(data, IO_WriteOnly);
      out << toolbarItem->internalTag();
      out << toolbarItem->internalName();
      out << toolbarItem->statusText();
      out << toolbarItem->text(1); // separators need this.
      setEncodedData(data);
    }
  }

  static bool canDecode(TQMimeSource* e)
  {
    return e->provides(TOOLBARITEMMIMETYPE);
  }

  static bool decode( const TQMimeSource* e, ToolbarItem& item )
  {
    if (!e)
      return false;

    TQByteArray data = e->tqencodedData(TOOLBARITEMMIMETYPE);
    if ( data.isEmpty() )
      return false;

    TQString internalTag, internalName, statusText, text;
    TQDataStream in(data, IO_ReadOnly);
    in >> internalTag;
    in >> internalName;
    in >> statusText;
    in >> text;

    item.setInternalTag( internalTag );
    item.setInternalName( internalName );
    item.setStatusText( statusText );
    item.setText(1, text);

    return true;
  }
};

class ToolbarListView : public KListView
{
public:
  ToolbarListView(TQWidget *parent=0, const char *name=0)
    : KListView(parent, name)
  {
  }
protected:
  virtual TQDragObject *dragObject()
  {
    ToolbarItem *item = dynamic_cast<ToolbarItem*>(selectedItem());
    if ( item ) {
      ToolbarItemDrag *obj = new ToolbarItemDrag(item,
                                 this, "ToolbarAction drag item");
      const TQPixmap *pm = item->pixmap(0);
      if( pm )
        obj->setPixmap( *pm );
      return obj;
    }
    return 0;
  }

  virtual bool acceptDrag(TQDropEvent *event) const
  {
    return ToolbarItemDrag::canDecode( event );
  }
};
} // namespace

class KEditToolbarWidgetPrivate
{
public:
    /**
     * @param instance The instance.
     * @param collection In a non-KParts application, this is the collection passed
     * to the KEditToolbar constructor.
     * In a KParts application we let create a KXMLGUIClient create a dummy one,
     * but it probably isn't used.
     */
  KEditToolbarWidgetPrivate(KInstance *instance, KActionCollection* collection)
      : m_collection( collection )
  {
    m_instance = instance;
    m_isPart   = false;
    m_helpArea = 0L;
    m_kdialogProcess = 0;
  }
  ~KEditToolbarWidgetPrivate()
  {
  }

  TQString xmlFile(const TQString& xml_file)
  {
    return xml_file.isNull() ? TQString(m_instance->instanceName()) + "ui.rc" :
                               xml_file;
  }

  /**
   * Load in the specified XML file and dump the raw xml
   */
  TQString loadXMLFile(const TQString& _xml_file)
  {
    TQString raw_xml;
    TQString xml_file = xmlFile(_xml_file);
    //kdDebug() << "loadXMLFile xml_file=" << xml_file << endl;

    if ( !TQDir::isRelativePath(xml_file) )
      raw_xml = KXMLGUIFactory::readConfigFile(xml_file);
    else
      raw_xml = KXMLGUIFactory::readConfigFile(xml_file, m_instance);

    return raw_xml;
  }

  /**
   * Return a list of toolbar elements given a toplevel element
   */
  ToolbarList findToolbars(TQDomNode n)
  {
    static const TQString &tagToolbar = KGlobal::staticQString( "ToolBar" );
    static const TQString &attrNoEdit = KGlobal::staticQString( "noEdit" );
    ToolbarList list;

    for( ; !n.isNull(); n = n.nextSibling() )
    {
      TQDomElement elem = n.toElement();
      if (elem.isNull())
        continue;

      if (elem.tagName() == tagToolbar && elem.attribute( attrNoEdit ) != "true" )
        list.append(elem);

      list += findToolbars(elem.firstChild());
    }

    return list;
  }

  /**
   * Return the name of a given toolbar
   */
  TQString toolbarName( const XmlData& xmlData, const TQDomElement& it ) const
  {
      static const TQString &tagText = KGlobal::staticQString( "text" );
      static const TQString &tagText2 = KGlobal::staticQString( "Text" );
      static const TQString &attrName = KGlobal::staticQString( "name" );

      TQString name;
      TQCString txt( it.namedItem( tagText ).toElement().text().utf8() );
      if ( txt.isEmpty() )
          txt = it.namedItem( tagText2 ).toElement().text().utf8();
      if ( txt.isEmpty() )
          name = it.attribute( attrName );
      else
          name = i18n( txt );

      // the name of the toolbar might depend on whether or not
      // it is in kparts
      if ( ( xmlData.m_type == XmlData::Shell ) ||
           ( xmlData.m_type == XmlData::Part ) )
      {
        TQString doc_name(xmlData.m_document.documentElement().attribute( attrName ));
        name += " <" + doc_name + ">";
      }
      return name;
  }
  /**
   * Look for a given item in the current toolbar
   */
  TQDomElement findElementForToolbarItem( const ToolbarItem* item ) const
  {
    static const TQString &attrName    = KGlobal::staticQString( "name" );
    for(TQDomNode n = m_currentToolbarElem.firstChild(); !n.isNull(); n = n.nextSibling())
    {
      TQDomElement elem = n.toElement();
      if ((elem.attribute(attrName) == item->internalName()) &&
          (elem.tagName() == item->internalTag()))
        return elem;
    }
    return TQDomElement();
  }

#ifndef NDEBUG
  void dump()
  {
    static const char* s_XmlTypeToString[] = { "Shell", "Part", "Local", "Merged" };
    XmlDataList::Iterator xit = m_xmlFiles.begin();
    for ( ; xit != m_xmlFiles.end(); ++xit )
    {
        kdDebug(240) << "XmlData type " << s_XmlTypeToString[(*xit).m_type] << " xmlFile: " << (*xit).m_xmlFile << endl;
        for( TQValueList<TQDomElement>::Iterator it = (*xit).m_barList.begin();
             it != (*xit).m_barList.end(); ++it ) {
            kdDebug(240) << "    Toolbar: " << toolbarName( *xit, *it ) << endl;
        }
        if ( (*xit).m_actionCollection )
            kdDebug(240) << "    " << (*xit).m_actionCollection->count() << " actions in the collection." << endl;
        else
            kdDebug(240) << "    no action collection." << endl;
    }
  }
#endif

  //TQValueList<KAction*> m_actionList;
  KActionCollection* m_collection;
  KInstance         *m_instance;

  XmlData*     m_currentXmlData;
  TQDomElement m_currentToolbarElem;

  TQString            m_xmlFile;
  TQString            m_globalFile;
  TQString            m_rcFile;
  TQDomDocument       m_localDoc;
  bool               m_isPart;

  ToolbarList        m_barList;

  XmlDataList m_xmlFiles;

  TQLabel     *m_comboLabel;
  KSeparator *m_comboSeparator;
  TQLabel * m_helpArea;
  KPushButton* m_changeIcon;
  KProcIO* m_kdialogProcess;
  bool m_hasKDialog;
};

class KEditToolbarPrivate {
public:
    bool m_accept;

    // Save parameters for recreating widget after resetting toolbar
    bool m_global;
    KActionCollection* m_collection;
    TQString m_file;
    KXMLGUIFactory* m_factory;
};

const char *KEditToolbar::s_defaultToolbar = 0L;

KEditToolbar::KEditToolbar(KActionCollection *collection, const TQString& file,
                           bool global, TQWidget* parent, const char* name)
  : KDialogBase(Swallow, i18n("Configure Toolbars"), Default|Ok|Apply|Cancel, Ok, parent, name),
    m_widget(new KEditToolbarWidget(TQString::tqfromLatin1(s_defaultToolbar), collection, file, global, this))
{
    init();
    d->m_global = global;
    d->m_collection = collection;
    d->m_file = file;
}

KEditToolbar::KEditToolbar(const TQString& defaultToolbar, KActionCollection *collection,
                           const TQString& file, bool global,
                           TQWidget* parent, const char* name)
  : KDialogBase(Swallow, i18n("Configure Toolbars"), Default|Ok|Apply|Cancel, Ok, parent, name),
    m_widget(new KEditToolbarWidget(defaultToolbar, collection, file, global, this))
{
    init();
    d->m_global = global;
    d->m_collection = collection;
    d->m_file = file;
}

KEditToolbar::KEditToolbar(KXMLGUIFactory* factory, TQWidget* parent, const char* name)
    : KDialogBase(Swallow, i18n("Configure Toolbars"), Default|Ok|Apply|Cancel, Ok, parent, name),
      m_widget(new KEditToolbarWidget(TQString::tqfromLatin1(s_defaultToolbar), factory, this))
{
    init();
    d->m_factory = factory;
}

KEditToolbar::KEditToolbar(const TQString& defaultToolbar,KXMLGUIFactory* factory,
                           TQWidget* parent, const char* name)
    : KDialogBase(Swallow, i18n("Configure Toolbars"), Default|Ok|Apply|Cancel, Ok, parent, name),
      m_widget(new KEditToolbarWidget(defaultToolbar, factory, this))
{
    init();
    d->m_factory = factory;
}

void KEditToolbar::init()
{
    d = new KEditToolbarPrivate();
    d->m_accept = false;
    d->m_factory = 0;

    setMainWidget(m_widget);

    connect(m_widget, TQT_SIGNAL(enableOk(bool)), TQT_SLOT(acceptOK(bool)));
    connect(m_widget, TQT_SIGNAL(enableOk(bool)), TQT_SLOT(enableButtonApply(bool)));
    enableButtonApply(false);

    setMinimumSize(sizeHint());
    s_defaultToolbar = 0L;
}

KEditToolbar::~KEditToolbar()
{
    delete d;
}

void KEditToolbar::acceptOK(bool b)
{
    enableButtonOK(b);
    d->m_accept = b;
}

void KEditToolbar::slotDefault()
{
    if ( KMessageBox::warningContinueCancel(this, i18n("Do you really want to reset all toolbars of this application to their default? The changes will be applied immediately."), i18n("Reset Toolbars"),i18n("Reset"))!=KMessageBox::Continue )
        return;

    delete m_widget;
    d->m_accept = false;

    if ( d->m_factory )
    {
        const TQString localPrefix = locateLocal("data", "");
        TQPtrList<KXMLGUIClient> clients(d->m_factory->clients());
        TQPtrListIterator<KXMLGUIClient> it( clients );

        for( ; it.current(); ++it)
        {
            KXMLGUIClient *client = it.current();
            TQString file = client->xmlFile();

            if (file.isNull())
                continue;

            if (TQDir::isRelativePath(file))
            {
                const KInstance *instance = client->instance() ? client->instance() : KGlobal::instance();
                file = locateLocal("data", TQString::tqfromLatin1( instance->instanceName() + '/' ) + file);
            }
            else
            {
                if (!file.startsWith(localPrefix))
                    continue;
            }

            if ( TQFile::exists( file ) )
                if ( !TQFile::remove( file ) )
                    kdWarning() << "Could not delete " << file << endl;
        }

        m_widget = new KEditToolbarWidget(TQString::null, d->m_factory, this);
        m_widget->rebuildKXMLGUIClients();
    }
    else
    {
        int slash = d->m_file.findRev('/')+1;
        if (slash)
            d->m_file = d->m_file.mid(slash);
        TQString xml_file = locateLocal("data", TQString::tqfromLatin1( KGlobal::instance()->instanceName() + '/' ) + d->m_file);

        if ( TQFile::exists( xml_file ) )
            if ( !TQFile::remove( xml_file ) )
                kdWarning() << "Could not delete " << xml_file << endl;

        m_widget = new KEditToolbarWidget(TQString::null, d->m_collection, d->m_file, d->m_global, this);
    }

    setMainWidget(m_widget);
    m_widget->show();

    connect(m_widget, TQT_SIGNAL(enableOk(bool)), TQT_SLOT(acceptOK(bool)));
    connect(m_widget, TQT_SIGNAL(enableOk(bool)), TQT_SLOT(enableButtonApply(bool)));

    enableButtonApply(false);
    emit newToolbarConfig();
}

void KEditToolbar::slotOk()
{
  if (!d->m_accept) {
      reject();
      return;
  }

  if (!m_widget->save())
  {
    // some error box here is needed
  }
  else
  {
    emit newToolbarConfig();
    accept();
  }
}

void KEditToolbar::slotApply()
{
    (void)m_widget->save();
    enableButtonApply(false);
    emit newToolbarConfig();
}

void KEditToolbar::setDefaultToolbar(const char *toolbarName)
{
    s_defaultToolbar = toolbarName;
}

KEditToolbarWidget::KEditToolbarWidget(KActionCollection *collection,
                                       const TQString& file,
                                       bool global, TQWidget *parent)
  : TQWidget(parent),
    d(new KEditToolbarWidgetPrivate(instance(), collection))
{
  initNonKPart(collection, file, global);
  // now load in our toolbar combo box
  loadToolbarCombo();
  adjustSize();
  setMinimumSize(sizeHint());
}

KEditToolbarWidget::KEditToolbarWidget(const TQString& defaultToolbar,
                                       KActionCollection *collection,
                                       const TQString& file, bool global,
                                       TQWidget *parent)
  : TQWidget(parent),
    d(new KEditToolbarWidgetPrivate(instance(), collection))
{
  initNonKPart(collection, file, global);
  // now load in our toolbar combo box
  loadToolbarCombo(defaultToolbar);
  adjustSize();
  setMinimumSize(sizeHint());
}

KEditToolbarWidget::KEditToolbarWidget( KXMLGUIFactory* factory,
                                        TQWidget *parent)
  : TQWidget(parent),
    d(new KEditToolbarWidgetPrivate(instance(), KXMLGUIClient::actionCollection() /*create new one*/))
{
  initKPart(factory);
  // now load in our toolbar combo box
  loadToolbarCombo();
  adjustSize();
  setMinimumSize(sizeHint());
}

KEditToolbarWidget::KEditToolbarWidget( const TQString& defaultToolbar,
                                        KXMLGUIFactory* factory,
                                        TQWidget *parent)
  : TQWidget(parent),
    d(new KEditToolbarWidgetPrivate(instance(), KXMLGUIClient::actionCollection() /*create new one*/))
{
  initKPart(factory);
  // now load in our toolbar combo box
  loadToolbarCombo(defaultToolbar);
  adjustSize();
  setMinimumSize(sizeHint());
}

KEditToolbarWidget::~KEditToolbarWidget()
{
    delete d;
}

void KEditToolbarWidget::initNonKPart(KActionCollection *collection,
                                      const TQString& file, bool global)
{
  //d->m_actionList = collection->actions();

  // handle the merging
  if (global)
    setXMLFile(locate("config", "ui/ui_standards.rc"));
  TQString localXML = d->loadXMLFile(file);
  setXML(localXML, true);

  // reusable vars
  TQDomElement elem;

  // first, get all of the necessary info for our local xml
  XmlData local;
  local.m_xmlFile = d->xmlFile(file);
  local.m_type    = XmlData::Local;
  local.m_document.setContent(localXML);
  elem = local.m_document.documentElement().toElement();
  local.m_barList = d->findToolbars(elem);
  local.m_actionCollection = collection;
  d->m_xmlFiles.append(local);

  // then, the merged one (ui_standards + local xml)
  XmlData merge;
  merge.m_xmlFile  = TQString::null;
  merge.m_type     = XmlData::Merged;
  merge.m_document = domDocument();
  elem = merge.m_document.documentElement().toElement();
  merge.m_barList  = d->findToolbars(elem);
  merge.m_actionCollection = collection;
  d->m_xmlFiles.append(merge);

#ifndef NDEBUG
  //d->dump();
#endif

  // okay, that done, we concern ourselves with the GUI aspects
  setupLayout();
}

void KEditToolbarWidget::initKPart(KXMLGUIFactory* factory)
{
  // reusable vars
  TQDomElement elem;

  setFactory( factory );
  actionCollection()->setWidget( this );

  // add all of the client data
  TQPtrList<KXMLGUIClient> clients(factory->clients());
  TQPtrListIterator<KXMLGUIClient> it( clients );
  for( ; it.current(); ++it)
  {
    KXMLGUIClient *client = it.current();

    if (client->xmlFile().isNull())
      continue;

    XmlData data;
    data.m_xmlFile = client->localXMLFile();
    if ( it.atFirst() )
      data.m_type = XmlData::Shell;
    else
      data.m_type = XmlData::Part;
    data.m_document.setContent( KXMLGUIFactory::readConfigFile( client->xmlFile(), client->instance() ) );
    elem = data.m_document.documentElement().toElement();
    data.m_barList = d->findToolbars(elem);
    data.m_actionCollection = client->actionCollection();
    d->m_xmlFiles.append(data);

    //d->m_actionList += client->actionCollection()->actions();
  }

#ifndef NDEBUG
  //d->dump();
#endif

  // okay, that done, we concern ourselves with the GUI aspects
  setupLayout();
}

bool KEditToolbarWidget::save()
{
  //kdDebug(240) << "KEditToolbarWidget::save" << endl;
  XmlDataList::Iterator it = d->m_xmlFiles.begin();
  for ( ; it != d->m_xmlFiles.end(); ++it)
  {
    // let's not save non-modified files
    if ( !((*it).m_isModified) )
      continue;

    // let's also skip (non-existent) merged files
    if ( (*it).m_type == XmlData::Merged )
      continue;

    dump_xml((*it).m_document);

    kdDebug(240) << "Saving " << (*it).m_xmlFile << endl;
    // if we got this far, we might as well just save it
    KXMLGUIFactory::saveConfigFile((*it).m_document, (*it).m_xmlFile);
  }

  if ( !factory() )
    return true;

  rebuildKXMLGUIClients();

  return true;
}

void KEditToolbarWidget::rebuildKXMLGUIClients()
{
  if ( !factory() )
    return;

  TQPtrList<KXMLGUIClient> clients(factory()->clients());
  //kdDebug(240) << "factory: " << clients.count() << " clients" << endl;

  // remove the elements starting from the last going to the first
  KXMLGUIClient *client = clients.last();
  while ( client )
  {
    //kdDebug(240) << "factory->removeClient " << client << endl;
    factory()->removeClient( client );
    client = clients.prev();
  }

  KXMLGUIClient *firstClient = clients.first();

  // now, rebuild the gui from the first to the last
  //kdDebug(240) << "rebuilding the gui" << endl;
  TQPtrListIterator<KXMLGUIClient> cit( clients );
  for( ; cit.current(); ++cit)
  {
    KXMLGUIClient* client = cit.current();
    //kdDebug(240) << "updating client " << client << " " << client->instance()->instanceName() << "  xmlFile=" << client->xmlFile() << endl;
    TQString file( client->xmlFile() ); // before setting ui_standards!
    if ( !file.isEmpty() )
    {
        // passing an empty stream forces the clients to reread the XML
        client->setXMLGUIBuildDocument( TQDomDocument() );

        // for the shell, merge in ui_standards.rc
        if ( client == firstClient ) // same assumption as in the ctor: first==shell
            client->setXMLFile(locate("config", "ui/ui_standards.rc"));

        // and this forces it to use the *new* XML file
        client->setXMLFile( file, client == firstClient /* merge if shell */ );
    }
  }

  // Now we can add the clients to the factory
  // We don't do it in the loop above because adding a part automatically
  // adds its plugins, so we must make sure the plugins were updated first.
  cit.toFirst();
  for( ; cit.current(); ++cit)
    factory()->addClient( cit.current() );
}

void KEditToolbarWidget::setupLayout()
{
  // the toolbar name combo
  d->m_comboLabel = new TQLabel(i18n("&Toolbar:"), this);
  m_toolbarCombo = new TQComboBox(this);
  m_toolbarCombo->setEnabled(false);
  d->m_comboLabel->setBuddy(m_toolbarCombo);
  d->m_comboSeparator = new KSeparator(this);
  connect(m_toolbarCombo, TQT_SIGNAL(activated(const TQString&)),
          this,           TQT_SLOT(slotToolbarSelected(const TQString&)));

//  TQPushButton *new_toolbar = new TQPushButton(i18n("&New"), this);
//  new_toolbar->setPixmap(BarIcon("filenew", KIcon::SizeSmall));
//  new_toolbar->setEnabled(false); // disabled until implemented
//  TQPushButton *del_toolbar = new TQPushButton(i18n("&Delete"), this);
//  del_toolbar->setPixmap(BarIcon("editdelete", KIcon::SizeSmall));
//  del_toolbar->setEnabled(false); // disabled until implemented

  // our list of inactive actions
  TQLabel *inactive_label = new TQLabel(i18n("A&vailable actions:"), this);
  m_inactiveList = new ToolbarListView(this);
  m_inactiveList->setDragEnabled(true);
  m_inactiveList->setAcceptDrops(true);
  m_inactiveList->setDropVisualizer(false);
  m_inactiveList->setAllColumnsShowFocus(true);
  m_inactiveList->setMinimumSize(180, 250);
  m_inactiveList->header()->hide();
  m_inactiveList->addColumn(""); // icon
  int column2 = m_inactiveList->addColumn(""); // text
  m_inactiveList->setSorting( column2 );
  inactive_label->setBuddy(m_inactiveList);
  connect(m_inactiveList, TQT_SIGNAL(selectionChanged(TQListViewItem *)),
          this,           TQT_SLOT(slotInactiveSelected(TQListViewItem *)));
  connect(m_inactiveList, TQT_SIGNAL( doubleClicked( TQListViewItem *, const TQPoint &, int  )),
          this,           TQT_SLOT(slotInsertButton()));

  // our list of active actions
  TQLabel *active_label = new TQLabel(i18n("Curr&ent actions:"), this);
  m_activeList = new ToolbarListView(this);
  m_activeList->setDragEnabled(true);
  m_activeList->setAcceptDrops(true);
  m_activeList->setDropVisualizer(true);
  m_activeList->setAllColumnsShowFocus(true);
  m_activeList->setMinimumWidth(m_inactiveList->minimumWidth());
  m_activeList->header()->hide();
  m_activeList->addColumn(""); // icon
  m_activeList->addColumn(""); // text
  m_activeList->setSorting(-1);
  active_label->setBuddy(m_activeList);

  connect(m_inactiveList, TQT_SIGNAL(dropped(KListView*,TQDropEvent*,TQListViewItem*)),
          this,              TQT_SLOT(slotDropped(KListView*,TQDropEvent*,TQListViewItem*)));
  connect(m_activeList, TQT_SIGNAL(dropped(KListView*,TQDropEvent*,TQListViewItem*)),
          this,            TQT_SLOT(slotDropped(KListView*,TQDropEvent*,TQListViewItem*)));
  connect(m_activeList, TQT_SIGNAL(selectionChanged(TQListViewItem *)),
          this,         TQT_SLOT(slotActiveSelected(TQListViewItem *)));
  connect(m_activeList, TQT_SIGNAL( doubleClicked( TQListViewItem *, const TQPoint &, int  )),
          this,           TQT_SLOT(slotRemoveButton()));

  // "change icon" button
  d->m_changeIcon = new KPushButton( i18n( "Change &Icon..." ), this );
  TQString kdialogExe = KStandardDirs::findExe(TQString::tqfromLatin1("kdialog"));
  d->m_hasKDialog = !kdialogExe.isEmpty();
  d->m_changeIcon->setEnabled( d->m_hasKDialog );

  connect( d->m_changeIcon, TQT_SIGNAL( clicked() ),
           this, TQT_SLOT( slotChangeIcon() ) );

  // The buttons in the middle
  TQIconSet iconSet;

  m_upAction     = new TQToolButton(this);
  iconSet = SmallIconSet( "up" );
  m_upAction->setIconSet( iconSet );
  m_upAction->setEnabled(false);
  m_upAction->setAutoRepeat(true);
  connect(m_upAction, TQT_SIGNAL(clicked()), TQT_SLOT(slotUpButton()));

  m_insertAction = new TQToolButton(this);
  iconSet = TQApplication::reverseLayout() ? SmallIconSet( "back" ) : SmallIconSet( "forward" );
  m_insertAction->setIconSet( iconSet );
  m_insertAction->setEnabled(false);
  connect(m_insertAction, TQT_SIGNAL(clicked()), TQT_SLOT(slotInsertButton()));

  m_removeAction = new TQToolButton(this);
  iconSet = TQApplication::reverseLayout() ? SmallIconSet( "forward" ) : SmallIconSet( "back" );
  m_removeAction->setIconSet( iconSet );
  m_removeAction->setEnabled(false);
  connect(m_removeAction, TQT_SIGNAL(clicked()), TQT_SLOT(slotRemoveButton()));

  m_downAction   = new TQToolButton(this);
  iconSet = SmallIconSet( "down" );
  m_downAction->setIconSet( iconSet );
  m_downAction->setEnabled(false);
  m_downAction->setAutoRepeat(true);
  connect(m_downAction, TQT_SIGNAL(clicked()), TQT_SLOT(slotDownButton()));

  d->m_helpArea = new TQLabel(this);
  d->m_helpArea->tqsetAlignment( TQt::WordBreak );

  // now start with our layouts
  TQVBoxLayout *top_layout = new TQVBoxLayout(this, 0, KDialog::spacingHint());

  TQVBoxLayout *name_layout = new TQVBoxLayout(KDialog::spacingHint());
  TQHBoxLayout *list_layout = new TQHBoxLayout(KDialog::spacingHint());

  TQVBoxLayout *inactive_layout = new TQVBoxLayout(KDialog::spacingHint());
  TQVBoxLayout *active_layout = new TQVBoxLayout(KDialog::spacingHint());
  TQHBoxLayout *changeIcon_layout = new TQHBoxLayout(KDialog::spacingHint());

  TQGridLayout *button_layout = new TQGridLayout(5, 3, 0);

  name_layout->addWidget(d->m_comboLabel);
  name_layout->addWidget(m_toolbarCombo);
//  name_layout->addWidget(new_toolbar);
//  name_layout->addWidget(del_toolbar);

  button_layout->setRowStretch( 0, 10 );
  button_layout->addWidget(m_upAction, 1, 1);
  button_layout->addWidget(m_removeAction, 2, 0);
  button_layout->addWidget(m_insertAction, 2, 2);
  button_layout->addWidget(m_downAction, 3, 1);
  button_layout->setRowStretch( 4, 10 );

  inactive_layout->addWidget(inactive_label);
  inactive_layout->addWidget(m_inactiveList, 1);

  active_layout->addWidget(active_label);
  active_layout->addWidget(m_activeList, 1);
  active_layout->addLayout(changeIcon_layout);

  changeIcon_layout->addStretch( 1 );
  changeIcon_layout->addWidget( d->m_changeIcon );
  changeIcon_layout->addStretch( 1 );

  list_layout->addLayout(inactive_layout);
  list_layout->addLayout(TQT_TQLAYOUT(button_layout));
  list_layout->addLayout(active_layout);

  top_layout->addLayout(name_layout);
  top_layout->addWidget(d->m_comboSeparator);
  top_layout->addLayout(list_layout,10);
  top_layout->addWidget(d->m_helpArea);
  top_layout->addWidget(new KSeparator(this));
}

void KEditToolbarWidget::loadToolbarCombo(const TQString& defaultToolbar)
{
  static const TQString &attrName = KGlobal::staticQString( "name" );
  // just in case, we clear our combo
  m_toolbarCombo->clear();

  int defaultToolbarId = -1;
  int count = 0;
  // load in all of the toolbar names into this combo box
  XmlDataList::Iterator xit = d->m_xmlFiles.begin();
  for ( ; xit != d->m_xmlFiles.end(); ++xit)
  {
    // skip the local one in favor of the merged
    if ( (*xit).m_type == XmlData::Local )
      continue;

    // each xml file may have any number of toolbars
    ToolbarList::Iterator it = (*xit).m_barList.begin();
    for ( ; it != (*xit).m_barList.end(); ++it)
    {
      TQString name = d->toolbarName( *xit, *it );
      m_toolbarCombo->setEnabled( true );
      m_toolbarCombo->insertItem( name );
      if (defaultToolbarId == -1 && (name == defaultToolbar || defaultToolbar == (*it).attribute( attrName )))
          defaultToolbarId = count;
      count++;
    }
  }
  bool showCombo = (count > 1);
  d->m_comboLabel->setShown(showCombo);
  d->m_comboSeparator->setShown(showCombo);
  m_toolbarCombo->setShown(showCombo);
  if (defaultToolbarId == -1)
      defaultToolbarId = 0;
  // we want to the specified item selected and its actions loaded
  m_toolbarCombo->setCurrentItem(defaultToolbarId);
  slotToolbarSelected(m_toolbarCombo->currentText());
}

void KEditToolbarWidget::loadActionList(TQDomElement& elem)
{
  static const TQString &tagSeparator = KGlobal::staticQString( "Separator" );
  static const TQString &tagMerge     = KGlobal::staticQString( "Merge" );
  static const TQString &tagActionList= KGlobal::staticQString( "ActionList" );
  static const TQString &attrName     = KGlobal::staticQString( "name" );
  static const TQString &attrLineSeparator = KGlobal::staticQString( "lineSeparator" );

  int     sep_num = 0;
  TQString sep_name("separator_%1");

  // clear our lists
  m_inactiveList->clear();
  m_activeList->clear();
  m_insertAction->setEnabled(false);
  m_removeAction->setEnabled(false);
  m_upAction->setEnabled(false);
  m_downAction->setEnabled(false);

  // We'll use this action collection
  KActionCollection* actionCollection = d->m_currentXmlData->m_actionCollection;

  // store the names of our active actions
  TQMap<TQString, bool> active_list;

  // see if our current action is in this toolbar
  KIconLoader *loader = KGlobal::instance()->iconLoader();
  TQDomNode n = elem.lastChild();
  for( ; !n.isNull(); n = n.previousSibling() )
  {
    TQDomElement it = n.toElement();
    if (it.isNull()) continue;
    if (it.tagName() == tagSeparator)
    {
      ToolbarItem *act = new ToolbarItem(m_activeList, tagSeparator, sep_name.arg(sep_num++), TQString::null);
      bool isLineSep = ( it.attribute(attrLineSeparator, "true").lower() == TQString::tqfromLatin1("true") );
      if(isLineSep)
        act->setText(1, LINESEPARATORSTRING);
      else
        act->setText(1, SEPARATORSTRING);
      it.setAttribute( attrName, act->internalName() );
      continue;
    }

    if (it.tagName() == tagMerge)
    {
      // Merge can be named or not - use the name if there is one
      TQString name = it.attribute( attrName );
      ToolbarItem *act = new ToolbarItem(m_activeList, tagMerge, name, i18n("This element will be replaced with all the elements of an embedded component."));
      if ( name.isEmpty() )
          act->setText(1, i18n("<Merge>"));
      else
          act->setText(1, i18n("<Merge %1>").arg(name));
      continue;
    }

    if (it.tagName() == tagActionList)
    {
      ToolbarItem *act = new ToolbarItem(m_activeList, tagActionList, it.attribute(attrName), i18n("This is a dynamic list of actions. You can move it, but if you remove it you won't be able to re-add it.") );
      act->setText(1, i18n("ActionList: %1").arg(it.attribute(attrName)));
      continue;
    }

    // iterate through this client's actions
    // This used to iterate through _all_ actions, but we don't support
    // putting any action into any client...
    for (unsigned int i = 0;  i < actionCollection->count(); i++)
    {
      KAction *action = actionCollection->action( i );

      // do we have a match?
      if (it.attribute( attrName ) == action->name())
      {
        // we have a match!
        ToolbarItem *act = new ToolbarItem(m_activeList, it.tagName(), action->name(), action->toolTip());
        act->setText(1, action->plainText());
        if (action->hasIcon())
          if (!action->icon().isEmpty())
            act->setPixmap(0, loader->loadIcon(action->icon(), KIcon::Toolbar, 16, KIcon::DefaultState, 0, true) );
          else // Has iconset
            act->setPixmap(0, action->iconSet(KIcon::Toolbar).pixmap());

        active_list.insert(action->name(), true);
        break;
      }
    }
  }

  // go through the rest of the collection
  for (int i = actionCollection->count() - 1; i > -1; --i)
  {
    KAction *action = actionCollection->action( i );

    // skip our active ones
    if (active_list.contains(action->name()))
      continue;

    ToolbarItem *act = new ToolbarItem(m_inactiveList, tagActionList, action->name(), action->toolTip());
    act->setText(1, action->plainText());
    if (action->hasIcon())
      if (!action->icon().isEmpty())
        act->setPixmap(0, loader->loadIcon(action->icon(), KIcon::Toolbar, 16, KIcon::DefaultState, 0, true) );
      else // Has iconset
        act->setPixmap(0, action->iconSet(KIcon::Toolbar).pixmap());
  }

  // finally, add default separators to the inactive list
  ToolbarItem *act = new ToolbarItem(m_inactiveList, tagSeparator, sep_name.arg(sep_num++), TQString::null);
  act->setText(1, LINESEPARATORSTRING);
  act = new ToolbarItem(m_inactiveList, tagSeparator, sep_name.arg(sep_num++), TQString::null);
  act->setText(1, SEPARATORSTRING);
}

KActionCollection *KEditToolbarWidget::actionCollection() const
{
  return d->m_collection;
}

void KEditToolbarWidget::slotToolbarSelected(const TQString& _text)
{
  // iterate through everything
  XmlDataList::Iterator xit = d->m_xmlFiles.begin();
  for ( ; xit != d->m_xmlFiles.end(); ++xit)
  {
    // each xml file may have any number of toolbars
    ToolbarList::Iterator it = (*xit).m_barList.begin();
    for ( ; it != (*xit).m_barList.end(); ++it)
    {
      TQString name = d->toolbarName( *xit, *it );
      // is this our toolbar?
      if ( name == _text )
      {
        // save our current settings
        d->m_currentXmlData     = & (*xit);
        d->m_currentToolbarElem = (*it);

        // load in our values
        loadActionList(d->m_currentToolbarElem);

        if ((*xit).m_type == XmlData::Part || (*xit).m_type == XmlData::Shell)
          setDOMDocument( (*xit).m_document );
        return;
      }
    }
  }
}

void KEditToolbarWidget::slotInactiveSelected(TQListViewItem *item)
{
  ToolbarItem* toolitem = static_cast<ToolbarItem *>(item);
  if (item)
  {
    m_insertAction->setEnabled(true);
    TQString statusText = toolitem->statusText();
    d->m_helpArea->setText( statusText );
  }
  else
  {
    m_insertAction->setEnabled(false);
    d->m_helpArea->setText( TQString::null );
  }
}

void KEditToolbarWidget::slotActiveSelected(TQListViewItem *item)
{
  ToolbarItem* toolitem = static_cast<ToolbarItem *>(item);
  m_removeAction->setEnabled( item );

  static const TQString &tagAction = KGlobal::staticQString( "Action" );
  d->m_changeIcon->setEnabled( item &&
                               d->m_hasKDialog &&
                               toolitem->internalTag() == tagAction );

  if (item)
  {
    if (item->itemAbove())
      m_upAction->setEnabled(true);
    else
      m_upAction->setEnabled(false);

    if (item->itemBelow())
      m_downAction->setEnabled(true);
    else
      m_downAction->setEnabled(false);
    TQString statusText = toolitem->statusText();
    d->m_helpArea->setText( statusText );
  }
  else
  {
    m_upAction->setEnabled(false);
    m_downAction->setEnabled(false);
    d->m_helpArea->setText( TQString::null );
  }
}

void KEditToolbarWidget::slotDropped(KListView *list, TQDropEvent *e, TQListViewItem *after)
{
  ToolbarItem *item = new ToolbarItem(m_inactiveList); // needs parent, use inactiveList temporarily
  if(!ToolbarItemDrag::decode(e, *item)) {
    delete item;
    return;
  }

  if (list == m_activeList) {
    if (e->source() == m_activeList) {
      // has been dragged within the active list (moved).
      moveActive(item, after);
    }
    else
      insertActive(item, after, true);
  } else if (list == m_inactiveList) {
    // has been dragged to the inactive list -> remove from the active list.
    removeActive(item);
  }

  delete item; item = 0; // not neded anymore

  // we're modified, so let this change
  emit enableOk(true);

  slotToolbarSelected( m_toolbarCombo->currentText() );
}

void KEditToolbarWidget::slotInsertButton()
{
  ToolbarItem *item = (ToolbarItem*)m_inactiveList->currentItem();
  insertActive(item, m_activeList->currentItem(), false);

  // we're modified, so let this change
  emit enableOk(true);

  // TODO: #### this causes #97572.
  // It would be better to just "delete item; loadActions( ... , ActiveListOnly );" or something.
  slotToolbarSelected( m_toolbarCombo->currentText() );
}

void KEditToolbarWidget::slotRemoveButton()
{
  removeActive( dynamic_cast<ToolbarItem*>(m_activeList->currentItem()) );

  // we're modified, so let this change
  emit enableOk(true);

  slotToolbarSelected( m_toolbarCombo->currentText() );
}

void KEditToolbarWidget::insertActive(ToolbarItem *item, TQListViewItem *before, bool prepend)
{
  if (!item)
    return;

  static const TQString &tagAction    = KGlobal::staticQString( "Action" );
  static const TQString &tagSeparator = KGlobal::staticQString( "Separator" );
  static const TQString &attrName     = KGlobal::staticQString( "name" );
  static const TQString &attrLineSeparator = KGlobal::staticQString( "lineSeparator" );
  static const TQString &attrNoMerge  = KGlobal::staticQString( "noMerge" );

  TQDomElement new_item;
  // let's handle the separator specially
  if (item->text(1) == LINESEPARATORSTRING) {
    new_item = domDocument().createElement(tagSeparator);
  } else if (item->text(1) == SEPARATORSTRING) {
    new_item = domDocument().createElement(tagSeparator);
    new_item.setAttribute(attrLineSeparator, "false");
  } else
    new_item = domDocument().createElement(tagAction);
  new_item.setAttribute(attrName, item->internalName());

  if (before)
  {
    // we have the item in the active list which is before the new
    // item.. so let's try our best to add our new item right after it
    ToolbarItem *act_item = (ToolbarItem*)before;
    TQDomElement elem = d->findElementForToolbarItem( act_item );
    Q_ASSERT( !elem.isNull() );
    d->m_currentToolbarElem.insertAfter(new_item, elem);
  }
  else
  {
    // simply put it at the beginning or the end of the list.
    if (prepend)
      d->m_currentToolbarElem.insertBefore(new_item, d->m_currentToolbarElem.firstChild());
    else
      d->m_currentToolbarElem.appendChild(new_item);
  }

  // and set this container as a noMerge
  d->m_currentToolbarElem.setAttribute( attrNoMerge, "1");

  // update the local doc
  updateLocal(d->m_currentToolbarElem);
}

void KEditToolbarWidget::removeActive(ToolbarItem *item)
{
  if (!item)
    return;

  static const TQString &attrNoMerge = KGlobal::staticQString( "noMerge" );

  // we're modified, so let this change
  emit enableOk(true);

  // now iterate through to find the child to nuke
  TQDomElement elem = d->findElementForToolbarItem( item );
  if ( !elem.isNull() )
  {
    // nuke myself!
    d->m_currentToolbarElem.removeChild(elem);

    // and set this container as a noMerge
    d->m_currentToolbarElem.setAttribute( attrNoMerge, "1");

    // update the local doc
    updateLocal(d->m_currentToolbarElem);
  }
}

void KEditToolbarWidget::slotUpButton()
{
  ToolbarItem *item = (ToolbarItem*)m_activeList->currentItem();

  // make sure we're not the top item already
  if (!item->itemAbove())
    return;

  // we're modified, so let this change
  emit enableOk(true);

  moveActive( item, item->itemAbove()->itemAbove() );
  delete item;
}

void KEditToolbarWidget::moveActive( ToolbarItem* item, TQListViewItem* before )
{
  TQDomElement e = d->findElementForToolbarItem( item );

  if ( e.isNull() )
    return;

  // cool, i found me.  now clone myself
  ToolbarItem *clone = new ToolbarItem(m_activeList,
                                       before,
                                       item->internalTag(),
                                       item->internalName(),
                                       item->statusText());

  clone->setText(1, item->text(1));

  // only set new pixmap if exists
  if( item->pixmap(0) )
    clone->setPixmap(0, *item->pixmap(0));

  // select my clone
  m_activeList->setSelected(clone, true);

  // make clone visible
  m_activeList->ensureItemVisible(clone);

  // and do the real move in the DOM
  if ( !before )
    d->m_currentToolbarElem.insertBefore(e, d->m_currentToolbarElem.firstChild() );
  else
    d->m_currentToolbarElem.insertAfter(e, d->findElementForToolbarItem( (ToolbarItem*)before ));

  // and set this container as a noMerge
  static const TQString &attrNoMerge = KGlobal::staticQString( "noMerge" );
  d->m_currentToolbarElem.setAttribute( attrNoMerge, "1");

  // update the local doc
  updateLocal(d->m_currentToolbarElem);
}

void KEditToolbarWidget::slotDownButton()
{
  ToolbarItem *item = (ToolbarItem*)m_activeList->currentItem();

  // make sure we're not the bottom item already
  if (!item->itemBelow())
    return;

  // we're modified, so let this change
  emit enableOk(true);

  moveActive( item, item->itemBelow() );
  delete item;
}

void KEditToolbarWidget::updateLocal(TQDomElement& elem)
{
  static const TQString &attrName = KGlobal::staticQString( "name" );

  XmlDataList::Iterator xit = d->m_xmlFiles.begin();
  for ( ; xit != d->m_xmlFiles.end(); ++xit)
  {
    if ( (*xit).m_type == XmlData::Merged )
      continue;

    if ( (*xit).m_type == XmlData::Shell ||
         (*xit).m_type == XmlData::Part )
    {
      if ( d->m_currentXmlData->m_xmlFile == (*xit).m_xmlFile )
      {
        (*xit).m_isModified = true;
        return;
      }

      continue;
    }

    (*xit).m_isModified = true;

    ToolbarList::Iterator it = (*xit).m_barList.begin();
    for ( ; it != (*xit).m_barList.end(); ++it)
    {
      TQString name( (*it).attribute( attrName ) );
      TQString tag( (*it).tagName() );
      if ( (tag != elem.tagName()) || (name != elem.attribute(attrName)) )
        continue;

      TQDomElement toolbar = (*xit).m_document.documentElement().toElement();
      toolbar.replaceChild(elem, (*it));
      return;
    }

    // just append it
    TQDomElement toolbar = (*xit).m_document.documentElement().toElement();
    toolbar.appendChild(elem);
  }
}

void KEditToolbarWidget::slotChangeIcon()
{
  // We can't use KIconChooser here, since it's in libkio
  // ##### KDE4: reconsider this, e.g. move KEditToolbar to libkio
  
  //if the process is already running (e.g. when somebody clicked the change button twice (see #127149)) - do nothing... 
  //otherwise m_kdialogProcess will be overwritten and set to zero in slotProcessExited()...crash!
  if ( d->m_kdialogProcess && d->m_kdialogProcess->isRunning() )
        return;
  
  d->m_kdialogProcess = new KProcIO;
  TQString kdialogExe = KStandardDirs::findExe(TQString::tqfromLatin1("kdialog"));
  (*d->m_kdialogProcess) << kdialogExe;
  (*d->m_kdialogProcess) << "--embed";
  (*d->m_kdialogProcess) << TQString::number( (ulong)tqtopLevelWidget()->winId() );
  (*d->m_kdialogProcess) << "--geticon";
  (*d->m_kdialogProcess) << "Toolbar";
  (*d->m_kdialogProcess) << "Actions";
  if ( !d->m_kdialogProcess->start( KProcess::NotifyOnExit ) ) {
    kdError(240) << "Can't run " << kdialogExe << endl;
    delete d->m_kdialogProcess;
    d->m_kdialogProcess = 0;
    return;
  }

  m_activeList->setEnabled( false ); // don't change the current item
  m_toolbarCombo->setEnabled( false ); // don't change the current toolbar

  connect( d->m_kdialogProcess, TQT_SIGNAL( processExited( KProcess* ) ),
           this, TQT_SLOT( slotProcessExited( KProcess* ) ) );
}

void KEditToolbarWidget::slotProcessExited( KProcess* )
{
  m_activeList->setEnabled( true );
  m_toolbarCombo->setEnabled( true );

  TQString icon;

  if (!d->m_kdialogProcess) {
         kdError(240) << "Something is wrong here! m_kdialogProcess is zero!" << endl;
         return;
  }

  if ( !d->m_kdialogProcess->normalExit() ||
       d->m_kdialogProcess->exitStatus() ||
       d->m_kdialogProcess->readln(icon, true) <= 0 ) {
    delete d->m_kdialogProcess;
    d->m_kdialogProcess = 0;
    return;
  }

  ToolbarItem *item = (ToolbarItem*)m_activeList->currentItem();
  if(item){
    item->setPixmap(0, BarIcon(icon, 16));

    Q_ASSERT( d->m_currentXmlData->m_type != XmlData::Merged );

    d->m_currentXmlData->m_isModified = true;

    // Get hold of ActionProperties tag
    TQDomElement elem = KXMLGUIFactory::actionPropertiesElement( d->m_currentXmlData->m_document );
    // Find or create an element for this action
    TQDomElement act_elem = KXMLGUIFactory::findActionByName( elem, item->internalName(), true /*create*/ );
    Q_ASSERT( !act_elem.isNull() );
    act_elem.setAttribute( "icon", icon );

    // we're modified, so let this change
    emit enableOk(true);
  }

  delete d->m_kdialogProcess;
  d->m_kdialogProcess = 0;
}

void KEditToolbar::virtual_hook( int id, void* data )
{ KDialogBase::virtual_hook( id, data ); }

void KEditToolbarWidget::virtual_hook( int id, void* data )
{ KXMLGUIClient::virtual_hook( id, data ); }

#include "kedittoolbar.moc"