attachmentcontrollerbase.cpp 33.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * This file is part of KMail.
 * Copyright (c) 2009 Constantin Berzan <exit3219@gmail.com>
 *
 * Parts based on KMail code by:
 * Various authors.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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.
 */

#include "attachmentcontrollerbase.h"

Laurent Montel's avatar
Laurent Montel committed
25
#include "messagecomposer/attachment/attachmentmodel.h"
Laurent Montel's avatar
Laurent Montel committed
26 27
#include "messagecomposer/job/attachmentjob.h"
#include "messagecomposer/job/attachmentfrompublickeyjob.h"
Laurent Montel's avatar
Laurent Montel committed
28
#include "messagecomposer/composer/composer.h"
Laurent Montel's avatar
Laurent Montel committed
29

Laurent Montel's avatar
Laurent Montel committed
30
#include "messagecomposer/part/globalpart.h"
Laurent Montel's avatar
Laurent Montel committed
31
#include "messageviewer/viewer/editorwatcher.h"
Laurent Montel's avatar
Laurent Montel committed
32
#include "messageviewer/viewer/nodehelper.h"
Laurent Montel's avatar
Laurent Montel committed
33
#include "messageviewer/utils/util.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

#include <akonadi/itemfetchjob.h>
#include <kio/jobuidelegate.h>

#include <QMenu>
#include <QPointer>

#include <KAction>
#include <KActionCollection>
#include <KDebug>
#include <KEncodingFileDialog>
#include <KFileDialog>
#include <KLocalizedString>
#include <KMessageBox>
#include <KMimeTypeTrader>
#include <KPushButton>
#include <KRun>
#include <KTemporaryFile>
52
#include <KFileItemActions>
53
#include <KActionMenu>
54 55 56 57 58 59

#include <kpimutils/kfileio.h>

#include <libkleo/kleo/cryptobackendfactory.h>
#include <libkleo/ui/keyselectiondialog.h>

Laurent Montel's avatar
Laurent Montel committed
60 61 62 63 64
#include <messagecore/attachment/attachmentcompressjob.h>
#include <messagecore/attachment/attachmentfromfolderjob.h>
#include <messagecore/attachment/attachmentfrommimecontentjob.h>
#include <messagecore/attachment/attachmentfromurljob.h>
#include <messagecore/attachment/attachmentpropertiesdialog.h>
Laurent Montel's avatar
Laurent Montel committed
65
#include <settings/messagecomposersettings.h>
66
#include <KIO/Job>
67

68 69
#include <KMime/Content>

70
using namespace MessageComposer;
71
using namespace MessageCore;
72

73
class MessageComposer::AttachmentControllerBase::Private
74
{
Laurent Montel's avatar
Laurent Montel committed
75
public:
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    Private( AttachmentControllerBase *qq );
    ~Private();

    void attachmentRemoved( AttachmentPart::Ptr part ); // slot
    void compressJobResult( KJob *job ); // slot
    void loadJobResult( KJob *job ); // slot
    void openSelectedAttachments(); // slot
    void viewSelectedAttachments(); // slot
    void editSelectedAttachment(); // slot
    void editSelectedAttachmentWith(); // slot
    void removeSelectedAttachments(); // slot
    void saveSelectedAttachmentAs(); // slot
    void selectedAttachmentProperties(); // slot
    void editDone( MessageViewer::EditorWatcher *watcher ); // slot
    void attachPublicKeyJobResult( KJob *job ); // slot
91
    void slotAttachmentContentCreated( KJob *job ); // slot
92
    void addAttachmentPart( AttachmentPart::Ptr part );
93
    void selectedAllAttachment();
94
    void createOpenWithMenu( QMenu *topMenu, AttachmentPart::Ptr part );
95 96 97 98

    AttachmentControllerBase *const q;
    bool encryptEnabled;
    bool signEnabled;
99
    MessageComposer::AttachmentModel *model;
100
    QWidget *wParent;
101 102 103 104
    QHash<MessageViewer::EditorWatcher*,AttachmentPart::Ptr> editorPart;
    QHash<MessageViewer::EditorWatcher*,KTemporaryFile*> editorTempFile;

    AttachmentPart::List selectedParts;
105
    KActionCollection *mActionCollection;
106 107 108 109 110 111 112 113 114 115 116 117 118 119
    QAction *attachPublicKeyAction;
    QAction *attachMyPublicKeyAction;
    QAction *openContextAction;
    QAction *viewContextAction;
    QAction *editContextAction;
    QAction *editWithContextAction;
    QAction *removeAction;
    QAction *removeContextAction;
    QAction *saveAsAction;
    QAction *saveAsContextAction;
    QAction *propertiesAction;
    QAction *propertiesContextAction;
    QAction *addAction;
    QAction *addContextAction;
120
    QAction *selectAllAction;
121 122
    KActionMenu *attachmentMenu;
    QAction *addOwnVcardAction;
123 124 125 126 127 128

    // If part p is compressed, uncompressedParts[p] is the uncompressed part.
    QHash<AttachmentPart::Ptr, AttachmentPart::Ptr> uncompressedParts;
};

AttachmentControllerBase::Private::Private( AttachmentControllerBase *qq )
Laurent Montel's avatar
Laurent Montel committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    : q( qq )
    , encryptEnabled( false )
    , signEnabled( false )
    , model( 0 )
    , wParent( 0 )
    , attachPublicKeyAction( 0 )
    , attachMyPublicKeyAction( 0 )
    , openContextAction( 0 )
    , viewContextAction( 0 )
    , editContextAction( 0 )
    , editWithContextAction( 0 )
    , removeAction( 0 )
    , removeContextAction( 0 )
    , saveAsAction( 0 )
    , saveAsContextAction( 0 )
    , propertiesAction( 0 )
    , propertiesContextAction( 0 )
    , addAction( 0 )
    , addContextAction( 0 )
    , selectAllAction( 0 )
    , attachmentMenu( 0 )
    , addOwnVcardAction( 0 )
151 152 153 154 155 156 157
{
}

AttachmentControllerBase::Private::~Private()
{
}

158
void AttachmentControllerBase::setSelectedParts( const AttachmentPart::List &selectedParts)
159
{
Laurent Montel's avatar
Laurent Montel committed
160 161 162 163
    d->selectedParts = selectedParts;
    const int selectedCount = selectedParts.count();
    const bool enableEditAction = (selectedCount == 1) &&
            ( !selectedParts.first()->isMessageOrMessageCollection() );
164

Laurent Montel's avatar
Laurent Montel committed
165 166 167 168 169 170 171 172 173 174
    d->openContextAction->setEnabled( selectedCount > 0 );
    d->viewContextAction->setEnabled( selectedCount > 0 );
    d->editContextAction->setEnabled( enableEditAction );
    d->editWithContextAction->setEnabled( enableEditAction );
    d->removeAction->setEnabled( selectedCount > 0 );
    d->removeContextAction->setEnabled( selectedCount > 0 );
    d->saveAsAction->setEnabled( selectedCount == 1 );
    d->saveAsContextAction->setEnabled( selectedCount == 1 );
    d->propertiesAction->setEnabled( selectedCount == 1 );
    d->propertiesContextAction->setEnabled( selectedCount == 1 );
175 176 177 178
}

void AttachmentControllerBase::Private::attachmentRemoved( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
179 180 181
    if( uncompressedParts.contains( part ) ) {
        uncompressedParts.remove( part );
    }
182 183 184 185
}

void AttachmentControllerBase::Private::compressJobResult( KJob *job )
{
Laurent Montel's avatar
Laurent Montel committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    if( job->error() ) {
        KMessageBox::sorry( wParent, job->errorString(), i18n( "Failed to compress attachment" ) );
        return;
    }

    Q_ASSERT( dynamic_cast<AttachmentCompressJob*>( job ) );
    AttachmentCompressJob *ajob = static_cast<AttachmentCompressJob*>( job );
    //AttachmentPart *originalPart = const_cast<AttachmentPart*>( ajob->originalPart() );
    AttachmentPart::Ptr originalPart = ajob->originalPart();
    AttachmentPart::Ptr compressedPart = ajob->compressedPart();

    if( ajob->isCompressedPartLarger() ) {
        const int result = KMessageBox::questionYesNo( wParent,
                                                       i18n( "The compressed attachment is larger than the original. "
                                                             "Do you want to keep the original one?" ),
                                                       QString( /*caption*/ ),
                                                       KGuiItem( i18nc( "Do not compress", "Keep" ) ),
                                                       KGuiItem( i18n( "Compress" ) ) );
        if( result == KMessageBox::Yes ) {
            // The user has chosen to keep the uncompressed file.
            return;
        }
    }

    kDebug() << "Replacing uncompressed part in model.";
    uncompressedParts[ compressedPart ] = originalPart;
    bool ok = model->replaceAttachment( originalPart, compressedPart );
    if( !ok ) {
        // The attachment was removed from the model while we were compressing.
        kDebug() << "Compressed a zombie.";
    }
217 218 219 220
}

void AttachmentControllerBase::Private::loadJobResult( KJob *job )
{
Laurent Montel's avatar
Laurent Montel committed
221 222 223 224
    if( job->error() ) {
        KMessageBox::sorry( wParent, job->errorString(), i18n( "Failed to attach file" ) );
        return;
    }
225

Laurent Montel's avatar
Laurent Montel committed
226 227 228 229
    Q_ASSERT( dynamic_cast<AttachmentLoadJob*>( job ) );
    AttachmentLoadJob *ajob = static_cast<AttachmentLoadJob*>( job );
    AttachmentPart::Ptr part = ajob->attachmentPart();
    q->addAttachment( part );
230 231 232 233
}

void AttachmentControllerBase::Private::openSelectedAttachments()
{
Laurent Montel's avatar
Laurent Montel committed
234 235 236 237
    Q_ASSERT( selectedParts.count() >= 1 );
    foreach( AttachmentPart::Ptr part, selectedParts ) {
        q->openAttachment( part );
    }
238 239 240 241
}

void AttachmentControllerBase::Private::viewSelectedAttachments()
{
Laurent Montel's avatar
Laurent Montel committed
242 243 244 245
    Q_ASSERT( selectedParts.count() >= 1 );
    foreach( AttachmentPart::Ptr part, selectedParts ) {
        q->viewAttachment( part );
    }
246 247 248 249
}

void AttachmentControllerBase::Private::editSelectedAttachment()
{
Laurent Montel's avatar
Laurent Montel committed
250 251 252
    Q_ASSERT( selectedParts.count() == 1 );
    q->editAttachment( selectedParts.first(), false /*openWith*/ );
    // TODO nicer api would be enum { OpenWithDialog, NoOpenWithDialog }
253 254 255 256
}

void AttachmentControllerBase::Private::editSelectedAttachmentWith()
{
Laurent Montel's avatar
Laurent Montel committed
257 258
    Q_ASSERT( selectedParts.count() == 1 );
    q->editAttachment( selectedParts.first(), true /*openWith*/ );
259 260 261 262
}

void AttachmentControllerBase::Private::removeSelectedAttachments()
{
Laurent Montel's avatar
Laurent Montel committed
263 264 265 266
    Q_ASSERT( selectedParts.count() >= 1 );
    foreach( AttachmentPart::Ptr part, selectedParts ) {
        model->removeAttachment( part );
    }
267 268 269 270
}

void AttachmentControllerBase::Private::saveSelectedAttachmentAs()
{
Laurent Montel's avatar
Laurent Montel committed
271 272
    Q_ASSERT( selectedParts.count() == 1 );
    q->saveAttachmentAs( selectedParts.first() );
273 274 275 276
}

void AttachmentControllerBase::Private::selectedAttachmentProperties()
{
Laurent Montel's avatar
Laurent Montel committed
277 278
    Q_ASSERT( selectedParts.count() == 1 );
    q->attachmentProperties( selectedParts.first() );
279 280 281 282
}

void AttachmentControllerBase::Private::editDone( MessageViewer::EditorWatcher *watcher )
{
Laurent Montel's avatar
Laurent Montel committed
283 284 285 286
    AttachmentPart::Ptr part = editorPart.take( watcher );
    Q_ASSERT( part );
    KTemporaryFile *tempFile = editorTempFile.take( watcher );
    Q_ASSERT( tempFile );
287

Laurent Montel's avatar
Laurent Montel committed
288 289
    if( watcher->fileChanged() ) {
        kDebug() << "File has changed.";
290

Laurent Montel's avatar
Laurent Montel committed
291 292 293 294 295 296
        // Read the new data and update the part in the model.
        tempFile->reset();
        QByteArray data = tempFile->readAll();
        part->setData( data );
        model->updateAttachment( part );
    }
297

Laurent Montel's avatar
Laurent Montel committed
298 299
    delete tempFile;
    // The watcher deletes itself.
300 301
}

302 303 304

void AttachmentControllerBase::Private::createOpenWithMenu( QMenu *topMenu, AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    const QString contentTypeStr = QString::fromLatin1(part->mimeType());
    const KService::List offers = KFileItemActions::associatedApplications(QStringList()<<contentTypeStr, QString() );
    if (!offers.isEmpty()) {
        QMenu* menu = topMenu;
        QActionGroup *actionGroup = new QActionGroup( menu );
        connect( actionGroup, SIGNAL(triggered(QAction*)), q, SLOT(slotOpenWithAction(QAction*)) );

        if (offers.count() > 1) { // submenu 'open with'
            menu = new QMenu(i18nc("@title:menu", "&Open With"), topMenu);
            menu->menuAction()->setObjectName(QLatin1String("openWith_submenu")); // for the unittest
            topMenu->addMenu(menu);
        }
        //kDebug() << offers.count() << "offers" << topMenu << menu;

        KService::List::ConstIterator it = offers.constBegin();
        KService::List::ConstIterator end = offers.constEnd();
        for(; it != end; ++it) {
            KAction* act = MessageViewer::Util::createAppAction(*it,
                                                                // no submenu -> prefix single offer
                                                                menu == topMenu, actionGroup,menu);
            menu->addAction(act);
        }

        QString openWithActionName;
        if (menu != topMenu) { // submenu
            menu->addSeparator();
            openWithActionName = i18nc("@action:inmenu Open With", "&Other...");
        } else {
            openWithActionName = i18nc("@title:menu", "&Open With...");
        }
        KAction *openWithAct = new KAction(menu);
        openWithAct->setText(openWithActionName);
        QObject::connect(openWithAct, SIGNAL(triggered()), q, SLOT(slotOpenWithDialog()));
        menu->addAction(openWithAct);
    }
    else { // no app offers -> Open With...
        KAction *act = new KAction(topMenu);
        act->setText(i18nc("@title:menu", "&Open With..."));
        QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotOpenWithDialog()));
        topMenu->addAction(act);
345 346 347 348 349
    }
}



350 351
void AttachmentControllerBase::exportPublicKey( const QString &fingerprint )
{
Laurent Montel's avatar
Laurent Montel committed
352 353 354 355 356
    if( fingerprint.isEmpty() || !Kleo::CryptoBackendFactory::instance()->openpgp() ) {
        kWarning() << "Tried to export key with empty fingerprint, or no OpenPGP.";
        Q_ASSERT( false ); // Can this happen?
        return;
    }
357

Laurent Montel's avatar
Laurent Montel committed
358 359 360
    MessageComposer::AttachmentFromPublicKeyJob *ajob = new MessageComposer::AttachmentFromPublicKeyJob( fingerprint, this );
    connect( ajob, SIGNAL(result(KJob*)), this, SLOT(attachPublicKeyJobResult(KJob*)) );
    ajob->start();
361 362 363 364
}

void AttachmentControllerBase::Private::attachPublicKeyJobResult( KJob *job )
{
Laurent Montel's avatar
Laurent Montel committed
365 366
    // The only reason we can't use loadJobResult() and need a separate method
    // is that we want to show the proper caption ("public key" instead of "file")...
367

Laurent Montel's avatar
Laurent Montel committed
368 369 370 371
    if( job->error() ) {
        KMessageBox::sorry( wParent, job->errorString(), i18n( "Failed to attach public key" ) );
        return;
    }
372

Laurent Montel's avatar
Laurent Montel committed
373 374 375 376
    Q_ASSERT( dynamic_cast<MessageComposer::AttachmentFromPublicKeyJob*>( job ) );
    MessageComposer::AttachmentFromPublicKeyJob *ajob = static_cast<MessageComposer::AttachmentFromPublicKeyJob*>( job );
    AttachmentPart::Ptr part = ajob->attachmentPart();
    q->addAttachment( part );
377 378
}

379

380 381
static KTemporaryFile *dumpAttachmentToTempFile( const AttachmentPart::Ptr part ) // local
{
Laurent Montel's avatar
Laurent Montel committed
382 383 384 385 386 387 388 389 390 391 392 393 394
    KTemporaryFile *file = new KTemporaryFile;
    if( !file->open() ) {
        kError() << "Could not open tempfile" << file->fileName();
        delete file;
        return 0;
    }
    if( file->write( part->data() ) == -1 ) {
        kError() << "Could not dump attachment to tempfile.";
        delete file;
        return 0;
    }
    file->flush();
    return file;
395 396 397 398
}



399
AttachmentControllerBase::AttachmentControllerBase( MessageComposer::AttachmentModel *model, QWidget *wParent, KActionCollection *actionCollection )
Laurent Montel's avatar
Laurent Montel committed
400 401
    : QObject( wParent )
    , d( new Private( this ) )
402
{
Laurent Montel's avatar
Laurent Montel committed
403 404 405 406 407 408 409 410
    d->model = model;
    connect( model, SIGNAL(attachUrlsRequested(KUrl::List)), this, SLOT(addAttachments(KUrl::List)) );
    connect( model, SIGNAL(attachmentRemoved(MessageCore::AttachmentPart::Ptr)),
             this, SLOT(attachmentRemoved(MessageCore::AttachmentPart::Ptr)) );
    connect( model, SIGNAL(attachmentCompressRequested(MessageCore::AttachmentPart::Ptr,bool)),
             this, SLOT(compressAttachment(MessageCore::AttachmentPart::Ptr,bool)) );
    connect( model, SIGNAL(encryptEnabled(bool)), this, SLOT(setEncryptEnabled(bool)) );
    connect( model, SIGNAL(signEnabled(bool)), this, SLOT(setSignEnabled(bool)) );
411

Laurent Montel's avatar
Laurent Montel committed
412 413
    d->wParent = wParent;
    d->mActionCollection = actionCollection;
414 415 416 417
}

AttachmentControllerBase::~AttachmentControllerBase()
{
Laurent Montel's avatar
Laurent Montel committed
418
    delete d;
419 420 421 422
}

void AttachmentControllerBase::createActions()
{
Laurent Montel's avatar
Laurent Montel committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    // Create the actions.
    d->attachPublicKeyAction = new KAction( i18n( "Attach &Public Key..." ), this );
    connect( d->attachPublicKeyAction, SIGNAL(triggered(bool)),
             this, SLOT(showAttachPublicKeyDialog()) );

    d->attachMyPublicKeyAction = new KAction( i18n( "Attach &My Public Key" ), this );
    connect( d->attachMyPublicKeyAction, SIGNAL(triggered(bool)), this, SLOT(attachMyPublicKey()) );

    d->attachmentMenu = new KActionMenu( KIcon( QLatin1String( "mail-attachment" ) ), i18n( "Attach" ), this );
    connect( d->attachmentMenu, SIGNAL(triggered(bool)), this, SLOT(showAddAttachmentDialog()) );

    d->attachmentMenu->setDelayed(true);

    d->addAction = new KAction( KIcon( QLatin1String( "mail-attachment" ) ), i18n( "&Attach File..." ), this );
    d->addAction->setIconText( i18n( "Attach" ) );
    d->addContextAction = new KAction( KIcon( QLatin1String( "mail-attachment" ) ),
                                       i18n( "Add Attachment..." ), this );
    connect( d->addAction, SIGNAL(triggered(bool)), this, SLOT(showAddAttachmentDialog()) );
    connect( d->addContextAction, SIGNAL(triggered(bool)), this, SLOT(showAddAttachmentDialog()) );

443 444
    d->addOwnVcardAction = new KAction( i18n("Attach Own vCard"),this );
    d->addOwnVcardAction->setIconText( i18n( "Own vCard" ) );
Laurent Montel's avatar
Laurent Montel committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    d->addOwnVcardAction->setCheckable(true);
    connect(d->addOwnVcardAction, SIGNAL(triggered(bool)), this, SIGNAL(addOwnVcard(bool)));

    d->attachmentMenu->addAction(d->addAction);
    d->attachmentMenu->addSeparator();
    d->attachmentMenu->addAction(d->addOwnVcardAction);

    d->removeAction = new KAction( KIcon(QLatin1String("edit-delete")), i18n( "&Remove Attachment" ), this );
    d->removeContextAction = new KAction( KIcon(QLatin1String("edit-delete")), i18n( "Remove" ), this ); // FIXME need two texts. is there a better way?
    connect( d->removeAction, SIGNAL(triggered(bool)), this, SLOT(removeSelectedAttachments()) );
    connect( d->removeContextAction, SIGNAL(triggered(bool)), this, SLOT(removeSelectedAttachments()) );

    d->openContextAction = new KAction( i18nc( "to open", "Open" ), this );
    connect( d->openContextAction, SIGNAL(triggered(bool)), this, SLOT(openSelectedAttachments()) );

    d->viewContextAction = new KAction( i18nc( "to view", "View" ), this );
    connect( d->viewContextAction, SIGNAL(triggered(bool)), this, SLOT(viewSelectedAttachments()) );

    d->editContextAction = new KAction( i18nc( "to edit", "Edit" ), this );
    connect( d->editContextAction, SIGNAL(triggered(bool)), this, SLOT(editSelectedAttachment()) );

    d->editWithContextAction = new KAction( i18n( "Edit With..." ), this );
    connect( d->editWithContextAction, SIGNAL(triggered(bool)), this, SLOT(editSelectedAttachmentWith()) );

    d->saveAsAction = new KAction( KIcon( QLatin1String( "document-save-as" ) ),
                                   i18n( "&Save Attachment As..." ), this );
    d->saveAsContextAction = new KAction( KIcon( QLatin1String( "document-save-as" ) ),
                                          i18n( "Save As..." ), this );
    connect( d->saveAsAction, SIGNAL(triggered(bool)),
             this, SLOT(saveSelectedAttachmentAs()) );
    connect( d->saveAsContextAction, SIGNAL(triggered(bool)),
             this, SLOT(saveSelectedAttachmentAs()) );

    d->propertiesAction = new KAction( i18n( "Attachment Pr&operties..." ), this );
    d->propertiesContextAction = new KAction( i18n( "Properties" ), this );
    connect( d->propertiesAction, SIGNAL(triggered(bool)),
             this, SLOT(selectedAttachmentProperties()) );
    connect( d->propertiesContextAction, SIGNAL(triggered(bool)),
             this, SLOT(selectedAttachmentProperties()) );

    d->selectAllAction = new KAction( i18n("Select All"), this);
    connect( d->selectAllAction, SIGNAL(triggered(bool)),
             this, SIGNAL(selectedAllAttachment()) );

    // Insert the actions into the composer window's menu.
    KActionCollection *collection = d->mActionCollection;
    collection->addAction( QLatin1String( "attach_public_key" ), d->attachPublicKeyAction );
    collection->addAction( QLatin1String( "attach_my_public_key" ), d->attachMyPublicKeyAction );
    collection->addAction( QLatin1String( "attach" ), d->addAction );
    collection->addAction( QLatin1String( "remove" ), d->removeAction );
    collection->addAction( QLatin1String( "attach_save" ), d->saveAsAction );
    collection->addAction( QLatin1String( "attach_properties" ), d->propertiesAction );
    collection->addAction( QLatin1String( "select_all_attachment"), d->selectAllAction);
    collection->addAction( QLatin1String( "attach_menu"), d->attachmentMenu );
    collection->addAction( QLatin1String( "attach_own_vcard"), d->addOwnVcardAction );

    setSelectedParts( AttachmentPart::List());
    emit actionsCreated();
503 504 505 506
}

void AttachmentControllerBase::setEncryptEnabled( bool enabled )
{
Laurent Montel's avatar
Laurent Montel committed
507
    d->encryptEnabled = enabled;
508 509 510 511
}

void AttachmentControllerBase::setSignEnabled( bool enabled )
{
Laurent Montel's avatar
Laurent Montel committed
512
    d->signEnabled = enabled;
513 514 515 516
}

void AttachmentControllerBase::compressAttachment( AttachmentPart::Ptr part, bool compress )
{
Laurent Montel's avatar
Laurent Montel committed
517 518
    if( compress ) {
        kDebug() << "Compressing part.";
519

Laurent Montel's avatar
Laurent Montel committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533
        AttachmentCompressJob *ajob = new AttachmentCompressJob( part, this );
        connect( ajob, SIGNAL(result(KJob*)), this, SLOT(compressJobResult(KJob*)) );
        ajob->start();
    } else {
        kDebug() << "Uncompressing part.";

        // Replace the compressed part with the original uncompressed part, and delete
        // the compressed part.
        AttachmentPart::Ptr originalPart = d->uncompressedParts.take( part );
        Q_ASSERT( originalPart ); // Found in uncompressedParts.
        bool ok = d->model->replaceAttachment( part, originalPart );
        Q_ASSERT( ok );
        Q_UNUSED( ok );
    }
534 535 536 537
}

void AttachmentControllerBase::showContextMenu()
{
Laurent Montel's avatar
Laurent Montel committed
538
    emit refreshSelection();
539 540


Laurent Montel's avatar
Laurent Montel committed
541 542
    const int numberOfParts(d->selectedParts.count());
    QMenu *menu = new QMenu;
543

Laurent Montel's avatar
Laurent Montel committed
544 545
    const bool enableEditAction = (numberOfParts == 1) &&
            ( !d->selectedParts.first()->isMessageOrMessageCollection() );
546

Laurent Montel's avatar
Laurent Montel committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    if(numberOfParts>0) {
        if(numberOfParts == 1)
            d->createOpenWithMenu(menu, d->selectedParts.first());
        else
            menu->addAction(d->openContextAction);
        menu->addAction(d->viewContextAction);
    }
    if(enableEditAction) {
        menu->addAction(d->editWithContextAction);
        menu->addAction(d->editContextAction);
    }
    if(numberOfParts>0) {
        menu->addAction(d->removeContextAction);
    }
    if(numberOfParts == 1) {
        menu->addAction(d->saveAsContextAction);
        menu->addAction(d->propertiesContextAction);
    }
565

566 567 568 569 570 571 572 573 574
    const int nbAttachment = d->model->rowCount();
    if (nbAttachment != numberOfParts) {
        menu->addSeparator();
        menu->addAction(d->selectAllAction);
    }
    if (numberOfParts == 0) {
        menu->addSeparator();
        menu->addAction(d->addContextAction);
    }
Laurent Montel's avatar
Laurent Montel committed
575 576
    menu->exec( QCursor::pos() );
    delete menu;
577 578
}

579 580
void AttachmentControllerBase::slotOpenWithDialog()
{
Laurent Montel's avatar
Laurent Montel committed
581
    openWith();
582 583 584 585
}

void AttachmentControllerBase::slotOpenWithAction(QAction*act)
{
Laurent Montel's avatar
Laurent Montel committed
586 587
    KService::Ptr app = act->data().value<KService::Ptr>();
    Q_ASSERT( d->selectedParts.count() == 1 );
588

Laurent Montel's avatar
Laurent Montel committed
589
    openWith(app);
Laurent Montel's avatar
Laurent Montel committed
590 591 592 593
}

void AttachmentControllerBase::openWith(KService::Ptr offer)
{
Laurent Montel's avatar
Laurent Montel committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    KTemporaryFile *tempFile = dumpAttachmentToTempFile( d->selectedParts.first() );
    if( !tempFile ) {
        KMessageBox::sorry( d->wParent,
                            i18n( "KMail was unable to write the attachment to a temporary file." ),
                            i18n( "Unable to open attachment" ) );
        return;
    }
    KUrl::List lst;
    KUrl url = KUrl::fromPath(tempFile->fileName());
    lst.append( url );
    bool result = false;
    if(offer) {
        result = KRun::run( *offer, lst, d->wParent, false );
    } else {
        result = KRun::displayOpenWithDialog( lst, d->wParent, false );
    }
    if ( !result ) {
        delete tempFile;
        tempFile = 0;
    } else {
        // The file was opened.  Delete it only when the composer is closed
        // (and this object is destroyed).
        tempFile->setParent( this ); // Manages lifetime.
    }
618 619
}

620 621
void AttachmentControllerBase::openAttachment( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    KTemporaryFile *tempFile = dumpAttachmentToTempFile( part );
    if( !tempFile ) {
        KMessageBox::sorry( d->wParent,
                            i18n( "KMail was unable to write the attachment to a temporary file." ),
                            i18n( "Unable to open attachment" ) );
        return;
    }

    bool success = KRun::runUrl( KUrl::fromPath( tempFile->fileName() ),
                                 QString::fromLatin1( part->mimeType() ),
                                 d->wParent,
                                 true /*tempFile*/,
                                 false /*runExecutables*/ );
    if( !success ) {
        if( KMimeTypeTrader::self()->preferredService( QString::fromLatin1( part->mimeType() ) ).isNull() ) {
            // KRun showed an Open-With dialog, and it was canceled.
        } else {
            // KRun failed.
            KMessageBox::sorry( d->wParent,
                                i18n( "KMail was unable to open the attachment." ),
                                i18n( "Unable to open attachment" ) );
        }
        delete tempFile;
        tempFile = 0;
646
    } else {
Laurent Montel's avatar
Laurent Montel committed
647 648 649
        // The file was opened.  Delete it only when the composer is closed
        // (and this object is destroyed).
        tempFile->setParent( this ); // Manages lifetime.
650 651 652 653 654
    }
}

void AttachmentControllerBase::viewAttachment( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
655 656 657 658 659 660
    MessageComposer::Composer *composer = new MessageComposer::Composer;
    composer->globalPart()->setFallbackCharsetEnabled( true );
    MessageComposer::AttachmentJob *attachmentJob = new MessageComposer::AttachmentJob( part, composer );
    connect( attachmentJob, SIGNAL(result(KJob*)),
             this, SLOT(slotAttachmentContentCreated(KJob*)) );
    attachmentJob->start();
661 662 663 664
}

void AttachmentControllerBase::Private::slotAttachmentContentCreated( KJob *job )
{
Laurent Montel's avatar
Laurent Montel committed
665 666 667 668 669 670 671 672
    if ( !job->error() ) {
        const MessageComposer::AttachmentJob * const attachmentJob = dynamic_cast<MessageComposer::AttachmentJob*>( job );
        Q_ASSERT( attachmentJob );
        emit q->showAttachment( attachmentJob->content(), QByteArray() );
    } else {
        // TODO: show warning to the user
        kWarning() << "Error creating KMime::Content for attachment:" << job->errorText();
    }
673 674 675 676
}

void AttachmentControllerBase::editAttachment( AttachmentPart::Ptr part, bool openWith )
{
Laurent Montel's avatar
Laurent Montel committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    KTemporaryFile *tempFile = dumpAttachmentToTempFile( part );
    if( !tempFile ) {
        KMessageBox::sorry( d->wParent,
                            i18n( "KMail was unable to write the attachment to a temporary file." ),
                            i18n( "Unable to edit attachment" ) );
        return;
    }

    MessageViewer::EditorWatcher *watcher = new MessageViewer::EditorWatcher(
                KUrl::fromPath( tempFile->fileName() ),
                QString::fromLatin1( part->mimeType() ), openWith,
                this, d->wParent );
    connect( watcher, SIGNAL(editDone(MessageViewer::EditorWatcher*)),
             this, SLOT(editDone(MessageViewer::EditorWatcher*)) );

    if( watcher->start() ) {
        // The attachment is being edited.
        // We will clean things up in editDone().
        d->editorPart[ watcher ] = part;
        d->editorTempFile[ watcher ] = tempFile;

        // Delete the temp file if the composer is closed (and this object is destroyed).
        tempFile->setParent( this ); // Manages lifetime.
    } else {
        kWarning() << "Could not start EditorWatcher.";
        delete watcher;
        delete tempFile;
    }
705 706 707 708
}

void AttachmentControllerBase::editAttachmentWith( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
709
    editAttachment( part, true );
710 711 712 713
}

void AttachmentControllerBase::saveAttachmentAs( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
714 715 716 717
    QString pname = part->name();
    if( pname.isEmpty() ) {
        pname = i18n( "unnamed" );
    }
718

Laurent Montel's avatar
Laurent Montel committed
719 720 721
    KUrl url = KFileDialog::getSaveUrl( pname,
                                        QString( /*filter*/ ), d->wParent,
                                        i18n( "Save Attachment As" ) );
722

Laurent Montel's avatar
Laurent Montel committed
723 724 725 726
    if( url.isEmpty() ) {
        kDebug() << "Save Attachment As dialog canceled.";
        return;
    }
727

Laurent Montel's avatar
Laurent Montel committed
728
    byteArrayToRemoteFile(part->data(), url);
729 730 731 732
}

void AttachmentControllerBase::byteArrayToRemoteFile(const QByteArray &aData, const KUrl &aURL, bool overwrite)
{
Laurent Montel's avatar
Laurent Montel committed
733 734
    KIO::StoredTransferJob *job = KIO::storedPut( aData, aURL, -1, overwrite ? KIO::Overwrite : KIO::DefaultFlags );
    connect( job, SIGNAL(result(KJob*)), SLOT(slotPutResult(KJob*)) );
735 736 737 738
}

void AttachmentControllerBase::slotPutResult(KJob *job)
{
Laurent Montel's avatar
Laurent Montel committed
739
    KIO::StoredTransferJob *_job = qobject_cast<KIO::StoredTransferJob *>( job );
740

Laurent Montel's avatar
Laurent Montel committed
741
    if (job->error())
742
    {
Laurent Montel's avatar
Laurent Montel committed
743 744 745 746 747 748 749 750 751 752 753
        if (job->error() == KIO::ERR_FILE_ALREADY_EXIST)
        {
            if (KMessageBox::warningContinueCancel(0,
                                                   i18n("File %1 exists.\nDo you want to replace it?", _job->url().toLocalFile()), i18n("Save to File"), KGuiItem(i18n("&Replace")))
                    == KMessageBox::Continue)
                byteArrayToRemoteFile(_job->data(), _job->url(), true);
        }
        else {
            KIO::JobUiDelegate *ui = static_cast<KIO::Job*>( job )->ui();
            ui->showErrorMessage();
        }
754
    }
755 756 757 758
}

void AttachmentControllerBase::attachmentProperties( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
759 760
    QPointer<AttachmentPropertiesDialog> dialog = new AttachmentPropertiesDialog(
                part, false, d->wParent );
761

Laurent Montel's avatar
Laurent Montel committed
762 763
    dialog->setEncryptEnabled( d->encryptEnabled );
    dialog->setSignEnabled( d->signEnabled );
764

Laurent Montel's avatar
Laurent Montel committed
765 766 767 768
    if( dialog->exec() && dialog ) {
        d->model->updateAttachment( part );
    }
    delete dialog;
769 770 771 772
}

void AttachmentControllerBase::showAddAttachmentDialog()
{
773
#ifndef KDEPIM_MOBILE_UI
Laurent Montel's avatar
Laurent Montel committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    QPointer<KEncodingFileDialog> dialog = new KEncodingFileDialog(
                QString( /*startDir*/ ), QString( /*encoding*/ ), QString( /*filter*/ ),
                i18n( "Attach File" ), KFileDialog::Other, d->wParent );

    dialog->okButton()->setGuiItem( KGuiItem( i18n("&Attach"), QLatin1String( "document-open" ) ) );
    dialog->setMode( KFile::Files|KFile::Directory );
    if( dialog->exec() == KDialog::Accepted && dialog ) {
        const KUrl::List files = dialog->selectedUrls();
        const QString encoding = MessageViewer::NodeHelper::fixEncoding( dialog->selectedEncoding() );
        const int numberOfFiles(files.count());
        for (int i=0; i<numberOfFiles; ++i) {
            const KUrl url = files.at( i );
            KUrl urlWithEncoding = url;
            urlWithEncoding.setFileEncoding( encoding );
            if ( KMimeType::findByUrl( urlWithEncoding )->name() == QLatin1String( "inode/directory" ) ) {
                const int rc = KMessageBox::warningYesNo( d->wParent,i18n("Do you really want to attach this directory \"%1\" ?", url.toLocalFile() ),i18n( "Attach directory" ) );
                if ( rc == KMessageBox::Yes ) {
                    addAttachment( urlWithEncoding );
                }
            } else {
                addAttachment( urlWithEncoding );
            }
796
        }
797
    }
Laurent Montel's avatar
Laurent Montel committed
798
    delete dialog;
799
#else
Laurent Montel's avatar
Laurent Montel committed
800 801 802 803 804
    // use native dialog, while being much simpler, it actually fits on the screen much better than our own monster dialog
    const QString fileName = KFileDialog::getOpenFileName( KUrl(), QString(), d->wParent, i18n("Attach File" ) );
    if ( !fileName.isEmpty() ) {
        addAttachment( KUrl::fromLocalFile( fileName ) );
    }
805
#endif
806 807 808 809
}

void AttachmentControllerBase::addAttachment( AttachmentPart::Ptr part )
{
Laurent Montel's avatar
Laurent Montel committed
810 811 812
    part->setEncrypted( d->model->isEncryptSelected() );
    part->setSigned( d->model->isSignSelected() );
    d->model->addAttachment( part );
813

Laurent Montel's avatar
Laurent Montel committed
814 815 816 817
    if( MessageComposer::MessageComposerSettings::self()->showMessagePartDialogOnAttach() ) {
        attachmentProperties( part );
    }
    emit fileAttached();
818 819
}

Laurent Montel's avatar
Laurent Montel committed
820
MessageCore::AttachmentFromUrlBaseJob * AttachmentControllerBase::createAttachmentJob(const KUrl &url)
821
{
Laurent Montel's avatar
Laurent Montel committed
822 823 824 825 826 827 828 829 830 831 832 833
    MessageCore::AttachmentFromUrlBaseJob *ajob = 0;
    if( KMimeType::findByUrl( url )->name() == QLatin1String( "inode/directory" ) ) {
        kDebug() << "Creating attachment from folder";
        ajob = new AttachmentFromFolderJob ( url, this );
    } else {
        ajob = new AttachmentFromUrlJob( url, this );
        kDebug() << "Creating attachment from file";
    }
    if( MessageComposer::MessageComposerSettings::maximumAttachmentSize() > 0 ) {
        ajob->setMaximumAllowedSize( MessageComposer::MessageComposerSettings::maximumAttachmentSize() );
    }
    return ajob;
Laurent Montel's avatar
Laurent Montel committed
834 835 836 837
}

void AttachmentControllerBase::addAttachmentUrlSync(const KUrl &url)
{
Laurent Montel's avatar
Laurent Montel committed
838 839 840 841 842 843 844 845
    MessageCore::AttachmentFromUrlBaseJob *ajob = createAttachmentJob(url);
    if(ajob->exec()) {
        AttachmentPart::Ptr part = ajob->attachmentPart();
        addAttachment( part );
    } else {
        if( ajob->error() ) {
            KMessageBox::sorry( d->wParent, ajob->errorString(), i18n( "Failed to attach file" ) );
        }
Laurent Montel's avatar
Laurent Montel committed
846
    }
847 848
}

849 850
void AttachmentControllerBase::addAttachment( const KUrl &url )
{
Laurent Montel's avatar
Laurent Montel committed
851 852 853
    MessageCore::AttachmentFromUrlBaseJob *ajob = createAttachmentJob(url);
    connect( ajob, SIGNAL(result(KJob*)), this, SLOT(loadJobResult(KJob*)) );
    ajob->start();
854 855 856 857
}

void AttachmentControllerBase::addAttachments( const KUrl::List &urls )
{
Laurent Montel's avatar
Laurent Montel committed
858 859 860
    foreach( const KUrl &url, urls ) {
        addAttachment( url );
    }
861 862 863 864
}

void AttachmentControllerBase::showAttachPublicKeyDialog()
{
Laurent Montel's avatar
Laurent Montel committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878
    using Kleo::KeySelectionDialog;
    QPointer<KeySelectionDialog> dialog = new KeySelectionDialog(
                i18n( "Attach Public OpenPGP Key" ),
                i18n( "Select the public key which should be attached." ),
                std::vector<GpgME::Key>(),
                KeySelectionDialog::PublicKeys|KeySelectionDialog::OpenPGPKeys,
                false /* no multi selection */,
                false /* no remember choice box */,
                d->wParent, "attach public key selection dialog" );

    if( dialog->exec() == KDialog::Accepted && dialog ) {
        exportPublicKey( dialog->fingerprint() );
    }
    delete dialog;
879 880
}

881 882
void AttachmentControllerBase::enableAttachPublicKey( bool enable )
{
Laurent Montel's avatar
Laurent Montel committed
883
    d->attachPublicKeyAction->setEnabled( enable );
884 885 886 887
}

void AttachmentControllerBase::enableAttachMyPublicKey( bool enable )
{
Laurent Montel's avatar
Laurent Montel committed
888
    d->attachMyPublicKeyAction->setEnabled( enable );
889 890
}

891 892
void AttachmentControllerBase::setAttachOwnVcard(bool attachVcard)
{
Laurent Montel's avatar
Laurent Montel committed
893
    d->addOwnVcardAction->setChecked(attachVcard);
894 895 896 897
}

bool AttachmentControllerBase::attachOwnVcard() const
{
Laurent Montel's avatar
Laurent Montel committed
898
    return  d->addOwnVcardAction->isChecked();
899 900
}

901 902
void AttachmentControllerBase::setIdentityHasOwnVcard(bool state)
{
Laurent Montel's avatar
Laurent Montel committed
903
    d->addOwnVcardAction->setEnabled(state);
904
}
905

Stephen Kelly's avatar
Stephen Kelly committed
906
#include "moc_attachmentcontrollerbase.cpp"