viewer_p.cpp 108 KB
Newer Older
1
/*
2
3
4
5
  SPDX-FileCopyrightText: 1997 Markus Wuebben <markus.wuebben@kde.org>
  SPDX-FileCopyrightText: 2009 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net
  SPDX-FileCopyrightText: 2009 Andras Mantia <andras@kdab.net>
  SPDX-FileCopyrightText: 2010 Torgny Nyblom <nyblom@kde.org>
Laurent Montel's avatar
Laurent Montel committed
6
  SPDX-FileCopyrightText: 2011-2021 Laurent Montel <montel@kde.org>
7

8
  SPDX-License-Identifier: GPL-2.0-or-later
9
10
*/
#include "viewer_p.h"
Laurent Montel's avatar
Laurent Montel committed
11
#include "viewerpurposemenuwidget.h"
12

Laurent Montel's avatar
Laurent Montel committed
13
#include "messagedisplayformatattribute.h"
14
#include "messageviewer_debug.h"
Laurent Montel's avatar
Laurent Montel committed
15
16
17
#include "scamdetection/scamattribute.h"
#include "scamdetection/scamdetectionwarningwidget.h"
#include "utils/iconnamecache.h"
Sandro Knauß's avatar
Sandro Knauß committed
18
#include "utils/mimetype.h"
Laurent Montel's avatar
Laurent Montel committed
19
#include "viewer/mimeparttree/mimeparttreeview.h"
20
21
#include "viewer/objecttreeemptysource.h"
#include "viewer/objecttreeviewersource.h"
Laurent Montel's avatar
Laurent Montel committed
22
#include "viewer/renderer/messageviewerrenderer.h"
23

24
#include "messageviewer/headerstrategy.h"
Laurent Montel's avatar
Laurent Montel committed
25
#include "messageviewer/headerstyle.h"
Laurent Montel's avatar
Laurent Montel committed
26
#include "widgets/developertooldialog.h"
Laurent Montel's avatar
Laurent Montel committed
27
#include <KPIMTextEdit/SlideContainer>
Laurent Montel's avatar
Laurent Montel committed
28

29
#include "job/modifymessagedisplayformatjob.h"
Laurent Montel's avatar
Laurent Montel committed
30

Laurent Montel's avatar
Laurent Montel committed
31
#include "htmlwriter/webengineembedpart.h"
32
#include "viewerplugins/viewerplugintoolmanager.h"
Laurent Montel's avatar
Laurent Montel committed
33
#include <KContacts/VCardConverter>
Laurent Montel's avatar
Laurent Montel committed
34
// KDE includes
35
36
37
#include <KActionCollection>
#include <KActionMenu>
#include <KCharsets>
Laurent Montel's avatar
Laurent Montel committed
38
39
#include <QAction>
#include <QHBoxLayout>
Laurent Montel's avatar
Laurent Montel committed
40
#include <QPrintPreviewDialog>
Laurent Montel's avatar
Laurent Montel committed
41
#include <QVBoxLayout>
Laurent Montel's avatar
Laurent Montel committed
42

Laurent Montel's avatar
Laurent Montel committed
43
44
45
#include <Akonadi/KMime/SpecialMailCollections>
#include <AkonadiCore/ItemCreateJob>
#include <AkonadiCore/ItemModifyJob>
Nicolas Fella's avatar
Nicolas Fella committed
46
#include <KApplicationTrader>
Laurent Montel's avatar
Laurent Montel committed
47
48
49
#include <KEmailAddress>
#include <KFileItemActions>
#include <KIO/ApplicationLauncherJob>
Laurent Montel's avatar
Laurent Montel committed
50
51
#include <KIO/JobUiDelegate>
#include <KIO/OpenUrlJob>
Laurent Montel's avatar
Laurent Montel committed
52
53
54
#include <KLocalizedString>
#include <KMessageBox>
#include <KMimeTypeChooser>
55
#include <KSelectAction>
56
#include <KSharedConfig>
57
58
#include <KStandardGuiItem>
#include <KToggleAction>
Laurent Montel's avatar
Laurent Montel committed
59
60
#include <MailTransportAkonadi/ErrorAttribute>
#include <MessageCore/Util>
61
#include <QIcon>
Laurent Montel's avatar
Laurent Montel committed
62
#include <QMenu>
63
#include <QMimeData>
Laurent Montel's avatar
Laurent Montel committed
64
#include <QTemporaryDir>
65
#include <messageflags.h>
66

Laurent Montel's avatar
Laurent Montel committed
67
// Qt includes
68
69
#include <QClipboard>
#include <QItemSelectionModel>
Laurent Montel's avatar
Laurent Montel committed
70
71
72
#include <QMimeDatabase>
#include <QPrintDialog>
#include <QPrinter>
73
74
#include <QSplitter>
#include <QTreeView>
Laurent Montel's avatar
Laurent Montel committed
75
#include <QWheelEvent>
Laurent Montel's avatar
Laurent Montel committed
76
#include <WebEngineViewer/WebEngineExportHtmlPageJob>
Laurent Montel's avatar
Laurent Montel committed
77
// libkdepim
78
#include <MessageCore/AttachmentPropertiesDialog>
Laurent Montel's avatar
Laurent Montel committed
79
#include <PimCommon/BroadcastStatus>
80

Laurent Montel's avatar
Laurent Montel committed
81
82
83
#include <Akonadi/KMime/MessageParts>
#include <Akonadi/KMime/MessageStatus>
#include <AkonadiCore/attributefactory.h>
84
85
86
87
#include <AkonadiCore/collection.h>
#include <AkonadiCore/itemfetchjob.h>
#include <AkonadiCore/itemfetchscope.h>

88
#include <MessageCore/AutocryptUtils>
89
90
91
#include <KIdentityManagement/Identity>
#include <KIdentityManagement/IdentityManager>

Laurent Montel's avatar
Laurent Montel committed
92
// own includes
93
#include "csshelper.h"
Laurent Montel's avatar
Laurent Montel committed
94
#include "messageviewer/messageviewerutil.h"
95
#include "settings/messageviewersettings.h"
Laurent Montel's avatar
Laurent Montel committed
96
#include "utils/messageviewerutil_p.h"
97
#include "viewer/attachmentstrategy.h"
98
99
#include "viewer/mimeparttree/mimetreemodel.h"
#include "viewer/urlhandlermanager.h"
Laurent Montel's avatar
Laurent Montel committed
100
101
#include "widgets/attachmentdialog.h"
#include "widgets/htmlstatusbar.h"
102
#include "widgets/shownextmessagewidget.h"
Laurent Montel's avatar
Laurent Montel committed
103
#include "widgets/vcardviewer.h"
104

105
#include "header/headerstylemenumanager.h"
Laurent Montel's avatar
Laurent Montel committed
106
107
#include "htmlwriter/webengineparthtmlwriter.h"
#include "viewer/webengine/mailwebengineview.h"
108
#include "widgets/submittedformwarningwidget.h"
Laurent Montel's avatar
Laurent Montel committed
109
#include <WebEngineViewer/FindBarWebEngineView>
Laurent Montel's avatar
Laurent Montel committed
110
#include <WebEngineViewer/LocalDataBaseManager>
111
#include <WebEngineViewer/WebEngineExportPdfPageJob>
Laurent Montel's avatar
Laurent Montel committed
112
113
#include <WebEngineViewer/WebHitTestResult>
#include <widgets/mailsourcewebengineviewer.h>
114

115
#include "interfaces/htmlwriter.h"
Laurent Montel's avatar
Laurent Montel committed
116
#include <MimeTreeParser/BodyPart>
117
118
#include <MimeTreeParser/NodeHelper>
#include <MimeTreeParser/ObjectTreeParser>
119
120
121

#include <MessageCore/StringUtil>

122
#include <MessageCore/MessageCoreSettings>
Laurent Montel's avatar
Laurent Montel committed
123
#include <MessageCore/NodeHelper>
124

Laurent Montel's avatar
Laurent Montel committed
125
#include <AkonadiCore/CollectionFetchJob>
126
127
128
129
#include <AkonadiCore/agentinstance.h>
#include <AkonadiCore/agentmanager.h>
#include <AkonadiCore/collectionfetchscope.h>

Laurent Montel's avatar
Laurent Montel committed
130
#include "widgets/mailtrackingwarningwidget.h"
131
#include <KJobWidgets/KJobWidgets>
Laurent Montel's avatar
Laurent Montel committed
132
#include <KPIMTextEdit/TextToSpeechWidget>
133
134
#include <QApplication>
#include <QStandardPaths>
135
#include <QWebEngineSettings>
Laurent Montel's avatar
Laurent Montel committed
136
137
#include <WebEngineViewer/ZoomActionMenu>
#include <boost/bind.hpp>
138
139
140
#include <header/headerstyleplugin.h>
#include <viewerplugins/viewerplugininterface.h>

Laurent Montel's avatar
Laurent Montel committed
141
#include <GrantleeTheme/GrantleeTheme>
Laurent Montel's avatar
Laurent Montel committed
142
#include <GrantleeTheme/GrantleeThemeManager>
143

144
#include "dkim-verify/dkimmanager.h"
Laurent Montel's avatar
Laurent Montel committed
145
#include "dkim-verify/dkimmanagerulesdialog.h"
Laurent Montel's avatar
Laurent Montel committed
146
#include "dkim-verify/dkimresultattribute.h"
Laurent Montel's avatar
Laurent Montel committed
147
#include "dkim-verify/dkimviewermenu.h"
Laurent Montel's avatar
Laurent Montel committed
148
#include "dkim-verify/dkimwidgetinfo.h"
149

150
151
152
153
154
155
156
using namespace boost;
using namespace MailTransport;
using namespace MessageViewer;
using namespace MessageCore;

static QAtomicInt _k_attributeInitialized;

Laurent Montel's avatar
Laurent Montel committed
157
template<typename Arg, typename R, typename C> struct InvokeWrapper {
158
159
    R *receiver;
    void (C::*memberFun)(Arg);
Laurent Montel's avatar
Laurent Montel committed
160
161
    void operator()(Arg result)
    {
162
163
164
165
        (receiver->*memberFun)(result);
    }
};

Laurent Montel's avatar
Laurent Montel committed
166
template<typename Arg, typename R, typename C> InvokeWrapper<Arg, R, C> invoke(R *receiver, void (C::*memberFun)(Arg))
167
168
169
170
171
{
    InvokeWrapper<Arg, R, C> wrapper = {receiver, memberFun};
    return wrapper;
}

Laurent Montel's avatar
Laurent Montel committed
172
ViewerPrivate::ViewerPrivate(Viewer *aParent, QWidget *mainWindow, KActionCollection *actionCollection)
Laurent Montel's avatar
Laurent Montel committed
173
174
175
176
177
178
    : QObject(aParent)
    , mNodeHelper(new MimeTreeParser::NodeHelper)
    , mOldGlobalOverrideEncoding(QStringLiteral("---"))
    , mMainWindow(mainWindow)
    , mActionCollection(actionCollection)
    , q(aParent)
Laurent Montel's avatar
Laurent Montel committed
179
    , mSession(new Akonadi::Session("MessageViewer-" + QByteArray::number(reinterpret_cast<quintptr>(this)), this))
180
181
182
183
{
    if (!mainWindow) {
        mMainWindow = aParent;
    }
184
185
    mMessageViewerRenderer = new MessageViewerRenderer;

186
    mDkimWidgetInfo = new MessageViewer::DKIMWidgetInfo(mMainWindow);
187
188
189
190
    if (_k_attributeInitialized.testAndSetAcquire(0, 1)) {
        Akonadi::AttributeFactory::registerAttribute<MessageViewer::MessageDisplayFormatAttribute>();
        Akonadi::AttributeFactory::registerAttribute<MessageViewer::ScamAttribute>();
    }
191
192
    mPhishingDatabase = new WebEngineViewer::LocalDataBaseManager(this);
    mPhishingDatabase->initialize();
Laurent Montel's avatar
Laurent Montel committed
193
    connect(mPhishingDatabase, &WebEngineViewer::LocalDataBaseManager::checkUrlFinished, this, &ViewerPrivate::slotCheckedUrlFinished);
Laurent Montel's avatar
Laurent Montel committed
194

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    mShareServiceManager = new PimCommon::ShareServiceUrlManager(this);

    mDisplayFormatMessageOverwrite = MessageViewer::Viewer::UseGlobalSetting;

    mUpdateReaderWinTimer.setObjectName(QStringLiteral("mUpdateReaderWinTimer"));
    mResizeTimer.setObjectName(QStringLiteral("mResizeTimer"));

    createWidgets();
    createActions();
    initHtmlWidget();
    readConfig();

    mLevelQuote = MessageViewer::MessageViewerSettings::self()->collapseQuoteLevelSpin() - 1;

    mResizeTimer.setSingleShot(true);
Laurent Montel's avatar
Laurent Montel committed
210
    connect(&mResizeTimer, &QTimer::timeout, this, &ViewerPrivate::slotDelayedResize);
211
212

    mUpdateReaderWinTimer.setSingleShot(true);
Laurent Montel's avatar
Laurent Montel committed
213
    connect(&mUpdateReaderWinTimer, &QTimer::timeout, this, &ViewerPrivate::updateReaderWin);
214

Laurent Montel's avatar
Laurent Montel committed
215
    connect(mNodeHelper, &MimeTreeParser::NodeHelper::update, this, &ViewerPrivate::update);
216

Laurent Montel's avatar
Laurent Montel committed
217
    connect(mColorBar, &HtmlStatusBar::clicked, this, &ViewerPrivate::slotToggleHtmlMode);
218
219
220

    // FIXME: Don't use the full payload here when attachment loading on demand is used, just
    //        like in KMMainWidget::slotMessageActivated().
221
    mMonitor.setObjectName(QStringLiteral("MessageViewerMonitor"));
222
    mMonitor.setSession(mSession);
223
224
225
226
227
    Akonadi::ItemFetchScope fs;
    fs.fetchFullPayload();
    fs.fetchAttribute<MailTransport::ErrorAttribute>();
    fs.fetchAttribute<MessageViewer::MessageDisplayFormatAttribute>();
    fs.fetchAttribute<MessageViewer::ScamAttribute>();
Laurent Montel's avatar
Laurent Montel committed
228
    fs.fetchAttribute<MessageViewer::DKIMResultAttribute>();
229
    mMonitor.setItemFetchScope(fs);
Laurent Montel's avatar
Laurent Montel committed
230
231
232
    connect(&mMonitor, &Akonadi::Monitor::itemChanged, this, &ViewerPrivate::slotItemChanged);
    connect(&mMonitor, &Akonadi::Monitor::itemRemoved, this, &ViewerPrivate::slotClear);
    connect(&mMonitor, &Akonadi::Monitor::itemMoved, this, &ViewerPrivate::slotItemMoved);
233
234
235
236
}

ViewerPrivate::~ViewerPrivate()
{
237
    delete mDeveloperToolDialog;
Laurent Montel's avatar
Laurent Montel committed
238
    delete mMessageViewerRenderer;
239
    MessageViewer::MessageViewerSettings::self()->save();
Laurent Montel's avatar
Laurent Montel committed
240
241
242
243
    delete mHtmlWriter;
    mHtmlWriter = nullptr;
    delete mViewer;
    mViewer = nullptr;
244
    mNodeHelper->forceCleanTempFiles();
245
    qDeleteAll(mListMailSourceViewer);
Laurent Montel's avatar
Laurent Montel committed
246
    mMessage.clear();
247
248
249
250
251
252
253
254
255
    delete mNodeHelper;
}

//-----------------------------------------------------------------------------
KMime::Content *ViewerPrivate::nodeFromUrl(const QUrl &url) const
{
    return mNodeHelper->fromHREF(mMessage, url);
}

256
void ViewerPrivate::openAttachment(KMime::Content *node, const QUrl &url)
257
258
259
260
261
{
    if (!node) {
        return;
    }

262
263
    if (auto ct = node->contentType(false)) {
        if (ct->mimeType() == "text/x-moz-deleted") {
264
265
            return;
        }
266
        if (ct->mimeType() == "message/external-body") {
Laurent Montel's avatar
Laurent Montel committed
267
            if (ct->hasParameter(QStringLiteral("url"))) {
Laurent Montel's avatar
Laurent Montel committed
268
                auto job = new KIO::OpenUrlJob(url, QStringLiteral("text/html"));
Laurent Montel's avatar
Laurent Montel committed
269
270
                job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, q));
                job->start();
271
272
273
274
275
276
277
278
279
                return;
            }
        }
    }

    const bool isEncapsulatedMessage = node->parent() && node->parent()->bodyIsMessage();
    if (isEncapsulatedMessage) {
        // the viewer/urlhandlermanager expects that the message (mMessage) it is passed is the root when doing index calculation
        // in urls. Simply passing the result of bodyAsMessage() does not cut it as the resulting pointer is a child in its tree.
Laurent Montel's avatar
Minor    
Laurent Montel committed
280
        KMime::Message::Ptr m(new KMime::Message);
281
282
        m->setContent(node->parent()->bodyAsMessage()->encodedContent());
        m->parse();
Laurent Montel's avatar
Laurent Montel committed
283
        attachmentViewMessage(m);
284
285
286
287
288
        return;
    }
    // determine the MIME type of the attachment
    // prefer the value of the Content-Type header
    QMimeDatabase mimeDb;
Laurent Montel's avatar
Laurent Montel committed
289
    auto mimetype = mimeDb.mimeTypeForName(QString::fromLatin1(node->contentType()->mimeType().toLower()));
290
291
292
293
294
295
    if (mimetype.isValid() && mimetype.inherits(KContacts::Addressee::mimeType())) {
        showVCard(node);
        return;
    }

    // special case treatment on mac and windows
296
297
298
    QUrl atmUrl = url;
    if (url.isEmpty()) {
        atmUrl = mNodeHelper->tempFileUrlFromNode(node);
299
    }
300
    if (Util::handleUrlWithQDesktopServices(atmUrl)) {
301
302
303
304
        return;
    }

    if (!mimetype.isValid() || mimetype.name() == QLatin1String("application/octet-stream")) {
Laurent Montel's avatar
Laurent Montel committed
305
        mimetype = MimeTreeParser::Util::mimetype(url.isLocalFile() ? url.toLocalFile() : url.fileName());
306
    }
Laurent Montel's avatar
Laurent Montel committed
307
    KService::Ptr offer = KApplicationTrader::preferredService(mimetype.name());
308

309
    const QString filenameText = MimeTreeParser::NodeHelper::fileName(node);
310

Laurent Montel's avatar
Laurent Montel committed
311
    QPointer<AttachmentDialog> dialog = new AttachmentDialog(mMainWindow, filenameText, offer, QLatin1String("askSave_") + mimetype.name());
Laurent Montel's avatar
Laurent Montel committed
312
313
    const int choice = dialog->exec();
    delete dialog;
314
    if (choice == AttachmentDialog::Save) {
315
        QList<QUrl> urlList;
Laurent Montel's avatar
Laurent Montel committed
316
        if (Util::saveContents(mMainWindow, KMime::Content::List() << node, urlList)) {
317
            showSavedFileFolderWidget(urlList, MessageViewer::OpenSavedFileFolderWidget::FileType::Attachment);
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        }
    } else if (choice == AttachmentDialog::Open) { // Open
        if (offer) {
            attachmentOpenWith(node, offer);
        } else {
            attachmentOpen(node);
        }
    } else if (choice == AttachmentDialog::OpenWith) {
        attachmentOpenWith(node);
    } else { // Cancel
        qCDebug(MESSAGEVIEWER_LOG) << "Canceled opening attachment";
    }
}

bool ViewerPrivate::deleteAttachment(KMime::Content *node, bool showWarning)
{
    if (!node) {
        return true;
    }
    KMime::Content *parent = node->parent();
    if (!parent) {
        return true;
    }

Laurent Montel's avatar
Laurent Montel committed
342
    const QVector<KMime::Content *> extraNodes = mNodeHelper->extraContents(mMessage.data());
343
344
    if (extraNodes.contains(node->topLevel())) {
        KMessageBox::error(mMainWindow,
Laurent Montel's avatar
Laurent Montel committed
345
                           i18n("Deleting an attachment from an encrypted or old-style mailman message is not supported."),
346
                           i18n("Delete Attachment"));
Laurent Montel's avatar
Laurent Montel committed
347
        return true; // cancelled
348
349
    }

Laurent Montel's avatar
Laurent Montel committed
350
351
352
353
354
355
356
357
358
    if (showWarning
        && KMessageBox::warningContinueCancel(mMainWindow,
                                              i18n("Deleting an attachment might invalidate any digital signature on this message."),
                                              i18n("Delete Attachment"),
                                              KStandardGuiItem::del(),
                                              KStandardGuiItem::cancel(),
                                              QStringLiteral("DeleteAttachmentSignatureWarning"))
            != KMessageBox::Continue) {
        return false; // cancelled
359
    }
Laurent Montel's avatar
Laurent Montel committed
360
    // don't confuse the model
361
362
363
364
    mMimePartTree->clearModel();
    QString filename;
    QString name;
    QByteArray mimetype;
Laurent Montel's avatar
Laurent Montel committed
365
366
    if (auto cd = node->contentDisposition(false)) {
        filename = cd->filename();
367
368
    }

369
370
371
    if (auto ct = node->contentType(false)) {
        name = ct->name();
        mimetype = ct->mimeType();
372
373
374
    }

    // text/plain part:
Laurent Montel's avatar
Laurent Montel committed
375
    auto deletePart = new KMime::Content(parent);
Laurent Montel's avatar
Laurent Montel committed
376
377
378
    auto deleteCt = deletePart->contentType(true);
    deleteCt->setMimeType("text/x-moz-deleted");
    deleteCt->setName(QStringLiteral("Deleted: %1").arg(name), "utf8");
Laurent Montel's avatar
Laurent Montel committed
379
380
    deletePart->contentDisposition(true)->setDisposition(KMime::Headers::CDattachment);
    deletePart->contentDisposition(false)->setFilename(QStringLiteral("Deleted: %1").arg(name));
381

Laurent Montel's avatar
Laurent Montel committed
382
    deleteCt->setCharset("utf-8");
383
    deletePart->contentTransferEncoding()->setEncoding(KMime::Headers::CE7Bit);
Laurent Montel's avatar
Laurent Montel committed
384
    QByteArray bodyMessage = QByteArrayLiteral("\nYou deleted an attachment from this message. The original MIME headers for the attachment were:");
385
386
387
388
389
390
391
392
393
394
395
    bodyMessage += ("\nContent-Type: ") + mimetype;
    bodyMessage += ("\nname=\"") + name.toUtf8() + "\"";
    bodyMessage += ("\nfilename=\"") + filename.toUtf8() + "\"";
    deletePart->setBody(bodyMessage);
    parent->replaceContent(node, deletePart);

    parent->assemble();

    KMime::Message *modifiedMessage = mNodeHelper->messageWithExtraContent(mMessage.data());
    mMimePartTree->mimePartModel()->setRoot(modifiedMessage);
    mMessageItem.setPayloadFromData(modifiedMessage->encodedContent());
Laurent Montel's avatar
Laurent Montel committed
396
    auto job = new Akonadi::ItemModifyJob(mMessageItem, mSession);
397
398
399
400
401
402
403
404
405
406
    job->disableRevisionCheck();
    connect(job, &KJob::result, this, &ViewerPrivate::itemModifiedResult);
    return true;
}

void ViewerPrivate::itemModifiedResult(KJob *job)
{
    if (job->error()) {
        qCDebug(MESSAGEVIEWER_LOG) << "Item update failed:" << job->errorString();
    } else {
407
        setMessageItem(mMessageItem, MimeTreeParser::Force);
408
409
410
    }
}

Laurent Montel's avatar
Laurent Montel committed
411
void ViewerPrivate::scrollToAnchor(const QString &anchor)
412
{
Laurent Montel's avatar
Laurent Montel committed
413
    mViewer->scrollToAnchor(anchor);
414
415
}

Laurent Montel's avatar
Laurent Montel committed
416
void ViewerPrivate::createOpenWithMenu(QMenu *topMenu, const QString &contentTypeStr, bool fromCurrentContent)
417
{
Laurent Montel's avatar
Laurent Montel committed
418
    const KService::List offers = KFileItemActions::associatedApplications(QStringList() << contentTypeStr, QString());
419
420
    if (!offers.isEmpty()) {
        QMenu *menu = topMenu;
Laurent Montel's avatar
Laurent Montel committed
421
        auto actionGroup = new QActionGroup(menu);
422
423

        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
424
            connect(actionGroup, &QActionGroup::triggered, this, &ViewerPrivate::slotOpenWithActionCurrentContent);
425
        } else {
Laurent Montel's avatar
Laurent Montel committed
426
            connect(actionGroup, &QActionGroup::triggered, this, &ViewerPrivate::slotOpenWithAction);
427
428
429
430
431
432
433
        }

        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);
        }
Laurent Montel's avatar
Laurent Montel committed
434
        // qCDebug(MESSAGEVIEWER_LOG) << offers.count() << "offers" << topMenu << menu;
435

Laurent Montel's avatar
Laurent Montel committed
436
437
        for (const KService::Ptr &ser : offers) {
            QAction *act = MessageViewer::Util::createAppAction(ser,
Laurent Montel's avatar
Laurent Montel committed
438
                                                                // no submenu -> prefix single offer
Laurent Montel's avatar
Laurent Montel committed
439
440
441
                                                                menu == topMenu,
                                                                actionGroup,
                                                                menu);
442
443
444
445
446
447
448
449
450
451
            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...");
        }
Laurent Montel's avatar
Laurent Montel committed
452
        auto openWithAct = new QAction(menu);
453
454
        openWithAct->setText(openWithActionName);
        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
455
            connect(openWithAct, &QAction::triggered, this, &ViewerPrivate::slotOpenWithDialogCurrentContent);
456
457
458
459
460
461
        } else {
            connect(openWithAct, &QAction::triggered, this, &ViewerPrivate::slotOpenWithDialog);
        }

        menu->addAction(openWithAct);
    } else { // no app offers -> Open With...
Laurent Montel's avatar
Laurent Montel committed
462
        auto act = new QAction(topMenu);
463
464
        act->setText(i18nc("@title:menu", "&Open With..."));
        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
465
            connect(act, &QAction::triggered, this, &ViewerPrivate::slotOpenWithDialogCurrentContent);
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        } else {
            connect(act, &QAction::triggered, this, &ViewerPrivate::slotOpenWithDialog);
        }
        topMenu->addAction(act);
    }
}

void ViewerPrivate::slotOpenWithDialogCurrentContent()
{
    if (!mCurrentContent) {
        return;
    }
    attachmentOpenWith(mCurrentContent);
}

void ViewerPrivate::slotOpenWithDialog()
{
Laurent Montel's avatar
Laurent Montel committed
483
    const auto contents = selectedContents();
484
485
486
487
488
489
490
491
492
493
    if (contents.count() == 1) {
        attachmentOpenWith(contents.first());
    }
}

void ViewerPrivate::slotOpenWithActionCurrentContent(QAction *act)
{
    if (!mCurrentContent) {
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
494
    const KService::Ptr app = act->data().value<KService::Ptr>();
495
496
497
498
499
    attachmentOpenWith(mCurrentContent, app);
}

void ViewerPrivate::slotOpenWithAction(QAction *act)
{
Laurent Montel's avatar
Laurent Montel committed
500
501
    const KService::Ptr app = act->data().value<KService::Ptr>();
    const auto contents = selectedContents();
502
503
504
505
506
    if (contents.count() == 1) {
        attachmentOpenWith(contents.first(), app);
    }
}

Laurent Montel's avatar
Laurent Montel committed
507
void ViewerPrivate::showAttachmentPopup(KMime::Content *node, const QString &name, const QPoint &globalPos)
508
{
Laurent Montel's avatar
Laurent Montel committed
509
    Q_UNUSED(name)
Laurent Montel's avatar
Laurent Montel committed
510
    prepareHandleAttachment(node);
511
    bool deletedAttachment = false;
Laurent Montel's avatar
Laurent Montel committed
512
513
514
    QString contentTypeStr;
    if (auto contentType = node->contentType(false)) {
        contentTypeStr = QLatin1String(contentType->mimeType());
515
    }
Laurent Montel's avatar
Laurent Montel committed
516
    deletedAttachment = (contentTypeStr == QStringLiteral("text/x-moz-deleted"));
Laurent Montel's avatar
Laurent Montel committed
517
    // Not necessary to show popup menu when attachment was removed
518
519
520
521
522
    if (deletedAttachment) {
        return;
    }

    QMenu menu;
523

Laurent Montel's avatar
Laurent Montel committed
524
    QAction *action = menu.addAction(QIcon::fromTheme(QStringLiteral("document-open")), i18nc("to open", "Open"));
525
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
526
527
528
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Open);
    });
529
    if (!deletedAttachment) {
Laurent Montel's avatar
Laurent Montel committed
530
        createOpenWithMenu(&menu, contentTypeStr, true);
531
532
533
534
535
536
    }

    QMimeDatabase mimeDb;
    auto mimetype = mimeDb.mimeTypeForName(contentTypeStr);
    if (mimetype.isValid()) {
        const QStringList parentMimeType = mimetype.parentMimeTypes();
Laurent Montel's avatar
Laurent Montel committed
537
538
539
        if ((contentTypeStr == QLatin1String("text/plain")) || (contentTypeStr == QLatin1String("image/png")) || (contentTypeStr == QLatin1String("image/jpeg"))
            || parentMimeType.contains(QLatin1String("text/plain")) || parentMimeType.contains(QLatin1String("image/png"))
            || parentMimeType.contains(QLatin1String("image/jpeg"))) {
Laurent Montel's avatar
Laurent Montel committed
540
            action = menu.addAction(i18nc("to view something", "View"));
541
            action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
542
543
544
            connect(action, &QAction::triggered, this, [this]() {
                slotHandleAttachment(Viewer::View);
            });
545
546
547
        }
    }

Laurent Montel's avatar
Laurent Montel committed
548
549
550
551
    action = menu.addAction(i18n("Scroll To"));
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ScrollTo);
    });
552

Laurent Montel's avatar
Laurent Montel committed
553
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("document-save-as")), i18n("Save As..."));
554
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
555
556
557
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Save);
    });
558

Laurent Montel's avatar
Laurent Montel committed
559
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18n("Copy"));
560
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
561
562
563
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Copy);
    });
564
565

    const bool isEncapsulatedMessage = node->parent() && node->parent()->bodyIsMessage();
Laurent Montel's avatar
Laurent Montel committed
566
    const bool canChange = mMessageItem.isValid() && mMessageItem.parentCollection().isValid()
Laurent Montel's avatar
Laurent Montel committed
567
        && (mMessageItem.parentCollection().rights() != Akonadi::Collection::ReadOnly) && !isEncapsulatedMessage;
568

Laurent Montel's avatar
Laurent Montel committed
569
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18n("Delete Attachment"));
Laurent Montel's avatar
Laurent Montel committed
570
571
572
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Delete);
    });
Laurent Montel's avatar
Laurent Montel committed
573

574
    action->setEnabled(canChange && !deletedAttachment);
575
576
577
#if 0
    menu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
578
579
580
    action
        = menu->addAction(QIcon::fromTheme(QStringLiteral("mail-reply-sender")),
                          i18n("Reply To Author"));
Laurent Montel's avatar
Laurent Montel committed
581
582
583
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ReplyMessageToAuthor);
    });
Laurent Montel's avatar
Laurent Montel committed
584
585
586

    menu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
587
588
    action = menu->addAction(QIcon::fromTheme(QStringLiteral("mail-reply-all")), i18n(
                                 "Reply To All"));
Laurent Montel's avatar
Laurent Montel committed
589
590
591
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ReplyMessageToAll);
    });
592
#endif
Laurent Montel's avatar
Laurent Montel committed
593
594
    menu.addSeparator();
    action = menu.addAction(i18n("Properties"));
Laurent Montel's avatar
Laurent Montel committed
595
596
597
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Properties);
    });
Laurent Montel's avatar
Laurent Montel committed
598
    menu.exec(globalPos);
599
600
}

Laurent Montel's avatar
Laurent Montel committed
601
void ViewerPrivate::prepareHandleAttachment(KMime::Content *node)
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
{
    mCurrentContent = node;
}

KService::Ptr ViewerPrivate::getServiceOffer(KMime::Content *content)
{
    const QString fileName = mNodeHelper->writeNodeToTempFile(content);

    const QString contentTypeStr = QLatin1String(content->contentType()->mimeType());

    // determine the MIME type of the attachment
    // prefer the value of the Content-Type header
    QMimeDatabase mimeDb;
    auto mimetype = mimeDb.mimeTypeForName(contentTypeStr);

    if (mimetype.isValid() && mimetype.inherits(KContacts::Addressee::mimeType())) {
        attachmentView(content);
Laurent Montel's avatar
Laurent Montel committed
619
        return KService::Ptr(nullptr);
620
621
622
623
    }

    if (!mimetype.isValid() || mimetype.name() == QLatin1String("application/octet-stream")) {
        /*TODO(Andris) port when on-demand loading is done   && msgPart.isComplete() */
624
        mimetype = MimeTreeParser::Util::mimetype(fileName);
625
    }
Nicolas Fella's avatar
Nicolas Fella committed
626
    return KApplicationTrader::preferredService(mimetype.name());
627
628
}

Laurent Montel's avatar
Laurent Montel committed
629
KMime::Content::List ViewerPrivate::selectedContents() const
630
631
632
633
634
635
636
637
{
    return mMimePartTree->selectedContents();
}

void ViewerPrivate::attachmentOpenWith(KMime::Content *node, const KService::Ptr &offer)
{
    QString name = mNodeHelper->writeNodeToTempFile(node);

638
    // Make sure that it will not deleted when we switch from message.
Laurent Montel's avatar
Laurent Montel committed
639
    auto tmpDir = new QTemporaryDir(QDir::tempPath() + QLatin1String("/messageviewer_attachment_XXXXXX"));
640
641
642
643
644
645
646
647
648
    if (tmpDir->isValid()) {
        tmpDir->setAutoRemove(false);
        const QString path = tmpDir->path();
        delete tmpDir;
        QFile f(name);
        const QUrl tmpFileName = QUrl::fromLocalFile(name);
        const QString newPath = path + QLatin1Char('/') + tmpFileName.fileName();

        if (!f.copy(newPath)) {
Laurent Montel's avatar
Laurent Montel committed
649
            qCDebug(MESSAGEVIEWER_LOG) << " File was not able to copy: filename: " << name << " to " << path;
650
651
652
653
        } else {
            name = newPath;
        }
        f.close();
654
    } else {
655
        delete tmpDir;
656
657
    }

658
659
660
661
    QList<QUrl> lst;
    const QFileDevice::Permissions perms = QFile::permissions(name);
    QFile::setPermissions(name, perms | QFileDevice::ReadUser | QFileDevice::WriteUser);
    const QUrl url = QUrl::fromLocalFile(name);
662
    lst.append(url);
Laurent Montel's avatar
Laurent Montel committed
663

Laurent Montel's avatar
Laurent Montel committed
664
    auto job = new KIO::ApplicationLauncherJob(offer);
Laurent Montel's avatar
Laurent Montel committed
665
666
667
668
669
    job->setUrls({url});
    job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, mMainWindow));
    job->start();
    connect(job, &KJob::result, this, [url, job]() {
        if (job->error()) {
670
671
            QFile::remove(url.toLocalFile());
        }
Laurent Montel's avatar
Laurent Montel committed
672
    });
673
674
675
676
}

void ViewerPrivate::attachmentOpen(KMime::Content *node)
{
Laurent Montel's avatar
Laurent Montel committed
677
    const KService::Ptr offer = getServiceOffer(node);
678
679
680
681
682
683
684
    if (!offer) {
        qCDebug(MESSAGEVIEWER_LOG) << "got no offer";
        return;
    }
    attachmentOpenWith(node, offer);
}

685
686
bool ViewerPrivate::showEmoticons() const
{
687
    return mForceEmoticons;
688
689
}

690
HtmlWriter *ViewerPrivate::htmlWriter() const
691
692
693
694
695
696
{
    return mHtmlWriter;
}

CSSHelper *ViewerPrivate::cssHelper() const
{
697
    return mMessageViewerRenderer->cssHelper();
698
699
}

700
MimeTreeParser::NodeHelper *ViewerPrivate::nodeHelper() const
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
{
    return mNodeHelper;
}

Viewer *ViewerPrivate::viewer() const
{
    return q;
}

Akonadi::Item ViewerPrivate::messageItem() const
{
    return mMessageItem;
}

KMime::Message::Ptr ViewerPrivate::message() const
{
    return mMessage;
}

bool ViewerPrivate::decryptMessage() const
{
Laurent Montel's avatar
Laurent Montel committed
722
    if (MessageViewer::MessageViewerSettings::self()->alwaysDecrypt()) {
723
        return true;
Laurent Montel's avatar
Laurent Montel committed
724
725
    } else {
        return mDecrytMessageOverwrite;
726
727
728
729
730
    }
}

void ViewerPrivate::displaySplashPage(const QString &message)
{
Laurent Montel's avatar
Laurent Montel committed
731
732
733
734
735
    displaySplashPage(QStringLiteral("status.html"),
                      {{QStringLiteral("icon"), QStringLiteral("kmail")},
                       {QStringLiteral("name"), i18n("KMail")},
                       {QStringLiteral("subtitle"), i18n("The KDE Mail Client")},
                       {QStringLiteral("message"), message}});
736
737
}

Laurent Montel's avatar
Laurent Montel committed
738
void ViewerPrivate::displaySplashPage(const QString &templateName, const QVariantHash &data, const QByteArray &domain)
739
{
Laurent Montel's avatar
Laurent Montel committed
740
741
742
743
    if (mViewer) {
        mMsgDisplay = false;
        adjustLayout();

Laurent Montel's avatar
Laurent Montel committed
744
        GrantleeTheme::ThemeManager manager(QStringLiteral("splashPage"), QStringLiteral("splash.theme"), nullptr, QStringLiteral("messageviewer/about/"));
Laurent Montel's avatar
Laurent Montel committed
745
746
        GrantleeTheme::Theme theme = manager.theme(QStringLiteral("default"));
        if (theme.isValid()) {
Laurent Montel's avatar
Laurent Montel committed
747
            mViewer->setHtml(theme.render(templateName, data, domain), QUrl::fromLocalFile(theme.absolutePath() + QLatin1Char('/')));
Laurent Montel's avatar
Laurent Montel committed
748
749
750
751
        } else {
            qCDebug(MESSAGEVIEWER_LOG) << "Theme error: failed to find splash theme";
        }
        mViewer->show();
752
753
754
755
756
    }
}

void ViewerPrivate::enableMessageDisplay()
{
757
758
759
    if (mMsgDisplay) {
        return;
    }
760
761
762
763
764
765
766
767
768
769
770
    mMsgDisplay = true;
    adjustLayout();
}

void ViewerPrivate::displayMessage()
{
    showHideMimeTree();

    mNodeHelper->setOverrideCodec(mMessage.data(), overrideCodec());

    if (mMessageItem.hasAttribute<MessageViewer::MessageDisplayFormatAttribute>()) {
Laurent Montel's avatar
Laurent Montel committed
771
        const MessageViewer::MessageDisplayFormatAttribute *const attr = mMessageItem.attribute<MessageViewer::MessageDisplayFormatAttribute>();
772
773
774
775
        setHtmlLoadExtOverride(attr->remoteContent());
        setDisplayFormatMessageOverwrite(attr->messageFormat());
    }

Volker Krause's avatar
Volker Krause committed
776
    htmlWriter()->begin();
Laurent Montel's avatar
Laurent Montel committed
777
    htmlWriter()->write(cssHelper()->htmlHead(mUseFixedFont));
778
779
780
781
782
783
784

    if (!mMainWindow) {
        q->setWindowTitle(mMessage->subject()->asUnicodeString());
    }

    // Don't update here, parseMsg() can overwrite the HTML mode, which would lead to flicker.
    // It is updated right after parseMsg() instead.
785
    mColorBar->setMode(MimeTreeParser::Util::Normal, HtmlStatusBar::NoUpdate);
786
787

    if (mMessageItem.hasAttribute<ErrorAttribute>()) {
Laurent Montel's avatar
Laurent Montel committed
788
        // TODO: Insert link to clear error so that message might be resent
789
790
        const ErrorAttribute *const attr = mMessageItem.attribute<ErrorAttribute>();
        Q_ASSERT(attr);
Laurent Montel's avatar
Laurent Montel committed
791
        initializeColorFromScheme();
792

Laurent Montel's avatar
Laurent Montel committed
793
794
        htmlWriter()->write(QStringLiteral("<div style=\"background:%1;color:%2;border:1px solid %2\">%3</div>")
                                .arg(mBackgroundError.name(), mForegroundError.name(), attr->message().toHtmlEscaped()));
Volker Krause's avatar
Volker Krause committed
795
        htmlWriter()->write(QStringLiteral("<p></p>"));
796
797
798
799
800
801
    }

    parseContent(mMessage.data());
    mMimePartTree->setRoot(mNodeHelper->messageWithExtraContent(mMessage.data()));
    mColorBar->update();

Laurent Montel's avatar
Laurent Montel committed
802
    htmlWriter()->write(cssHelper()->endBodyHtml());
Laurent Montel's avatar
Laurent Montel committed
803
804
    connect(mViewer, &MailWebEngineView::loadFinished, this, &ViewerPrivate::executeCustomScriptsAfterLoading, Qt::UniqueConnection);
    connect(mPartHtmlWriter.data(), &WebEnginePartHtmlWriter::finished, this, &ViewerPrivate::slotMessageRendered, Qt::UniqueConnection);
805

Volker Krause's avatar
Volker Krause committed
806
    htmlWriter()->end();
807
808
809
810
}

void ViewerPrivate::parseContent(KMime::Content *content)
{
Laurent Montel's avatar
Laurent Montel committed
811
    assert(content != nullptr);
812
    mNodeHelper->removeTempFiles();
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832

    // Check if any part of this message is a v-card
    // v-cards can be either text/x-vcard or text/directory, so we need to check
    // both.
    KMime::Content *vCardContent = findContentByType(content, "text/x-vcard");
    if (!vCardContent) {
        vCardContent = findContentByType(content, "text/directory");
    }
    bool hasVCard = false;
    if (vCardContent) {
        // ### FIXME: We should only do this if the vCard belongs to the sender,
        // ### i.e. if the sender's email address is contained in the vCard.
        const QByteArray vCard = vCardContent->decodedContent();
        KContacts::VCardConverter t;
        if (!t.parseVCards(vCard).isEmpty()) {
            hasVCard = true;
            mNodeHelper->writeNodeToTempFile(vCardContent);
        }
    }

Laurent Montel's avatar
Laurent Montel committed
833
    auto *message = dynamic_cast<KMime::Message *>(content);
834
    bool onlySingleNode = mMessage.data() != content;
835
836
837
838

    // Pass control to the OTP now, which does the real work
    mNodeHelper->setNodeUnprocessed(mMessage.data(), true);
    MailViewerSource otpSource(this);
839
    MimeTreeParser::ObjectTreeParser otp(&otpSource, mNodeHelper);
840

841
    otp.setAllowAsync(!mPrinting);
842
    otp.parseObjectTree(content, onlySingleNode);
843
    htmlWriter()->setCodec(otp.plainTextContentCharset());
844
845
846
847
    if (message) {
        htmlWriter()->write(writeMessageHeader(message, hasVCard ? vCardContent : nullptr, true));
    }

848
    otpSource.render(otp.parsedPart(), onlySingleNode);
849

850
851
852
853
854
    // TODO: Setting the signature state to nodehelper is not enough, it should actually
    // be added to the store, so that the message list correctly displays the signature state
    // of messages that were parsed at least once
    // store encrypted/signed status information in the KMMessage
    //  - this can only be done *after* calling parseObjectTree()
Laurent Montel's avatar
Laurent Montel committed
855
856
    MimeTreeParser::KMMsgEncryptionState encryptionState = mNodeHelper->overallEncryptionState(content);
    MimeTreeParser::KMMsgSignatureState signatureState = mNodeHelper->overallSignatureState(content);
857
858
859
    mNodeHelper->setEncryptionState(content, encryptionState);
    // Don't reset the signature state to "not signed" (e.g. if one canceled the
    // decryption of a signed messages which has already been decrypted before).
Laurent Montel's avatar
Laurent Montel committed
860
    if (signatureState != MimeTreeParser::KMMsgNotSigned || mNodeHelper->signatureState(content) == MimeTreeParser::KMMsgSignatureStateUnknown) {
861
862
863
        mNodeHelper->setSignatureState(content, signatureState);
    }

864
865
866
867
868
    if (!onlySingleNode && isAutocryptEnabled(message)) {
        auto mixup = HeaderMixupNodeHelper(mNodeHelper, message);
        processAutocryptfromMail(mixup);
    }

869
870
871
    showHideMimeTree();
}

Laurent Montel's avatar
Laurent Montel committed
872
QString ViewerPrivate::writeMessageHeader(KMime::Message *aMsg, KMime::Content *vCardNode, bool topLevel)
873
874
{
    if (!headerStylePlugin()) {
Laurent Montel's avatar
Laurent Montel committed
875
        qCCritical(MESSAGEVIEWER_LOG) << "trying to writeMessageHeader() without a header style set!";
876
        return {};
877
    }
Laurent Montel's avatar
Laurent Montel committed
878
    HeaderStyle *style = headerStylePlugin()->headerStyle();
879
    if (vCardNode) {
Laurent Montel's avatar
Laurent Montel committed
880
        style->setVCardName(mNodeHelper->asHREF(vCardNode, QStringLiteral("body")));
881
882
    } else {
        style->setVCardName(QString());
Laurent Montel's avatar
Laurent Montel committed
883
884
885
886
887
888
889
890
    }
    style->setHeaderStrategy(headerStylePlugin()->headerStrategy());
    style->setPrinting(mPrinting);
    style->setTopLevel(topLevel);
    style->setAllowAsync(true);
    style->setSourceObject(this);
    style->setNodeHelper(mNodeHelper);
    style->setAttachmentHtml(attachmentHtml());
891
892
893
894
    if (mMessageItem.isValid()) {
        Akonadi::MessageStatus status;
        status.setStatusFromFlags(mMessageItem.flags());

Laurent Montel's avatar
Laurent Montel committed
895
        style->setMessageStatus(status);
Laurent Montel's avatar
Laurent Montel committed
896
    } else {
Laurent Montel's avatar
Laurent Montel committed
897
        style->setReadOnlyMessage(true);
898
899
    }

Laurent Montel's avatar
Laurent Montel committed
900
    return style->format(aMsg);
901
902
903
904
905
906
}

void ViewerPrivate::showVCard(KMime::Content *msgPart)
{
    const QByteArray vCard = msgPart->decodedContent();

Laurent Montel's avatar
Laurent Montel committed
907
    auto vcv = new VCardViewer(mMainWindow, vCard);
908
909
910
911
912
913
914
    vcv->setAttribute(Qt::WA_DeleteOnClose);
    vcv->show();
}

void ViewerPrivate::initHtmlWidget()
{
    if (!htmlWriter()) {
Laurent Montel's avatar
Laurent Montel committed
915
        mPartHtmlWriter = new WebEnginePartHtmlWriter(mViewer, nullptr);
916
917
        mHtmlWriter = mPartHtmlWriter;
    }
Laurent Montel's avatar
Laurent Montel committed
918
919
920
921
922
    connect(mViewer->page(), &QWebEnginePage::linkHovered, this, &ViewerPrivate::slotUrlOn);
    connect(mViewer, &MailWebEngineView::openUrl, this, &ViewerPrivate::slotUrlOpen, Qt::QueuedConnection);
    connect(mViewer, &MailWebEngineView::popupMenu, this, &ViewerPrivate::slotUrlPopup);
    connect(mViewer, &MailWebEngineView::wheelZoomChanged, this, &ViewerPrivate::slotWheelZoomChanged);
    connect(mViewer, &MailWebEngineView::messageMayBeAScam, this, &ViewerPrivate::slotMessageMayBeAScam);
923
924
    connect(mViewer, &MailWebEngineView::formSubmittedForbidden, mSubmittedFormWarning, &SubmittedFormWarningWidget::showWarning);
    connect(mViewer, &MailWebEngineView::mailTrackingFound, mMailTrackingWarning, &MailTrackingWarningWidget::addTracker);
Laurent Montel's avatar
Laurent Montel committed
925
926
927
928
929
    connect(mScamDetectionWarning, &ScamDetectionWarningWidget::showDetails, mViewer, &MailWebEngineView::slotShowDetails);
    connect(mScamDetectionWarning, &ScamDetectionWarningWidget::moveMessageToTrash, this, &ViewerPrivate::moveMessageToTrash);
    connect(mScamDetectionWarning, &ScamDetectionWarningWidget::messageIsNotAScam, this, &ViewerPrivate::slotMessageIsNotAScam);
    connect(mScamDetectionWarning, &ScamDetectionWarningWidget::addToWhiteList, this, &ViewerPrivate::slotAddToWhiteList);
    connect(mViewer, &MailWebEngineView::pageIsScrolledToBottom, this, &ViewerPrivate::pageIsScrolledToBottom);
Laurent Montel's avatar
Laurent Montel committed
930
931
932
933
934
    connect(mViewer, &MailWebEngineView::urlBlocked, this, &ViewerPrivate::slotUrlBlocked);
}

void ViewerPrivate::slotUrlBlocked(const QUrl &url)
{
935
936
}

Laurent Montel's avatar
Laurent Montel committed
937
void ViewerPrivate::applyZoomValue(qreal factor, bool saveConfig)
938
{
Laurent Montel's avatar
Laurent Montel committed
939
940
    if (mZoomActionMenu) {
        if (factor >= 10 && factor <= 300) {
Laurent Montel's avatar
Laurent Montel committed
941
942
943
944
945
946
947
            if (mZoomActionMenu->zoomFactor() != factor) {
                mZoomActionMenu->setZoomFactor(factor);
                mZoomActionMenu->setWebViewerZoomFactor(factor / 100.0);
                if (saveConfig) {
                    MessageViewer::MessageViewerSettings::self()->setZoomFactor(factor);
                }
            }
Laurent Montel's avatar
Laurent Montel committed
948
        }
949
950
951
    }
}

952
953
void ViewerPrivate::setWebViewZoomFactor(qreal factor)
{
Laurent Montel's avatar
Laurent Montel committed
954
    applyZoomValue(factor, false);
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
}

qreal ViewerPrivate::webViewZoomFactor() const
{
    qreal zoomFactor = -1;
    if (mZoomActionMenu) {
        zoomFactor = mZoomActionMenu->zoomFactor();
    }
    return zoomFactor;
}

void ViewerPrivate::slotWheelZoomChanged(int numSteps)
{
    const qreal factor = mZoomActionMenu->zoomFactor() + numSteps * 10;
    applyZoomValue(factor);
}

972
973
void ViewerPrivate::readConfig()
{
974
    mMessageViewerRenderer->setCurrentWidget(mViewer);
Laurent Montel's avatar
Laurent Montel committed
975
    recreateCssHelper();
976

977
978
979
980
    mForceEmoticons = MessageViewer::MessageViewerSettings::self()->showEmoticons();
    if (mDisableEmoticonAction) {
        mDisableEmoticonAction->setChecked(!mForceEmoticons);
    }
981
982
983
984
    if (headerStylePlugin()) {
        headerStylePlugin()->headerStyle()->setShowEmoticons(mForceEmoticons);
    }

985
986
987
988
989
990
991
    mUseFixedFont = MessageViewer::MessageViewerSettings::self()->useFixedFont();
    if (mToggleFixFontAction) {
        mToggleFixFontAction->setChecked(mUseFixedFont);
    }

    mHtmlMailGlobalSetting = MessageViewer::MessageViewerSettings::self()->htmlMail();

Laurent Montel's avatar
Laurent Montel committed
992
    MessageViewer::Util::readGravatarConfig();
993
994
995
996
    if (mHeaderStyleMenuManager) {
        mHeaderStyleMenuManager->readConfig();
    }

Laurent Montel's avatar
Laurent Montel committed
997
    setAttachmentStrategy(AttachmentStrategy::create(MessageViewer::MessageViewerSettings::self()->attachmentStrategy()));
998
999
1000
    KToggleAction *raction = actionForAttachmentStrategy(attachmentStrategy());
    if (raction) {
        raction->setChecked(true);