attachmentcontrollerbase.cpp 40.1 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/AttachmentModel>
26
27
28
#include "MessageComposer/AttachmentJob"
#include "MessageComposer/AttachmentFromPublicKeyJob"
#include "MessageComposer/AttachmentVcardFromAddressBookJob"
29
#include "MessageComposer/AttachmentClipBoardJob"
30
31
#include "MessageComposer/Composer"
#include "MessageComposer/GlobalPart"
Sandro Knauß's avatar
Sandro Knauß committed
32
33
34
35

#include <MessageViewer/EditorWatcher>
#include <MessageViewer/MessageViewerUtil>

36
#include <MimeTreeParser/NodeHelper>
Sandro Knauß's avatar
Sandro Knauß committed
37
38

#include <MessageCore/StringUtil>
39
40
41
42
43
44
45
46

#include <AkonadiCore/itemfetchjob.h>
#include <kio/jobuidelegate.h>
#include <QIcon>

#include <QMenu>
#include <QPointer>
#include <QTreeView>
Laurent Montel's avatar
Laurent Montel committed
47
#include <QUrlQuery>
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

#include <QAction>
#include <KActionCollection>
#include "messagecomposer_debug.h"
#include <KEncodingFileDialog>
#include <KLocalizedString>
#include <KMessageBox>
#include <KMimeTypeTrader>
#include <QPushButton>
#include <KRun>
#include <QTemporaryFile>
#include <QMimeDatabase>
#include <KFileItemActions>
#include <KActionMenu>

63
#include <QGpgME/Protocol>
64
65
66
#include <Libkleo/KeySelectionDialog>

#include <MessageCore/AttachmentCompressJob>
67
68
#include "attachment/attachmentfrommimecontentjob.h"
#include "attachment/attachmentfromurljob.h"
69
#include <MessageCore/AttachmentPropertiesDialog>
70
#include "messagecore/attachmentupdatejob.h"
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <MessageCore/AttachmentFromUrlUtils>
#include <settings/messagecomposersettings.h>
#include <KIO/Job>
#include <Akonadi/Contact/EmailAddressSelectionDialog>
#include <Akonadi/Contact/EmailAddressSelectionWidget>

#include <KMime/Content>
#include <QFileDialog>

using namespace MessageComposer;
using namespace MessageCore;

class Q_DECL_HIDDEN MessageComposer::AttachmentControllerBase::Private
{
public:
    Private(AttachmentControllerBase *qq);
    ~Private();

Laurent Montel's avatar
Laurent Montel committed
89
    void attachmentRemoved(const AttachmentPart::Ptr &part);   // slot
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    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
    void slotAttachmentContentCreated(KJob *job);   // slot
    void addAttachmentPart(AttachmentPart::Ptr part);
    void attachVcardFromAddressBook(KJob *job);   //slot
104
    void attachClipBoardElement(KJob *job);
105
    void selectedAllAttachment();
Laurent Montel's avatar
Laurent Montel committed
106
    void createOpenWithMenu(QMenu *topMenu, const AttachmentPart::Ptr &part);
107
108
109
    void reloadAttachment();
    void updateJobResult(KJob *);

Laurent Montel's avatar
Laurent Montel committed
110
    AttachmentPart::List selectedParts;
111
    AttachmentControllerBase *const q;
Laurent Montel's avatar
Laurent Montel committed
112
113
    MessageComposer::AttachmentModel *model = nullptr;
    QWidget *wParent = nullptr;
114
115
116
    QHash<MessageViewer::EditorWatcher *, AttachmentPart::Ptr> editorPart;
    QHash<MessageViewer::EditorWatcher *, QTemporaryFile *> editorTempFile;

Laurent Montel's avatar
Laurent Montel committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    KActionCollection *mActionCollection = nullptr;
    QAction *attachPublicKeyAction = nullptr;
    QAction *attachMyPublicKeyAction = nullptr;
    QAction *openContextAction = nullptr;
    QAction *viewContextAction = nullptr;
    QAction *editContextAction = nullptr;
    QAction *editWithContextAction = nullptr;
    QAction *removeAction = nullptr;
    QAction *removeContextAction = nullptr;
    QAction *saveAsAction = nullptr;
    QAction *saveAsContextAction = nullptr;
    QAction *propertiesAction = nullptr;
    QAction *propertiesContextAction = nullptr;
    QAction *addAttachmentFileAction = nullptr;
    QAction *addAttachmentDirectoryAction = nullptr;
    QAction *addContextAction = nullptr;
    QAction *selectAllAction = nullptr;
    KActionMenu *attachmentMenu = nullptr;
    QAction *addOwnVcardAction = nullptr;
    QAction *reloadAttachmentAction = nullptr;
    QAction *attachVCardsAction = nullptr;
138
    QAction *attachClipBoardAction = nullptr;
139
140
    // If part p is compressed, uncompressedParts[p] is the uncompressed part.
    QHash<AttachmentPart::Ptr, AttachmentPart::Ptr> uncompressedParts;
Laurent Montel's avatar
Laurent Montel committed
141
142
    bool encryptEnabled = false;
    bool signEnabled = false;
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
};

AttachmentControllerBase::Private::Private(AttachmentControllerBase *qq)
    : q(qq)
{
}

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

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

    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);
}

Laurent Montel's avatar
Laurent Montel committed
173
void AttachmentControllerBase::Private::attachmentRemoved(const AttachmentPart::Ptr &part)
174
{
Laurent Montel's avatar
Laurent Montel committed
175
    uncompressedParts.remove(part);
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
}

void AttachmentControllerBase::Private::compressJobResult(KJob *job)
{
    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::Ptr originalPart = ajob->originalPart();
    AttachmentPart::Ptr compressedPart = ajob->compressedPart();

    if (ajob->isCompressedPartLarger()) {
        const int result = KMessageBox::questionYesNo(wParent,
Laurent Montel's avatar
Laurent Montel committed
192
193
194
195
196
                                                      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")));
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        if (result == KMessageBox::Yes) {
            // The user has chosen to keep the uncompressed file.
            return;
        }
    }

    qCDebug(MESSAGECOMPOSER_LOG) << "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.
        qCDebug(MESSAGECOMPOSER_LOG) << "Compressed a zombie.";
    }
}

void AttachmentControllerBase::Private::loadJobResult(KJob *job)
{
    if (job->error()) {
        KMessageBox::sorry(wParent, job->errorString(), i18n("Failed to attach file"));
        return;
    }

    Q_ASSERT(dynamic_cast<AttachmentLoadJob *>(job));
    AttachmentLoadJob *ajob = static_cast<AttachmentLoadJob *>(job);
    AttachmentPart::Ptr part = ajob->attachmentPart();
    q->addAttachment(part);
}

void AttachmentControllerBase::Private::openSelectedAttachments()
{
    Q_ASSERT(selectedParts.count() >= 1);
Laurent Montel's avatar
Laurent Montel committed
228
    for (const AttachmentPart::Ptr &part : qAsConst(selectedParts)) {
229
230
231
232
233
234
235
        q->openAttachment(part);
    }
}

void AttachmentControllerBase::Private::viewSelectedAttachments()
{
    Q_ASSERT(selectedParts.count() >= 1);
Laurent Montel's avatar
Laurent Montel committed
236
    for (const AttachmentPart::Ptr &part : qAsConst(selectedParts)) {
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        q->viewAttachment(part);
    }
}

void AttachmentControllerBase::Private::editSelectedAttachment()
{
    Q_ASSERT(selectedParts.count() == 1);
    q->editAttachment(selectedParts.first(), MessageViewer::EditorWatcher::NoOpenWithDialog);
}

void AttachmentControllerBase::Private::editSelectedAttachmentWith()
{
    Q_ASSERT(selectedParts.count() == 1);
    q->editAttachment(selectedParts.first(), MessageViewer::EditorWatcher::OpenWithDialog);
}

void AttachmentControllerBase::Private::removeSelectedAttachments()
{
    Q_ASSERT(selectedParts.count() >= 1);
256
257
258
    //We must store list, otherwise when we remove it changes selectedParts (as selection changed) => it will crash.
    const AttachmentPart::List toRemove = selectedParts;
    for (const AttachmentPart::Ptr &part : toRemove) {
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        model->removeAttachment(part);
    }
}

void AttachmentControllerBase::Private::saveSelectedAttachmentAs()
{
    Q_ASSERT(selectedParts.count() == 1);
    q->saveAttachmentAs(selectedParts.first());
}

void AttachmentControllerBase::Private::selectedAttachmentProperties()
{
    Q_ASSERT(selectedParts.count() == 1);
    q->attachmentProperties(selectedParts.first());
}

void AttachmentControllerBase::Private::reloadAttachment()
{
    Q_ASSERT(selectedParts.count() == 1);
    AttachmentUpdateJob *ajob = new AttachmentUpdateJob(selectedParts.first(), q);
Laurent Montel's avatar
Laurent Montel committed
279
280
281
    connect(ajob, &AttachmentUpdateJob::result, q, [this](KJob *job) {
        updateJobResult(job);
    });
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
    ajob->start();
}

void AttachmentControllerBase::Private::updateJobResult(KJob *job)
{
    if (job->error()) {
        KMessageBox::sorry(wParent, job->errorString(), i18n("Failed to reload attachment"));
        return;
    }
    Q_ASSERT(dynamic_cast<AttachmentUpdateJob *>(job));
    AttachmentUpdateJob *ajob = static_cast<AttachmentUpdateJob *>(job);
    AttachmentPart::Ptr originalPart = ajob->originalPart();
    AttachmentPart::Ptr updatedPart = ajob->updatedPart();

    attachmentRemoved(originalPart);
    bool ok = model->replaceAttachment(originalPart, updatedPart);
    if (!ok) {
        // The attachment was removed from the model while we were compressing.
        qCDebug(MESSAGECOMPOSER_LOG) << "Updated a zombie.";
    }
}

void AttachmentControllerBase::Private::editDone(MessageViewer::EditorWatcher *watcher)
{
    AttachmentPart::Ptr part = editorPart.take(watcher);
    Q_ASSERT(part);
    QTemporaryFile *tempFile = editorTempFile.take(watcher);
    Q_ASSERT(tempFile);
    if (watcher->fileChanged()) {
        qCDebug(MESSAGECOMPOSER_LOG) << "File has changed.";
        const QString name = watcher->url().path();
        QFile file(name);
        if (file.open(QIODevice::ReadOnly)) {
            const QByteArray data = file.readAll();
            part->setData(data);
            model->updateAttachment(part);
        }
    }

    delete tempFile;
    // The watcher deletes itself.
}

Laurent Montel's avatar
Laurent Montel committed
325
void AttachmentControllerBase::Private::createOpenWithMenu(QMenu *topMenu, const AttachmentPart::Ptr &part)
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, &QActionGroup::triggered, q, &AttachmentControllerBase::slotOpenWithAction);

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

        KService::List::ConstIterator it = offers.constBegin();
        KService::List::ConstIterator end = offers.constEnd();
        for (; it != end; ++it) {
            QAction *act = MessageViewer::Util::createAppAction(*it,
Laurent Montel's avatar
Laurent Montel committed
345
346
                                                                // no submenu -> prefix single offer
                                                                menu == topMenu, actionGroup, menu);
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
            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...");
        }
        QAction *openWithAct = new QAction(menu);
        openWithAct->setText(openWithActionName);
        QObject::connect(openWithAct, &QAction::triggered, q, &AttachmentControllerBase::slotOpenWithDialog);
        menu->addAction(openWithAct);
    } else { // no app offers -> Open With...
        QAction *act = new QAction(topMenu);
        act->setText(i18nc("@title:menu", "&Open With..."));
        QObject::connect(act, &QAction::triggered, q, &AttachmentControllerBase::slotOpenWithDialog);
        topMenu->addAction(act);
    }
}

void AttachmentControllerBase::exportPublicKey(const QString &fingerprint)
{
371
    if (fingerprint.isEmpty() || !QGpgME::openpgp()) {
372
373
374
375
376
        qCWarning(MESSAGECOMPOSER_LOG) << "Tried to export key with empty fingerprint, or no OpenPGP.";
        return;
    }

    MessageComposer::AttachmentFromPublicKeyJob *ajob = new MessageComposer::AttachmentFromPublicKeyJob(fingerprint, this);
Laurent Montel's avatar
Laurent Montel committed
377
378
379
    connect(ajob, &AttachmentFromPublicKeyJob::result, this, [this](KJob *job) {
        d->attachPublicKeyJobResult(job);
    });
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
    ajob->start();
}

void AttachmentControllerBase::Private::attachPublicKeyJobResult(KJob *job)
{
    // 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")...

    if (job->error()) {
        KMessageBox::sorry(wParent, job->errorString(), i18n("Failed to attach public key"));
        return;
    }

    Q_ASSERT(dynamic_cast<MessageComposer::AttachmentFromPublicKeyJob *>(job));
    MessageComposer::AttachmentFromPublicKeyJob *ajob = static_cast<MessageComposer::AttachmentFromPublicKeyJob *>(job);
    AttachmentPart::Ptr part = ajob->attachmentPart();
    q->addAttachment(part);
}

void AttachmentControllerBase::Private::attachVcardFromAddressBook(KJob *job)
{
    if (job->error()) {
Luigi Toscano's avatar
Luigi Toscano committed
402
403
        qCDebug(MESSAGECOMPOSER_LOG) << " Error during when get vCard";
        KMessageBox::sorry(wParent, job->errorString(), i18n("Failed to attach vCard"));
404
405
406
407
408
409
410
411
        return;
    }

    MessageComposer::AttachmentVcardFromAddressBookJob *ajob = static_cast<MessageComposer::AttachmentVcardFromAddressBookJob *>(job);
    AttachmentPart::Ptr part = ajob->attachmentPart();
    q->addAttachment(part);
}

412
413
414
void AttachmentControllerBase::Private::attachClipBoardElement(KJob *job)
{
    if (job->error()) {
415
416
        qCDebug(MESSAGECOMPOSER_LOG) << " Error during when get try to attach text from clipboard";
        KMessageBox::sorry(wParent, job->errorString(), i18n("Failed to attach text from clipboard"));
417
418
419
420
421
422
423
424
        return;
    }

    MessageComposer::AttachmentClipBoardJob *ajob = static_cast<MessageComposer::AttachmentClipBoardJob *>(job);
    AttachmentPart::Ptr part = ajob->attachmentPart();
    q->addAttachment(part);
}

Laurent Montel's avatar
Laurent Montel committed
425
static QTemporaryFile *dumpAttachmentToTempFile(const AttachmentPart::Ptr &part)   // local
426
427
428
429
430
{
    QTemporaryFile *file = new QTemporaryFile;
    if (!file->open()) {
        qCCritical(MESSAGECOMPOSER_LOG) << "Could not open tempfile" << file->fileName();
        delete file;
Laurent Montel's avatar
Laurent Montel committed
431
        return nullptr;
432
433
434
435
    }
    if (file->write(part->data()) == -1) {
        qCCritical(MESSAGECOMPOSER_LOG) << "Could not dump attachment to tempfile.";
        delete file;
Laurent Montel's avatar
Laurent Montel committed
436
        return nullptr;
437
438
439
440
441
442
443
444
445
446
447
    }
    file->flush();
    return file;
}

AttachmentControllerBase::AttachmentControllerBase(MessageComposer::AttachmentModel *model, QWidget *wParent, KActionCollection *actionCollection)
    : QObject(wParent)
    , d(new Private(this))
{
    d->model = model;
    connect(model, &MessageComposer::AttachmentModel::attachUrlsRequested, this, &AttachmentControllerBase::addAttachments);
Laurent Montel's avatar
Laurent Montel committed
448
    connect(model, &MessageComposer::AttachmentModel::attachmentRemoved,
Laurent Montel's avatar
Laurent Montel committed
449
450
451
            this, [this](const MessageCore::AttachmentPart::Ptr &attr) {
        d->attachmentRemoved(attr);
    });
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
    connect(model, &AttachmentModel::attachmentCompressRequested,
            this, &AttachmentControllerBase::compressAttachment);
    connect(model, &MessageComposer::AttachmentModel::encryptEnabled, this, &AttachmentControllerBase::setEncryptEnabled);
    connect(model, &MessageComposer::AttachmentModel::signEnabled, this, &AttachmentControllerBase::setSignEnabled);

    d->wParent = wParent;
    d->mActionCollection = actionCollection;
}

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

void AttachmentControllerBase::createActions()
{
    // Create the actions.
    d->attachPublicKeyAction = new QAction(i18n("Attach &Public Key..."), this);
    connect(d->attachPublicKeyAction, &QAction::triggered,
            this, &AttachmentControllerBase::showAttachPublicKeyDialog);

    d->attachMyPublicKeyAction = new QAction(i18n("Attach &My Public Key"), this);
    connect(d->attachMyPublicKeyAction, &QAction::triggered, this, &AttachmentControllerBase::attachMyPublicKey);

    d->attachmentMenu = new KActionMenu(QIcon::fromTheme(QStringLiteral("mail-attachment")), i18n("Attach"), this);
    connect(d->attachmentMenu, &QAction::triggered, this, &AttachmentControllerBase::showAddAttachmentFileDialog);

    d->attachmentMenu->setDelayed(true);

    d->addAttachmentFileAction = new QAction(QIcon::fromTheme(QStringLiteral("mail-attachment")), i18n("&Attach File..."), this);
    d->addAttachmentFileAction->setIconText(i18n("Attach"));
    d->addContextAction = new QAction(QIcon::fromTheme(QStringLiteral("mail-attachment")),
                                      i18n("Add Attachment..."), this);
    connect(d->addAttachmentFileAction, &QAction::triggered, this, &AttachmentControllerBase::showAddAttachmentFileDialog);
    connect(d->addContextAction, &QAction::triggered, this, &AttachmentControllerBase::showAddAttachmentFileDialog);

    d->addAttachmentDirectoryAction = new QAction(QIcon::fromTheme(QStringLiteral("mail-attachment")), i18n("&Attach Directory..."), this);
    d->addAttachmentDirectoryAction->setIconText(i18n("Attach"));
    connect(d->addAttachmentDirectoryAction, &QAction::triggered, this, &AttachmentControllerBase::showAddAttachmentCompressedDirectoryDialog);

    d->addOwnVcardAction = new QAction(i18n("Attach Own vCard"), this);
    d->addOwnVcardAction->setIconText(i18n("Own vCard"));
    d->addOwnVcardAction->setCheckable(true);
    connect(d->addOwnVcardAction, &QAction::triggered, this, &AttachmentControllerBase::addOwnVcard);

    d->attachVCardsAction = new QAction(QIcon::fromTheme(QStringLiteral("mail-attachment")), i18n("&Attach vCards..."), this);
    d->attachVCardsAction->setIconText(i18n("Attach"));
    connect(d->attachVCardsAction, &QAction::triggered, this, &AttachmentControllerBase::showAttachVcard);

Laurent Montel's avatar
Laurent Montel committed
501
502
    d->attachClipBoardAction = new QAction(QIcon::fromTheme(QStringLiteral("mail-attachment")), i18n("&Attach Text From Clipboard..."), this);
    d->attachClipBoardAction->setIconText(i18n("Attach Text From Clipboard"));
503
504
    connect(d->attachClipBoardAction, &QAction::triggered, this, &AttachmentControllerBase::showAttachClipBoard);

505
506
507
508
509
510
    d->attachmentMenu->addAction(d->addAttachmentFileAction);
    d->attachmentMenu->addAction(d->addAttachmentDirectoryAction);
    d->attachmentMenu->addSeparator();
    d->attachmentMenu->addAction(d->addOwnVcardAction);
    d->attachmentMenu->addSeparator();
    d->attachmentMenu->addAction(d->attachVCardsAction);
511
512
513
    d->attachmentMenu->addSeparator();
    d->attachmentMenu->addAction(d->attachClipBoardAction);

514
515
    d->removeAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18n("&Remove Attachment"), this);
    d->removeContextAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18n("Remove"), this);     // FIXME need two texts. is there a better way?
Laurent Montel's avatar
Laurent Montel committed
516
517
518
519
520
521
    connect(d->removeAction, &QAction::triggered, this, [this]() {
        d->removeSelectedAttachments();
    });
    connect(d->removeContextAction, &QAction::triggered, this, [this]() {
        d->removeSelectedAttachments();
    });
522
523

    d->openContextAction = new QAction(i18nc("to open", "Open"), this);
Laurent Montel's avatar
Laurent Montel committed
524
525
526
    connect(d->openContextAction, &QAction::triggered, this, [this]() {
        d->openSelectedAttachments();
    });
527
528

    d->viewContextAction = new QAction(i18nc("to view", "View"), this);
Laurent Montel's avatar
Laurent Montel committed
529
530
531
    connect(d->viewContextAction, &QAction::triggered, this, [this]() {
        d->viewSelectedAttachments();
    });
532
533

    d->editContextAction = new QAction(i18nc("to edit", "Edit"), this);
Laurent Montel's avatar
Laurent Montel committed
534
535
536
    connect(d->editContextAction, &QAction::triggered, this, [this]() {
        d->editSelectedAttachment();
    });
537
538

    d->editWithContextAction = new QAction(i18n("Edit With..."), this);
Laurent Montel's avatar
Laurent Montel committed
539
540
541
    connect(d->editWithContextAction, &QAction::triggered, this, [this]() {
        d->editSelectedAttachmentWith();
    });
542
543
544
545
546

    d->saveAsAction = new QAction(QIcon::fromTheme(QStringLiteral("document-save-as")),
                                  i18n("&Save Attachment As..."), this);
    d->saveAsContextAction = new QAction(QIcon::fromTheme(QStringLiteral("document-save-as")),
                                         i18n("Save As..."), this);
Laurent Montel's avatar
Laurent Montel committed
547
    connect(d->saveAsAction, &QAction::triggered,
Laurent Montel's avatar
Laurent Montel committed
548
549
550
            this, [this]() {
        d->saveSelectedAttachmentAs();
    });
Laurent Montel's avatar
Laurent Montel committed
551
    connect(d->saveAsContextAction, &QAction::triggered,
Laurent Montel's avatar
Laurent Montel committed
552
553
554
            this, [this]() {
        d->saveSelectedAttachmentAs();
    });
555
556
557

    d->propertiesAction = new QAction(i18n("Attachment Pr&operties..."), this);
    d->propertiesContextAction = new QAction(i18n("Properties"), this);
Laurent Montel's avatar
Laurent Montel committed
558
    connect(d->propertiesAction, &QAction::triggered,
Laurent Montel's avatar
Laurent Montel committed
559
560
561
            this, [this]() {
        d->selectedAttachmentProperties();
    });
Laurent Montel's avatar
Laurent Montel committed
562
    connect(d->propertiesContextAction, &QAction::triggered,
Laurent Montel's avatar
Laurent Montel committed
563
564
565
            this, [this]() {
        d->selectedAttachmentProperties();
    });
566
567
568
569
570
571

    d->selectAllAction = new QAction(i18n("Select All"), this);
    connect(d->selectAllAction, &QAction::triggered,
            this, &AttachmentControllerBase::selectedAllAttachment);

    d->reloadAttachmentAction = new QAction(QIcon::fromTheme(QStringLiteral("view-refresh")), i18n("Reload"), this);
Laurent Montel's avatar
Laurent Montel committed
572
    connect(d->reloadAttachmentAction, &QAction::triggered,
Laurent Montel's avatar
Laurent Montel committed
573
574
575
            this, [this]() {
        d->reloadAttachment();
    });
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605

    // Insert the actions into the composer window's menu.
    KActionCollection *collection = d->mActionCollection;
    collection->addAction(QStringLiteral("attach_public_key"), d->attachPublicKeyAction);
    collection->addAction(QStringLiteral("attach_my_public_key"), d->attachMyPublicKeyAction);
    collection->addAction(QStringLiteral("attach"), d->addAttachmentFileAction);
    collection->addAction(QStringLiteral("attach_directory"), d->addAttachmentDirectoryAction);

    collection->addAction(QStringLiteral("remove"), d->removeAction);
    collection->addAction(QStringLiteral("attach_save"), d->saveAsAction);
    collection->addAction(QStringLiteral("attach_properties"), d->propertiesAction);
    collection->addAction(QStringLiteral("select_all_attachment"), d->selectAllAction);
    collection->addAction(QStringLiteral("attach_menu"), d->attachmentMenu);
    collection->addAction(QStringLiteral("attach_own_vcard"), d->addOwnVcardAction);
    collection->addAction(QStringLiteral("attach_vcards"), d->attachVCardsAction);

    setSelectedParts(AttachmentPart::List());
    Q_EMIT actionsCreated();
}

void AttachmentControllerBase::setEncryptEnabled(bool enabled)
{
    d->encryptEnabled = enabled;
}

void AttachmentControllerBase::setSignEnabled(bool enabled)
{
    d->signEnabled = enabled;
}

Laurent Montel's avatar
Laurent Montel committed
606
void AttachmentControllerBase::compressAttachment(const AttachmentPart::Ptr &part, bool compress)
607
608
609
610
611
{
    if (compress) {
        qCDebug(MESSAGECOMPOSER_LOG) << "Compressing part.";

        AttachmentCompressJob *ajob = new AttachmentCompressJob(part, this);
Laurent Montel's avatar
Laurent Montel committed
612
613
614
        connect(ajob, &AttachmentCompressJob::result, this, [this](KJob *job) {
            d->compressJobResult(job);
        });
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
        ajob->start();
    } else {
        qCDebug(MESSAGECOMPOSER_LOG) << "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);
    }
}

void AttachmentControllerBase::showContextMenu()
{
    Q_EMIT refreshSelection();

    const int numberOfParts(d->selectedParts.count());
Laurent Montel's avatar
Laurent Montel committed
634
    QMenu menu;
635

Laurent Montel's avatar
Laurent Montel committed
636
637
    const bool enableEditAction = (numberOfParts == 1)
                                  && (!d->selectedParts.first()->isMessageOrMessageCollection());
638
639
640
641
642
643
644
645
646
647

    if (numberOfParts > 0) {
        if (numberOfParts == 1) {
            const QString mimetype = QString::fromLatin1(d->selectedParts.first()->mimeType());
            QMimeDatabase mimeDb;
            auto mime = mimeDb.mimeTypeForName(mimetype);
            QStringList parentMimeType;
            if (mime.isValid()) {
                parentMimeType = mime.allAncestors();
            }
Laurent Montel's avatar
Laurent Montel committed
648
649
650
            if ((mimetype == QLatin1String("text/plain"))
                || (mimetype == QLatin1String("image/png"))
                || (mimetype == QLatin1String("image/jpeg"))
Laurent Montel's avatar
Laurent Montel committed
651
652
653
                || parentMimeType.contains(QLatin1String("text/plain"))
                || parentMimeType.contains(QLatin1String("image/png"))
                || parentMimeType.contains(QLatin1String("image/jpeg"))
Laurent Montel's avatar
Laurent Montel committed
654
                ) {
Laurent Montel's avatar
Laurent Montel committed
655
                menu.addAction(d->viewContextAction);
656
            }
Laurent Montel's avatar
Laurent Montel committed
657
            d->createOpenWithMenu(&menu, d->selectedParts.first());
658
        }
Laurent Montel's avatar
Laurent Montel committed
659
        menu.addAction(d->openContextAction);
660
661
    }
    if (enableEditAction) {
Laurent Montel's avatar
Laurent Montel committed
662
663
        menu.addAction(d->editWithContextAction);
        menu.addAction(d->editContextAction);
664
665
    }
    if (numberOfParts > 0) {
Laurent Montel's avatar
Laurent Montel committed
666
        menu.addAction(d->removeContextAction);
667
668
669
    }
    if (numberOfParts == 1) {
        if (!d->selectedParts.first()->url().isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
670
            menu.addAction(d->reloadAttachmentAction);
671
        }
Laurent Montel's avatar
Laurent Montel committed
672
673
674
        menu.addAction(d->saveAsContextAction);
        menu.addSeparator();
        menu.addAction(d->propertiesContextAction);
675
676
677
678
    }

    const int nbAttachment = d->model->rowCount();
    if (nbAttachment != numberOfParts) {
Laurent Montel's avatar
Laurent Montel committed
679
680
        menu.addSeparator();
        menu.addAction(d->selectAllAction);
681
682
    }
    if (numberOfParts == 0) {
Laurent Montel's avatar
Laurent Montel committed
683
684
        menu.addSeparator();
        menu.addAction(d->addContextAction);
685
686
    }

Laurent Montel's avatar
Laurent Montel committed
687
    menu.exec(QCursor::pos());
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
}

void AttachmentControllerBase::slotOpenWithDialog()
{
    openWith();
}

void AttachmentControllerBase::slotOpenWithAction(QAction *act)
{
    KService::Ptr app = act->data().value<KService::Ptr>();
    Q_ASSERT(d->selectedParts.count() == 1);

    openWith(app);
}

void AttachmentControllerBase::openWith(const KService::Ptr &offer)
{
    QTemporaryFile *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;
    }
    QList<QUrl> lst;
    QUrl url = QUrl::fromLocalFile(tempFile->fileName());
    lst.append(url);
    tempFile->setPermissions(QFile::ReadUser);
    bool result = false;
    if (offer) {
        result = KRun::runService(*offer, lst, d->wParent, false);
    } else {
        result = KRun::displayOpenWithDialog(lst, d->wParent, false);
    }
    if (!result) {
        delete tempFile;
Laurent Montel's avatar
Laurent Montel committed
724
        tempFile = nullptr;
725
726
727
728
729
730
731
    } else {
        // The file was opened.  Delete it only when the composer is closed
        // (and this object is destroyed).
        tempFile->setParent(this);   // Manages lifetime.
    }
}

Laurent Montel's avatar
Laurent Montel committed
732
void AttachmentControllerBase::openAttachment(const AttachmentPart::Ptr &part)
733
734
735
736
737
738
739
740
741
{
    QTemporaryFile *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;
    }
    tempFile->setPermissions(QFile::ReadUser);
Laurent Montel's avatar
Laurent Montel committed
742
743
    KRun::RunFlags flags;
    flags |= KRun::DeleteTemporaryFiles;
744
745
746
    bool success = KRun::runUrl(QUrl::fromLocalFile(tempFile->fileName()),
                                QString::fromLatin1(part->mimeType()),
                                d->wParent,
Laurent Montel's avatar
Laurent Montel committed
747
                                flags);
748
749
750
751
752
753
754
755
756
757
    if (!success) {
        if (!KMimeTypeTrader::self()->preferredService(QString::fromLatin1(part->mimeType())).data()) {
            // 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;
Laurent Montel's avatar
Laurent Montel committed
758
        tempFile = nullptr;
759
760
761
762
763
764
765
    } else {
        // The file was opened.  Delete it only when the composer is closed
        // (and this object is destroyed).
        tempFile->setParent(this);   // Manages lifetime.
    }
}

Laurent Montel's avatar
Laurent Montel committed
766
void AttachmentControllerBase::viewAttachment(const AttachmentPart::Ptr &part)
767
768
769
770
{
    MessageComposer::Composer *composer = new MessageComposer::Composer;
    composer->globalPart()->setFallbackCharsetEnabled(true);
    MessageComposer::AttachmentJob *attachmentJob = new MessageComposer::AttachmentJob(part, composer);
Laurent Montel's avatar
Laurent Montel committed
771
772
773
    connect(attachmentJob, &AttachmentJob::result, this, [this](KJob *job) {
        d->slotAttachmentContentCreated(job);
    });
774
775
776
777
778
779
780
781
    attachmentJob->start();
}

void AttachmentControllerBase::Private::slotAttachmentContentCreated(KJob *job)
{
    if (!job->error()) {
        const MessageComposer::AttachmentJob *const attachmentJob = dynamic_cast<MessageComposer::AttachmentJob *>(job);
        Q_ASSERT(attachmentJob);
782
783
784
        if (attachmentJob) {
            Q_EMIT q->showAttachment(attachmentJob->content(), QByteArray());
        }
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
    } else {
        // TODO: show warning to the user
        qCWarning(MESSAGECOMPOSER_LOG) << "Error creating KMime::Content for attachment:" << job->errorText();
    }
}

void AttachmentControllerBase::editAttachment(AttachmentPart::Ptr part, MessageViewer::EditorWatcher::OpenWithOption openWithOption)
{
    QTemporaryFile *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(
        QUrl::fromLocalFile(tempFile->fileName()),
        QString::fromLatin1(part->mimeType()), openWithOption,
        this, d->wParent);
805
    connect(watcher, &MessageViewer::EditorWatcher::editDone,
Laurent Montel's avatar
Laurent Montel committed
806
807
808
            this, [this](MessageViewer::EditorWatcher *watcher)  {
        d->editDone(watcher);
    });
809
810

    switch (watcher->start()) {
Laurent Montel's avatar
Laurent Montel committed
811
    case MessageViewer::EditorWatcher::NoError:
812
813
814
815
816
817
818
819
820
821
        // 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.
        break;
    case MessageViewer::EditorWatcher::CannotStart:
        qCWarning(MESSAGECOMPOSER_LOG) << "Could not start EditorWatcher.";
Laurent Montel's avatar
Laurent Montel committed
822
        Q_FALLTHROUGH();
823
824
    case MessageViewer::EditorWatcher::Unknown:
    case MessageViewer::EditorWatcher::Canceled:
Laurent Montel's avatar
Laurent Montel committed
825
    case MessageViewer::EditorWatcher::NoServiceFound:
826
827
828
829
830
831
        delete watcher;
        delete tempFile;
        break;
    }
}

Laurent Montel's avatar
Laurent Montel committed
832
void AttachmentControllerBase::editAttachmentWith(const AttachmentPart::Ptr &part)
833
834
835
836
{
    editAttachment(part, MessageViewer::EditorWatcher::OpenWithDialog);
}

Laurent Montel's avatar
Laurent Montel committed
837
void AttachmentControllerBase::saveAttachmentAs(const AttachmentPart::Ptr &part)
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
{
    QString pname = part->name();
    if (pname.isEmpty()) {
        pname = i18n("unnamed");
    }

    QUrl url = QFileDialog::getSaveFileUrl(d->wParent, i18n("Save Attachment As"), QUrl::fromLocalFile(pname));

    if (url.isEmpty()) {
        qCDebug(MESSAGECOMPOSER_LOG) << "Save Attachment As dialog canceled.";
        return;
    }

    byteArrayToRemoteFile(part->data(), url);
}

void AttachmentControllerBase::byteArrayToRemoteFile(const QByteArray &aData, const QUrl &aURL, bool overwrite)
{
    KIO::StoredTransferJob *job = KIO::storedPut(aData, aURL, -1, overwrite ? KIO::Overwrite : KIO::DefaultFlags);
    connect(job, &KIO::StoredTransferJob::result, this, &AttachmentControllerBase::slotPutResult);
}

void AttachmentControllerBase::slotPutResult(KJob *job)
{
    KIO::StoredTransferJob *_job = qobject_cast<KIO::StoredTransferJob *>(job);

    if (job->error()) {
        if (job->error() == KIO::ERR_FILE_ALREADY_EXIST) {
Laurent Montel's avatar
Laurent Montel committed
866
            if (KMessageBox::warningContinueCancel(nullptr,
867
                                                   i18n("File %1 exists.\nDo you want to replace it?", _job->url().toLocalFile()), i18n("Save to File"), KGuiItem(i18n("&Replace")))
Laurent Montel's avatar
Laurent Montel committed
868
                == KMessageBox::Continue) {
869
870
871
                byteArrayToRemoteFile(_job->data(), _job->url(), true);
            }
        } else {
Laurent Montel's avatar
Laurent Montel committed
872
            KJobUiDelegate *ui = static_cast<KIO::Job *>(job)->uiDelegate();
873
874
875
876
877
            ui->showErrorMessage();
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
878
void AttachmentControllerBase::attachmentProperties(const AttachmentPart::Ptr &part)
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
{
    QPointer<AttachmentPropertiesDialog> dialog = new AttachmentPropertiesDialog(
        part, false, d->wParent);

    dialog->setEncryptEnabled(d->encryptEnabled);
    dialog->setSignEnabled(d->signEnabled);

    if (dialog->exec() && dialog) {
        d->model->updateAttachment(part);
    }
    delete dialog;
}

void AttachmentControllerBase::attachDirectory(const QUrl &url)
{
    const int rc = KMessageBox::warningYesNo(d->wParent, i18n("Do you really want to attach this directory \"%1\"?", url.toLocalFile()),
Laurent Montel's avatar
Laurent Montel committed
895
                                             i18nc("@title:window", "Attach directory"));
896
897
898
899
900
901
902
903
904
905
906
    if (rc == KMessageBox::Yes) {
        addAttachment(url);
    }
}

void AttachmentControllerBase::showAttachVcard()
{
    QPointer<Akonadi::EmailAddressSelectionDialog> dlg = new Akonadi::EmailAddressSelectionDialog(d->wParent);
    dlg->view()->view()->setSelectionMode(QAbstractItemView::MultiSelection);
    if (dlg->exec()) {
        const Akonadi::EmailAddressSelection::List selectedEmail = dlg->selectedAddresses();
Laurent Montel's avatar
Laurent Montel committed
907
        for (const Akonadi::EmailAddressSelection &selected : selectedEmail) {
908
            MessageComposer::AttachmentVcardFromAddressBookJob *ajob = new MessageComposer::AttachmentVcardFromAddressBookJob(selected.item(), this);
Laurent Montel's avatar
Laurent Montel committed
909
910
911
            connect(ajob, &AttachmentVcardFromAddressBookJob::result, this, [this](KJob *job) {
                d->attachVcardFromAddressBook(job);
            });
912
913
914
915
916
917
            ajob->start();
        }
    }
    delete dlg;
}

918
919
920
void AttachmentControllerBase::showAttachClipBoard()
{
    MessageComposer::AttachmentClipBoardJob *job = new MessageComposer::AttachmentClipBoardJob(this);
Laurent Montel's avatar
Laurent Montel committed
921
922
923
    connect(job, &AttachmentClipBoardJob::result, this, [this](KJob *job) {
        d->attachClipBoardElement(job);
    });
924
925
926
    job->start();
}

927
928
929
930
931
932
933
934
935
936
937
void AttachmentControllerBase::showAddAttachmentCompressedDirectoryDialog()
{
    const QUrl url = QFileDialog::getExistingDirectoryUrl(d->wParent, i18nc("@title:window", "Attach Directory"));
    if (url.isValid()) {
        attachDirectory(url);
    }
}

void AttachmentControllerBase::showAddAttachmentFileDialog()
{
    KEncodingFileDialog::Result result = KEncodingFileDialog::getOpenUrlsAndEncoding(QString(),
Laurent Montel's avatar
Laurent Montel committed
938
939
940
941
                                                                                     QUrl(),
                                                                                     QString(),
                                                                                     d->wParent,
                                                                                     i18nc("@title:window", "Attach File"));
942
    if (!result.URLs.isEmpty()) {
943
        const QString encoding = MimeTreeParser::NodeHelper::fixEncoding(result.encoding);
944
945
946
947
948
949
950
951
952
        const int numberOfFiles(result.URLs.count());
        for (int i = 0; i < numberOfFiles; ++i) {
            const QUrl url = result.URLs.at(i);
            QUrl urlWithEncoding = url;
            MessageCore::StringUtil::setEncodingFile(urlWithEncoding, encoding);
            QMimeDatabase mimeDb;
            auto mimeType = mimeDb.mimeTypeForUrl(urlWithEncoding);
            if (mimeType.name() == QLatin1String("inode/directory")) {
                const int rc = KMessageBox::warningYesNo(d->wParent, i18n("Do you really want to attach this directory \"%1\"?", url.toLocalFile()),
Laurent Montel's avatar
Laurent Montel committed
953
                                                         i18nc("@title:window", "Attach directory"));
954
955
956
957
958
959
960
961
962
963
                if (rc == KMessageBox::Yes) {
                    addAttachment(urlWithEncoding);
                }
            } else {
                addAttachment(urlWithEncoding);
            }
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
964
void AttachmentControllerBase::addAttachment(const AttachmentPart::Ptr &part)
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
{
    part->setEncrypted(d->model->isEncryptSelected());
    part->setSigned(d->model->isSignSelected());
    d->model->addAttachment(part);

    Q_EMIT fileAttached();
}

void AttachmentControllerBase::addAttachmentUrlSync(const QUrl &url)
{
    MessageCore::AttachmentFromUrlBaseJob *ajob = MessageCore::AttachmentFromUrlUtils::createAttachmentJob(url, this);
    if (ajob->exec()) {
        AttachmentPart::Ptr part = ajob->attachmentPart();
        addAttachment(part);
    } else {
        if (ajob->error()) {
            KMessageBox::sorry(d->wParent, ajob->errorString(), i18nc("@title:window", "Failed to attach file"));
        }
    }
}

void AttachmentControllerBase::addAttachment(const QUrl &url)
{
    MessageCore::AttachmentFromUrlBaseJob *ajob = MessageCore::AttachmentFromUrlUtils::createAttachmentJob(url, this);
Laurent Montel's avatar
Laurent Montel committed
989
990
991
    connect(ajob, &AttachmentFromUrlBaseJob::result, this, [this](KJob *job) {
        d->loadJobResult(job);
    });
992
993
994
995
996
    ajob->start();
}

void AttachmentControllerBase::addAttachments(const QList<QUrl> &urls)
{
Laurent Montel's avatar
Laurent Montel committed
997
    for (const QUrl &url : urls) {
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
        addAttachment(url);
    }
}

void AttachmentControllerBase::showAttachPublicKeyDialog()
{
    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 */,
Laurent Montel's avatar
Laurent Montel committed
1012
        d->wParent);
1013

Laurent Montel's avatar
Laurent Montel committed
1014
    if (dialog->exec() == QDialog::Accepted) {
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
        exportPublicKey(dialog->fingerprint());
    }
    delete dialog;
}

void AttachmentControllerBase::attachMyPublicKey()
{
}

void AttachmentControllerBase::enableAttachPublicKey(bool enable)
{
    d->attachPublicKeyAction->setEnabled(enable);
}

void AttachmentControllerBase::enableAttachMyPublicKey(bool enable)
{
    d->attachMyPublicKeyAction->setEnabled(enable);
}

void AttachmentControllerBase::setAttachOwnVcard(bool attachVcard)
{
    d->addOwnVcardAction->setChecked(attachVcard);
}

bool AttachmentControllerBase::attachOwnVcard() const
{
Laurent Montel's avatar
Laurent Montel committed
1041
    return d->addOwnVcardAction->isChecked();
1042
1043
1044
1045
1046
1047
1048
1049
}

void AttachmentControllerBase::setIdentityHasOwnVcard(bool state)
{
    d->addOwnVcardAction->setEnabled(state);
}

#include "moc_attachmentcontrollerbase.cpp"