lib

KoMainWindow.cpp

00001 /* This file is part of the KDE project
00002    Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
00003    Copyright (C) 2000-2006 David Faure <faure@kde.org>
00004 
00005    This library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Library General Public
00007    License as published by the Free Software Foundation; either
00008    version 2 of the License, or (at your option) any later version.
00009 
00010    This library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Library General Public License for more details.
00014 
00015    You should have received a copy of the GNU Library General Public License
00016    along with this library; see the file COPYING.LIB.  If not, write to
00017    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00018  * Boston, MA 02110-1301, USA.
00019 */
00020 
00021 #include "KoMainWindow.h"
00022 #include "KoDocument.h"
00023 #include "KoView.h"
00024 #include "KoFilterManager.h"
00025 #include "KoDocumentInfo.h"
00026 #include "KoDocumentInfoDlg.h"
00027 #include "KoQueryTrader.h"
00028 #include "KoMainWindowIface.h"
00029 #include "KoFrame.h"
00030 #include "KoFileDialog.h"
00031 #include "Koversiondialog.h"
00032 #include "kkbdaccessextensions.h"
00033 #include "KoSpeaker.h"
00034 
00035 #include <kprinter.h>
00036 #include <kdeversion.h>
00037 #include <kstdaction.h>
00038 #include <kapplication.h>
00039 #include <kmessagebox.h>
00040 #include <kstandarddirs.h>
00041 #include <kio/netaccess.h>
00042 #include <kkeydialog.h>
00043 #include <kedittoolbar.h>
00044 #include <kprogress.h>
00045 #include <kpushbutton.h>
00046 #include <kdebug.h>
00047 #include <ktempfile.h>
00048 #include <krecentdocument.h>
00049 #include <kparts/partmanager.h>
00050 #include <kparts/plugin.h>
00051 #include <kparts/event.h>
00052 #include <klocale.h>
00053 #include <kstatusbar.h>
00054 #include <kglobalsettings.h>
00055 #include <ksharedptr.h>
00056 
00057 #include <qobjectlist.h>
00058 
00059 #include <unistd.h>
00060 #include <stdlib.h>
00061 
00062 class KoPartManager : public KParts::PartManager
00063 {
00064 public:
00065   KoPartManager( QWidget * parent, const char * name = 0L )
00066     : KParts::PartManager( parent, name )
00067   {
00068       setSelectionPolicy( KParts::PartManager::TriState );
00069       setAllowNestedParts( true );
00070       setIgnoreScrollBars( true );
00071       // Allow right-click on embedded objects (without activating them)
00072       // But beware: this means right-click on parent, from embedded object,
00073       // doesn't make the parent active first...
00074       setActivationButtonMask( Qt::LeftButton | Qt::MidButton );
00075   }
00076   virtual bool eventFilter( QObject *obj, QEvent *ev )
00077   {
00078     if ( !obj->isWidgetType() || ::qt_cast<KoFrame *>( obj ) )
00079       return false;
00080     return KParts::PartManager::eventFilter( obj, ev );
00081   }
00082 };
00083 
00084 class KoMainWindowPrivate
00085 {
00086 public:
00087   KoMainWindowPrivate()
00088   {
00089     m_rootDoc = 0L;
00090     m_docToOpen = 0L;
00091     m_manager = 0L;
00092     bMainWindowGUIBuilt = false;
00093     m_forQuit=false;
00094     m_splitted=false;
00095     m_activePart = 0L;
00096     m_activeView = 0L;
00097     m_splitter=0L;
00098     m_orientation=0L;
00099     m_removeView=0L;
00100     m_toolbarList.setAutoDelete( true );
00101     m_firstTime=true;
00102     m_progress=0L;
00103     m_paDocInfo = 0;
00104     m_paSave = 0;
00105     m_paSaveAs = 0;
00106     m_paPrint = 0;
00107     m_paPrintPreview = 0;
00108     statusBarLabel = 0L;
00109     m_dcopObject = 0;
00110     m_sendfile = 0;
00111     m_paCloseFile = 0L;
00112     m_reloadfile = 0L;
00113     m_versionsfile = 0L;
00114     m_importFile = 0;
00115     m_exportFile = 0;
00116     m_isImporting = false;
00117     m_isExporting = false;
00118     m_windowSizeDirty = false;
00119     m_lastExportSpecialOutputFlag = 0;
00120 
00121     // TTS accessibility enhancement (only if KDE 3.4 or later and KTTSD daemon is installed.)
00122     if (KoSpeaker::isKttsdInstalled()) {
00123         if (kospeaker)
00124             m_koSpeaker = kospeaker;
00125         else
00126             m_koSpeaker = new KoSpeaker();
00127     } else
00128         m_koSpeaker = 0;
00129   }
00130   ~KoMainWindowPrivate()
00131   {
00132     delete m_dcopObject;
00133   }
00134 
00135   KoDocument *m_rootDoc;
00136   KoDocument *m_docToOpen;
00137   QPtrList<KoView> m_rootViews;
00138   KParts::PartManager *m_manager;
00139 
00140   KParts::Part *m_activePart;
00141   KoView *m_activeView;
00142 
00143   QLabel * statusBarLabel;
00144   KProgress *m_progress;
00145 
00146   QPtrList<KAction> m_splitViewActionList;
00147   // This additional list is needed, because we don't plug
00148   // the first list, when an embedded view gets activated (Werner)
00149   QPtrList<KAction> m_veryHackyActionList;
00150   QSplitter *m_splitter;
00151   KSelectAction *m_orientation;
00152   KAction *m_removeView;
00153   KoMainWindowIface *m_dcopObject;
00154 
00155   QPtrList <KAction> m_toolbarList;
00156 
00157   bool bMainWindowGUIBuilt;
00158   bool m_splitted;
00159   bool m_forQuit;
00160   bool m_firstTime;
00161   bool m_windowSizeDirty;
00162 
00163   KAction *m_paDocInfo;
00164   KAction *m_paSave;
00165   KAction *m_paSaveAs;
00166   KAction *m_paPrint;
00167   KAction *m_paPrintPreview;
00168   KAction *m_sendfile;
00169   KAction *m_paCloseFile;
00170   KAction *m_reloadfile;
00171   KAction *m_versionsfile;
00172   KAction *m_importFile;
00173   KAction *m_exportFile;
00174 
00175   bool m_isImporting;
00176   bool m_isExporting;
00177 
00178   KURL m_lastExportURL;
00179   QCString m_lastExportFormat;
00180   int m_lastExportSpecialOutputFlag;
00181 
00182   KSharedPtr<KoSpeaker> m_koSpeaker;
00183 };
00184 
00185 KoMainWindow::KoMainWindow( KInstance *instance, const char* name )
00186     : KParts::MainWindow( name )
00187 {
00188     setStandardToolBarMenuEnabled(true); // should there be a check for >= 3.1 ?
00189     Q_ASSERT(instance);
00190     d = new KoMainWindowPrivate;
00191 
00192     d->m_manager = new KoPartManager( this );
00193 
00194     connect( d->m_manager, SIGNAL( activePartChanged( KParts::Part * ) ),
00195              this, SLOT( slotActivePartChanged( KParts::Part * ) ) );
00196 
00197     if ( instance )
00198         setInstance( instance, false ); // don't load plugins! we don't want
00199     // the part's plugins with this shell, even though we are using the
00200     // part's instance! (Simon)
00201 
00202     QString doc;
00203     QStringList allFiles = KGlobal::dirs()->findAllResources( "data", "koffice/koffice_shell.rc" );
00204     setXMLFile( findMostRecentXMLFile( allFiles, doc ) );
00205     setLocalXMLFile( locateLocal( "data", "koffice/koffice_shell.rc" ) );
00206 
00207     KStdAction::openNew( this, SLOT( slotFileNew() ), actionCollection(), "file_new" );
00208     KStdAction::open( this, SLOT( slotFileOpen() ), actionCollection(), "file_open" );
00209     m_recent = KStdAction::openRecent( this, SLOT(slotFileOpenRecent(const KURL&)), actionCollection() );
00210     d->m_paSave = KStdAction::save( this, SLOT( slotFileSave() ), actionCollection(), "file_save" );
00211     d->m_paSaveAs = KStdAction::saveAs( this, SLOT( slotFileSaveAs() ), actionCollection(), "file_save_as" );
00212     d->m_paPrint = KStdAction::print( this, SLOT( slotFilePrint() ), actionCollection(), "file_print" );
00213     d->m_paPrintPreview = KStdAction::printPreview( this, SLOT( slotFilePrintPreview() ), actionCollection(), "file_print_preview" );
00214     d->m_sendfile = KStdAction::mail( this, SLOT( slotEmailFile() ), actionCollection(), "file_send_file");
00215 
00216     d->m_paCloseFile = KStdAction::close( this, SLOT( slotFileClose() ), actionCollection(), "file_close" );
00217     KStdAction::quit( this, SLOT( slotFileQuit() ), actionCollection(), "file_quit" );
00218 
00219     d->m_reloadfile = new KAction( i18n( "Reload"), 0,
00220                     this, SLOT( slotReloadFile() ),
00221                     actionCollection(), "file_reload_file");
00222 
00223     d->m_versionsfile = new KAction( i18n( "Versions..."), 0,
00224                     this, SLOT( slotVersionsFile() ),
00225                     actionCollection(), "file_versions_file");
00226 
00227     d->m_importFile = new KAction( i18n( "I&mport..." ), 0, // clashing accel key :(
00228                     this, SLOT( slotImportFile() ),
00229                     actionCollection(), "file_import_file");
00230     d->m_exportFile = new KAction( i18n( "E&xport..." ), 0,
00231                     this, SLOT( slotExportFile() ),
00232                     actionCollection(), "file_export_file");
00233 
00234     /* The following entry opens the document information dialog.  Since the action is named so it
00235         intends to show data this entry should not have a trailing ellipses (...).  */
00236     d->m_paDocInfo = new KAction( i18n( "&Document Information" ), "documentinfo", 0,
00237                         this, SLOT( slotDocumentInfo() ),
00238                         actionCollection(), "file_documentinfo" );
00239 
00240     KStdAction::keyBindings( this, SLOT( slotConfigureKeys() ), actionCollection() );
00241     KStdAction::configureToolbars( this, SLOT( slotConfigureToolbars() ), actionCollection() );
00242 
00243     d->m_paDocInfo->setEnabled( false );
00244     d->m_paSaveAs->setEnabled( false );
00245     d->m_reloadfile->setEnabled( false );
00246     d->m_versionsfile->setEnabled( false );
00247     d->m_importFile->setEnabled( true );  // always enabled like File --> Open
00248     d->m_exportFile->setEnabled( false );
00249     d->m_paSave->setEnabled( false );
00250     d->m_paPrint->setEnabled( false );
00251     d->m_paPrintPreview->setEnabled( false );
00252     d->m_sendfile->setEnabled( false);
00253     d->m_paCloseFile->setEnabled( false);
00254 
00255     d->m_splitter=new QSplitter(Qt::Vertical, this, "mw-splitter");
00256     setCentralWidget( d->m_splitter );
00257     // Keyboard accessibility enhancements.
00258     new KKbdAccessExtensions(this, "mw-panelSizer");
00259     // set up the action "list" for "Close all Views" (hacky :) (Werner)
00260     d->m_veryHackyActionList.append(
00261         new KAction(i18n("&Close All Views"), "fileclose",
00262                     "ctrl+shift+w", this, SLOT(slotCloseAllViews()),
00263                     actionCollection(), "view_closeallviews") );
00264 
00265     // set up the action list for the splitter stuff
00266     d->m_splitViewActionList.append(new KAction(i18n("&Split View"), "view_split", 0,
00267         this, SLOT(slotSplitView()),
00268         actionCollection(), "view_split"));
00269     d->m_removeView=new KAction(i18n("&Remove View"), "view_remove", 0,
00270         this, SLOT(slotRemoveView()),
00271         actionCollection(), "view_rm_splitter");
00272     d->m_splitViewActionList.append(d->m_removeView);
00273     d->m_removeView->setEnabled(false);
00274     d->m_orientation=new KSelectAction(i18n("Splitter &Orientation"), "view_orientation", 0,
00275         this, SLOT(slotSetOrientation()),
00276         actionCollection(), "view_splitter_orientation");
00277     QStringList items;
00278     items << i18n("&Vertical")
00279           << i18n("&Horizontal");
00280     d->m_orientation->setItems(items);
00281     d->m_orientation->setCurrentItem(static_cast<int>(d->m_splitter->orientation()));
00282     d->m_splitViewActionList.append(d->m_orientation);
00283     d->m_splitViewActionList.append(new KActionSeparator(this));
00284 
00285     // Load list of recent files
00286     KConfig * config = instance ? instance->config() : KGlobal::config();
00287     m_recent->loadEntries( config );
00288 
00289     createShellGUI();
00290     d->bMainWindowGUIBuilt = true;
00291 
00292     if ( !initialGeometrySet() )
00293     {
00294         // Default size
00295         const int deskWidth = KGlobalSettings::desktopGeometry(this).width();
00296         if (deskWidth > 1100) // very big desktop ?
00297             resize( 1000, 800 );
00298         if (deskWidth > 850) // big desktop ?
00299             resize( 800, 600 );
00300         else // small (800x600, 640x480) desktop
00301             resize( 600, 400 );
00302     }
00303 
00304     // Saved size
00305     config->setGroup( "MainWindow" );
00306     //kdDebug(30003) << "KoMainWindow::restoreWindowSize" << endl;
00307     restoreWindowSize( config );
00308 }
00309 
00310 KoMainWindow::~KoMainWindow()
00311 {
00312     // The doc and view might still exist (this is the case when closing the window)
00313     if (d->m_rootDoc)
00314         d->m_rootDoc->removeShell(this);
00315 
00316     if (d->m_docToOpen) {
00317       d->m_docToOpen->removeShell(this);
00318       delete d->m_docToOpen;
00319     }
00320 
00321     // safety first ;)
00322     d->m_manager->setActivePart(0);
00323 
00324     if(d->m_rootViews.findRef(d->m_activeView)==-1) {
00325         delete d->m_activeView;
00326         d->m_activeView=0L;
00327     }
00328     d->m_rootViews.setAutoDelete( true );
00329     d->m_rootViews.clear();
00330 
00331     // We have to check if this was a root document.
00332     // -> We aren't allowed to delete the (embedded) document!
00333     // This has to be checked from queryClose, too :)
00334     if ( d->m_rootDoc && d->m_rootDoc->viewCount() == 0 &&
00335          !d->m_rootDoc->isEmbedded())
00336     {
00337         //kdDebug(30003) << "Destructor. No more views, deleting old doc " << d->m_rootDoc << endl;
00338         delete d->m_rootDoc;
00339     }
00340 
00341     delete d->m_manager;
00342     delete d;
00343 }
00344 
00345 void KoMainWindow::setRootDocument( KoDocument *doc )
00346 {
00347   if ( d->m_rootDoc == doc )
00348     return;
00349 
00350   if (d->m_docToOpen && d->m_docToOpen != doc) {
00351     d->m_docToOpen->removeShell(this);
00352     delete d->m_docToOpen;
00353     d->m_docToOpen = 0;
00354   } else {
00355     d->m_docToOpen = 0;
00356   }
00357 
00358   //kdDebug(30003) <<  "KoMainWindow::setRootDocument this = " << this << " doc = " << doc << endl;
00359   QPtrList<KoView> oldRootViews = d->m_rootViews;
00360   d->m_rootViews.clear();
00361   KoDocument *oldRootDoc = d->m_rootDoc;
00362 
00363   if ( oldRootDoc )
00364     oldRootDoc->removeShell( this );
00365 
00366   d->m_rootDoc = doc;
00367 
00368   if ( doc )
00369   {
00370     doc->setSelectable( false );
00371     //d->m_manager->addPart( doc, false ); // done by KoView::setPartManager
00372     d->m_rootViews.append( doc->createView( d->m_splitter, "view" /*not unique, but better than unnamed*/ ) );
00373     d->m_rootViews.current()->setPartManager( d->m_manager );
00374 
00375     d->m_rootViews.current()->show();
00376     // The addShell has been done already if using openURL
00377     if ( !d->m_rootDoc->shells().contains( this ) )
00378         d->m_rootDoc->addShell( this );
00379     d->m_removeView->setEnabled(false);
00380     d->m_orientation->setEnabled(false);
00381   }
00382 
00383   bool enable = d->m_rootDoc != 0 ? true : false;
00384   d->m_paDocInfo->setEnabled( enable );
00385   d->m_paSave->setEnabled( enable );
00386   d->m_paSaveAs->setEnabled( enable );
00387   d->m_importFile->setEnabled( enable );
00388   d->m_exportFile->setEnabled( enable );
00389   d->m_paPrint->setEnabled( enable );
00390   d->m_paPrintPreview->setEnabled( enable );
00391   d->m_sendfile->setEnabled( enable);
00392   d->m_paCloseFile->setEnabled( enable);
00393   updateCaption();
00394 
00395   d->m_manager->setActivePart( d->m_rootDoc, d->m_rootViews.current() );
00396 
00397   oldRootViews.setAutoDelete( true );
00398   oldRootViews.clear();
00399 
00400   if ( oldRootDoc && oldRootDoc->viewCount() == 0 )
00401   {
00402     //kdDebug(30003) << "No more views, deleting old doc " << oldRootDoc << endl;
00403     delete oldRootDoc;
00404   }
00405 }
00406 
00407 void KoMainWindow::updateReloadFileAction(KoDocument *doc)
00408 {
00409     d->m_reloadfile->setEnabled( doc && !doc->url().isEmpty() );
00410 }
00411 
00412 void KoMainWindow::updateVersionsFileAction(KoDocument *doc)
00413 {
00414     //TODO activate it just when we save it in oasis file format
00415     d->m_versionsfile->setEnabled( doc && !doc->url().isEmpty()&&doc->isModified());
00416 }
00417 
00418 
00419 void KoMainWindow::setRootDocumentDirect( KoDocument *doc, const QPtrList<KoView> & views )
00420 {
00421   d->m_rootDoc = doc;
00422   d->m_rootViews = views;
00423   bool enable = d->m_rootDoc != 0 ? true : false;
00424   d->m_paDocInfo->setEnabled( enable );
00425   d->m_paSave->setEnabled( enable );
00426   d->m_paSaveAs->setEnabled( enable );
00427   d->m_exportFile->setEnabled( enable );
00428   d->m_paPrint->setEnabled( enable );
00429   d->m_paPrintPreview->setEnabled( enable );
00430   d->m_sendfile->setEnabled( enable);
00431   d->m_paCloseFile->setEnabled( enable );
00432 }
00433 
00434 void KoMainWindow::addRecentURL( const KURL& url )
00435 {
00436     kdDebug(30003) << "KoMainWindow::addRecentURL url=" << url.prettyURL() << endl;
00437     // Add entry to recent documents list
00438     // (call coming from KoDocument because it must work with cmd line, template dlg, file/open, etc.)
00439     if ( !url.isEmpty() )
00440     {
00441         bool ok = true;
00442         if ( url.isLocalFile() )
00443         {
00444             QString path = url.path( -1 );
00445             QStringList tmpDirs = KGlobal::dirs()->resourceDirs( "tmp" );
00446             for ( QStringList::Iterator it = tmpDirs.begin() ; ok && it != tmpDirs.end() ; ++it )
00447                 if ( path.contains( *it ) )
00448                     ok = false; // it's in the tmp resource
00449             if ( ok )
00450                 KRecentDocument::add(path);
00451         }
00452         else
00453             KRecentDocument::add(url.url(-1), true);
00454 
00455         if ( ok )
00456             m_recent->addURL( url );
00457         saveRecentFiles();
00458     }
00459 }
00460 
00461 void KoMainWindow::saveRecentFiles()
00462 {
00463     // Save list of recent files
00464     KConfig * config = instance() ? instance()->config() : KGlobal::config();
00465     kdDebug(30003) << this << " Saving recent files list into config. instance()=" << instance() << endl;
00466     m_recent->saveEntries( config );
00467     config->sync();
00468     if (KMainWindow::memberList)
00469     {
00470         // Tell all windows to reload their list, after saving
00471         // Doesn't work multi-process, but it's a start
00472         KMainWindow *window = KMainWindow::memberList->first();
00473         for (; window; window = KMainWindow::memberList->next())
00474             static_cast<KoMainWindow *>(window)->reloadRecentFileList();
00475     }
00476 }
00477 
00478 void KoMainWindow::reloadRecentFileList()
00479 {
00480     KConfig * config = instance() ? instance()->config() : KGlobal::config();
00481     m_recent->loadEntries( config );
00482 }
00483 
00484 KoDocument* KoMainWindow::createDoc() const
00485 {
00486     KoDocumentEntry entry = KoDocumentEntry( KoDocument::readNativeService() );
00487     return entry.createDoc();
00488 }
00489 
00490 void KoMainWindow::updateCaption()
00491 {
00492   //kdDebug(30003) << "KoMainWindow::updateCaption()" << endl;
00493   if ( !d->m_rootDoc )
00494     setCaption(QString::null);
00495   else if ( rootDocument()->isCurrent() )
00496   {
00497       QString caption;
00498       // Get caption from document info (title(), in about page)
00499       if ( rootDocument()->documentInfo() )
00500       {
00501           KoDocumentInfoPage * page = rootDocument()->documentInfo()->page( QString::fromLatin1("about") );
00502           if (page)
00503               caption = static_cast<KoDocumentInfoAbout *>(page)->title();
00504       }
00505       const QString url = rootDocument()->url().prettyURL( 0, KURL::StripFileProtocol );
00506       if ( !caption.isEmpty() && !url.isEmpty() )
00507           caption = QString( "%1 - %2" ).arg( caption ).arg( url );
00508       else if ( caption.isEmpty() )
00509           caption = url;
00510 
00511       setCaption( caption, rootDocument()->isModified() );
00512       if ( !rootDocument()->url().fileName(false).isEmpty() )
00513         d->m_paSave->setToolTip( i18n("Save as %1").arg(rootDocument()->url().fileName(false)) );
00514       else
00515         d->m_paSave->setToolTip( i18n("Save") );
00516   }
00517 }
00518 
00519 void KoMainWindow::updateCaption( QString caption, bool mod )
00520 {
00521   //kdDebug(30003)<<"KoMainWindow::updateCaption("<<caption<<","<<mod<<")"<<endl;
00522   setCaption( caption, mod );
00523 }
00524 
00525 KoDocument *KoMainWindow::rootDocument() const
00526 {
00527     return d->m_rootDoc;
00528 }
00529 
00530 KoView *KoMainWindow::rootView() const
00531 {
00532   if(d->m_rootViews.find(d->m_activeView)!=-1)
00533     return d->m_activeView;
00534   return d->m_rootViews.first();
00535 }
00536 
00537 KParts::PartManager *KoMainWindow::partManager()
00538 {
00539   return d->m_manager;
00540 }
00541 
00542 bool KoMainWindow::openDocument( const KURL & url )
00543 {
00544     if ( !KIO::NetAccess::exists(url,true,0) )
00545     {
00546         KMessageBox::error(0L, i18n("The file %1 does not exist.").arg(url.url()) );
00547         m_recent->removeURL(url); //remove the file from the recent-opened-file-list
00548         saveRecentFiles();
00549         return false;
00550     }
00551     return  openDocumentInternal( url );
00552 }
00553 
00554 // (not virtual)
00555 bool KoMainWindow::openDocument( KoDocument *newdoc, const KURL & url )
00556 {
00557     if (!KIO::NetAccess::exists(url,true,0) )
00558     {
00559         if (!newdoc->checkAutoSaveFile())
00560         {
00561           newdoc->initEmpty(); //create an emtpy document
00562         }
00563 
00564         setRootDocument( newdoc );
00565         newdoc->setURL(url);
00566         QString mime = KMimeType::findByURL(url)->name();
00567         if ( mime.isEmpty() || mime == KMimeType::defaultMimeType() )
00568             mime = newdoc->nativeFormatMimeType();
00569         if ( url.isLocalFile() ) // workaround for kde<=3.3 kparts bug, fixed for 3.4
00570             newdoc->setFile(url.path());
00571         newdoc->setMimeTypeAfterLoading( mime );
00572         updateCaption();
00573         return true;
00574     }
00575     return openDocumentInternal( url, newdoc );
00576 }
00577 
00578 // ## If you modify anything here, please check KoShellWindow::openDocumentInternal
00579 bool KoMainWindow::openDocumentInternal( const KURL & url, KoDocument *newdoc )
00580 {
00581     //kdDebug(30003) << "KoMainWindow::openDocument " << url.url() << endl;
00582 
00583     if ( !newdoc )
00584         newdoc = createDoc();
00585 
00586     d->m_firstTime=true;
00587     connect(newdoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
00588     connect(newdoc, SIGNAL(completed()), this, SLOT(slotLoadCompleted()));
00589     connect(newdoc, SIGNAL(canceled( const QString & )), this, SLOT(slotLoadCanceled( const QString & )));
00590     newdoc->addShell( this ); // used by openURL
00591     bool openRet = (!isImporting ()) ? newdoc->openURL(url) : newdoc->import(url);
00592     if(!newdoc || !openRet)
00593     {
00594         newdoc->removeShell(this);
00595         delete newdoc;
00596         return false;
00597     }
00598     updateReloadFileAction(newdoc);
00599     updateVersionsFileAction( newdoc );
00600     return true;
00601 }
00602 
00603 // Separate from openDocument to handle async loading (remote URLs)
00604 void KoMainWindow::slotLoadCompleted()
00605 {
00606     kdDebug(30003) << "KoMainWindow::slotLoadCompleted" << endl;
00607     KoDocument* doc = rootDocument();
00608     KoDocument* newdoc = (KoDocument *)(sender());
00609 
00610     if ( doc && doc->isEmpty() && !doc->isEmbedded() )
00611     {
00612         // Replace current empty document
00613         setRootDocument( newdoc );
00614     }
00615     else if ( doc && !doc->isEmpty() )
00616     {
00617         // Open in a new shell
00618         // (Note : could create the shell first and the doc next for this
00619         // particular case, that would give a better user feedback...)
00620         KoMainWindow *s = new KoMainWindow( newdoc->instance() );
00621         s->show();
00622         newdoc->removeShell( this );
00623         s->setRootDocument( newdoc );
00624     }
00625     else
00626     {
00627         // We had no document, set the new one
00628        setRootDocument( newdoc );
00629     }
00630     disconnect(newdoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
00631     disconnect(newdoc, SIGNAL(completed()), this, SLOT(slotLoadCompleted()));
00632     disconnect(newdoc, SIGNAL(canceled( const QString & )), this, SLOT(slotLoadCanceled( const QString & )));
00633 }
00634 
00635 void KoMainWindow::slotLoadCanceled( const QString & errMsg )
00636 {
00637     kdDebug(30003) << "KoMainWindow::slotLoadCanceled" << endl;
00638     if ( !errMsg.isEmpty() ) // empty when canceled by user
00639         KMessageBox::error( this, errMsg );
00640     // ... can't delete the document, it's the one who emitted the signal...
00641 
00642     KoDocument* newdoc = (KoDocument *)(sender());
00643     disconnect(newdoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
00644     disconnect(newdoc, SIGNAL(completed()), this, SLOT(slotLoadCompleted()));
00645     disconnect(newdoc, SIGNAL(canceled( const QString & )), this, SLOT(slotLoadCanceled( const QString & )));
00646 
00647     newdoc->removeShell(this);
00648     delete newdoc;
00649 }
00650 
00651 void KoMainWindow::slotSaveCanceled( const QString &errMsg )
00652 {
00653     kdDebug(30003) << "KoMainWindow::slotSaveCanceled" << endl;
00654     if ( !errMsg.isEmpty() ) // empty when canceled by user
00655         KMessageBox::error( this, errMsg );
00656     slotSaveCompleted();
00657 }
00658 
00659 void KoMainWindow::slotSaveCompleted()
00660 {
00661     kdDebug(30003) << "KoMainWindow::slotSaveCompleted" << endl;
00662     KoDocument* pDoc = (KoDocument *)(sender());
00663     disconnect(pDoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
00664     disconnect(pDoc, SIGNAL(completed()), this, SLOT(slotSaveCompleted()));
00665     disconnect(pDoc, SIGNAL(canceled( const QString & )),
00666                this, SLOT(slotSaveCanceled( const QString & )));
00667 }
00668 
00669 // returns true if we should save, false otherwise.
00670 bool KoMainWindow::exportConfirmation( const QCString &outputFormat )
00671 {
00672     if (!rootDocument()->wantExportConfirmation()) return true;
00673     KMimeType::Ptr mime = KMimeType::mimeType( outputFormat );
00674 
00675     const bool neverHeardOfIt = ( mime->name() == KMimeType::defaultMimeType() );
00676     QString comment = neverHeardOfIt ?
00677                       i18n( "%1 (unknown file type)" ).arg( outputFormat )
00678                       : mime->comment();
00679 
00680     // Warn the user
00681     int ret;
00682     if (!isExporting ()) // File --> Save
00683     {
00684         ret = KMessageBox::warningContinueCancel
00685               (
00686                   this,
00687                   i18n( "<qt>Saving as a %1 may result in some loss of formatting."
00688                         "<p>Do you still want to save in this format?</qt>" )
00689                   .arg( QString( "<b>%1</b>" ).arg( comment ) ), // in case we want to remove the bold later
00690                   i18n( "Confirm Save" ),
00691                   KStdGuiItem::save (),
00692                   "NonNativeSaveConfirmation",
00693                   true
00694                   );
00695     }
00696     else // File --> Export
00697     {
00698         ret = KMessageBox::warningContinueCancel
00699               (
00700                   this,
00701                   i18n( "<qt>Exporting as a %1 may result in some loss of formatting."
00702                         "<p>Do you still want to export to this format?</qt>" )
00703                   .arg( QString( "<b>%1</b>" ).arg( comment ) ), // in case we want to remove the bold later
00704                   i18n( "Confirm Export" ),
00705                   i18n ("Export"),
00706                   "NonNativeExportConfirmation", // different to the one used for Save (above)
00707                   true
00708                   );
00709     }
00710 
00711     return (ret == KMessageBox::Continue);
00712 }
00713 
00714 bool KoMainWindow::saveDocument( bool saveas, bool silent )
00715 {
00716     KoDocument* pDoc = rootDocument();
00717     if(!pDoc)
00718         return true;
00719 
00720     bool reset_url;
00721     if ( pDoc->url().isEmpty() )
00722     {
00723         emit saveDialogShown();
00724         reset_url = true;
00725         saveas = true;
00726     }
00727     else
00728         reset_url = false;
00729 
00730     connect(pDoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
00731     connect(pDoc, SIGNAL(completed()), this, SLOT(slotSaveCompleted()));
00732     connect(pDoc, SIGNAL(canceled( const QString & )),
00733             this, SLOT(slotSaveCanceled( const QString & )));
00734 
00735     KURL oldURL = pDoc->url();
00736     QString oldFile = pDoc->file();
00737     QCString _native_format = pDoc->nativeFormatMimeType();
00738     QCString oldOutputFormat = pDoc->outputMimeType();
00739     int oldSpecialOutputFlag = pDoc->specialOutputFlag();
00740     KURL suggestedURL = pDoc->url();
00741 
00742     QStringList mimeFilter = KoFilterManager::mimeFilter( _native_format, KoFilterManager::Export, pDoc->extraNativeMimeTypes() );
00743     if (mimeFilter.findIndex (oldOutputFormat) < 0 && !isExporting())
00744     {
00745         kdDebug(30003) << "KoMainWindow::saveDocument no export filter for '" << oldOutputFormat << "'" << endl;
00746 
00747         // --- don't setOutputMimeType in case the user cancels the Save As
00748         // dialog and then tries to just plain Save ---
00749 
00750         // suggest a different filename extension (yes, we fortunately don't all live in a world of magic :))
00751         QString suggestedFilename = suggestedURL.fileName ();
00752         if ( !suggestedFilename.isEmpty () ) // ".kwd" looks strange for a name
00753         {
00754             int c = suggestedFilename.findRev ('.');
00755 
00756             KMimeType::Ptr mime = KMimeType::mimeType( _native_format );
00757             QString ext = mime->property( "X-KDE-NativeExtension" ).toString();
00758             if (!ext.isEmpty ())
00759             {
00760                 if (c < 0)
00761                     suggestedFilename += ext;
00762                 else
00763                     suggestedFilename = suggestedFilename.left (c) + ext;
00764             }
00765             else  // current filename extension wrong anyway
00766             {
00767                 if (c > 0)
00768                 {
00769                     // this assumes that a . signifies an extension, not just a .
00770                     suggestedFilename = suggestedFilename.left (c);
00771                 }
00772             }
00773 
00774             suggestedURL.setFileName (suggestedFilename);
00775         }
00776 
00777         // force the user to choose outputMimeType
00778         saveas = true;
00779     }
00780 
00781     bool ret = false;
00782 
00783     if ( pDoc->url().isEmpty() || saveas )
00784     {
00785         // if you're just File/Save As'ing to change filter options you
00786         // don't want to be reminded about overwriting files etc.
00787         bool justChangingFilterOptions = false;
00788 
00789         KoFileDialog *dialog = new KoFileDialog( (isExporting() && !d->m_lastExportURL.isEmpty() )? d->m_lastExportURL.url () : suggestedURL.url (),
00790                                                 QString::null, this, "file dialog", true);
00791 
00792         if (!isExporting())
00793             dialog->setCaption( i18n("Save Document As") );
00794         else
00795             dialog->setCaption( i18n("Export Document As") );
00796 
00797         dialog->setOperationMode( KFileDialog::Saving );
00798         dialog->setSpecialMimeFilter( mimeFilter,
00799                                       isExporting() ? d->m_lastExportFormat : pDoc->mimeType(),
00800                                       isExporting() ? d->m_lastExportSpecialOutputFlag : oldSpecialOutputFlag,
00801                                       _native_format,
00802                                       pDoc->supportedSpecialFormats() );
00803 
00804         KURL newURL;
00805         QCString outputFormat = _native_format;
00806         int specialOutputFlag = 0;
00807         bool bOk;
00808         do {
00809             bOk=true;
00810             if(dialog->exec()==QDialog::Accepted) {
00811                 newURL=dialog->selectedURL();
00812                 outputFormat=dialog->currentMimeFilter().latin1();
00813                 specialOutputFlag = dialog->specialEntrySelected();
00814                 kdDebug(30003) << "KoMainWindow::saveDocument outputFormat = " << outputFormat << endl;
00815 
00816                 if (!isExporting())
00817                     justChangingFilterOptions = (newURL == pDoc->url()) &&
00818                                                 (outputFormat == pDoc->mimeType()) &&
00819                                                 (specialOutputFlag == oldSpecialOutputFlag);
00820                 else
00821                     justChangingFilterOptions = (newURL == d->m_lastExportURL) &&
00822                                                 (outputFormat == d->m_lastExportFormat) &&
00823                                                 (specialOutputFlag == d->m_lastExportSpecialOutputFlag);
00824             }
00825             else
00826             {
00827                 bOk = false;
00828                 break;
00829             }
00830 
00831             if ( newURL.isEmpty() )
00832             {
00833                 bOk = false;
00834                 break;
00835             }
00836 
00837             // this file exists and we are not just clicking "Save As" to change filter options
00838             // => ask for confirmation
00839             if ( KIO::NetAccess::exists( newURL, false /*will write*/, this ) && !justChangingFilterOptions )
00840             {
00841                 bOk = KMessageBox::questionYesNo( this,
00842                                                   i18n("A document with this name already exists.\n"\
00843                                                        "Do you want to overwrite it?"),
00844                                                   i18n("Warning") ) == KMessageBox::Yes;
00845             }
00846         } while ( !bOk );
00847 
00848         delete dialog;
00849 
00850         if (bOk)
00851         {
00852             bool wantToSave = true;
00853 
00854             // don't change this line unless you know what you're doing :)
00855             if (!justChangingFilterOptions || pDoc->confirmNonNativeSave (isExporting ())) {
00856                 if ( !pDoc->isNativeFormat( outputFormat ) )
00857                         wantToSave = exportConfirmation( outputFormat );
00858             }
00859 
00860             if (wantToSave)
00861             {
00862                 //
00863                 // Note:
00864                 // If the user is stupid enough to Export to the current URL,
00865                 // we do _not_ change this operation into a Save As.  Reasons
00866                 // follow:
00867                 //
00868                 // 1. A check like "isExporting() && oldURL == newURL"
00869                 //    doesn't _always_ work on case-insensitive filesystems
00870                 //    and inconsistent behaviour is bad.
00871                 // 2. It is probably not a good idea to change pDoc->mimeType
00872                 //    and friends because the next time the user File/Save's,
00873                 //    (not Save As) they won't be expecting that they are
00874                 //    using their File/Export settings
00875                 //
00876                 // As a bad side-effect of this, the modified flag will not
00877                 // be updated and it is possible that what is currently on
00878                 // their screen is not what is stored on disk (through loss
00879                 // of formatting).  But if you are dumb enough to change
00880                 // mimetype but not the filename, then arguably, _you_ are
00881                 // the "bug" :)
00882                 //
00883                 // - Clarence
00884                 //
00885 
00886 
00887                 pDoc->setOutputMimeType( outputFormat, specialOutputFlag );
00888                 if (!isExporting ())   // Save As
00889                 {
00890                     ret = pDoc->saveAs( newURL );
00891 
00892                     if (ret)
00893                     {
00894                         kdDebug(30003) << "Successful Save As!" << endl;
00895                         addRecentURL( newURL );
00896                     }
00897                     else
00898                     {
00899                         kdDebug(30003) << "Failed Save As!" << endl;
00900                         pDoc->setURL( oldURL ), pDoc->setFile( oldFile );
00901                         pDoc->setOutputMimeType( oldOutputFormat, oldSpecialOutputFlag );
00902                     }
00903                 }
00904                 else    // Export
00905                 {
00906                     ret = pDoc->exp0rt( newURL );
00907 
00908                     if (ret)
00909                     {
00910                         // a few file dialog convenience things
00911                         d->m_lastExportURL = newURL;
00912                         d->m_lastExportFormat = outputFormat;
00913                         d->m_lastExportSpecialOutputFlag = specialOutputFlag;
00914                     }
00915 
00916                     // always restore output format
00917                     pDoc->setOutputMimeType( oldOutputFormat, oldSpecialOutputFlag );
00918                 }
00919 
00920                 if (silent) // don't let the document change the window caption
00921                   pDoc->setTitleModified();
00922             }   // if (wantToSave)  {
00923             else
00924                 ret = false;
00925         }   // if (bOk) {
00926         else
00927             ret = false;
00928     }
00929     else {  // saving
00930         bool needConfirm = pDoc->confirmNonNativeSave( false ) &&
00931                            !pDoc->isNativeFormat( oldOutputFormat );
00932         if (!needConfirm ||
00933                (needConfirm && exportConfirmation( oldOutputFormat /* not so old :) */ ))
00934            )
00935         {
00936             // be sure pDoc has the correct outputMimeType!
00937             ret = pDoc->save();
00938 
00939             if (!ret)
00940             {
00941                 kdDebug(30003) << "Failed Save!" << endl;
00942                 pDoc->setURL( oldURL ), pDoc->setFile( oldFile );
00943             }
00944         }
00945         else
00946             ret = false;
00947     }
00948 
00949 // Now that there's a File/Export option, this is no longer necessary.
00950 // If you continue to use File/Save to export to a foreign format,
00951 // this signals your intention to continue working in a foreign format.
00952 // You have already been warned by the DoNotAskAgain exportConfirmation
00953 // about losing formatting when you first saved so don't set modified
00954 // here or else it will be reported as a bug by some MSOffice user.
00955 // You have been warned!  Do not click DoNotAskAgain!!!
00956 #if 0
00957     if (ret && !isExporting())
00958     {
00959         // When exporting to a non-native format, we don't reset modified.
00960         // This way the user will be reminded to save it again in the native format,
00961         // if he/she doesn't want to lose formatting.
00962         if ( wasModified && pDoc->outputMimeType() != _native_format )
00963             pDoc->setModified( true );
00964     }
00965 #endif
00966 
00967     if (!ret && reset_url)
00968         pDoc->resetURL(); //clean the suggested filename as the save dialog was rejected
00969     return ret;
00970 }
00971 
00972 void KoMainWindow::closeEvent(QCloseEvent *e) {
00973     if(queryClose()) {
00974         saveWindowSettings();
00975         setRootDocument(0L);
00976         KParts::MainWindow::closeEvent(e);
00977     }
00978 }
00979 
00980 void KoMainWindow::saveWindowSettings()
00981 {
00982     if (d->m_windowSizeDirty && rootDocument())
00983     {
00984         // Save window size into the config file of our instance
00985         instance()->config()->setGroup( "MainWindow" );
00986         //kdDebug(30003) << "KoMainWindow::saveWindowSettings" << endl;
00987         saveWindowSize( instance()->config() );
00988         d->m_windowSizeDirty = false;
00989         // Save toolbar position into the config file of the app, under the doc's instance name
00990         //kdDebug(30003) << "KoMainWindow::closeEvent -> saveMainWindowSettings rootdoc's instance=" << rootDocument()->instance()->instanceName() << endl;
00991         saveMainWindowSettings( KGlobal::config(), rootDocument()->instance()->instanceName() );
00992         KGlobal::config()->sync();
00993         resetAutoSaveSettings(); // Don't let KMainWindow override the good stuff we wrote down
00994     }
00995 }
00996 
00997 void KoMainWindow::resizeEvent( QResizeEvent * e )
00998 {
00999     d->m_windowSizeDirty = true;
01000     KParts::MainWindow::resizeEvent( e );
01001 }
01002 
01003 bool KoMainWindow::queryClose()
01004 {
01005     if ( rootDocument() == 0 )
01006         return true;
01007     //kdDebug(30003) << "KoMainWindow::queryClose() viewcount=" << rootDocument()->viewCount()
01008     //               << " shellcount=" << rootDocument()->shellCount() << endl;
01009     if ( !d->m_forQuit && rootDocument()->shellCount() > 1 )
01010         // there are more open, and we are closing just one, so no problem for closing
01011         return true;
01012 
01013     // see DTOR for a descr. of the test
01014     if ( d->m_rootDoc->isEmbedded() )
01015         return true;
01016 
01017     // main doc + internally stored child documents
01018     if ( d->m_rootDoc->isModified() )
01019     {
01020         QString name;
01021         if ( rootDocument()->documentInfo() )
01022         {
01023             name = rootDocument()->documentInfo()->title();
01024         }
01025         if ( name.isEmpty() )
01026             name = rootDocument()->url().fileName();
01027 
01028         if ( name.isEmpty() )
01029             name = i18n( "Untitled" );
01030 
01031         int res = KMessageBox::warningYesNoCancel( this,
01032                         i18n( "<p>The document <b>'%1'</b> has been modified.</p><p>Do you want to save it?</p>" ).arg(name),
01033                         QString::null,
01034                         KStdGuiItem::save(),
01035                         KStdGuiItem::discard());
01036 
01037         switch(res) {
01038             case KMessageBox::Yes : {
01039                 d->m_rootDoc->setDoNotSaveExtDoc(); // external docs are saved later
01040                 bool isNative = ( d->m_rootDoc->outputMimeType() == d->m_rootDoc->nativeFormatMimeType() );
01041                 if (! saveDocument( !isNative ) )
01042                     return false;
01043                 break;
01044             }
01045             case KMessageBox::No :
01046                 rootDocument()->removeAutoSaveFiles();
01047                 rootDocument()->setModified( false ); // Now when queryClose() is called by closeEvent it won't do anything.
01048                 break;
01049             default : // case KMessageBox::Cancel :
01050                 return false;
01051         }
01052     }
01053 
01054     if ( d->m_rootDoc->queryCloseExternalChildren() == KMessageBox::Cancel )
01055     {
01056         return false;
01057     }
01058 
01059     return true;
01060 }
01061 
01062 // Helper method for slotFileNew and slotFileClose
01063 void KoMainWindow::chooseNewDocument( int /*KoDocument::InitDocFlags*/ initDocFlags )
01064 {
01065     KoDocument* doc = rootDocument();
01066     KoDocument *newdoc = createDoc();
01067 
01068     if ( !newdoc )
01069         return;
01070 
01071     //FIXME: This needs to be handled differently
01072     connect(newdoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
01073     disconnect(newdoc, SIGNAL(sigProgress(int)), this, SLOT(slotProgress(int)));
01074 
01075     if ( ( !doc  && ( initDocFlags == KoDocument::InitDocFileNew ) ) || ( doc && !doc->isEmpty() ) )
01076     {
01077         KoMainWindow *s = new KoMainWindow( newdoc->instance() );
01078         s->show();
01079         newdoc->addShell( s );
01080         newdoc->showStartUpWidget( s, true /*Always show widget*/ );
01081         return;
01082     }
01083 
01084     if( doc ) {
01085         setRootDocument( 0 );
01086         delete d->m_rootDoc;
01087         d->m_rootDoc = 0;
01088     }
01089 
01090     newdoc->addShell( this );
01091     newdoc->showStartUpWidget( this, true /*Always show widget*/ );
01092 }
01093 
01094 void KoMainWindow::slotFileNew()
01095 {
01096     chooseNewDocument( KoDocument::InitDocFileNew );
01097 }
01098 
01099 void KoMainWindow::slotFileOpen()
01100 {
01101     KFileDialog *dialog = new KFileDialog(":OpenDialog", QString::null, this, "file dialog", true);
01102     if (!isImporting())
01103         dialog->setCaption( i18n("Open Document") );
01104     else
01105         dialog->setCaption( i18n("Import Document") );
01106 
01107     // The few lines below need to be kept in sync with KoTemplateChooseDia::setupFileDialog
01108     const QStringList mimeFilter = KoFilterManager::mimeFilter( KoDocument::readNativeFormatMimeType(),
01109                                                                 KoFilterManager::Import,
01110                                                                 KoDocument::readExtraNativeMimeTypes() );
01111     dialog->setMimeFilter( mimeFilter );
01112     if(dialog->exec()!=QDialog::Accepted) {
01113         delete dialog;
01114         return;
01115     }
01116     KURL url( dialog->selectedURL() );
01117     delete dialog;
01118 
01119     if ( url.isEmpty() )
01120         return;
01121 
01122     (void) openDocument( url );
01123 }
01124 
01125 void KoMainWindow::slotFileOpenRecent( const KURL & url )
01126 {
01127     (void) openDocument( url );
01128 }
01129 
01130 void KoMainWindow::slotFileSave()
01131 {
01132     if ( saveDocument() )
01133         emit documentSaved();
01134 }
01135 
01136 void KoMainWindow::slotFileSaveAs()
01137 {
01138     if ( saveDocument( true ) )
01139         emit documentSaved();
01140 }
01141 
01142 void KoMainWindow::slotDocumentInfo()
01143 {
01144   if ( !rootDocument() )
01145     return;
01146 
01147   KoDocumentInfo *docInfo = rootDocument()->documentInfo();
01148 
01149   if ( !docInfo )
01150     return;
01151 
01152   KoDocumentInfoDlg *dlg = new KoDocumentInfoDlg( docInfo, this, "documentInfoDlg" );
01153   if ( dlg->exec() )
01154   {
01155     dlg->save();
01156     rootDocument()->setModified( true );
01157     rootDocument()->setTitleModified();
01158   }
01159 
01160   delete dlg;
01161 }
01162 
01163 void KoMainWindow::slotFileClose()
01164 {
01165     if (queryClose())
01166     {
01167         saveWindowSettings();
01168         setRootDocument( 0 ); // don't delete this shell when deleting the document
01169         delete d->m_rootDoc;
01170         d->m_rootDoc = 0;
01171         chooseNewDocument( KoDocument::InitDocFileClose );
01172     }
01173 }
01174 
01175 void KoMainWindow::slotFileQuit()
01176 {
01177     close();
01178 }
01179 
01180 void KoMainWindow::print(bool quick) {
01181     if ( !rootView() )
01182     {
01183         kdDebug(30003) << "KoMainWindow::slotFilePrint : No root view!" << endl;
01184         return;
01185     }
01186 
01187     KPrinter printer( true /*, QPrinter::HighResolution*/ );
01188     QString title = rootView()->koDocument()->documentInfo()->title();
01189     QString fileName = rootView()->koDocument()->url().fileName();
01190 
01191     // strip off the native extension (I don't want foobar.kwd.ps when printing into a file)
01192     KMimeType::Ptr mime = KMimeType::mimeType( rootView()->koDocument()->outputMimeType() );
01193     if ( mime ) {
01194         QString extension = mime->property( "X-KDE-NativeExtension" ).toString();
01195 
01196         if ( fileName.endsWith( extension ) )
01197             fileName.truncate( fileName.length() - extension.length() );
01198     }
01199 
01200     if ( title.isEmpty() )
01201         title = fileName;
01202     printer.setDocName( title );
01203     printer.setDocFileName( fileName );
01204     printer.setDocDirectory( rootView()->koDocument()->url().directory() );
01205 
01206     // ### TODO: apply global koffice settings here
01207 
01208     rootView()->setupPrinter( printer );
01209 
01210     if ( quick ||  printer.setup( this ) )
01211         rootView()->print( printer );
01212 }
01213 
01214 
01215 void KoMainWindow::slotFilePrint()
01216 {
01217     print(false);
01218 }
01219 
01220 void KoMainWindow::slotFilePrintPreview()
01221 {
01222     if ( !rootView() )
01223     {
01224         kdWarning() << "KoMainWindow::slotFilePrint : No root view!" << endl;
01225         return;
01226     }
01227     KPrinter printer( false );
01228     KTempFile tmpFile;
01229     // The temp file is deleted by KoPrintPreview
01230 
01231     // This line has to be before setupPrinter to let the apps decide what to
01232     // print and what not (if they want to :)
01233     printer.setFromTo( printer.minPage(), printer.maxPage() );
01234     printer.setPreviewOnly( true );
01235     rootView()->setupPrinter( printer );
01236 
01237     QString oldFileName = printer.outputFileName();
01238     printer.setOutputFileName( tmpFile.name() );
01239     int oldNumCopies = printer.numCopies();
01240     printer.setNumCopies( 1 );
01241     // Disable kdeprint's own preview, we'd get two. This shows that KPrinter needs
01242     // a "don't use the previous settings" mode. The current way is really too much of a hack.
01243     QString oldKDEPreview = printer.option( "kde-preview" );
01244     printer.setOption( "kde-preview", "0" );
01245 
01246     rootView()->print(printer);
01247     //KoPrintPreview::preview(this, "KoPrintPreviewDialog", tmpFile.name());
01248 
01249     // Restore previous values
01250     printer.setOutputFileName( oldFileName );
01251     printer.setNumCopies( oldNumCopies );
01252     printer.setOption( "kde-preview", oldKDEPreview );
01253 }
01254 
01255 void KoMainWindow::slotConfigureKeys()
01256 {
01257     guiFactory()->configureShortcuts();
01258 }
01259 
01260 void KoMainWindow::slotConfigureToolbars()
01261 {
01262     if (rootDocument())
01263         saveMainWindowSettings( KGlobal::config(), rootDocument()->instance()->instanceName() );
01264     KEditToolbar edit(factory(), this);
01265     connect(&edit,SIGNAL(newToolbarConfig()),this,SLOT(slotNewToolbarConfig()));
01266     (void) edit.exec();
01267 }
01268 
01269 void KoMainWindow::slotNewToolbarConfig()
01270 {
01271   if (rootDocument())
01272       applyMainWindowSettings( KGlobal::config(), rootDocument()->instance()->instanceName() );
01273   KXMLGUIFactory *factory = guiFactory();
01274 
01275   // Check if there's an active view
01276   if( !d->m_activeView )
01277       return;
01278 
01279   // This gets plugged in even for embedded views
01280   factory->plugActionList(d->m_activeView, "view_closeallviews",
01281                           d->m_veryHackyActionList);
01282 
01283   // This one only for root views
01284   if(d->m_rootViews.findRef(d->m_activeView)!=-1)
01285     factory->plugActionList(d->m_activeView, "view_split",
01286                             d->m_splitViewActionList );
01287   plugActionList( "toolbarlist", d->m_toolbarList );
01288 }
01289 
01290 void KoMainWindow::slotToolbarToggled( bool toggle )
01291 {
01292   //kdDebug(30003) << "KoMainWindow::slotToolbarToggled " << sender()->name() << " toggle=" << true << endl;
01293   // The action (sender) and the toolbar have the same name
01294   KToolBar * bar = toolBar( sender()->name() );
01295   if (bar)
01296   {
01297     if (toggle)
01298       bar->show();
01299     else
01300       bar->hide();
01301 
01302     if (rootDocument())
01303         saveMainWindowSettings( KGlobal::config(), rootDocument()->instance()->instanceName() );
01304   }
01305   else
01306     kdWarning(30003) << "slotToolbarToggled : Toolbar " << sender()->name() << " not found!" << endl;
01307 }
01308 
01309 bool KoMainWindow::toolbarIsVisible(const char *tbName)
01310 {
01311     QWidget *tb = toolBar( tbName);
01312     return !tb->isHidden();
01313 }
01314 
01315 void KoMainWindow::showToolbar( const char * tbName, bool shown )
01316 {
01317     QWidget * tb = toolBar( tbName );
01318     if ( !tb )
01319     {
01320         kdWarning(30003) << "KoMainWindow: toolbar " << tbName << " not found." << endl;
01321         return;
01322     }
01323     if ( shown )
01324         tb->show();
01325     else
01326         tb->hide();
01327 
01328     // Update the action appropriately
01329     QPtrListIterator<KAction> it( d->m_toolbarList );
01330     for ( ; it.current() ; ++it )
01331         if ( !strcmp( it.current()->name(), tbName ) )
01332         {
01333             //kdDebug(30003) << "KoMainWindow::showToolbar setChecked " << shown << endl;
01334             static_cast<KToggleAction *>(it.current())->setChecked( shown );
01335             break;
01336         }
01337 }
01338 
01339 void KoMainWindow::slotSplitView() {
01340     d->m_splitted=true;
01341     d->m_rootViews.append(d->m_rootDoc->createView(d->m_splitter, "splitted-view"));
01342     d->m_rootViews.current()->show();
01343     d->m_rootViews.current()->setPartManager( d->m_manager );
01344     d->m_manager->setActivePart( d->m_rootDoc, d->m_rootViews.current() );
01345     d->m_removeView->setEnabled(true);
01346     d->m_orientation->setEnabled(true);
01347 }
01348 
01349 void KoMainWindow::slotCloseAllViews() {
01350 
01351     // Attention: Very touchy code... you know what you're doing? Goooood :)
01352     d->m_forQuit=true;
01353     if(queryClose()) {
01354         // In case the document is embedded we close all open "extra-shells"
01355         if(d->m_rootDoc && d->m_rootDoc->isEmbedded()) {
01356             hide();
01357             d->m_rootDoc->removeShell(this);
01358             QPtrListIterator<KoMainWindow> it(d->m_rootDoc->shells());
01359             while (it.current()) {
01360                 it.current()->hide();
01361                 delete it.current(); // this updates the lists' current pointer and thus
01362                                      // the iterator (the shell dtor calls removeShell)
01363             d->m_rootDoc=0;
01364             }
01365         }
01366         // not embedded -> destroy the document and all shells/views ;)
01367         else
01368             setRootDocument( 0L );
01369         close();  // close this window (and quit the app if necessary)
01370     }
01371     d->m_forQuit=false;
01372 }
01373 
01374 void KoMainWindow::slotRemoveView() {
01375     KoView *view;
01376     if(d->m_rootViews.findRef(d->m_activeView)!=-1)
01377         view=d->m_rootViews.current();
01378     else
01379         view=d->m_rootViews.first();
01380     view->hide();
01381     if ( !d->m_rootViews.removeRef(view) )
01382         kdWarning() << "view not found in d->m_rootViews!" << endl;
01383 
01384     if(d->m_rootViews.count()==1)
01385     {
01386         d->m_removeView->setEnabled(false);
01387         d->m_orientation->setEnabled(false);
01388     }
01389     // Prevent the view's destroyed() signal from triggering GUI rebuilding (too early)
01390     d->m_manager->setActivePart( 0, 0 );
01391 
01392     delete view;
01393     view=0L;
01394 
01395     d->m_rootViews.first()->setPartManager( d->m_manager );
01396     d->m_manager->setActivePart( d->m_rootDoc, d->m_rootViews.first() );
01397 
01398     if(d->m_rootViews.count()==1)
01399         d->m_splitted=false;
01400 }
01401 
01402 void KoMainWindow::slotSetOrientation() {
01403     d->m_splitter->setOrientation(static_cast<Qt::Orientation>
01404                                   (d->m_orientation->currentItem()));
01405 }
01406 
01407 void KoMainWindow::slotProgress(int value) {
01408     //kdDebug(30003) << "KoMainWindow::slotProgress " << value << endl;
01409     if(value==-1) {
01410         if ( d->m_progress )
01411         {
01412             statusBar()->removeWidget(d->m_progress);
01413             delete d->m_progress;
01414             d->m_progress=0L;
01415         }
01416         d->m_firstTime=true;
01417         return;
01418     }
01419     if(d->m_firstTime)
01420     {
01421         // The statusbar might not even be created yet.
01422         // So check for that first, and create it if necessary
01423         QObjectList *l = queryList( "QStatusBar" );
01424         if ( !l || !l->first() ) {
01425             statusBar()->show();
01426             QApplication::sendPostedEvents( this, QEvent::ChildInserted );
01427             setUpLayout();
01428         }
01429         delete l;
01430 
01431         if ( d->m_progress )
01432         {
01433             statusBar()->removeWidget(d->m_progress);
01434             delete d->m_progress;
01435             d->m_progress=0L;
01436         }
01437         statusBar()->setMaximumHeight(statusBar()->height());
01438         d->m_progress=new KProgress(statusBar());
01439         //d->m_progress->setMaximumHeight(statusBar()->height());
01440         statusBar()->addWidget( d->m_progress, 0, true );
01441         d->m_progress->show();
01442         d->m_firstTime=false;
01443     }
01444     d->m_progress->setProgress(value);
01445     kapp->processEvents();
01446 }
01447 
01448 
01449 void KoMainWindow::slotActivePartChanged( KParts::Part *newPart )
01450 {
01451 
01452   // This looks very much like KParts::MainWindow::createGUI, but we have
01453   // to reimplement it because it works with an active part, whereas we work
01454   // with an active view _and_ an active part, depending for what.
01455   // Both are KXMLGUIClients, but e.g. the plugin query needs a QObject.
01456   //kdDebug(30003) <<  "KoMainWindow::slotActivePartChanged( Part * newPart) newPart = " << newPart << endl;
01457   //kdDebug(30003) <<  "current active part is " << d->m_activePart << endl;
01458 
01459   if ( d->m_activePart && d->m_activePart == newPart && !d->m_splitted )
01460   {
01461     //kdDebug(30003) << "no need to change the GUI" << endl;
01462     return;
01463   }
01464 
01465   KXMLGUIFactory *factory = guiFactory();
01466 
01467   setUpdatesEnabled( false );
01468 
01469   if ( d->m_activeView )
01470   {
01471     KParts::GUIActivateEvent ev( false );
01472     QApplication::sendEvent( d->m_activePart, &ev );
01473     QApplication::sendEvent( d->m_activeView, &ev );
01474 
01475 
01476     factory->removeClient( d->m_activeView );
01477 
01478     unplugActionList( "toolbarlist" );
01479     d->m_toolbarList.clear(); // deletes the actions
01480   }
01481 
01482   if ( !d->bMainWindowGUIBuilt )
01483   {
01484     // Load mainwindow plugins
01485     KParts::Plugin::loadPlugins( this, this, instance(), true );
01486     createShellGUI();
01487   }
01488 
01489   if ( newPart && d->m_manager->activeWidget() && d->m_manager->activeWidget()->inherits( "KoView" ) )
01490   {
01491     d->m_activeView = (KoView *)d->m_manager->activeWidget();
01492     d->m_activePart = newPart;
01493     //kdDebug(30003) <<  "new active part is " << d->m_activePart << endl;
01494 
01495     factory->addClient( d->m_activeView );
01496 
01497 
01498     // This gets plugged in even for embedded views
01499     factory->plugActionList(d->m_activeView, "view_closeallviews",
01500                             d->m_veryHackyActionList);
01501     // This one only for root views
01502     if(d->m_rootViews.findRef(d->m_activeView)!=-1)
01503         factory->plugActionList(d->m_activeView, "view_split", d->m_splitViewActionList );
01504 
01505     // Position and show toolbars according to user's preference
01506     setAutoSaveSettings( newPart->instance()->instanceName(), false );
01507 
01508     // Create and plug toolbar list for Settings menu
01509     //QPtrListIterator<KToolBar> it = toolBarIterator();
01510     QPtrList<QWidget> toolBarList = factory->containers( "ToolBar" );
01511     QPtrListIterator<QWidget> it( toolBarList );
01512     for ( ; it.current() ; ++it )
01513     {
01514       if ( it.current()->inherits("KToolBar") )
01515       {
01516           KToolBar * tb = static_cast<KToolBar *>(it.current());
01517           KToggleAction * act = new KToggleAction( i18n("Show %1 Toolbar").arg( tb->text() ), 0,
01518                                                actionCollection(), tb->name() );
01519       act->setCheckedState(i18n("Hide %1 Toolbar").arg( tb->text() ));
01520       connect( act, SIGNAL( toggled( bool ) ), this, SLOT( slotToolbarToggled( bool ) ) );
01521           act->setChecked ( !tb->isHidden() );
01522           d->m_toolbarList.append( act );
01523       }
01524       else
01525           kdWarning(30003) << "Toolbar list contains a " << it.current()->className() << " which is not a toolbar!" << endl;
01526     }
01527     plugActionList( "toolbarlist", d->m_toolbarList );
01528 
01529     // Send the GUIActivateEvent only now, since it might show/hide toolbars too
01530     // (and this has priority over applyMainWindowSettings)
01531     KParts::GUIActivateEvent ev( true );
01532     QApplication::sendEvent( d->m_activePart, &ev );
01533     QApplication::sendEvent( d->m_activeView, &ev );
01534   }
01535   else
01536   {
01537     d->m_activeView = 0L;
01538     d->m_activePart = 0L;
01539   }
01540   setUpdatesEnabled( true );
01541 }
01542 
01543 QLabel * KoMainWindow::statusBarLabel()
01544 {
01545   if ( !d->statusBarLabel )
01546   {
01547     d->statusBarLabel = new QLabel( statusBar() );
01548     statusBar()->addWidget( d->statusBarLabel, 1, true );
01549   }
01550   return d->statusBarLabel;
01551 }
01552 
01553 void KoMainWindow::setMaxRecentItems(uint _number)
01554 {
01555         m_recent->setMaxItems( _number );
01556 }
01557 
01558 DCOPObject * KoMainWindow::dcopObject()
01559 {
01560     if ( !d->m_dcopObject )
01561     {
01562         d->m_dcopObject = new KoMainWindowIface( this );
01563     }
01564 
01565     return d->m_dcopObject;
01566 }
01567 
01568 void KoMainWindow::slotEmailFile()
01569 {
01570     if (!rootDocument())
01571         return;
01572 
01573     // Subject = Document file name
01574     // Attachment = The current file
01575     // Message Body = The current document in HTML export? <-- This may be an option.
01576     QString theSubject;
01577     QStringList urls;
01578     QString fileURL;
01579     if (rootDocument()->url ().isEmpty () ||
01580         rootDocument()->isModified())
01581     {
01582         //Save the file as a temporary file
01583         bool const tmp_modified = rootDocument()->isModified();
01584         KURL const tmp_url = rootDocument()->url();
01585         QCString const tmp_mimetype = rootDocument()->outputMimeType();
01586         KTempFile tmpfile; //TODO: The temorary file should be deleted when the mail program is closed
01587         KURL u;
01588         u.setPath(tmpfile.name());
01589         rootDocument()->setURL(u);
01590         rootDocument()->setModified(true);
01591         rootDocument()->setOutputMimeType(rootDocument()->nativeFormatMimeType());
01592 
01593         saveDocument(false, true);
01594 
01595         fileURL = tmpfile.name();
01596         theSubject = i18n("Document");
01597         urls.append( fileURL );
01598 
01599         rootDocument()->setURL(tmp_url);
01600         rootDocument()->setModified(tmp_modified);
01601         rootDocument()->setOutputMimeType(tmp_mimetype);
01602     }
01603     else
01604     {
01605         fileURL = rootDocument()->url().url();
01606         theSubject = i18n("Document - %1").arg(rootDocument()->url().fileName(false));
01607         urls.append( fileURL );
01608     }
01609 
01610     kdDebug(30003) << "(" << fileURL <<")" << endl;
01611 
01612     if (!fileURL.isEmpty())
01613     {
01614         kapp->invokeMailer(QString::null, QString::null, QString::null, theSubject,
01615                             QString::null, //body
01616                             QString::null,
01617                             urls); // attachments
01618     }
01619 }
01620 
01621 void KoMainWindow::slotVersionsFile()
01622 {
01623     KoVersionDialog *dlg = new KoVersionDialog(  this );
01624     dlg->exec();
01625     delete dlg;
01626 }
01627 
01628 void KoMainWindow::slotReloadFile()
01629 {
01630     KoDocument* pDoc = rootDocument();
01631     if(!pDoc || pDoc->url().isEmpty() || !pDoc->isModified())
01632         return;
01633 
01634     bool bOk = KMessageBox::questionYesNo( this,
01635                                       i18n("You will lose all your changes!\n"
01636                                            "Do you want to continue?"),
01637                                       i18n("Warning") ) == KMessageBox::Yes;
01638     if ( !bOk )
01639         return;
01640 
01641     KURL url = pDoc->url();
01642     if ( pDoc && !pDoc->isEmpty() )
01643     {
01644         setRootDocument( 0L ); // don't delete this shell when deleting the document
01645         delete d->m_rootDoc;
01646         d->m_rootDoc = 0L;
01647     }
01648     openDocument( url );
01649     return;
01650 
01651 }
01652 
01653 void KoMainWindow::slotImportFile()
01654 {
01655     kdDebug(30003) << "slotImportFile()" << endl;
01656 
01657     d->m_isImporting = true;
01658     slotFileOpen();
01659     d->m_isImporting = false;
01660 }
01661 
01662 void KoMainWindow::slotExportFile()
01663 {
01664     kdDebug(30003) << "slotExportFile()" << endl;
01665 
01666     d->m_isExporting = true;
01667     slotFileSaveAs();
01668     d->m_isExporting = false;
01669 }
01670 
01671 bool KoMainWindow::isImporting() const
01672 {
01673     return d->m_isImporting;
01674 }
01675 
01676 bool KoMainWindow::isExporting() const
01677 {
01678     return d->m_isExporting;
01679 }
01680 
01681 void KoMainWindow::setDocToOpen( KoDocument *doc )
01682 {
01683   d->m_docToOpen = doc;
01684 }
01685 
01686 #include <KoMainWindow.moc>
KDE Home | KDE Accessibility Home | Description of Access Keys