kmmainwidget.cpp 199 KB
Newer Older
1 2 3
/* -*- mode: C++; c-file-style: "gnu" -*-
  This file is part of KMail, the KDE mail client.
  Copyright (c) 2002 Don Sanders <sanders@kde.org>
4
  Copyright (c) 2009, 2010, 2011, 2012 Montel Laurent <montel@kde.org>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

  Based on the work of Stefan Taferner <taferner@kde.org>

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

  KMail is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
Stephan Kulow's avatar
Stephan Kulow committed
21

Thomas McGuire's avatar
Thomas McGuire committed
22
// KMail includes
Leo Franchi's avatar
Leo Franchi committed
23
#include "kmreadermainwin.h"
Laurent Montel's avatar
Laurent Montel committed
24
#include "editor/composer.h"
Laurent Montel's avatar
Laurent Montel committed
25
#include "searchdialog/searchwindow.h"
Laurent Montel's avatar
Laurent Montel committed
26
#include "antispam-virus/antispamwizard.h"
27
#include "widgets/vacationscriptindicatorwidget.h"
Thomas McGuire's avatar
Thomas McGuire committed
28 29 30 31 32
#include "undostack.h"
#include "kmcommands.h"
#include "kmmainwin.h"
#include "kmsystemtray.h"
#include "customtemplatesmenu.h"
33 34
#include "folderselectiondialog.h"
#include "foldertreewidget.h"
Laurent Montel's avatar
Port++  
Laurent Montel committed
35
#include "util.h"
Laurent Montel's avatar
Laurent Montel committed
36
#include "util/mailutil.h"
Laurent Montel's avatar
Laurent Montel committed
37
#include "kernel/mailkernel.h"
Laurent Montel's avatar
Laurent Montel committed
38
#include "dialog/archivefolderdialog.h"
Laurent Montel's avatar
Laurent Montel committed
39
#include "settings/globalsettings.h"
Thomas McGuire's avatar
Thomas McGuire committed
40
#include "foldertreeview.h"
Laurent Montel's avatar
Laurent Montel committed
41
#include "tag/tagactionmanager.h"
42
#include "foldershortcutactionmanager.h"
Laurent Montel's avatar
Laurent Montel committed
43
#include "widgets/collectionpane.h"
44
#if !defined(NDEBUG)
Laurent Montel's avatar
Laurent Montel committed
45 46
#include <ksieveui/debug/sievedebugdialog.h>
using KSieveUi::SieveDebugDialog;
47
#endif
48

Laurent Montel's avatar
Laurent Montel committed
49 50 51 52 53 54
#include "collectionpage/collectionmaintenancepage.h"
#include "collectionpage/collectionquotapage.h"
#include "collectionpage/collectiontemplatespage.h"
#include "collectionpage/collectionshortcutpage.h"
#include "collectionpage/collectionviewpage.h"
#include "collectionpage/collectionmailinglistpage.h"
Laurent Montel's avatar
Laurent Montel committed
55
#include "tag/tagselectdialog.h"
Laurent Montel's avatar
Laurent Montel committed
56
#include "job/createnewcontactjob.h"
57 58
#include "folderarchive/folderarchiveutil.h"
#include "folderarchive/folderarchivemanager.h"
59

Laurent Montel's avatar
Laurent Montel committed
60
#include "pimcommon/acl/collectionaclpage.h"
Laurent Montel's avatar
Laurent Montel committed
61 62 63
#include "mailcommon/collectionpage/collectiongeneralpage.h"
#include "mailcommon/collectionpage/collectionexpirypage.h"
#include "mailcommon/collectionpage/expirecollectionattribute.h"
64 65
#include "mailcommon/filter/filtermanager.h"
#include "mailcommon/filter/mailfilter.h"
Laurent Montel's avatar
Laurent Montel committed
66
#include "mailcommon/widgets/favoritecollectionwidget.h"
67 68
#include "mailcommon/folder/foldertreewidget.h"
#include "mailcommon/folder/foldertreeview.h"
Laurent Montel's avatar
Laurent Montel committed
69
#include "mailcommon/mailcommonsettings_base.h"
Stephen Kelly's avatar
Stephen Kelly committed
70
#include "kmmainwidget.h"
71

Thomas McGuire's avatar
Thomas McGuire committed
72
// Other PIM includes
73 74
#include "kdepim-version.h"

Laurent Montel's avatar
Laurent Montel committed
75
#include "messageviewer/utils/autoqpointer.h"
Laurent Montel's avatar
Laurent Montel committed
76
#include "messageviewer/settings/globalsettings.h"
Laurent Montel's avatar
Laurent Montel committed
77
#include "messageviewer/viewer/viewer.h"
Laurent Montel's avatar
Laurent Montel committed
78
#include "messageviewer/viewer/attachmentstrategy.h"
Laurent Montel's avatar
Laurent Montel committed
79 80
#include "messageviewer/header/headerstrategy.h"
#include "messageviewer/header/headerstyle.h"
81
#ifndef QT_NO_CURSOR
Laurent Montel's avatar
Laurent Montel committed
82
#include "messageviewer/utils/kcursorsaver.h"
83
#endif
84

Laurent Montel's avatar
Laurent Montel committed
85 86
#include "messagecomposer/sender/messagesender.h"
#include "messagecomposer/helper/messagehelper.h"
87 88 89

#include "templateparser/templateparser.h"

Laurent Montel's avatar
Laurent Montel committed
90
#include "messagecore/settings/globalsettings.h"
Laurent Montel's avatar
Laurent Montel committed
91
#include "messagecore/misc/mailinglist.h"
Laurent Montel's avatar
Laurent Montel committed
92
#include "messagecore/helpers/messagehelpers.h"
93

Laurent Montel's avatar
Laurent Montel committed
94
#include "dialog/kmknotify.h"
95
#include "widgets/displaymessageformatactionmenu.h"
96

Laurent Montel's avatar
Laurent Montel committed
97
#include "ksieveui/vacation/vacationmanager.h"
Laurent Montel's avatar
Laurent Montel committed
98
#include "kmconfigureagent.h"
Laurent Montel's avatar
Laurent Montel committed
99

Thomas McGuire's avatar
Thomas McGuire committed
100
// LIBKDEPIM includes
Laurent Montel's avatar
Laurent Montel committed
101
#include "progresswidget/progressmanager.h"
Laurent Montel's avatar
Laurent Montel committed
102
#include "misc/broadcaststatus.h"
103

Thomas McGuire's avatar
Thomas McGuire committed
104
// KDEPIMLIBS includes
105
#include <Akonadi/AgentManager>
106
#include <Akonadi/AttributeFactory>
Thomas McGuire's avatar
Thomas McGuire committed
107
#include <akonadi/itemfetchjob.h>
108
#include <akonadi/collectionattributessynchronizationjob.h>
Thomas McGuire's avatar
Thomas McGuire committed
109 110 111 112 113
#include <akonadi/collectionfetchjob.h>
#include <akonadi/collectionfetchscope.h>
#include <akonadi/contact/contactsearchjob.h>
#include <akonadi/collectionpropertiesdialog.h>
#include <akonadi/entitydisplayattribute.h>
Thomas McGuire's avatar
Thomas McGuire committed
114
#include <akonadi/entitylistview.h>
Stephen Kelly's avatar
Stephen Kelly committed
115
#include <akonadi/etmviewstatesaver.h>
Thomas McGuire's avatar
Thomas McGuire committed
116 117
#include <akonadi/agentinstance.h>
#include <akonadi/agenttype.h>
Laurent Montel's avatar
Laurent Montel committed
118
#include <akonadi/changerecorder.h>
Laurent Montel's avatar
Laurent Montel committed
119 120 121 122
#include <akonadi/session.h>
#include <akonadi/entitytreemodel.h>
#include <akonadi/favoritecollectionsmodel.h>
#include <akonadi/itemfetchscope.h>
123
#include <akonadi/itemmodifyjob.h>
124
#include <akonadi/control.h>
125
#include <akonadi/collectiondialog.h>
Laurent Montel's avatar
Laurent Montel committed
126
#include <akonadi/collectionstatistics.h>
127
#include <akonadi/collectionstatisticsdelegate.h>
Laurent Montel's avatar
Laurent Montel committed
128
#include <Akonadi/EntityMimeTypeFilterModel>
129
#include <akonadi/kmime/messageflags.h>
130
#include <akonadi/kmime/removeduplicatesjob.h>
131
#include <akonadi/collectiondeletejob.h>
132
#include <akonadi/dbusconnectionpool.h>
133
#include <Akonadi/CachePolicy>
134

Thomas McGuire's avatar
Thomas McGuire committed
135 136 137 138 139 140 141
#include <kpimidentities/identity.h>
#include <kpimidentities/identitymanager.h>
#include <kpimutils/email.h>
#include <mailtransport/transportmanager.h>
#include <mailtransport/transport.h>
#include <kmime/kmime_mdn.h>
#include <kmime/kmime_header_parsing.h>
142
#include <kmime/kmime_message.h>
143
#include <ksieveui/managesievescriptsdialog.h>
Laurent Montel's avatar
Laurent Montel committed
144
#include <ksieveui/util/util.h>
145

Thomas McGuire's avatar
Thomas McGuire committed
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
// KDELIBS includes
#include <kaboutdata.h>
#include <kicon.h>
#include <kwindowsystem.h>
#include <krun.h>
#include <kmessagebox.h>
#include <kactionmenu.h>
#include <kmenu.h>
#include <kacceleratormanager.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kstandardshortcut.h>
#include <kshortcutsdialog.h>
#include <kcharsets.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <ktip.h>
#include <kstandarddirs.h>
#include <kstandardaction.h>
#include <ktoggleaction.h>
#include <knotification.h>
#include <knotifyconfigwidget.h>
#include <kstringhandler.h>
#include <kconfiggroup.h>
#include <ktoolinvocation.h>
#include <kxmlguifactory.h>
#include <kxmlguiclient.h>
#include <kstatusbar.h>
#include <kaction.h>
#include <ktreewidgetsearchline.h>
176
#include <Solid/Networking>
Laurent Montel's avatar
Laurent Montel committed
177
#include <KRecentFilesAction>
178

Thomas McGuire's avatar
Thomas McGuire committed
179 180
// Qt includes
#include <QByteArray>
181
#include <QHeaderView>
Thomas McGuire's avatar
Thomas McGuire committed
182 183 184 185 186 187
#include <QLabel>
#include <QList>
#include <QSplitter>
#include <QVBoxLayout>
#include <QShortcut>
#include <QProcess>
188 189
#include <QDBusMessage>
#include <QDBusConnection>
190
#include <QTextDocument>
191
#include <QMenu>
192 193
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
194
#include <QDBusPendingCallWatcher>
195

Thomas McGuire's avatar
Thomas McGuire committed
196 197 198
// System includes
#include <assert.h>
#include <errno.h> // ugh
199
#include <akonadi/standardactionmanager.h>
200
#include <job/removeduplicatemailjob.h>
201

Thomas McGuire's avatar
Thomas McGuire committed
202 203

using namespace KMime;
204
using namespace Akonadi;
Andras Mantia's avatar
Andras Mantia committed
205
using namespace MailCommon;
Thomas McGuire's avatar
Thomas McGuire committed
206 207 208 209 210 211
using KPIM::ProgressManager;
using KPIM::BroadcastStatus;
using KMail::SearchWindow;
using KMail::AntiSpamWizard;
using KMime::Types::AddrSpecList;
using MessageViewer::AttachmentStrategy;
Stephan Kulow's avatar
Stephan Kulow committed
212

213 214
Q_DECLARE_METATYPE(KPIM::ProgressItem*)
Q_DECLARE_METATYPE(Akonadi::Job*)
215
Q_DECLARE_METATYPE(QPointer<KPIM::ProgressItem>)
216
K_GLOBAL_STATIC( KMMainWidget::PtrList, theMainWidgetList )
217

Stephan Kulow's avatar
Stephan Kulow committed
218
//-----------------------------------------------------------------------------
Laurent Montel's avatar
Laurent Montel committed
219 220
KMMainWidget::KMMainWidget( QWidget *parent, KXMLGUIClient *aGUIClient,
                            KActionCollection *actionCollection, KSharedConfig::Ptr config ) :
221
    QWidget( parent ),
222
    mMoveMsgToFolderAction(0),
Thomas McGuire's avatar
Thomas McGuire committed
223
    mCollectionProperties( 0 ),
224
    mFavoriteCollectionsView( 0 ),
225 226 227
    mMsgView( 0 ),
    mSplitter1( 0 ),
    mSplitter2( 0 ),
228
    mFolderViewSplitter( 0 ),
Thomas McGuire's avatar
Thomas McGuire committed
229
    mArchiveFolderAction( 0 ),
230
    mShowBusySplashTimer( 0 ),
231
    mMsgActions( 0 ),
Laurent Montel's avatar
Laurent Montel committed
232
    mCurrentFolder( 0 ),
233
    mVacationIndicatorActive( false ),
234
    mGoToFirstUnreadMessageInSelectedFolder( false ),
235
    mDisplayMessageFormatMenu( 0 ),
236 237
    mFolderDisplayFormatPreference(MessageViewer::Viewer::UseGlobalSetting),
    mSearchMessages( 0 )
Stephan Kulow's avatar
Stephan Kulow committed
238
{
Laurent Montel's avatar
Laurent Montel committed
239
    mConfigAgent = new KMConfigureAgent(this, this);
Laurent Montel's avatar
Laurent Montel committed
240 241 242 243 244
    // must be the first line of the constructor:
    mStartupDone = false;
    mWasEverShown = false;
    mReaderWindowActive = true;
    mReaderWindowBelow = true;
245
    mFolderHtmlLoadExtPreference = false;
Laurent Montel's avatar
Laurent Montel committed
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
    mDestructed = false;
    mActionCollection = actionCollection;
    mTopLayout = new QVBoxLayout( this );
    mTopLayout->setMargin( 0 );
    mConfig = config;
    mGUIClient = aGUIClient;
    mFolderTreeWidget = 0;
    mPreferHtmlLoadExtAction = 0;
    Akonadi::Control::widgetNeedsAkonadi( this );
    mFavoritesModel = 0;
    mVacationManager = new KSieveUi::VacationManager(this);


    // FIXME This should become a line separator as soon as the API
    // is extended in kdelibs.
    mToolbarActionSeparator = new QAction( this );
    mToolbarActionSeparator->setSeparator( true );

    theMainWidgetList->append( this );

    readPreConfig();
    createWidgets();
    setupActions();


    readConfig();

    if ( !kmkernel->isOffline() ) { //kmail is set to online mode, make sure the agents are also online
        kmkernel->setAccountStatus(true);
    }


    QTimer::singleShot( 0, this, SLOT(slotShowStartupFolder()));

    connect( kmkernel, SIGNAL(startCheckMail()),
             this, SLOT(slotStartCheckMail()) );

    connect( kmkernel, SIGNAL(endCheckMail()),
             this, SLOT(slotEndCheckMail()) );

    connect( kmkernel, SIGNAL(configChanged()),
             this, SLOT(slotConfigChanged()) );

    connect( kmkernel, SIGNAL(onlineStatusChanged(GlobalSettings::EnumNetworkState::type)),
             this, SLOT(slotUpdateOnlineStatus(GlobalSettings::EnumNetworkState::type)) );

    connect( mTagActionManager, SIGNAL(tagActionTriggered(Akonadi::Tag)),
             this, SLOT(slotUpdateMessageTagList(Akonadi::Tag)) );

    connect( mTagActionManager, SIGNAL(tagMoreActionClicked()),
             this, SLOT(slotSelectMoreMessageTagList()) );

    kmkernel->toggleSystemTray();

    { // make sure the pages are registered only once, since there can be multiple instances of KMMainWidget
        static bool pagesRegistered = false;

        if ( !pagesRegistered ) {
            Akonadi::CollectionPropertiesDialog::registerPage( new PimCommon::CollectionAclPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new MailCommon::CollectionGeneralPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new CollectionMaintenancePageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new CollectionQuotaPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new CollectionTemplatesPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new MailCommon::CollectionExpiryPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new CollectionViewPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new CollectionMailingListPageFactory );
            Akonadi::CollectionPropertiesDialog::registerPage( new CollectionShortcutPageFactory );

            pagesRegistered = true;
        }
    }

    KMainWindow *mainWin = dynamic_cast<KMainWindow*>(window());
    KStatusBar *sb =  mainWin ? mainWin->statusBar() : 0;
    mVacationScriptIndicator = new KMail::VacationScriptIndicatorWidget( sb );
    mVacationScriptIndicator->hide();
    connect( mVacationScriptIndicator, SIGNAL(clicked(QString)), SLOT(slotEditVacation(QString)) );
    if ( KSieveUi::Util::checkOutOfOfficeOnStartup() )
        QTimer::singleShot( 0, this, SLOT(slotCheckVacation()) );

    connect( mFolderTreeWidget->folderTreeView()->model(), SIGNAL(modelReset()),
             this, SLOT(restoreCollectionFolderViewConfig()) );
    restoreCollectionFolderViewConfig();

    if ( kmkernel->firstStart() ) {
        if (MailCommon::Util::foundMailer()) {
            if (KMessageBox::questionYesNo(this,i18n("Another mailer was found on system. Do you want to import data from it?")) == KMessageBox::Yes) {
                const QString path = KStandardDirs::findExe( QLatin1String("importwizard" ) );
                if ( !QProcess::startDetached( path ) ) {
                    KMessageBox::error( this, i18n( "Could not start the import wizard. "
                                                    "Please check your installation." ),
                                        i18n( "Unable to start import wizard" ) );
                }
            } else {
                KMail::Util::launchAccountWizard( this );
            }
        } else {
            KMail::Util::launchAccountWizard( this );
344 345
        }
    }
Laurent Montel's avatar
Laurent Montel committed
346 347
    // must be the last line of the constructor:
    mStartupDone = true;
348

349

Laurent Montel's avatar
Laurent Montel committed
350 351 352
    mCheckMailTimer.setInterval( 3 * 1000 );
    mCheckMailTimer.setSingleShot( true );
    connect( &mCheckMailTimer, SIGNAL(timeout()), SLOT(slotUpdateActionsAfterMailChecking()) );
353

354 355
}

356
void KMMainWidget::restoreCollectionFolderViewConfig()
357
{
Laurent Montel's avatar
Laurent Montel committed
358 359 360 361 362 363
    ETMViewStateSaver *saver = new ETMViewStateSaver;
    saver->setView( mFolderTreeWidget->folderTreeView() );
    const KConfigGroup cfg( KMKernel::self()->config(), "CollectionFolderView" );
    mFolderTreeWidget->restoreHeaderState( cfg.readEntry( "HeaderState", QByteArray() ) );
    saver->restoreState( cfg );
    //Restore startup folder
364

Laurent Montel's avatar
Laurent Montel committed
365 366 367 368
    Akonadi::Collection::Id id = -1;
    if (mCurrentFolder && mCurrentFolder->collection().isValid() ) {
        id = mCurrentFolder->collection().id();
    }
369

Laurent Montel's avatar
Laurent Montel committed
370 371 372 373 374 375 376 377
    if (id == -1) {
        if (GlobalSettings::self()->startSpecificFolderAtStartup()) {
            Akonadi::Collection::Id startupFolder = GlobalSettings::self()->startupFolder();
            if ( startupFolder > 0 )
                saver->restoreCurrentItem( QString::fromLatin1("c%1").arg(startupFolder) );
        }
    } else {
        saver->restoreCurrentItem( QString::fromLatin1("c%1").arg(id) );
378
    }
Stephan Kulow's avatar
Stephan Kulow committed
379 380 381 382 383 384
}


//-----------------------------------------------------------------------------
//The kernel may have already been deleted when this method is called,
//perform all cleanup that requires the kernel in destruct()
385
KMMainWidget::~KMMainWidget()
Stephan Kulow's avatar
Stephan Kulow committed
386
{
Laurent Montel's avatar
Laurent Montel committed
387 388 389
    theMainWidgetList->removeAll( this );
    qDeleteAll( mFilterCommands );
    destruct();
Stephan Kulow's avatar
Stephan Kulow committed
390 391 392 393 394
}


//-----------------------------------------------------------------------------
//This method performs all cleanup that requires the kernel to exist.
395
void KMMainWidget::destruct()
Stephan Kulow's avatar
Stephan Kulow committed
396
{
Laurent Montel's avatar
Laurent Montel committed
397 398 399 400 401 402 403 404 405 406
    if ( mDestructed )
        return;
    if ( mSearchWin )
        mSearchWin->close();
    writeConfig(false); /* don't force kmkernel sync when close BUG: 289287 */
    writeFolderConfig();
    deleteWidgets();
    mCurrentFolder.clear();
    delete mMoveOrCopyToDialog;
    delete mSelectFromAllFoldersDialog;
Laurent Montel's avatar
Laurent Montel committed
407

Laurent Montel's avatar
Laurent Montel committed
408 409 410 411 412
    disconnect( kmkernel->folderCollectionMonitor(), SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), this, 0);
    disconnect( kmkernel->folderCollectionMonitor(), SIGNAL(itemRemoved(Akonadi::Item)), this, 0);
    disconnect( kmkernel->folderCollectionMonitor(), SIGNAL(itemMoved(Akonadi::Item,Akonadi::Collection,Akonadi::Collection)), this, 0);
    disconnect( kmkernel->folderCollectionMonitor(), SIGNAL(collectionChanged(Akonadi::Collection,QSet<QByteArray>)), this, 0);
    disconnect( kmkernel->folderCollectionMonitor(), SIGNAL(collectionStatisticsChanged(Akonadi::Collection::Id,Akonadi::CollectionStatistics)), this, 0);
Laurent Montel's avatar
Laurent Montel committed
413

Laurent Montel's avatar
Laurent Montel committed
414
    mDestructed = true;
Stephan Kulow's avatar
Stephan Kulow committed
415 416 417
}


418 419
void KMMainWidget::slotStartCheckMail()
{
Laurent Montel's avatar
Laurent Montel committed
420 421
    if ( mCheckMailTimer.isActive() )
        mCheckMailTimer.stop();
422 423 424 425
}

void KMMainWidget::slotEndCheckMail()
{
Laurent Montel's avatar
Laurent Montel committed
426 427
    if ( !mCheckMailTimer.isActive() )
        mCheckMailTimer.start();
428 429
}

Laurent Montel's avatar
Laurent Montel committed
430
void KMMainWidget::slotUpdateActionsAfterMailChecking()
431
{
Laurent Montel's avatar
Laurent Montel committed
432 433 434 435 436 437 438 439 440 441
    const bool sendOnAll =
            GlobalSettings::self()->sendOnCheck() == GlobalSettings::EnumSendOnCheck::SendOnAllChecks;
    const bool sendOnManual =
            GlobalSettings::self()->sendOnCheck() == GlobalSettings::EnumSendOnCheck::SendOnManualChecks;
    if ( !kmkernel->isOffline() && ( sendOnAll || (sendOnManual /*&& sendOnCheck*/ ) ) ) {
        slotSendQueued();
    }
    // update folder menus in case some mail got filtered to trash/current folder
    // and we can enable "empty trash/move all to trash" action etc.
    updateFolderMenu();
442 443
}

444 445
void KMMainWidget::slotCollectionFetched( int collectionId )
{
Laurent Montel's avatar
Laurent Montel committed
446 447 448 449 450 451 452 453 454 455 456 457
    // Called when a collection is fetched for the first time by the ETM.
    // This is the right time to update the caption (which still says "Loading...")
    // and to update the actions that depend on the number of mails in the folder.
    if ( mCurrentFolder && collectionId == mCurrentFolder->collection().id() ) {
        mCurrentFolder->setCollection( MailCommon::Util::updatedCollection( mCurrentFolder->collection() ) );
        updateMessageActions();
        updateFolderMenu();
    }
    // We call this for any collection, it could be one of our parents...
    if ( mCurrentFolder ) {
        emit captionChangeRequest( MailCommon::Util::fullCollectionPath( mCurrentFolder->collection() ) );
    }
458 459
}

460
void KMMainWidget::slotFolderChanged( const Akonadi::Collection& collection )
461
{
Laurent Montel's avatar
Laurent Montel committed
462 463 464 465 466
    folderSelected( collection );
    if (collection.cachePolicy().syncOnDemand())
        AgentManager::self()->synchronizeCollection( collection, false );
    mMsgActions->setCurrentMessage( Akonadi::Item() );
    emit captionChangeRequest( MailCommon::Util::fullCollectionPath( collection ) );
Laurent Montel's avatar
Laurent Montel committed
467 468
}

Laurent Montel's avatar
Laurent Montel committed
469
void KMMainWidget::folderSelected( const Akonadi::Collection & col )
Laurent Montel's avatar
Laurent Montel committed
470
{
Laurent Montel's avatar
Laurent Montel committed
471
    // This is connected to the MainFolderView signal triggering when a folder is selected
Laurent Montel's avatar
Laurent Montel committed
472

Laurent Montel's avatar
Laurent Montel committed
473
    if ( mGoToFirstUnreadMessageInSelectedFolder )
Laurent Montel's avatar
Laurent Montel committed
474
    {
Laurent Montel's avatar
Laurent Montel committed
475
        // the default action has been overridden from outside
476
        mPreSelectionMode = MessageList::Core::PreSelectFirstUnreadCentered;
Laurent Montel's avatar
Laurent Montel committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    } else {
        // use the default action
        switch ( GlobalSettings::self()->actionEnterFolder() )
        {
        case GlobalSettings::EnumActionEnterFolder::SelectFirstUnread:
            mPreSelectionMode = MessageList::Core::PreSelectFirstUnreadCentered;
            break;
        case GlobalSettings::EnumActionEnterFolder::SelectLastSelected:
            mPreSelectionMode = MessageList::Core::PreSelectLastSelected;
            break;
        case GlobalSettings::EnumActionEnterFolder::SelectNewest:
            mPreSelectionMode = MessageList::Core::PreSelectNewestCentered;
            break;
        case GlobalSettings::EnumActionEnterFolder::SelectOldest:
            mPreSelectionMode = MessageList::Core::PreSelectOldestCentered;
            break;
        default:
            mPreSelectionMode = MessageList::Core::PreSelectNone;
            break;
        }
    }

    mGoToFirstUnreadMessageInSelectedFolder = false;
500
#ifndef QT_NO_CURSOR
Laurent Montel's avatar
Laurent Montel committed
501
    MessageViewer::KCursorSaver busy( MessageViewer::KBusyPtr::busy() );
502
#endif
Laurent Montel's avatar
Laurent Montel committed
503

Laurent Montel's avatar
Laurent Montel committed
504 505 506
    if (mMsgView)
        mMsgView->clear(true);
    const bool newFolder = mCurrentFolder && ( mCurrentFolder->collection() != col );
David Faure's avatar
David Faure committed
507

Laurent Montel's avatar
Laurent Montel committed
508 509 510 511 512 513 514 515
    // Delete any pending timer, if needed it will be recreated below
    delete mShowBusySplashTimer;
    mShowBusySplashTimer = 0;
    if ( newFolder )
    {
        // We're changing folder: write configuration for the old one
        writeFolderConfig();
    }
Laurent Montel's avatar
Laurent Montel committed
516

Laurent Montel's avatar
Laurent Montel committed
517
    mCurrentFolder = FolderCollection::forCollection( col );
Laurent Montel's avatar
Laurent Montel committed
518

Laurent Montel's avatar
Laurent Montel committed
519 520 521
    readFolderConfig();
    if (mMsgView)
    {
522
        mMsgView->setDisplayFormatMessageOverwrite(mFolderDisplayFormatPreference);
523
        mMsgView->setHtmlLoadExtOverride(mFolderHtmlLoadExtPreference);
Laurent Montel's avatar
Laurent Montel committed
524
    }
Laurent Montel's avatar
Laurent Montel committed
525

Laurent Montel's avatar
Laurent Montel committed
526 527
    if ( !mCurrentFolder->isValid() && ( mMessagePane->count() < 2 ) )
        slotIntro();
Laurent Montel's avatar
Laurent Montel committed
528

Laurent Montel's avatar
Laurent Montel committed
529 530
    updateMessageActions();
    updateFolderMenu();
531

Laurent Montel's avatar
Laurent Montel committed
532 533 534 535
    // The message pane uses the selection model of the folder view to load the correct aggregation model and theme
    //  settings. At this point the selection model hasn't been updated yet to the user's new choice, so it would load
    //  the old folder settings instead.
    QTimer::singleShot( 0, this, SLOT(slotShowSelectedFolderInPane()) );
536 537
}

Laurent Montel's avatar
Laurent Montel committed
538
void KMMainWidget::slotShowSelectedFolderInPane()
539
{
Laurent Montel's avatar
Laurent Montel committed
540 541 542
    if ( mCurrentFolder && mCurrentFolder->collection().isValid() ) {
        mMessagePane->setCurrentFolder( mCurrentFolder->collection(), false , mPreSelectionMode );
    }
543 544
}

545 546
void KMMainWidget::clearViewer()
{
Laurent Montel's avatar
Laurent Montel committed
547 548 549 550
    if (mMsgView) {
        mMsgView->clear( true );
        mMsgView->displayAboutPage();
    }
551
}
552

Stephan Kulow's avatar
Stephan Kulow committed
553
//-----------------------------------------------------------------------------
554
void KMMainWidget::readPreConfig()
Stephan Kulow's avatar
Stephan Kulow committed
555
{
Laurent Montel's avatar
Laurent Montel committed
556 557 558
    mLongFolderList = GlobalSettings::self()->folderList() == GlobalSettings::EnumFolderList::longlist;
    mReaderWindowActive = GlobalSettings::self()->readerWindowMode() != GlobalSettings::EnumReaderWindowMode::hide;
    mReaderWindowBelow = GlobalSettings::self()->readerWindowMode() == GlobalSettings::EnumReaderWindowMode::below;
Dirk Mueller's avatar
Dirk Mueller committed
559

Laurent Montel's avatar
Laurent Montel committed
560 561 562
    mHtmlGlobalSetting = MessageViewer::GlobalSettings::self()->htmlMail();
    mHtmlLoadExtGlobalSetting = MessageViewer::GlobalSettings::self()->htmlLoadExternal();

Laurent Montel's avatar
Laurent Montel committed
563 564
    mEnableFavoriteFolderView = ( MailCommon::MailCommonSettings::self()->favoriteCollectionViewMode() != MailCommon::MailCommonSettings::EnumFavoriteCollectionViewMode::HiddenMode );
    mEnableFolderQuickSearch = GlobalSettings::self()->enableFolderQuickSearch();
565
    readFolderConfig();
Laurent Montel's avatar
Laurent Montel committed
566
    updateHtmlMenuEntry();
567 568 569 570
    if (mMsgView) {
        mMsgView->setDisplayFormatMessageOverwrite(mFolderDisplayFormatPreference);
        mMsgView->update( true );
    }
Stephan Kulow's avatar
Stephan Kulow committed
571 572 573 574
}


//-----------------------------------------------------------------------------
575
void KMMainWidget::readFolderConfig()
Stephan Kulow's avatar
Stephan Kulow committed
576
{
Laurent Montel's avatar
Laurent Montel committed
577 578 579 580
    if ( !mCurrentFolder || !mCurrentFolder->isValid() )
        return;
    KSharedConfig::Ptr config = KMKernel::self()->config();
    KConfigGroup group( config, MailCommon::FolderCollection::configGroupName( mCurrentFolder->collection() ) );
581 582 583 584 585 586 587
    if (group.hasKey( "htmlMailOverride")) {
        const bool useHtml = group.readEntry( "htmlMailOverride", false );
        mFolderDisplayFormatPreference = useHtml ? MessageViewer::Viewer::Html : MessageViewer::Viewer::Text;
        group.deleteEntry("htmlMailOverride");
        group.sync();
    } else {
        mFolderDisplayFormatPreference = static_cast<MessageViewer::Viewer::DisplayFormatMessage>(group.readEntry( "displayFormatOverride", static_cast<int>(MessageViewer::Viewer::UseGlobalSetting)));
588
    }
589 590
    mFolderHtmlLoadExtPreference =
            group.readEntry( "htmlLoadExternalOverride", false );
Stephan Kulow's avatar
Stephan Kulow committed
591 592 593 594
}


//-----------------------------------------------------------------------------
595
void KMMainWidget::writeFolderConfig()
Stephan Kulow's avatar
Stephan Kulow committed
596
{
Laurent Montel's avatar
Laurent Montel committed
597 598 599
    if ( mCurrentFolder && mCurrentFolder->isValid() ) {
        KSharedConfig::Ptr config = KMKernel::self()->config();
        KConfigGroup group( config, MailCommon::FolderCollection::configGroupName( mCurrentFolder->collection() ) );
600
        group.writeEntry( "htmlLoadExternalOverride", mFolderHtmlLoadExtPreference );
601 602 603 604
        if (mFolderDisplayFormatPreference == MessageViewer::Viewer::UseGlobalSetting)
            group.deleteEntry("displayFormatOverride");
        else
            group.writeEntry( "displayFormatOverride", static_cast<int>(mFolderDisplayFormatPreference) );
Laurent Montel's avatar
Laurent Montel committed
605
    }
Stephan Kulow's avatar
Stephan Kulow committed
606 607
}

608 609 610
//-----------------------------------------------------------------------------
void KMMainWidget::layoutSplitters()
{
Laurent Montel's avatar
Laurent Montel committed
611 612 613
    // This function can only be called when the old splitters are already deleted
    assert( !mSplitter1 );
    assert( !mSplitter2 );
614

Laurent Montel's avatar
Laurent Montel committed
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
    // For some reason, this is necessary here so that the copy action still
    // works after changing the folder layout.
    if ( mMsgView )
        disconnect( mMsgView->copyAction(), SIGNAL(triggered(bool)),
                    mMsgView, SLOT(slotCopySelectedText()) );

    // If long folder list is enabled, the splitters are:
    // Splitter 1: FolderView vs (HeaderAndSearch vs MessageViewer)
    // Splitter 2: HeaderAndSearch vs MessageViewer
    //
    // If long folder list is disabled, the splitters are:
    // Splitter 1: (FolderView vs HeaderAndSearch) vs MessageViewer
    // Splitter 2: FolderView vs HeaderAndSearch

    // The folder view is both the folder tree and the favorite folder view, if
    // enabled

    const bool opaqueResize = KGlobalSettings::opaqueResize();
    const bool readerWindowAtSide = !mReaderWindowBelow && mReaderWindowActive;
    const bool readerWindowBelow = mReaderWindowBelow && mReaderWindowActive;

    mSplitter1 = new QSplitter( this );
    mSplitter2 = new QSplitter( mSplitter1 );

    QWidget * folderTreeWidget = mSearchAndTree;
    if ( mFavoriteCollectionsView ) {
        mFolderViewSplitter = new QSplitter( Qt::Vertical );
        mFolderViewSplitter->setOpaqueResize( opaqueResize );
        //mFolderViewSplitter->setChildrenCollapsible( false );
        mFolderViewSplitter->addWidget( mFavoriteCollectionsView );
        mFavoriteCollectionsView->setParent( mFolderViewSplitter );
        mFolderViewSplitter->addWidget( mSearchAndTree );
        folderTreeWidget = mFolderViewSplitter;
Till Adam's avatar
Till Adam committed
648
    }
649

Laurent Montel's avatar
Laurent Montel committed
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
    if ( mLongFolderList ) {

        // add folder tree
        mSplitter1->setOrientation( Qt::Horizontal );
        mSplitter1->addWidget( folderTreeWidget );

        // and the rest to the right
        mSplitter1->addWidget( mSplitter2 );

        // add the message list to the right or below
        if ( readerWindowAtSide ) {
            mSplitter2->setOrientation( Qt::Horizontal );
        } else {
            mSplitter2->setOrientation( Qt::Vertical );
        }
        mSplitter2->addWidget( mMessagePane );

        // add the preview window, if there is one
        if ( mMsgView ) {
            mSplitter2->addWidget( mMsgView );
        }

    } else { // short folder list
        if ( mReaderWindowBelow ) {
            mSplitter1->setOrientation( Qt::Vertical );
            mSplitter2->setOrientation( Qt::Horizontal );
        } else { // at side or none
            mSplitter1->setOrientation( Qt::Horizontal );
            mSplitter2->setOrientation( Qt::Vertical );
        }

        mSplitter1->addWidget( mSplitter2 );

        // add folder tree
        mSplitter2->addWidget( folderTreeWidget );
        // add message list to splitter 2
        mSplitter2->addWidget( mMessagePane );

        // add the preview window, if there is one
        if ( mMsgView )
            mSplitter1->addWidget( mMsgView );
Till Adam's avatar
Till Adam committed
691
    }
692

Laurent Montel's avatar
Laurent Montel committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    //
    // Set splitter properties
    //
    mSplitter1->setObjectName( QLatin1String("splitter1") );
    mSplitter1->setOpaqueResize( opaqueResize );
    //mSplitter1->setChildrenCollapsible( false );
    mSplitter2->setObjectName( QLatin1String("splitter2") );
    mSplitter2->setOpaqueResize( opaqueResize );
    //mSplitter2->setChildrenCollapsible( false );

    //
    // Set the stretch factors
    //
    mSplitter1->setStretchFactor( 0, 0 );
    mSplitter2->setStretchFactor( 0, 0 );
    mSplitter1->setStretchFactor( 1, 1 );
    mSplitter2->setStretchFactor( 1, 1 );

    if ( mFavoriteCollectionsView ) {
        mFolderViewSplitter->setStretchFactor( 0, 0 );
        mFolderViewSplitter->setStretchFactor( 1, 1 );
    }
715

Laurent Montel's avatar
Laurent Montel committed
716 717 718 719 720 721 722
    // Because the reader windows's width increases a tiny bit after each
    // restart in short folder list mode with message window at side, disable
    // the stretching as a workaround here
    if ( readerWindowAtSide && !mLongFolderList ) {
        mSplitter1->setStretchFactor( 0, 1 );
        mSplitter1->setStretchFactor( 1, 0 );
    }
723

Laurent Montel's avatar
Laurent Montel committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    //
    // Set the sizes of the splitters to the values stored in the config
    //
    QList<int> splitter1Sizes;
    QList<int> splitter2Sizes;

    const int folderViewWidth = GlobalSettings::self()->folderViewWidth();
    int ftHeight = GlobalSettings::self()->folderTreeHeight();
    int headerHeight = GlobalSettings::self()->searchAndHeaderHeight();
    const int messageViewerWidth = GlobalSettings::self()->readerWindowWidth();
    int headerWidth = GlobalSettings::self()->searchAndHeaderWidth();
    int messageViewerHeight = GlobalSettings::self()->readerWindowHeight();

    int ffvHeight = mFolderViewSplitter ? MailCommon::MailCommonSettings::self()->favoriteCollectionViewHeight() : 0;

    // If the message viewer was hidden before, make sure it is not zero height
    if ( messageViewerHeight < 10 && readerWindowBelow ) {
        headerHeight /= 2;
        messageViewerHeight = headerHeight;
743
    }
Laurent Montel's avatar
Laurent Montel committed
744 745 746 747 748 749 750 751 752

    if ( mLongFolderList ) {
        if ( !readerWindowAtSide ) {
            splitter1Sizes << folderViewWidth << headerWidth;
            splitter2Sizes << headerHeight << messageViewerHeight;
        } else {
            splitter1Sizes << folderViewWidth << ( headerWidth + messageViewerWidth );
            splitter2Sizes << headerWidth << messageViewerWidth;
        }
753
    } else {
Laurent Montel's avatar
Laurent Montel committed
754 755 756 757 758 759 760
        if ( !readerWindowAtSide ) {
            splitter1Sizes << headerHeight << messageViewerHeight;
            splitter2Sizes << folderViewWidth << headerWidth;
        } else {
            splitter1Sizes << headerWidth << messageViewerWidth;
            splitter2Sizes << ftHeight + ffvHeight << messageViewerHeight;
        }
761 762
    }

Laurent Montel's avatar
Laurent Montel committed
763 764
    mSplitter1->setSizes( splitter1Sizes );
    mSplitter2->setSizes( splitter2Sizes );
765

Laurent Montel's avatar
Laurent Montel committed
766 767 768 769 770
    if ( mFolderViewSplitter ) {
        QList<int> splitterSizes;
        splitterSizes << ffvHeight << ftHeight;
        mFolderViewSplitter->setSizes( splitterSizes );
    }
771

Laurent Montel's avatar
Laurent Montel committed
772 773 774 775
    //
    // Now add the splitters to the main layout
    //
    mTopLayout->addWidget( mSplitter1 );
776

Laurent Montel's avatar
Laurent Montel committed
777 778 779 780 781
    // Make sure the focus is on the view, and not on the quick search line edit, because otherwise
    // shortcuts like + or j go to the wrong place.
    // This would normally be done in the message list itself, but apparently something resets the focus
    // again, probably all the reparenting we do here.
    mMessagePane->focusView();
Laurent Montel's avatar
Laurent Montel committed
782

Laurent Montel's avatar
Laurent Montel committed
783 784 785 786 787 788 789
    // By default hide th unread and size columns on first run.
    if ( kmkernel->firstStart() )
    {
        mFolderTreeWidget->folderTreeView()->hideColumn( 1 );
        mFolderTreeWidget->folderTreeView()->hideColumn( 3 );
        mFolderTreeWidget->folderTreeView()->header()->resizeSection( 0, folderViewWidth * 0.8 );
    }
790

Laurent Montel's avatar
Laurent Montel committed
791 792 793 794
    // Make the copy action work, see disconnect comment above
    if ( mMsgView )
        connect( mMsgView->copyAction(), SIGNAL(triggered(bool)),
                 mMsgView, SLOT(slotCopySelectedText()) );
795
}
Stephan Kulow's avatar
Stephan Kulow committed
796

797 798 799
//-----------------------------------------------------------------------------
void KMMainWidget::refreshFavoriteFoldersViewProperties()
{
Laurent Montel's avatar
Laurent Montel committed
800 801
    if ( mFavoriteCollectionsView ) {
        if ( MailCommon::MailCommonSettings::self()->favoriteCollectionViewMode() == MailCommon::MailCommonSettings::EnumFavoriteCollectionViewMode::IconMode )
802
            mFavoriteCollectionsView->changeViewMode( QListView::IconMode );
Laurent Montel's avatar
Laurent Montel committed
803
        else if ( MailCommon::MailCommonSettings::self()->favoriteCollectionViewMode() == MailCommon::MailCommonSettings::EnumFavoriteCollectionViewMode::ListMode )
804
            mFavoriteCollectionsView->changeViewMode( QListView::ListMode );
Laurent Montel's avatar
Laurent Montel committed
805 806 807 808 809 810
        else
            Q_ASSERT(false); // we should never get here in hidden mode
        mFavoriteCollectionsView->setDropActionMenuEnabled( kmkernel->showPopupAfterDnD() );
        mFavoriteCollectionsView->setWordWrap( true );
        mFavoriteCollectionsView->updateMode();
    }
811 812
}

Stephan Kulow's avatar
Stephan Kulow committed
813
//-----------------------------------------------------------------------------
814
void KMMainWidget::readConfig()
Stephan Kulow's avatar
Stephan Kulow committed
815
{
Laurent Montel's avatar
Laurent Montel committed
816 817 818 819 820
    const bool oldLongFolderList = mLongFolderList;
    const bool oldReaderWindowActive = mReaderWindowActive;
    const bool oldReaderWindowBelow = mReaderWindowBelow;
    const bool oldFavoriteFolderView = mEnableFavoriteFolderView;
    const bool oldFolderQuickSearch = mEnableFolderQuickSearch;
821

Laurent Montel's avatar
Laurent Montel committed
822 823
    // on startup, the layout is always new and we need to relayout the widgets
    bool layoutChanged = !mStartupDone;
Stephan Kulow's avatar
Stephan Kulow committed
824

Laurent Montel's avatar
Laurent Montel committed
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
    if ( mStartupDone )
    {
        readPreConfig();

        layoutChanged = ( oldLongFolderList != mLongFolderList ) ||
                ( oldReaderWindowActive != mReaderWindowActive ) ||
                ( oldReaderWindowBelow != mReaderWindowBelow ) ||
                ( oldFavoriteFolderView != mEnableFavoriteFolderView );

        if ( layoutChanged ) {
            deleteWidgets();
            createWidgets();
            restoreCollectionFolderViewConfig();
            emit recreateGui();
        } else if ( oldFolderQuickSearch != mEnableFolderQuickSearch ) {
            if ( mEnableFolderQuickSearch )
                mFolderTreeWidget->filterFolderLineEdit()->show();
            else
                mFolderTreeWidget->filterFolderLineEdit()->hide();
        }
Stephan Kulow's avatar
Stephan Kulow committed
845 846 847
    }


Laurent Montel's avatar
Laurent Montel committed
848 849 850 851 852 853 854 855 856 857
    { // Read the config of the folder views and the header
        if ( mMsgView ) {
            mMsgView->readConfig();
        }
        mMessagePane->reloadGlobalConfiguration();
        mFolderTreeWidget->readConfig();
        if ( mFavoriteCollectionsView ) {
            mFavoriteCollectionsView->readConfig();
        }
        refreshFavoriteFoldersViewProperties();
858
    }
Stephan Kulow's avatar
Stephan Kulow committed
859

Laurent Montel's avatar
Laurent Montel committed
860 861 862 863 864 865 866
    { // area for config group "General"
        if ( !mStartupDone )
        {
            // check mail on startup
            // do it after building the kmmainwin, so that the progressdialog is available
            QTimer::singleShot( 0, this, SLOT(slotCheckMailOnStartup()) );
        }
867
    }
Stephan Kulow's avatar
Stephan Kulow committed
868

Laurent Montel's avatar
Laurent Montel committed
869 870 871
    if ( layoutChanged ) {
        layoutSplitters();
    }
872

Laurent Montel's avatar
Laurent Montel committed
873 874 875
    updateMessageMenu();
    updateFileMenu();
    kmkernel->toggleSystemTray();
876

Laurent Montel's avatar
Laurent Montel committed
877 878 879 880
    connect( Akonadi::AgentManager::self(), SIGNAL(instanceAdded(Akonadi::AgentInstance)),
             this, SLOT(updateFileMenu()) );
    connect( Akonadi::AgentManager::self(), SIGNAL(instanceRemoved(Akonadi::AgentInstance)),
             this, SLOT(updateFileMenu()) );
Stephan Kulow's avatar
Stephan Kulow committed
881 882 883
}

//-----------------------------------------------------------------------------
884
void KMMainWidget::writeConfig(bool force)
Stephan Kulow's avatar
Stephan Kulow committed
885
{
Laurent Montel's avatar
Laurent Montel committed
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
    // Don't save the sizes of all the widgets when we were never shown.
    // This can happen in Kontact, where the KMail plugin is automatically
    // loaded, but not necessarily shown.
    // This prevents invalid sizes from being saved
    if ( mWasEverShown ) {
        // The height of the header widget can be 0, this happens when the user
        // did not switch to the header widget onced and the "Welcome to KMail"
        // HTML widget was shown the whole time
        int headersHeight = mMessagePane->height();
        if ( headersHeight == 0 )
            headersHeight = height() / 2;

        GlobalSettings::self()->setSearchAndHeaderHeight( headersHeight );
        GlobalSettings::self()->setSearchAndHeaderWidth( mMessagePane->width() );
        if ( mFavoriteCollectionsView ) {
            MailCommon::MailCommonSettings::self()->setFavoriteCollectionViewHeight( mFavoriteCollectionsView->height() );
            GlobalSettings::self()->setFolderTreeHeight( mFolderTreeWidget->height() );
            if ( !mLongFolderList ) {
                GlobalSettings::self()->setFolderViewHeight( mFolderViewSplitter->height() );
            }
        }
        else if ( !mLongFolderList && mFolderTreeWidget )
        {
            GlobalSettings::self()->setFolderTreeHeight( mFolderTreeWidget->height() );
        }
        if ( mFolderTreeWidget )
        {
            GlobalSettings::self()->setFolderViewWidth( mFolderTreeWidget->width() );
            KSharedConfig::Ptr config = KMKernel::self()->config();
            KConfigGroup group(config, "CollectionFolderView");

            ETMViewStateSaver saver;
            saver.setView( mFolderTreeWidget->folderTreeView() );
            saver.saveState( group );

            group.writeEntry( "HeaderState", mFolderTreeWidget->folderTreeView()->header()->saveState() );
            //Work around from startup folder
            group.deleteEntry( "Selection" );
Laurent Montel's avatar
Laurent Montel committed
924
#if 0
Laurent Montel's avatar
Laurent Montel committed
925 926 927
            if (!GlobalSettings::self()->startSpecificFolderAtStartup()) {
                group.deleteEntry( "Current" );
            }
Laurent Montel's avatar
Laurent Montel committed
928
#endif
Laurent Montel's avatar
Laurent Montel committed
929 930
            group.sync();
        }
931

Laurent Montel's avatar
Laurent Montel committed
932 933 934 935 936 937
        if ( mMsgView ) {
            if ( !mReaderWindowBelow )
                GlobalSettings::self()->setReaderWindowWidth( mMsgView->width() );
            mMsgView->viewer()->writeConfig(force);
            GlobalSettings::self()->setReaderWindowHeight( mMsgView->height() );
        }
938
    }
Stephan Kulow's avatar
Stephan Kulow committed
939 940
}

941 942
void KMMainWidget::writeReaderConfig()
{
Laurent Montel's avatar
Laurent Montel committed
943 944 945 946
    if ( mWasEverShown ) {
        if ( mMsgView ) {
            mMsgView->viewer()->writeConfig();
        }
947 948 949
    }
}

950 951 952
//-----------------------------------------------------------------------------
void KMMainWidget::deleteWidgets()
{
Laurent Montel's avatar
Laurent Montel committed
953 954 955 956 957 958 959 960 961 962 963 964 965 966
    // Simply delete the top splitter, which always is mSplitter1, regardless
    // of the layout. This deletes all children.
    // akonadi action manager is created in createWidgets(), parented to this
    //  so not autocleaned up.
    delete mAkonadiStandardActionManager;
    mAkonadiStandardActionManager = 0;
    delete mSplitter1;
    mMsgView = 0;
    mSearchAndTree = 0;
    mFolderViewSplitter = 0;
    mFavoriteCollectionsView = 0;
    mSplitter1 = 0;
    mSplitter2 = 0;
    mFavoritesModel = 0;
967
}
Stephan Kulow's avatar
Stephan Kulow committed
968 969

//-----------------------------------------------------------------------------
970
void KMMainWidget::createWidgets()
Stephan Kulow's avatar
Stephan Kulow committed
971
{
Laurent Montel's avatar
Laurent Montel committed
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
    // Note that all widgets we create in this function have the parent 'this'.
    // They will be properly reparented in layoutSplitters()

    //
    // Create header view and search bar
    //
    FolderTreeWidget::TreeViewOptions opt = FolderTreeWidget::ShowUnreadCount;
    opt |= FolderTreeWidget::UseLineEditForFiltering;
    opt |= FolderTreeWidget::ShowCollectionStatisticAnimation;
    opt |= FolderTreeWidget::DontKeyFilter;
    mFolderTreeWidget = new FolderTreeWidget( this, mGUIClient, opt );

    connect( mFolderTreeWidget->folderTreeView(), SIGNAL(currentChanged(Akonadi::Collection)), this, SLOT(slotFolderChanged(Akonadi::Collection)) );

    connect( mFolderTreeWidget->folderTreeView()->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(updateFolderMenu()) );

    connect( mFolderTreeWidget->folderTreeView(), SIGNAL(prefereCreateNewTab(bool)), this, SLOT(slotCreateNewTab(bool)) );

    mFolderTreeWidget->setSelectionMode( QAbstractItemView::ExtendedSelection );
    mMessagePane = new CollectionPane( !GlobalSettings::self()->startSpecificFolderAtStartup(), KMKernel::self()->entityTreeModel(),
                                       mFolderTreeWidget->folderTreeView()->selectionModel(),
                                       this );
    connect( KMKernel::self()->entityTreeModel(), SIGNAL(collectionFetched(int)), this, SLOT(slotCollectionFetched(int)));

    mMessagePane->setXmlGuiClient( mGUIClient );
    connect( mMessagePane, SIGNAL(messageSelected(Akonadi::Item)),
             this, SLOT(slotMessageSelected(Akonadi::Item)) );
    connect( mMessagePane, SIGNAL(selectionChanged()),
             SLOT(startUpdateMessageActionsTimer()) );
    connect( mMessagePane, SIGNAL(currentTabChanged()), this, SLOT(refreshMessageListSelection()) );
    connect( mMessagePane, SIGNAL(messageActivated(Akonadi::Item)),
             this, SLOT(slotMessageActivated(Akonadi::Item)) );
    connect( mMessagePane, SIGNAL(messageStatusChangeRequest(Akonadi::Item,Akonadi::MessageStatus,Akonadi::MessageStatus)),
             SLOT(slotMessageStatusChangeRequest(Akonadi::Item,Akonadi::MessageStatus,Akonadi::MessageStatus)) );

    connect( mMessagePane, SIGNAL(statusMessage(QString)),
             BroadcastStatus::instance(), SLOT(setStatusMsg(QString)) );


    //
    // Create the reader window
    //
    if ( mReaderWindowActive ) {
        mMsgView = new KMReaderWin( this, this, actionCollection(), 0 );
        if ( mMsgActions ) {
            mMsgActions->setMessageView( mMsgView );
        }
        connect( mMsgView->viewer(), SIGNAL(replaceMsgByUnencryptedVersion()),
                 this, SLOT(slotReplaceMsgByUnencryptedVersion()) );
        connect( mMsgView->viewer(), SIGNAL(popupMenu(Akonadi::Item,KUrl,KUrl,QPoint)),
                 this, SLOT(slotMessagePopup(Akonadi::Item,KUrl,KUrl,QPoint)) );
        connect( mMsgView->viewer(), SIGNAL(moveMessageToTrash()),
                 this, SLOT(slotMoveMessageToTrash()) );
    }
    else {
        if ( mMsgActions ) {
            mMsgActions->setMessageView( 0 );
        }
    }

    //
    // Create the folder tree
    // the "folder tree" consists of a quicksearch input field and the tree itself
    //

    mSearchAndTree = new QWidget( this );
    QVBoxLayout *vboxlayout = new QVBoxLayout;
    vboxlayout->setMargin(0);
    mSearchAndTree->setLayout( vboxlayout );

    vboxlayout->addWidget( mFolderTreeWidget );

    if ( !GlobalSettings::self()->enableFolderQuickSearch() ) {
        mFolderTreeWidget->filterFolderLineEdit()->hide();
    }
    //
    // Create the favorite folder view
    //
    mAkonadiStandardActionManager = new Akonadi::StandardMailActionManager( mGUIClient->actionCollection(), this );
    connect( mAkonadiStandardActionManager, SIGNAL(actionStateUpdated()), this, SLOT(slotAkonadiStandardActionUpdated()) );

    mAkonadiStandardActionManager->setCollectionSelectionModel( mFolderTreeWidget->folderTreeView()->selectionModel() );
    mAkonadiStandardActionManager->setItemSelectionModel( mMessagePane->currentItemSelectionModel() );

    if ( mEnableFavoriteFolderView ) {

        mFavoriteCollectionsView = new FavoriteCollectionWidget( mGUIClient, this );
        refreshFavoriteFoldersViewProperties();

        connect( mFavoriteCollectionsView, SIGNAL(currentChanged(Akonadi::Collection)), this, SLOT(slotFolderChanged(Akonadi::Collection)) );

        mFavoritesModel = new Akonadi::FavoriteCollectionsModel(
                    mFolderTreeWidget->folderTreeView()->model(),
                    KMKernel::self()->config()->group( "FavoriteCollections" ), this );

        mFavoriteCollectionsView->setModel( mFavoritesModel );

        Akonadi::CollectionStatisticsDelegate *delegate = new Akonadi::CollectionStatisticsDelegate( mFavoriteCollectionsView );
        delegate->setProgressAnimationEnabled( true );
        mFavoriteCollectionsView->setItemDelegate(delegate);
        delegate->setUnreadCountShown( true );

        mAkonadiStandardActionManager->setFavoriteCollectionsModel( mFavoritesModel );
        mAkonadiStandardActionManager->setFavoriteSelectionModel( mFavoriteCollectionsView->selectionModel() );
    }

    //Don't use mMailActionManager->createAllActions() to save memory by not
    //creating actions that doesn't make sense.
    QList<StandardActionManager::Type> standardActions;
    standardActions << StandardActionManager::CreateCollection
                    << StandardActionManager::CopyCollections
                    << StandardActionManager::DeleteCollections
                    << StandardActionManager::SynchronizeCollections
                    << StandardActionManager::CollectionProperties
                    << StandardActionManager::CopyItems
                    << StandardActionManager::Paste
                    << StandardActionManager::DeleteItems
                    << StandardActionManager::ManageLocalSubscriptions
                    << StandardActionManager::CopyCollectionToMenu
                    << StandardActionManager::CopyItemToMenu
                    << StandardActionManager::MoveItemToMenu
                    << StandardActionManager::MoveCollectionToMenu
                    << StandardActionManager::CutItems
                    << StandardActionManager::CutCollections
                    << StandardActionManager::CreateResource
                    << StandardActionManager::DeleteResources
                    << StandardActionManager::ResourceProperties
                    << StandardActionManager::SynchronizeResources
                    << StandardActionManager::ToggleWorkOffline
                    << StandardActionManager::SynchronizeCollectionsRecursive;

    Q_FOREACH( StandardActionManager::Type standardAction, standardActions ) {
        mAkonadiStandardActionManager->createAction( standardAction );
    }


    if (mEnableFavoriteFolderView) {
        QList<StandardActionManager::Type> favoriteActions;
        favoriteActions << StandardActionManager::AddToFavoriteCollections
                        << StandardActionManager::RemoveFromFavoriteCollections
                        << StandardActionManager::RenameFavoriteCollection
                        << StandardActionManager::SynchronizeFavoriteCollections;
        Q_FOREACH( StandardActionManager::Type favoriteAction, favoriteActions) {
            mAkonadiStandardActionManager->createAction( favoriteAction );
        }
    }

    QList<StandardMailActionManager::Type> mailActions;
    mailActions << StandardMailActionManager::MarkAllMailAsRead
                << StandardMailActionManager::MoveToTrash
                << StandardMailActionManager::MoveAllToTrash
                << StandardMailActionManager::RemoveDuplicates
                << StandardMailActionManager::EmptyAllTrash
                << StandardMailActionManager::MarkMailAsRead
                << StandardMailActionManager::MarkMailAsUnread
                << StandardMailActionManager::MarkMailAsImportant
                << StandardMailActionManager::MarkMailAsActionItem;

    Q_FOREACH( StandardMailActionManager::Type mailAction, mailActions ) {
        mAkonadiStandardActionManager->createAction( mailAction );
    }

    mAkonadiStandardActionManager->interceptAction( Akonadi::StandardActionManager::CollectionProperties );
    connect( mAkonadiStandardActionManager->action( Akonadi::StandardActionManager::CollectionProperties ), SIGNAL(triggered(bool)), this, SLOT(slotCollectionProperties()) );


    //
    // Create all kinds of actions
    //
    mAkonadiStandardActionManager->action( Akonadi::StandardMailActionManager::RemoveDuplicates )->setShortcut( QKeySequence( Qt::CTRL + Qt::Key_Asterisk ) );
    mAkonadiStandardActionManager->interceptAction( Akonadi::StandardMailActionManager::RemoveDuplicates );
    connect( mAkonadiStandardActionManager->action( Akonadi::StandardMailActionManager::RemoveDuplicates ), SIGNAL(triggered(bool)), this, SLOT(slotRemoveDuplicates()) );

    {
        mCollectionProperties = mAkonadiStandardActionManager->action( Akonadi::StandardActionManager::CollectionProperties );
    }
    connect( kmkernel->folderCollectionMonitor(), SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)),
             SLOT(slotItemAdded(Akonadi::Item,Akonadi::Collection)) );
    connect( kmkernel->folderCollectionMonitor(), SIGNAL(itemRemoved(Akonadi::Item)),
             SLOT(slotItemRemoved(Akonadi::Item)) );
    connect( kmkernel->folderCollectionMonitor(), SIGNAL(itemMoved(Akonadi::Item,Akonadi::Collection,Akonadi::Collection)),
             SLOT(slotItemMoved(Akonadi::Item,Akonadi::Collection,Akonadi::Collection)) );
    connect( kmkernel->folderCollectionMonitor(), SIGNAL(collectionChanged(Akonadi::Collection,QSet<QByteArray>)), SLOT(slotCollectionChanged(Akonadi::Collection,QSet<QByteArray>)) );

    connect( kmkernel->folderCollectionMonitor(), SIGNAL(collectionStatisticsChanged(Akonadi::Collection::Id,Akonadi::CollectionStatistics)), SLOT(slotCollectionStatisticsChanged(Akonad