summaryrefslogtreecommitdiffstats
path: root/lib/kofficecore/KoMainWindow.cpp
blob: a16755140ade0215f0554fe7161673606fedd4fb (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
/* This file is part of the KDE project
   Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
   Copyright (C) 2000-2006 David Faure <faure@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 as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   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 "KoMainWindow.h"
#include "KoDocument.h"
#include "KoView.h"
#include "KoFilterManager.h"
#include "KoDocumentInfo.h"
#include "KoDocumentInfoDlg.h"
#include "KoQueryTrader.h"
#include "KoMainWindowIface.h"
#include "KoFrame.h"
#include "KoFileDialog.h"
#include "Koversiondialog.h"
#include "kkbdaccessextensions.h"
#include "KoSpeaker.h"

#include <tdeaboutdata.h>
#include <kprinter.h>
#include <tdeversion.h>
#include <kstdaction.h>
#include <tdeapplication.h>
#include <tdemessagebox.h>
#include <kstandarddirs.h>
#include <tdeio/netaccess.h>
#include <kkeydialog.h>
#include <kedittoolbar.h>
#include <kprogress.h>
#include <kpushbutton.h>
#include <kdebug.h>
#include <tdetempfile.h>
#include <tderecentdocument.h>
#include <tdeparts/partmanager.h>
#include <tdeparts/plugin.h>
#include <tdeparts/event.h>
#include <tdelocale.h>
#include <kstatusbar.h>
#include <tdeglobalsettings.h>
#include <ksharedptr.h>

#include <tqobjectlist.h>

#include <unistd.h>
#include <stdlib.h>

class KoPartManager : public KParts::PartManager
{
public:
  KoPartManager( TQWidget * parent, const char * name = 0L )
    : KParts::PartManager( parent, name )
  {
      setSelectionPolicy( KParts::PartManager::TriState );
      setAllowNestedParts( true );
      setIgnoreScrollBars( true );
      // Allow right-click on embedded objects (without activating them)
      // But beware: this means right-click on parent, from embedded object,
      // doesn't make the parent active first...
      setActivationButtonMask( TQt::LeftButton | TQt::MidButton );
  }
  virtual bool eventFilter( TQObject *obj, TQEvent *ev )
  {
    if ( !obj->isWidgetType() || ::tqt_cast<KoFrame *>( obj ) )
      return false;
    return KParts::PartManager::eventFilter( obj, ev );
  }
};

class KoMainWindowPrivate
{
public:
  KoMainWindowPrivate()
  {
    m_rootDoc = 0L;
    m_docToOpen = 0L;
    m_manager = 0L;
    bMainWindowGUIBuilt = false;
    m_forQuit=false;
    m_splitted=false;
    m_activePart = 0L;
    m_activeView = 0L;
    m_splitter=0L;
    m_orientation=0L;
    m_removeView=0L;
    m_toolbarList.setAutoDelete( true );
    m_firstTime=true;
    m_progress=0L;
    m_paDocInfo = 0;
    m_paSave = 0;
    m_paSaveAs = 0;
    m_paPrint = 0;
    m_paPrintPreview = 0;
    statusBarLabel = 0L;
    m_dcopObject = 0;
    m_sendfile = 0;
    m_paCloseFile = 0L;
    m_reloadfile = 0L;
    m_versionsfile = 0L;
    m_importFile = 0;
    m_exportFile = 0;
    m_isImporting = false;
    m_isExporting = false;
    m_windowSizeDirty = false;
    m_lastExportSpecialOutputFlag = 0;

    // TTS accessibility enhancement (only if KDE 3.4 or later and KTTSD daemon is installed.)
    if (KoSpeaker::isKttsdInstalled()) {
        if (kospeaker)
            m_koSpeaker = kospeaker;
        else
            m_koSpeaker = new KoSpeaker();
    } else
        m_koSpeaker = 0;
  }
  ~KoMainWindowPrivate()
  {
    delete m_dcopObject;
  }

  KoDocument *m_rootDoc;
  KoDocument *m_docToOpen;
  TQPtrList<KoView> m_rootViews;
  KParts::PartManager *m_manager;

  KParts::Part *m_activePart;
  KoView *m_activeView;

  TQLabel * statusBarLabel;
  KProgress *m_progress;

  TQPtrList<TDEAction> m_splitViewActionList;
  // This additional list is needed, because we don't plug
  // the first list, when an embedded view gets activated (Werner)
  TQPtrList<TDEAction> m_veryHackyActionList;
  TQSplitter *m_splitter;
  TDESelectAction *m_orientation;
  TDEAction *m_removeView;
  KoMainWindowIface *m_dcopObject;

  TQPtrList <TDEAction> m_toolbarList;

  bool bMainWindowGUIBuilt;
  bool m_splitted;
  bool m_forQuit;
  bool m_firstTime;
  bool m_windowSizeDirty;

  TDEAction *m_paDocInfo;
  TDEAction *m_paSave;
  TDEAction *m_paSaveAs;
  TDEAction *m_paPrint;
  TDEAction *m_paPrintPreview;
  TDEAction *m_sendfile;
  TDEAction *m_paCloseFile;
  TDEAction *m_reloadfile;
  TDEAction *m_versionsfile;
  TDEAction *m_importFile;
  TDEAction *m_exportFile;

  bool m_isImporting;
  bool m_isExporting;

  KURL m_lastExportURL;
  TQCString m_lastExportFormat;
  int m_lastExportSpecialOutputFlag;

  TDESharedPtr<KoSpeaker> m_koSpeaker;
};

KoMainWindow::KoMainWindow( TDEInstance *instance, const char* name )
    : KParts::MainWindow( 0, 0L, name )
{
    setStandardToolBarMenuEnabled(true); // should there be a check for >= 3.1 ?
    Q_ASSERT(instance);
    d = new KoMainWindowPrivate;

    d->m_manager = new KoPartManager( this );

    connect( d->m_manager, TQT_SIGNAL( activePartChanged( KParts::Part * ) ),
             TQT_TQOBJECT(this), TQT_SLOT( slotActivePartChanged( KParts::Part * ) ) );

    if ( instance )
        setInstance( instance, false ); // don't load plugins! we don't want
    // the part's plugins with this shell, even though we are using the
    // part's instance! (Simon)

    TQString doc;
    TQStringList allFiles = TDEGlobal::dirs()->findAllResources( "data", "koffice/koffice_shell.rc" );
    setXMLFile( findMostRecentXMLFile( allFiles, doc ) );
    setLocalXMLFile( locateLocal( "data", "koffice/koffice_shell.rc" ) );

    KStdAction::openNew( TQT_TQOBJECT(this), TQT_SLOT( slotFileNew() ), actionCollection(), "file_new" );
    KStdAction::open( TQT_TQOBJECT(this), TQT_SLOT( slotFileOpen() ), actionCollection(), "file_open" );
    m_recent = KStdAction::openRecent( TQT_TQOBJECT(this), TQT_SLOT(slotFileOpenRecent(const KURL&)), actionCollection() );
    d->m_paSave = KStdAction::save( TQT_TQOBJECT(this), TQT_SLOT( slotFileSave() ), actionCollection(), "file_save" );
    d->m_paSaveAs = KStdAction::saveAs( TQT_TQOBJECT(this), TQT_SLOT( slotFileSaveAs() ), actionCollection(), "file_save_as" );
    d->m_paPrint = KStdAction::print( TQT_TQOBJECT(this), TQT_SLOT( slotFilePrint() ), actionCollection(), "file_print" );
    d->m_paPrintPreview = KStdAction::printPreview( TQT_TQOBJECT(this), TQT_SLOT( slotFilePrintPreview() ), actionCollection(), "file_print_preview" );
    d->m_sendfile = KStdAction::mail( TQT_TQOBJECT(this), TQT_SLOT( slotEmailFile() ), actionCollection(), "file_send_file");

    d->m_paCloseFile = KStdAction::close( TQT_TQOBJECT(this), TQT_SLOT( slotFileClose() ), actionCollection(), "file_close" );
    KStdAction::quit( TQT_TQOBJECT(this), TQT_SLOT( slotFileQuit() ), actionCollection(), "file_quit" );

    d->m_reloadfile = new TDEAction( i18n( "Reload"), 0,
                    TQT_TQOBJECT(this), TQT_SLOT( slotReloadFile() ),
                    actionCollection(), "file_reload_file");

    d->m_versionsfile = new TDEAction( i18n( "Versions..."), 0,
                    TQT_TQOBJECT(this), TQT_SLOT( slotVersionsFile() ),
                    actionCollection(), "file_versions_file");

    d->m_importFile = new TDEAction( i18n( "I&mport..." ), 0, // clashing accel key :(
                    TQT_TQOBJECT(this), TQT_SLOT( slotImportFile() ),
                    actionCollection(), "file_import_file");
    d->m_exportFile = new TDEAction( i18n( "E&xport..." ), 0,
                    TQT_TQOBJECT(this), TQT_SLOT( slotExportFile() ),
                    actionCollection(), "file_export_file");

    /* The following entry opens the document information dialog.  Since the action is named so it
        intends to show data this entry should not have a trailing ellipses (...).  */
    d->m_paDocInfo = new TDEAction( i18n( "&Document Information" ), "documentinfo", 0,
                        TQT_TQOBJECT(this), TQT_SLOT( slotDocumentInfo() ),
                        actionCollection(), "file_documentinfo" );

    KStdAction::keyBindings( TQT_TQOBJECT(this), TQT_SLOT( slotConfigureKeys() ), actionCollection() );
    KStdAction::configureToolbars( TQT_TQOBJECT(this), TQT_SLOT( slotConfigureToolbars() ), actionCollection() );

    d->m_paDocInfo->setEnabled( false );
    d->m_paSaveAs->setEnabled( false );
    d->m_reloadfile->setEnabled( false );
    d->m_versionsfile->setEnabled( false );
    d->m_importFile->setEnabled( true );  // always enabled like File --> Open
    d->m_exportFile->setEnabled( false );
    d->m_paSave->setEnabled( false );
    d->m_paPrint->setEnabled( false );
    d->m_paPrintPreview->setEnabled( false );
    d->m_sendfile->setEnabled( false);
    d->m_paCloseFile->setEnabled( false);

    d->m_splitter=new TQSplitter(TQt::Vertical, this, "mw-splitter");
    setCentralWidget( d->m_splitter );
    // Keyboard accessibility enhancements.
    new KKbdAccessExtensions(this, "mw-panelSizer");
    // set up the action "list" for "Close all Views" (hacky :) (Werner)
    d->m_veryHackyActionList.append(
        new TDEAction(i18n("&Close All Views"), "window-close",
                    "ctrl+shift+w", TQT_TQOBJECT(this), TQT_SLOT(slotCloseAllViews()),
                    actionCollection(), "view_closeallviews") );

    // set up the action list for the splitter stuff
    d->m_splitViewActionList.append(new TDEAction(i18n("&Split View"), "view_split", 0,
        TQT_TQOBJECT(this), TQT_SLOT(slotSplitView()),
        actionCollection(), "view_split"));
    d->m_removeView=new TDEAction(i18n("&Remove View"), "view_remove", 0,
        TQT_TQOBJECT(this), TQT_SLOT(slotRemoveView()),
        actionCollection(), "view_rm_splitter");
    d->m_splitViewActionList.append(d->m_removeView);
    d->m_removeView->setEnabled(false);
    d->m_orientation=new TDESelectAction(i18n("Splitter &Orientation"), "view_orientation", 0,
        TQT_TQOBJECT(this), TQT_SLOT(slotSetOrientation()),
        actionCollection(), "view_splitter_orientation");
    TQStringList items;
    items << i18n("&Vertical")
          << i18n("&Horizontal");
    d->m_orientation->setItems(items);
    d->m_orientation->setCurrentItem(static_cast<int>(d->m_splitter->orientation()));
    d->m_splitViewActionList.append(d->m_orientation);
    d->m_splitViewActionList.append(new TDEActionSeparator(TQT_TQOBJECT(this)));

    // Load list of recent files
    TDEConfig * config = instance ? instance->config() : TDEGlobal::config();
    m_recent->loadEntries( config );

    createShellGUI();
    d->bMainWindowGUIBuilt = true;

    if ( !initialGeometrySet() )
    {
        // Default size
        const int deskWidth = TDEGlobalSettings::desktopGeometry(this).width();
        if (deskWidth > 1100) // very big desktop ?
            resize( 1000, 800 );
        if (deskWidth > 850) // big desktop ?
            resize( 800, 600 );
        else // small (800x600, 640x480) desktop
            resize( 600, 400 );
    }

    // Saved size
    config->setGroup( "MainWindow" );
    //kdDebug(30003) << "KoMainWindow::restoreWindowSize" << endl;
    restoreWindowSize( config );
}

KoMainWindow::~KoMainWindow()
{
    if (!d) {
        return;
    }

    // The doc and view might still exist (this is the case when closing the window)
    if (d->m_rootDoc) {
        d->m_rootDoc->removeShell(this);
    }

    if (d->m_docToOpen) {
      d->m_docToOpen->removeShell(this);
      delete d->m_docToOpen;
      d->m_docToOpen=0L;
    }

    // safety first ;)
    d->m_manager->setActivePart(0);

    if(d->m_rootViews.findRef(d->m_activeView)==-1) {
        delete d->m_activeView;
        d->m_activeView=0L;
    }
    d->m_rootViews.setAutoDelete( true );
    d->m_rootViews.clear();

    // We have to check if this was a root document.
    // -> We aren't allowed to delete the (embedded) document!
    // This has to be checked from queryClose, too :)
    if ( d->m_rootDoc && d->m_rootDoc->viewCount() == 0 &&
         !d->m_rootDoc->isEmbedded())
    {
        //kdDebug(30003) << "Destructor. No more views, deleting old doc " << d->m_rootDoc << endl;
        delete d->m_rootDoc;
        d->m_rootDoc=0L;
    }

    delete d->m_manager;
    d->m_manager=0L;
    delete d;
    d=0L;
}

void KoMainWindow::setRootDocument( KoDocument *doc )
{
  if ( d->m_rootDoc == doc )
    return;

  if (d->m_docToOpen && d->m_docToOpen != doc) {
    d->m_docToOpen->removeShell(this);
    delete d->m_docToOpen;
    d->m_docToOpen = 0;
  } else {
    d->m_docToOpen = 0;
  }

  //kdDebug(30003) <<  "KoMainWindow::setRootDocument this = " << this << " doc = " << doc << endl;
  TQPtrList<KoView> oldRootViews = d->m_rootViews;
  d->m_rootViews.clear();
  KoDocument *oldRootDoc = d->m_rootDoc;

  if ( oldRootDoc )
    oldRootDoc->removeShell( this );

  d->m_rootDoc = doc;

  if ( doc )
  {
    doc->setSelectable( false );
    //d->m_manager->addPart( doc, false ); // done by KoView::setPartManager
    d->m_rootViews.append( doc->createView( d->m_splitter, "view" /*not unique, but better than unnamed*/ ) );
    d->m_rootViews.current()->setPartManager( d->m_manager );

    d->m_rootViews.current()->show();
    // The addShell has been done already if using openURL
    if ( !d->m_rootDoc->shells().contains( this ) )
        d->m_rootDoc->addShell( this );
    d->m_removeView->setEnabled(false);
    d->m_orientation->setEnabled(false);
  }

  bool enable = d->m_rootDoc != 0 ? true : false;
  d->m_paDocInfo->setEnabled( enable );
  d->m_paSave->setEnabled( enable );
  d->m_paSaveAs->setEnabled( enable );
  d->m_importFile->setEnabled( enable );
  d->m_exportFile->setEnabled( enable );
  d->m_paPrint->setEnabled( enable );
  d->m_paPrintPreview->setEnabled( enable );
  d->m_sendfile->setEnabled( enable);
  d->m_paCloseFile->setEnabled( enable);
  updateCaption();

  d->m_manager->setActivePart( d->m_rootDoc, d->m_rootViews.current() );

  oldRootViews.setAutoDelete( true );
  oldRootViews.clear();

  if ( oldRootDoc && oldRootDoc->viewCount() == 0 )
  {
    //kdDebug(30003) << "No more views, deleting old doc " << oldRootDoc << endl;
    delete oldRootDoc;
  }
}

void KoMainWindow::updateReloadFileAction(KoDocument *doc)
{
    d->m_reloadfile->setEnabled( doc && !doc->url().isEmpty() );
}

void KoMainWindow::updateVersionsFileAction(KoDocument *doc)
{
    //TODO activate it just when we save it in oasis file format
    d->m_versionsfile->setEnabled( doc && !doc->url().isEmpty()&&doc->isModified());
}


void KoMainWindow::setRootDocumentDirect( KoDocument *doc, const TQPtrList<KoView> & views )
{
  d->m_rootDoc = doc;
  d->m_rootViews = views;
  bool enable = d->m_rootDoc != 0 ? true : false;
  d->m_paDocInfo->setEnabled( enable );
  d->m_paSave->setEnabled( enable );
  d->m_paSaveAs->setEnabled( enable );
  d->m_exportFile->setEnabled( enable );
  d->m_paPrint->setEnabled( enable );
  d->m_paPrintPreview->setEnabled( enable );
  d->m_sendfile->setEnabled( enable);
  d->m_paCloseFile->setEnabled( enable );
}

void KoMainWindow::addRecentURL( const KURL& url )
{
    kdDebug(30003) << "KoMainWindow::addRecentURL url=" << url.prettyURL() << endl;
    // Add entry to recent documents list
    // (call coming from KoDocument because it must work with cmd line, template dlg, file/open, etc.)
    if ( !url.isEmpty() )
    {
        bool ok = true;
        if ( url.isLocalFile() )
        {
            TQString path = url.path( -1 );
            TQStringList tmpDirs = TDEGlobal::dirs()->resourceDirs( "tmp" );
            for ( TQStringList::Iterator it = tmpDirs.begin() ; ok && it != tmpDirs.end() ; ++it )
                if ( path.contains( *it ) )
                    ok = false; // it's in the tmp resource
            if ( ok )
                TDERecentDocument::add(path);
        }
        else
            TDERecentDocument::add(url.url(-1), true);

        if ( ok )
            m_recent->addURL( url );
        saveRecentFiles();
    }
}

void KoMainWindow::saveRecentFiles()
{
    // Save list of recent files
    TDEConfig * config = instance() ? instance()->config() : TDEGlobal::config();
    kdDebug(30003) << this << " Saving recent files list into config. instance()=" << instance() << endl;
    m_recent->saveEntries( config );
    config->sync();
    if (TDEMainWindow::memberList)
    {
        // Tell all windows to reload their list, after saving
        // Doesn't work multi-process, but it's a start
        TDEMainWindow *window = TDEMainWindow::memberList->first();
        for (; window; window = TDEMainWindow::memberList->next())
            static_cast<KoMainWindow *>(window)->reloadRecentFileList();
    }
}

void KoMainWindow::reloadRecentFileList()
{
    TDEConfig * config = instance() ? instance()->config() : TDEGlobal::config();
    m_recent->loadEntries( config );
}

KoDocument* KoMainWindow::createDoc() const
{
    KoDocumentEntry entry = KoDocumentEntry( KoDocument::readNativeService() );
    return entry.createDoc();
}

void KoMainWindow::updateCaption()
{
  //kdDebug(30003) << "KoMainWindow::updateCaption()" << endl;
  if ( !d->m_rootDoc )
    setCaption(TQString());
  else if ( rootDocument()->isCurrent() )
  {
      TQString caption;
      // Get caption from document info (title(), in about page)
      if ( rootDocument()->documentInfo() )
      {
          KoDocumentInfoPage * page = rootDocument()->documentInfo()->page( TQString::fromLatin1("about") );
          if (page)
              caption = static_cast<KoDocumentInfoAbout *>(page)->title();
      }
      const TQString url = rootDocument()->url().prettyURL( 0, KURL::StripFileProtocol );
      if ( !caption.isEmpty() && !url.isEmpty() )
          caption = TQString( "%1 - %2" ).arg( caption ).arg( url );
      else if ( caption.isEmpty() )
          caption = url;

      setCaption( caption, rootDocument()->isModified() );
      if ( !rootDocument()->url().fileName(false).isEmpty() )
        d->m_paSave->setToolTip( i18n("Save as %1").arg(rootDocument()->url().fileName(false)) );
      else
        d->m_paSave->setToolTip( i18n("Save") );
  }
}

void KoMainWindow::updateCaption( TQString caption, bool mod )
{
  //kdDebug(30003)<<"KoMainWindow::updateCaption("<<caption<<","<<mod<<")"<<endl;
  setCaption( caption, mod );
}

KoDocument *KoMainWindow::rootDocument() const
{
    return d->m_rootDoc;
}

KoView *KoMainWindow::rootView() const
{
  if(d->m_rootViews.find(d->m_activeView)!=-1)
    return d->m_activeView;
  return d->m_rootViews.first();
}

KParts::PartManager *KoMainWindow::partManager()
{
  return d->m_manager;
}

bool KoMainWindow::openDocument( const KURL & url )
{
    if ( !TDEIO::NetAccess::exists(url,true,0) )
    {
        KMessageBox::error(0L, i18n("The file %1 does not exist.").arg(url.url()) );
        m_recent->removeURL(url); //remove the file from the recent-opened-file-list
        saveRecentFiles();
        return false;
    }
    return  openDocumentInternal( url );
}

// (not virtual)
bool KoMainWindow::openDocument( KoDocument *newdoc, const KURL & url )
{
    if (!TDEIO::NetAccess::exists(url,true,0) )
    {
        if (!newdoc->checkAutoSaveFile())
        {
          newdoc->initEmpty(); //create an emtpy document
        }

        setRootDocument( newdoc );
        newdoc->setURL(url);
        TQString mime = KMimeType::findByURL(url)->name();
        if ( mime.isEmpty() || mime == KMimeType::defaultMimeType() )
            mime = newdoc->nativeFormatMimeType();
        if ( url.isLocalFile() ) // workaround for kde<=3.3 tdeparts bug, fixed for 3.4
            newdoc->setFile(url.path());
        newdoc->setMimeTypeAfterLoading( mime );
        updateCaption();
        return true;
    }
    return openDocumentInternal( url, newdoc );
}

// ## If you modify anything here, please check KoShellWindow::openDocumentInternal
bool KoMainWindow::openDocumentInternal( const KURL & url, KoDocument *newdoc )
{
    //kdDebug(30003) << "KoMainWindow::openDocument " << url.url() << endl;

    if ( !newdoc )
        newdoc = createDoc();
    if ( !newdoc )
        return false;

    d->m_firstTime=true;
    connect(newdoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));
    connect(newdoc, TQT_SIGNAL(completed()), TQT_TQOBJECT(this), TQT_SLOT(slotLoadCompleted()));
    connect(newdoc, TQT_SIGNAL(canceled( const TQString & )), TQT_TQOBJECT(this), TQT_SLOT(slotLoadCanceled( const TQString & )));
    newdoc->addShell( this ); // used by openURL
    bool openRet = (!isImporting ()) ? newdoc->openURL(url) : newdoc->import(url);
    if(!openRet)
    {
        newdoc->removeShell(this);
        delete newdoc;
        return false;
    }
    updateReloadFileAction(newdoc);
    updateVersionsFileAction( newdoc );
    return true;
}

// Separate from openDocument to handle async loading (remote URLs)
void KoMainWindow::slotLoadCompleted()
{
    kdDebug(30003) << "KoMainWindow::slotLoadCompleted" << endl;
    KoDocument* doc = rootDocument();
    KoDocument* newdoc = (KoDocument *)(sender());

    if ( doc && doc->isEmpty() && !doc->isEmbedded() )
    {
        // Replace current empty document
        setRootDocument( newdoc );
    }
    else if ( doc && !doc->isEmpty() )
    {
        // Open in a new shell
        // (Note : could create the shell first and the doc next for this
        // particular case, that would give a better user feedback...)
        KoMainWindow *s = new KoMainWindow( newdoc->instance() );
        s->show();
        newdoc->removeShell( this );
        s->setRootDocument( newdoc );
    }
    else
    {
        // We had no document, set the new one
       setRootDocument( newdoc );
    }
    disconnect(newdoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));
    disconnect(newdoc, TQT_SIGNAL(completed()), TQT_TQOBJECT(this), TQT_SLOT(slotLoadCompleted()));
    disconnect(newdoc, TQT_SIGNAL(canceled( const TQString & )), TQT_TQOBJECT(this), TQT_SLOT(slotLoadCanceled( const TQString & )));
}

void KoMainWindow::slotLoadCanceled( const TQString & errMsg )
{
    kdDebug(30003) << "KoMainWindow::slotLoadCanceled" << endl;
    if ( !errMsg.isEmpty() ) // empty when canceled by user
        KMessageBox::error( this, errMsg );
    // ... can't delete the document, it's the one who emitted the signal...

    KoDocument* newdoc = (KoDocument *)(sender());
    disconnect(newdoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));
    disconnect(newdoc, TQT_SIGNAL(completed()), TQT_TQOBJECT(this), TQT_SLOT(slotLoadCompleted()));
    disconnect(newdoc, TQT_SIGNAL(canceled( const TQString & )), TQT_TQOBJECT(this), TQT_SLOT(slotLoadCanceled( const TQString & )));

    newdoc->removeShell(this);
    delete newdoc;
}

void KoMainWindow::slotSaveCanceled( const TQString &errMsg )
{
    kdDebug(30003) << "KoMainWindow::slotSaveCanceled" << endl;
    if ( !errMsg.isEmpty() ) // empty when canceled by user
        KMessageBox::error( this, errMsg );
    slotSaveCompleted();
}

void KoMainWindow::slotSaveCompleted()
{
    kdDebug(30003) << "KoMainWindow::slotSaveCompleted" << endl;
    KoDocument* pDoc = (KoDocument *)(sender());
    disconnect(pDoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));
    disconnect(pDoc, TQT_SIGNAL(completed()), TQT_TQOBJECT(this), TQT_SLOT(slotSaveCompleted()));
    disconnect(pDoc, TQT_SIGNAL(canceled( const TQString & )),
               TQT_TQOBJECT(this), TQT_SLOT(slotSaveCanceled( const TQString & )));
}

// returns true if we should save, false otherwise.
bool KoMainWindow::exportConfirmation( const TQCString &outputFormat )
{
    if (!rootDocument()->wantExportConfirmation()) return true;
    KMimeType::Ptr mime = KMimeType::mimeType( outputFormat );

    const bool neverHeardOfIt = ( mime->name() == KMimeType::defaultMimeType() );
    TQString comment = neverHeardOfIt ?
                      i18n( "%1 (unknown file type)" ).arg( outputFormat.data() )
                      : mime->comment();

    // Warn the user
    int ret;
    if (!isExporting ()) // File --> Save
    {
        ret = KMessageBox::warningContinueCancel
              (
                  this,
                  i18n( "<qt>Saving as a %1 may result in some loss of formatting."
                        "<p>Do you still want to save in this format?</qt>" )
                  .arg( TQString( "<b>%1</b>" ).arg( comment ) ), // in case we want to remove the bold later
                  i18n( "Confirm Save" ),
                  KStdGuiItem::save (),
                  "NonNativeSaveConfirmation",
                  true
                  );
    }
    else // File --> Export
    {
        ret = KMessageBox::warningContinueCancel
              (
                  this,
                  i18n( "<qt>Exporting as a %1 may result in some loss of formatting."
                        "<p>Do you still want to export to this format?</qt>" )
                  .arg( TQString( "<b>%1</b>" ).arg( comment ) ), // in case we want to remove the bold later
                  i18n( "Confirm Export" ),
                  i18n ("Export"),
                  "NonNativeExportConfirmation", // different to the one used for Save (above)
                  true
                  );
    }

    return (ret == KMessageBox::Continue);
}

bool KoMainWindow::saveDocument( bool saveas, bool silent )
{
    KoDocument* pDoc = rootDocument();
    if(!pDoc)
        return true;

    bool reset_url;
    if ( pDoc->url().isEmpty() )
    {
        emit saveDialogShown();
        reset_url = true;
        saveas = true;
    }
    else
        reset_url = false;

    connect(pDoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));
    connect(pDoc, TQT_SIGNAL(completed()), TQT_TQOBJECT(this), TQT_SLOT(slotSaveCompleted()));
    connect(pDoc, TQT_SIGNAL(canceled( const TQString & )),
            TQT_TQOBJECT(this), TQT_SLOT(slotSaveCanceled( const TQString & )));

    KURL oldURL = pDoc->url();
    TQString oldFile = pDoc->file();
    TQCString _native_format = pDoc->nativeFormatMimeType();
    TQCString oldOutputFormat = pDoc->outputMimeType();
    int oldSpecialOutputFlag = pDoc->specialOutputFlag();
    KURL suggestedURL = pDoc->url();

    TQStringList mimeFilter = KoFilterManager::mimeFilter( _native_format, KoFilterManager::Export, pDoc->extraNativeMimeTypes() );
    if (mimeFilter.findIndex (oldOutputFormat) < 0 && !isExporting())
    {
        kdDebug(30003) << "KoMainWindow::saveDocument no export filter for '" << oldOutputFormat << "'" << endl;

        // --- don't setOutputMimeType in case the user cancels the Save As
        // dialog and then tries to just plain Save ---

        // suggest a different filename extension (yes, we fortunately don't all live in a world of magic :))
        TQString suggestedFilename = suggestedURL.fileName ();
        if ( !suggestedFilename.isEmpty () ) // ".kwd" looks strange for a name
        {
            int c = suggestedFilename.findRev ('.');

            KMimeType::Ptr mime = KMimeType::mimeType( _native_format );
            TQString ext = mime->property( "X-TDE-NativeExtension" ).toString();
            if (!ext.isEmpty ())
            {
                if (c < 0)
                    suggestedFilename += ext;
                else
                    suggestedFilename = suggestedFilename.left (c) + ext;
            }
            else  // current filename extension wrong anyway
            {
                if (c > 0)
                {
                    // this assumes that a . signifies an extension, not just a .
                    suggestedFilename = suggestedFilename.left (c);
                }
            }

            suggestedURL.setFileName (suggestedFilename);
        }

        // force the user to choose outputMimeType
        saveas = true;
    }

    bool ret = false;

    if ( pDoc->url().isEmpty() || saveas )
    {
        // if you're just File/Save As'ing to change filter options you
        // don't want to be reminded about overwriting files etc.
        bool justChangingFilterOptions = false;

        KoFileDialog *dialog = new KoFileDialog( (isExporting() && !d->m_lastExportURL.isEmpty() )? d->m_lastExportURL.url () : suggestedURL.url (),
                                                TQString(), this, "file dialog", true);

        if (!isExporting())
            dialog->setCaption( i18n("Save Document As") );
        else
            dialog->setCaption( i18n("Export Document As") );

        dialog->setOperationMode( KFileDialog::Saving );
        dialog->setSpecialMimeFilter( mimeFilter,
                                      isExporting() ? d->m_lastExportFormat : pDoc->mimeType(),
                                      isExporting() ? d->m_lastExportSpecialOutputFlag : oldSpecialOutputFlag,
                                      _native_format,
                                      pDoc->supportedSpecialFormats() );

        KURL newURL;
        TQCString outputFormat = _native_format;
        int specialOutputFlag = 0;
        bool bOk;
        do {
            bOk=true;
            if(dialog->exec()==TQDialog::Accepted) {
                newURL=dialog->selectedURL();
                outputFormat=dialog->currentMimeFilter().latin1();
                specialOutputFlag = dialog->specialEntrySelected();
                kdDebug(30003) << "KoMainWindow::saveDocument outputFormat = " << outputFormat << endl;

                if (!isExporting())
                    justChangingFilterOptions = (newURL == pDoc->url()) &&
                                                (outputFormat == pDoc->mimeType()) &&
                                                (specialOutputFlag == oldSpecialOutputFlag);
                else
                    justChangingFilterOptions = (newURL == d->m_lastExportURL) &&
                                                (outputFormat == d->m_lastExportFormat) &&
                                                (specialOutputFlag == d->m_lastExportSpecialOutputFlag);
            }
            else
            {
                bOk = false;
                break;
            }

            if ( newURL.isEmpty() )
            {
                bOk = false;
                break;
            }

            // adjust URL before doing checks on whether the file exists.
            if ( specialOutputFlag == KoDocument::SaveAsDirectoryStore ) {
                TQString fileName = newURL.fileName();
                if ( fileName != "content.xml"  ) {
                    newURL.addPath( "content.xml" );
                }
            }

            // this file exists and we are not just clicking "Save As" to change filter options
            // => ask for confirmation
            if ( TDEIO::NetAccess::exists( newURL, false /*will write*/, this ) && !justChangingFilterOptions )
            {
                bOk = KMessageBox::questionYesNo( this,
                                                  i18n("A document with this name already exists.\n"\
                                                       "Do you want to overwrite it?"),
                                                  i18n("Warning") ) == KMessageBox::Yes;
            }
        } while ( !bOk );

        delete dialog;

        if (bOk)
        {
            bool wantToSave = true;

            // don't change this line unless you know what you're doing :)
            if (!justChangingFilterOptions || pDoc->confirmNonNativeSave (isExporting ())) {
                if ( !pDoc->isNativeFormat( outputFormat ) )
                        wantToSave = exportConfirmation( outputFormat );
            }

            if (wantToSave)
            {
                //
                // Note:
                // If the user is stupid enough to Export to the current URL,
                // we do _not_ change this operation into a Save As.  Reasons
                // follow:
                //
                // 1. A check like "isExporting() && oldURL == newURL"
                //    doesn't _always_ work on case-insensitive filesystems
                //    and inconsistent behaviour is bad.
                // 2. It is probably not a good idea to change pDoc->mimeType
                //    and friends because the next time the user File/Save's,
                //    (not Save As) they won't be expecting that they are
                //    using their File/Export settings
                //
                // As a bad side-effect of TQT_TQOBJECT(this), the modified flag will not
                // be updated and it is possible that what is currently on
                // their screen is not what is stored on disk (through loss
                // of formatting).  But if you are dumb enough to change
                // mimetype but not the filename, then arguably, _you_ are
                // the "bug" :)
                //
                // - Clarence
                //


                pDoc->setOutputMimeType( outputFormat, specialOutputFlag );
                if (!isExporting ())   // Save As
                {
                    ret = pDoc->saveAs( newURL );

                    if (ret)
                    {
                        kdDebug(30003) << "Successful Save As!" << endl;
                        addRecentURL( newURL );
                    }
                    else
                    {
                        kdDebug(30003) << "Failed Save As!" << endl;
                        pDoc->setURL( oldURL ), pDoc->setFile( oldFile );
                        pDoc->setOutputMimeType( oldOutputFormat, oldSpecialOutputFlag );
                    }
                }
                else    // Export
                {
                    ret = pDoc->exp0rt( newURL );

                    if (ret)
                    {
                        // a few file dialog convenience things
                        d->m_lastExportURL = newURL;
                        d->m_lastExportFormat = outputFormat;
                        d->m_lastExportSpecialOutputFlag = specialOutputFlag;
                    }

                    // always restore output format
                    pDoc->setOutputMimeType( oldOutputFormat, oldSpecialOutputFlag );
                }
            }   // if (wantToSave)
            else
                ret = false;
        }   // if (bOk)
        else
            ret = false;
    }
    else {  // saving
        bool needConfirm = pDoc->confirmNonNativeSave( false ) &&
                           !pDoc->isNativeFormat( oldOutputFormat );
        if (!needConfirm ||
               (needConfirm && exportConfirmation( oldOutputFormat /* not so old :) */ ))
           )
        {
            // be sure pDoc has the correct outputMimeType!
            ret = pDoc->save();

            if (!ret)
            {
                kdDebug(30003) << "Failed Save!" << endl;
                pDoc->setURL( oldURL ), pDoc->setFile( oldFile );
            }
        }
        else
            ret = false;
    }

// Now that there's a File/Export option, this is no longer necessary.
// If you continue to use File/Save to export to a foreign format,
// this signals your intention to continue working in a foreign format.
// You have already been warned by the DoNotAskAgain exportConfirmation
// about losing formatting when you first saved so don't set modified
// here or else it will be reported as a bug by some MSOffice user.
// You have been warned!  Do not click DoNotAskAgain!!!
#if 0
    if (ret && !isExporting())
    {
        // When exporting to a non-native format, we don't reset modified.
        // This way the user will be reminded to save it again in the native format,
        // if he/she doesn't want to lose formatting.
        if ( wasModified && pDoc->outputMimeType() != _native_format )
            pDoc->setModified( true );
    }
#endif

    if (!ret && reset_url)
        pDoc->resetURL(); //clean the suggested filename as the save dialog was rejected
    else if (! silent) // don't let the document change the window caption
        pDoc->setTitleModified();
    return ret;
}

void KoMainWindow::closeEvent(TQCloseEvent *e) {
    if(queryClose()) {
        saveWindowSettings();
        setRootDocument(0L);
        KParts::MainWindow::closeEvent(e);
    }
}

void KoMainWindow::saveWindowSettings()
{
    if (d->m_windowSizeDirty && rootDocument())
    {
        // Save window size into the config file of our instance
        instance()->config()->setGroup( "MainWindow" );
        //kdDebug(30003) << "KoMainWindow::saveWindowSettings" << endl;
        saveWindowSize( instance()->config() );
        d->m_windowSizeDirty = false;
        // Save toolbar position into the config file of the app, under the doc's instance name
        //kdDebug(30003) << "KoMainWindow::closeEvent -> saveMainWindowSettings rootdoc's instance=" << rootDocument()->instance()->instanceName() << endl;
        saveMainWindowSettings( TDEGlobal::config(), rootDocument()->instance()->instanceName() );
        TDEGlobal::config()->sync();
        resetAutoSaveSettings(); // Don't let TDEMainWindow override the good stuff we wrote down
    }
}

void KoMainWindow::resizeEvent( TQResizeEvent * e )
{
    d->m_windowSizeDirty = true;
    KParts::MainWindow::resizeEvent( e );
}

bool KoMainWindow::queryClose()
{
    if ( rootDocument() == 0 )
        return true;
    //kdDebug(30003) << "KoMainWindow::queryClose() viewcount=" << rootDocument()->viewCount()
    //               << " shellcount=" << rootDocument()->shellCount() << endl;
    if ( !d->m_forQuit && rootDocument()->shellCount() > 1 )
        // there are more open, and we are closing just one, so no problem for closing
        return true;

    // see DTOR for a descr. of the test
    if ( d->m_rootDoc->isEmbedded() )
        return true;

    // main doc + internally stored child documents
    if ( d->m_rootDoc->isModified() )
    {
        TQString name;
        if ( rootDocument()->documentInfo() )
        {
            name = rootDocument()->documentInfo()->title();
        }
        if ( name.isEmpty() )
            name = rootDocument()->url().fileName();

        if ( name.isEmpty() )
            name = i18n( "Untitled" );

        int res = KMessageBox::warningYesNoCancel( this,
                        i18n( "<p>The document <b>'%1'</b> has been modified.</p><p>Do you want to save it?</p>" ).arg(name),
                        TQString(),
                        KStdGuiItem::save(),
                        KStdGuiItem::discard());

        switch(res) {
            case KMessageBox::Yes : {
                d->m_rootDoc->setDoNotSaveExtDoc(); // external docs are saved later
                bool isNative = ( d->m_rootDoc->outputMimeType() == d->m_rootDoc->nativeFormatMimeType() );
                if (! saveDocument( !isNative ) )
                    return false;
                break;
            }
            case KMessageBox::No :
                rootDocument()->removeAutoSaveFiles();
                rootDocument()->setModified( false ); // Now when queryClose() is called by closeEvent it won't do anything.
                break;
            default : // case KMessageBox::Cancel :
                return false;
        }
    }

    if ( d->m_rootDoc->queryCloseExternalChildren() == KMessageBox::Cancel )
    {
        return false;
    }

    return true;
}

// Helper method for slotFileNew and slotFileClose
void KoMainWindow::chooseNewDocument( int /*KoDocument::InitDocFlags*/ initDocFlags )
{
    KoDocument* doc = rootDocument();
    KoDocument *newdoc = createDoc();

    if ( !newdoc )
        return;

    //FIXME: This needs to be handled differently
    connect(newdoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));
    disconnect(newdoc, TQT_SIGNAL(sigProgress(int)), TQT_TQOBJECT(this), TQT_SLOT(slotProgress(int)));

    if ( ( !doc  && ( initDocFlags == KoDocument::InitDocFileNew ) ) || ( doc && !doc->isEmpty() ) )
    {
        KoMainWindow *s = new KoMainWindow( newdoc->instance() );
        s->show();
        newdoc->addShell( s );
        newdoc->showStartUpWidget( s, true /*Always show widget*/ );
        return;
    }

    if( doc ) {
        setRootDocument( 0 );
        delete d->m_rootDoc;
        d->m_rootDoc = 0;
    }

    newdoc->addShell( this );
    newdoc->showStartUpWidget( this, true /*Always show widget*/ );
}

void KoMainWindow::slotFileNew()
{
    chooseNewDocument( KoDocument::InitDocFileNew );
}

void KoMainWindow::slotFileOpen()
{
    KFileDialog *dialog = new KFileDialog(":OpenDialog", TQString(), this, "file dialog", true);
    if (!isImporting())
        dialog->setCaption( i18n("Open Document") );
    else
        dialog->setCaption( i18n("Import Document") );

    // The few lines below need to be kept in sync with KoTemplateChooseDia::setupFileDialog
    const TQStringList mimeFilter = KoFilterManager::mimeFilter( KoDocument::readNativeFormatMimeType(),
                                                                KoFilterManager::Import,
                                                                KoDocument::readExtraNativeMimeTypes() );
    dialog->setMimeFilter( mimeFilter );
    if(dialog->exec()!=TQDialog::Accepted) {
        delete dialog;
        return;
    }
    KURL url( dialog->selectedURL() );
    delete dialog;

    if ( url.isEmpty() )
        return;

    (void) openDocument( url );
}

void KoMainWindow::slotFileOpenRecent( const KURL & url )
{
    (void) openDocument( url );
}

void KoMainWindow::slotFileSave()
{
    if ( saveDocument() )
        emit documentSaved();
}

void KoMainWindow::slotFileSaveAs()
{
    if ( saveDocument( true ) )
        emit documentSaved();
}

void KoMainWindow::slotDocumentInfo()
{
  if ( !rootDocument() )
    return;

  KoDocumentInfo *docInfo = rootDocument()->documentInfo();

  if ( !docInfo )
    return;

  KoDocumentInfoDlg *dlg = new KoDocumentInfoDlg( docInfo, this, "documentInfoDlg" );
  if ( dlg->exec() )
  {
    dlg->save();
    rootDocument()->setModified( true );
    rootDocument()->setTitleModified();
  }

  delete dlg;
}

void KoMainWindow::slotFileClose()
{
    if (queryClose())
    {
        saveWindowSettings();
        setRootDocument( 0 ); // don't delete this shell when deleting the document
        delete d->m_rootDoc;
        d->m_rootDoc = 0;
        chooseNewDocument( KoDocument::InitDocFileClose );
    }
}

void KoMainWindow::slotFileQuit()
{
    close();
}

void KoMainWindow::print(bool quick) {
    if ( !rootView() )
    {
        kdDebug(30003) << "KoMainWindow::slotFilePrint : No root view!" << endl;
        return;
    }

    KPrinter printer( true /*, TQPrinter::HighResolution*/ );
    TQString title = rootView()->koDocument()->documentInfo()->title();
    TQString fileName = rootView()->koDocument()->url().fileName();

    // strip off the native extension (I don't want foobar.kwd.ps when printing into a file)
    KMimeType::Ptr mime = KMimeType::mimeType( rootView()->koDocument()->outputMimeType() );
    if ( mime ) {
        TQString extension = mime->property( "X-TDE-NativeExtension" ).toString();

        if ( fileName.endsWith( extension ) )
            fileName.truncate( fileName.length() - extension.length() );
    }

    if ( title.isEmpty() )
        title = fileName;
    if ( title.isEmpty() ) {
        // #139905 - breaks message freeze though
        //const TQString programName = instance()->aboutData() ? instance()->aboutData()->programName() : instance()->instanceName();
        //title = i18n("%1 unsaved document (%2)").arg(programName).arg(TDEGlobal::locale()->formatDate(TQDate::currentDate(), true/*short*/));
    }
    printer.setDocName( title );
    printer.setDocFileName( fileName );
    printer.setDocDirectory( rootView()->koDocument()->url().directory() );

    // ### TODO: apply global koffice settings here

    rootView()->setupPrinter( printer );

    if ( quick ||  printer.setup( this ) )
        rootView()->print( printer );
}


void KoMainWindow::slotFilePrint()
{
    print(false);
}

void KoMainWindow::slotFilePrintPreview()
{
    if ( !rootView() )
    {
        kdWarning() << "KoMainWindow::slotFilePrint : No root view!" << endl;
        return;
    }
    KPrinter printer( false );
    KTempFile tmpFile;
    // The temp file is deleted by KoPrintPreview

    // This line has to be before setupPrinter to let the apps decide what to
    // print and what not (if they want to :)
    printer.setFromTo( printer.minPage(), printer.maxPage() );
    printer.setPreviewOnly( true );
    rootView()->setupPrinter( printer );

    TQString oldFileName = printer.outputFileName();
    printer.setOutputFileName( tmpFile.name() );
    int oldNumCopies = printer.numCopies();
    printer.setNumCopies( 1 );
    // Disable tdeprint's own preview, we'd get two. This shows that KPrinter needs
    // a "don't use the previous settings" mode. The current way is really too much of a hack.
    TQString oldKDEPreview = printer.option( "kde-preview" );
    printer.setOption( "kde-preview", "0" );

    rootView()->print(printer);
    //KoPrintPreview::preview(this, "KoPrintPreviewDialog", tmpFile.name());

    // Restore previous values
    printer.setOutputFileName( oldFileName );
    printer.setNumCopies( oldNumCopies );
    printer.setOption( "kde-preview", oldKDEPreview );
}

void KoMainWindow::slotConfigureKeys()
{
    guiFactory()->configureShortcuts();
}

void KoMainWindow::slotConfigureToolbars()
{
    if (rootDocument())
        saveMainWindowSettings( TDEGlobal::config(), rootDocument()->instance()->instanceName() );
    KEditToolbar edit(factory(), this);
    connect(&edit,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(slotNewToolbarConfig()));
    (void) edit.exec();
}

void KoMainWindow::slotNewToolbarConfig()
{
  if (rootDocument())
      applyMainWindowSettings( TDEGlobal::config(), rootDocument()->instance()->instanceName() );
  KXMLGUIFactory *factory = guiFactory();

  // Check if there's an active view
  if( !d->m_activeView )
      return;

  // This gets plugged in even for embedded views
  factory->plugActionList(d->m_activeView, "view_closeallviews",
                          d->m_veryHackyActionList);

  // This one only for root views
  if(d->m_rootViews.findRef(d->m_activeView)!=-1)
    factory->plugActionList(d->m_activeView, "view_split",
                            d->m_splitViewActionList );
  plugActionList( "toolbarlist", d->m_toolbarList );
}

void KoMainWindow::slotToolbarToggled( bool toggle )
{
  //kdDebug(30003) << "KoMainWindow::slotToolbarToggled " << sender()->name() << " toggle=" << true << endl;
  // The action (sender) and the toolbar have the same name
  TDEToolBar * bar = toolBar( sender()->name() );
  if (bar)
  {
    if (toggle)
      bar->show();
    else
      bar->hide();

    if (rootDocument())
        saveMainWindowSettings( TDEGlobal::config(), rootDocument()->instance()->instanceName() );
  }
  else
    kdWarning(30003) << "slotToolbarToggled : Toolbar " << sender()->name() << " not found!" << endl;
}

bool KoMainWindow::toolbarIsVisible(const char *tbName)
{
    TQWidget *tb = toolBar( tbName);
    return !tb->isHidden();
}

void KoMainWindow::showToolbar( const char * tbName, bool shown )
{
    TQWidget * tb = toolBar( tbName );
    if ( !tb )
    {
        kdWarning(30003) << "KoMainWindow: toolbar " << tbName << " not found." << endl;
        return;
    }
    if ( shown )
        tb->show();
    else
        tb->hide();

    // Update the action appropriately
    TQPtrListIterator<TDEAction> it( d->m_toolbarList );
    for ( ; it.current() ; ++it )
        if ( !strcmp( it.current()->name(), tbName ) )
        {
            //kdDebug(30003) << "KoMainWindow::showToolbar setChecked " << shown << endl;
            static_cast<TDEToggleAction *>(it.current())->setChecked( shown );
            break;
        }
}

void KoMainWindow::slotSplitView() {
    d->m_splitted=true;
    d->m_rootViews.append(d->m_rootDoc->createView(d->m_splitter, "splitted-view"));
    d->m_rootViews.current()->show();
    d->m_rootViews.current()->setPartManager( d->m_manager );
    d->m_manager->setActivePart( d->m_rootDoc, d->m_rootViews.current() );
    d->m_removeView->setEnabled(true);
    d->m_orientation->setEnabled(true);
}

void KoMainWindow::slotCloseAllViews() {

    // Attention: Very touchy code... you know what you're doing? Goooood :)
    d->m_forQuit=true;
    if(queryClose()) {
        // In case the document is embedded we close all open "extra-shells"
        if(d->m_rootDoc && d->m_rootDoc->isEmbedded()) {
            hide();
            d->m_rootDoc->removeShell(this);
            TQPtrListIterator<KoMainWindow> it(d->m_rootDoc->shells());
            while (it.current()) {
                it.current()->hide();
                delete it.current(); // this updates the lists' current pointer and thus
                                     // the iterator (the shell dtor calls removeShell)
            d->m_rootDoc=0;
            }
        }
        // not embedded -> destroy the document and all shells/views ;)
        else
            setRootDocument( 0L );
        close();  // close this window (and quit the app if necessary)
    }
    d->m_forQuit=false;
}

void KoMainWindow::slotRemoveView() {
    KoView *view;
    if(d->m_rootViews.findRef(d->m_activeView)!=-1)
        view=d->m_rootViews.current();
    else
        view=d->m_rootViews.first();
    view->hide();
    if ( !d->m_rootViews.removeRef(view) )
        kdWarning() << "view not found in d->m_rootViews!" << endl;

    if(d->m_rootViews.count()==1)
    {
        d->m_removeView->setEnabled(false);
        d->m_orientation->setEnabled(false);
    }
    // Prevent the view's destroyed() signal from triggering GUI rebuilding (too early)
    d->m_manager->setActivePart( 0, 0 );

    delete view;
    view=0L;

    d->m_rootViews.first()->setPartManager( d->m_manager );
    d->m_manager->setActivePart( d->m_rootDoc, d->m_rootViews.first() );

    if(d->m_rootViews.count()==1)
        d->m_splitted=false;
}

void KoMainWindow::slotSetOrientation() {
    d->m_splitter->setOrientation(static_cast<TQt::Orientation>
                                  (d->m_orientation->currentItem()));
}

void KoMainWindow::slotProgress(int value) {
    //kdDebug(30003) << "KoMainWindow::slotProgress " << value << endl;
    if(value==-1) {
        if ( d->m_progress )
        {
            statusBar()->removeWidget(d->m_progress);
            delete d->m_progress;
            d->m_progress=0L;
        }
        d->m_firstTime=true;
        return;
    }
    if(d->m_firstTime)
    {
        // The statusbar might not even be created yet.
        // So check for that first, and create it if necessary
        TQObjectList *l = queryList( "TQStatusBar" );
        if ( !l || !l->first() ) {
            statusBar()->show();
            TQApplication::sendPostedEvents( TQT_TQOBJECT(this), TQEvent::ChildInserted );
            setUpLayout();
        }
        delete l;

        if ( d->m_progress )
        {
            statusBar()->removeWidget(d->m_progress);
            delete d->m_progress;
            d->m_progress=0L;
        }
        statusBar()->setMaximumHeight(statusBar()->height());
        d->m_progress=new KProgress(statusBar());
        //d->m_progress->setMaximumHeight(statusBar()->height());
        statusBar()->addWidget( d->m_progress, 0, true );
        d->m_progress->show();
        d->m_firstTime=false;
    }
    d->m_progress->setProgress(value);
    kapp->processEvents();
}


void KoMainWindow::slotActivePartChanged( KParts::Part *newPart )
{

  // This looks very much like KParts::MainWindow::createGUI, but we have
  // to reimplement it because it works with an active part, whereas we work
  // with an active view _and_ an active part, depending for what.
  // Both are KXMLGUIClients, but e.g. the plugin query needs a TQObject.
  //kdDebug(30003) <<  "KoMainWindow::slotActivePartChanged( Part * newPart) newPart = " << newPart << endl;
  //kdDebug(30003) <<  "current active part is " << d->m_activePart << endl;

  if ( d->m_activePart && d->m_activePart == newPart && !d->m_splitted )
  {
    //kdDebug(30003) << "no need to change the GUI" << endl;
    return;
  }

  KXMLGUIFactory *factory = guiFactory();

  setUpdatesEnabled( false );

  if ( d->m_activeView )
  {
    KParts::GUIActivateEvent ev( false );
    TQApplication::sendEvent( d->m_activePart, &ev );
    TQApplication::sendEvent( d->m_activeView, &ev );


    factory->removeClient( d->m_activeView );

    unplugActionList( "toolbarlist" );
    d->m_toolbarList.clear(); // deletes the actions
  }

  if ( !d->bMainWindowGUIBuilt )
  {
    // Load mainwindow plugins
    KParts::Plugin::loadPlugins( TQT_TQOBJECT(this), this, instance(), true );
    createShellGUI();
  }

  if ( newPart && d->m_manager->activeWidget() && d->m_manager->activeWidget()->inherits( "KoView" ) )
  {
    d->m_activeView = (KoView *)d->m_manager->activeWidget();
    d->m_activePart = newPart;
    //kdDebug(30003) <<  "new active part is " << d->m_activePart << endl;

    factory->addClient( d->m_activeView );


    // This gets plugged in even for embedded views
    factory->plugActionList(d->m_activeView, "view_closeallviews",
                            d->m_veryHackyActionList);
    // This one only for root views
    if(d->m_rootViews.findRef(d->m_activeView)!=-1)
        factory->plugActionList(d->m_activeView, "view_split", d->m_splitViewActionList );

    // Position and show toolbars according to user's preference
    setAutoSaveSettings( newPart->instance()->instanceName(), false );

    // Create and plug toolbar list for Settings menu
    //TQPtrListIterator<TDEToolBar> it = toolBarIterator();
    TQPtrList<TQWidget> toolBarList = factory->containers( "ToolBar" );
    TQPtrListIterator<TQWidget> it( toolBarList );
    for ( ; it.current() ; ++it )
    {
      if ( it.current()->inherits("TDEToolBar") )
      {
          TDEToolBar * tb = static_cast<TDEToolBar *>(it.current());
          TDEToggleAction * act = new TDEToggleAction( i18n("Show %1 Toolbar").arg( tb->text() ), 0,
                                               actionCollection(), tb->name() );
	  act->setCheckedState(i18n("Hide %1 Toolbar").arg( tb->text() ));
	  connect( act, TQT_SIGNAL( toggled( bool ) ), TQT_TQOBJECT(this), TQT_SLOT( slotToolbarToggled( bool ) ) );
          act->setChecked ( !tb->isHidden() );
          d->m_toolbarList.append( act );
      }
      else
          kdWarning(30003) << "Toolbar list contains a " << it.current()->className() << " which is not a toolbar!" << endl;
    }
    plugActionList( "toolbarlist", d->m_toolbarList );

    // Send the GUIActivateEvent only now, since it might show/hide toolbars too
    // (and this has priority over applyMainWindowSettings)
    KParts::GUIActivateEvent ev( true );
    TQApplication::sendEvent( d->m_activePart, &ev );
    TQApplication::sendEvent( d->m_activeView, &ev );
  }
  else
  {
    d->m_activeView = 0L;
    d->m_activePart = 0L;
  }
  setUpdatesEnabled( true );
}

TQLabel * KoMainWindow::statusBarLabel()
{
  if ( !d->statusBarLabel )
  {
    d->statusBarLabel = new TQLabel( statusBar() );
    statusBar()->addWidget( d->statusBarLabel, 1, true );
  }
  return d->statusBarLabel;
}

void KoMainWindow::setMaxRecentItems(uint _number)
{
        m_recent->setMaxItems( _number );
}

DCOPObject * KoMainWindow::dcopObject()
{
    if ( !d->m_dcopObject )
    {
        d->m_dcopObject = new KoMainWindowIface( this );
    }

    return d->m_dcopObject;
}

void KoMainWindow::slotEmailFile()
{
    if (!rootDocument())
        return;

    // Subject = Document file name
    // Attachment = The current file
    // Message Body = The current document in HTML export? <-- This may be an option.
    TQString theSubject;
    TQStringList urls;
    TQString fileURL;
    if (rootDocument()->url ().isEmpty () ||
        rootDocument()->isModified())
    {
        //Save the file as a temporary file
        bool const tmp_modified = rootDocument()->isModified();
        KURL const tmp_url = rootDocument()->url();
        TQCString const tmp_mimetype = rootDocument()->outputMimeType();
        KTempFile tmpfile; //TODO: The temorary file should be deleted when the mail program is closed
        KURL u;
        u.setPath(tmpfile.name());
        rootDocument()->setURL(u);
        rootDocument()->setModified(true);
        rootDocument()->setOutputMimeType(rootDocument()->nativeFormatMimeType());

        saveDocument(false, true);

        fileURL = tmpfile.name();
        theSubject = i18n("Document");
        urls.append( fileURL );

        rootDocument()->setURL(tmp_url);
        rootDocument()->setModified(tmp_modified);
        rootDocument()->setOutputMimeType(tmp_mimetype);
    }
    else
    {
        fileURL = rootDocument()->url().url();
        theSubject = i18n("Document - %1").arg(rootDocument()->url().fileName(false));
        urls.append( fileURL );
    }

    kdDebug(30003) << "(" << fileURL <<")" << endl;

    if (!fileURL.isEmpty())
    {
        kapp->invokeMailer(TQString(), TQString(), TQString(), theSubject,
                            TQString(), //body
                            TQString(),
                            urls); // attachments
    }
}

void KoMainWindow::slotVersionsFile()
{
    KoVersionDialog *dlg = new KoVersionDialog(  this );
    dlg->exec();
    delete dlg;
}

void KoMainWindow::slotReloadFile()
{
    KoDocument* pDoc = rootDocument();
    if(!pDoc || pDoc->url().isEmpty() || !pDoc->isModified())
        return;

    bool bOk = KMessageBox::questionYesNo( this,
                                      i18n("You will lose all your changes!\n"
                                           "Do you want to continue?"),
                                      i18n("Warning") ) == KMessageBox::Yes;
    if ( !bOk )
        return;

    KURL url = pDoc->url();
    if ( pDoc && !pDoc->isEmpty() )
    {
        setRootDocument( 0L ); // don't delete this shell when deleting the document
        delete d->m_rootDoc;
        d->m_rootDoc = 0L;
    }
    openDocument( url );
    return;

}

void KoMainWindow::slotImportFile()
{
    kdDebug(30003) << "slotImportFile()" << endl;

    d->m_isImporting = true;
    slotFileOpen();
    d->m_isImporting = false;
}

void KoMainWindow::slotExportFile()
{
    kdDebug(30003) << "slotExportFile()" << endl;

    d->m_isExporting = true;
    slotFileSaveAs();
    d->m_isExporting = false;
}

bool KoMainWindow::isImporting() const
{
    return d->m_isImporting;
}

bool KoMainWindow::isExporting() const
{
    return d->m_isExporting;
}

void KoMainWindow::setDocToOpen( KoDocument *doc )
{
  d->m_docToOpen = doc;
}

#include <KoMainWindow.moc>