viewer_p.cpp 109 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

Laurent Montel's avatar
Laurent Montel committed
150
151
#include "remote-content/remotecontentmenu.h"

152
153
154
155
156
157
158
using namespace boost;
using namespace MailTransport;
using namespace MessageViewer;
using namespace MessageCore;

static QAtomicInt _k_attributeInitialized;

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

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

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

Laurent Montel's avatar
Laurent Montel committed
188
189
    mRemoteContentMenu = new MessageViewer::RemoteContentMenu(mMainWindow);

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

199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    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
214
    connect(&mResizeTimer, &QTimer::timeout, this, &ViewerPrivate::slotDelayedResize);
215
216

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

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

Laurent Montel's avatar
Laurent Montel committed
221
    connect(mColorBar, &HtmlStatusBar::clicked, this, &ViewerPrivate::slotToggleHtmlMode);
222
223
224

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

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

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

260
void ViewerPrivate::openAttachment(KMime::Content *node, const QUrl &url)
261
262
263
264
265
{
    if (!node) {
        return;
    }

266
267
    if (auto ct = node->contentType(false)) {
        if (ct->mimeType() == "text/x-moz-deleted") {
268
269
            return;
        }
270
        if (ct->mimeType() == "message/external-body") {
Laurent Montel's avatar
Laurent Montel committed
271
            if (ct->hasParameter(QStringLiteral("url"))) {
Laurent Montel's avatar
Laurent Montel committed
272
                auto job = new KIO::OpenUrlJob(url, QStringLiteral("text/html"));
Laurent Montel's avatar
Laurent Montel committed
273
274
                job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, q));
                job->start();
275
276
277
278
279
280
281
282
283
                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
284
        KMime::Message::Ptr m(new KMime::Message);
285
286
        m->setContent(node->parent()->bodyAsMessage()->encodedContent());
        m->parse();
Laurent Montel's avatar
Laurent Montel committed
287
        attachmentViewMessage(m);
288
289
290
291
292
        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
293
    auto mimetype = mimeDb.mimeTypeForName(QString::fromLatin1(node->contentType()->mimeType().toLower()));
294
295
296
297
298
299
    if (mimetype.isValid() && mimetype.inherits(KContacts::Addressee::mimeType())) {
        showVCard(node);
        return;
    }

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

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

313
    const QString filenameText = MimeTreeParser::NodeHelper::fileName(node);
314

Laurent Montel's avatar
Laurent Montel committed
315
    QPointer<AttachmentDialog> dialog = new AttachmentDialog(mMainWindow, filenameText, offer, QLatin1String("askSave_") + mimetype.name());
Laurent Montel's avatar
Laurent Montel committed
316
317
    const int choice = dialog->exec();
    delete dialog;
318
    if (choice == AttachmentDialog::Save) {
319
        QList<QUrl> urlList;
Laurent Montel's avatar
Laurent Montel committed
320
        if (Util::saveContents(mMainWindow, KMime::Content::List() << node, urlList)) {
321
            showSavedFileFolderWidget(urlList, MessageViewer::OpenSavedFileFolderWidget::FileType::Attachment);
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        }
    } 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
346
    const QVector<KMime::Content *> extraNodes = mNodeHelper->extraContents(mMessage.data());
347
348
    if (extraNodes.contains(node->topLevel())) {
        KMessageBox::error(mMainWindow,
Laurent Montel's avatar
Laurent Montel committed
349
                           i18n("Deleting an attachment from an encrypted or old-style mailman message is not supported."),
350
                           i18n("Delete Attachment"));
Laurent Montel's avatar
Laurent Montel committed
351
        return true; // cancelled
352
353
    }

Laurent Montel's avatar
Laurent Montel committed
354
355
356
357
358
359
360
361
362
    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
363
    }
Laurent Montel's avatar
Laurent Montel committed
364
    // don't confuse the model
365
366
367
368
    mMimePartTree->clearModel();
    QString filename;
    QString name;
    QByteArray mimetype;
Laurent Montel's avatar
Laurent Montel committed
369
370
    if (auto cd = node->contentDisposition(false)) {
        filename = cd->filename();
371
372
    }

373
374
375
    if (auto ct = node->contentType(false)) {
        name = ct->name();
        mimetype = ct->mimeType();
376
377
378
    }

    // text/plain part:
Laurent Montel's avatar
Laurent Montel committed
379
    auto deletePart = new KMime::Content(parent);
Laurent Montel's avatar
Laurent Montel committed
380
381
382
    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
383
384
    deletePart->contentDisposition(true)->setDisposition(KMime::Headers::CDattachment);
    deletePart->contentDisposition(false)->setFilename(QStringLiteral("Deleted: %1").arg(name));
385

Laurent Montel's avatar
Laurent Montel committed
386
    deleteCt->setCharset("utf-8");
387
    deletePart->contentTransferEncoding()->setEncoding(KMime::Headers::CE7Bit);
Laurent Montel's avatar
Laurent Montel committed
388
    QByteArray bodyMessage = QByteArrayLiteral("\nYou deleted an attachment from this message. The original MIME headers for the attachment were:");
389
390
391
392
393
394
395
396
397
398
399
    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
400
    auto job = new Akonadi::ItemModifyJob(mMessageItem, mSession);
401
402
403
404
405
406
407
408
409
410
    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 {
411
        setMessageItem(mMessageItem, MimeTreeParser::Force);
412
413
414
    }
}

Laurent Montel's avatar
Laurent Montel committed
415
void ViewerPrivate::scrollToAnchor(const QString &anchor)
416
{
Laurent Montel's avatar
Laurent Montel committed
417
    mViewer->scrollToAnchor(anchor);
418
419
}

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

        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
428
            connect(actionGroup, &QActionGroup::triggered, this, &ViewerPrivate::slotOpenWithActionCurrentContent);
429
        } else {
Laurent Montel's avatar
Laurent Montel committed
430
            connect(actionGroup, &QActionGroup::triggered, this, &ViewerPrivate::slotOpenWithAction);
431
432
433
434
435
436
437
        }

        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
438
        // qCDebug(MESSAGEVIEWER_LOG) << offers.count() << "offers" << topMenu << menu;
439

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

        menu->addAction(openWithAct);
    } else { // no app offers -> Open With...
Laurent Montel's avatar
Laurent Montel committed
466
        auto act = new QAction(topMenu);
467
468
        act->setText(i18nc("@title:menu", "&Open With..."));
        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
469
            connect(act, &QAction::triggered, this, &ViewerPrivate::slotOpenWithDialogCurrentContent);
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
        } 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
487
    const auto contents = selectedContents();
488
489
490
491
492
493
494
495
496
497
    if (contents.count() == 1) {
        attachmentOpenWith(contents.first());
    }
}

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

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

Laurent Montel's avatar
Laurent Montel committed
511
void ViewerPrivate::showAttachmentPopup(KMime::Content *node, const QString &name, const QPoint &globalPos)
512
{
Laurent Montel's avatar
Laurent Montel committed
513
    Q_UNUSED(name)
Laurent Montel's avatar
Laurent Montel committed
514
    prepareHandleAttachment(node);
515
    bool deletedAttachment = false;
Laurent Montel's avatar
Laurent Montel committed
516
517
518
    QString contentTypeStr;
    if (auto contentType = node->contentType(false)) {
        contentTypeStr = QLatin1String(contentType->mimeType());
519
    }
520
521
522
    if (contentTypeStr == QStringLiteral("message/global")) { // Not registred in mimetype => it's a message/rfc822
        contentTypeStr = QStringLiteral("message/rfc822");
    }
Laurent Montel's avatar
Laurent Montel committed
523
    deletedAttachment = (contentTypeStr == QStringLiteral("text/x-moz-deleted"));
Laurent Montel's avatar
Laurent Montel committed
524
    // Not necessary to show popup menu when attachment was removed
525
526
527
528
529
    if (deletedAttachment) {
        return;
    }

    QMenu menu;
530

Laurent Montel's avatar
Laurent Montel committed
531
    QAction *action = menu.addAction(QIcon::fromTheme(QStringLiteral("document-open")), i18nc("to open", "Open"));
532
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
533
534
535
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Open);
    });
536
    if (!deletedAttachment) {
Laurent Montel's avatar
Laurent Montel committed
537
        createOpenWithMenu(&menu, contentTypeStr, true);
538
539
540
541
542
543
    }

    QMimeDatabase mimeDb;
    auto mimetype = mimeDb.mimeTypeForName(contentTypeStr);
    if (mimetype.isValid()) {
        const QStringList parentMimeType = mimetype.parentMimeTypes();
Laurent Montel's avatar
Laurent Montel committed
544
545
546
        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
547
            action = menu.addAction(i18nc("to view something", "View"));
548
            action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
549
550
551
            connect(action, &QAction::triggered, this, [this]() {
                slotHandleAttachment(Viewer::View);
            });
552
553
554
        }
    }

Laurent Montel's avatar
Laurent Montel committed
555
556
557
558
    action = menu.addAction(i18n("Scroll To"));
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ScrollTo);
    });
559

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

Laurent Montel's avatar
Laurent Montel committed
566
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18n("Copy"));
567
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
568
569
570
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Copy);
    });
571
572

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

Laurent Montel's avatar
Laurent Montel committed
576
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18n("Delete Attachment"));
Laurent Montel's avatar
Laurent Montel committed
577
578
579
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Delete);
    });
Laurent Montel's avatar
Laurent Montel committed
580

581
    action->setEnabled(canChange && !deletedAttachment);
582
583
584
#if 0
    menu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
585
586
587
    action
        = menu->addAction(QIcon::fromTheme(QStringLiteral("mail-reply-sender")),
                          i18n("Reply To Author"));
Laurent Montel's avatar
Laurent Montel committed
588
589
590
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ReplyMessageToAuthor);
    });
Laurent Montel's avatar
Laurent Montel committed
591
592
593

    menu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
594
595
    action = menu->addAction(QIcon::fromTheme(QStringLiteral("mail-reply-all")), i18n(
                                 "Reply To All"));
Laurent Montel's avatar
Laurent Montel committed
596
597
598
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ReplyMessageToAll);
    });
599
#endif
Laurent Montel's avatar
Laurent Montel committed
600
601
    menu.addSeparator();
    action = menu.addAction(i18n("Properties"));
Laurent Montel's avatar
Laurent Montel committed
602
603
604
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Properties);
    });
Laurent Montel's avatar
Laurent Montel committed
605
    menu.exec(globalPos);
606
607
}

Laurent Montel's avatar
Laurent Montel committed
608
void ViewerPrivate::prepareHandleAttachment(KMime::Content *node)
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
{
    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
626
        return KService::Ptr(nullptr);
627
628
629
630
    }

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

Laurent Montel's avatar
Laurent Montel committed
636
KMime::Content::List ViewerPrivate::selectedContents() const
637
638
639
640
641
642
643
644
{
    return mMimePartTree->selectedContents();
}

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

645
    // Make sure that it will not deleted when we switch from message.
Laurent Montel's avatar
Laurent Montel committed
646
    auto tmpDir = new QTemporaryDir(QDir::tempPath() + QLatin1String("/messageviewer_attachment_XXXXXX"));
647
648
649
650
651
652
653
654
655
    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
656
            qCDebug(MESSAGEVIEWER_LOG) << " File was not able to copy: filename: " << name << " to " << path;
657
658
659
660
        } else {
            name = newPath;
        }
        f.close();
661
    } else {
662
        delete tmpDir;
663
664
    }

665
666
667
668
    QList<QUrl> lst;
    const QFileDevice::Permissions perms = QFile::permissions(name);
    QFile::setPermissions(name, perms | QFileDevice::ReadUser | QFileDevice::WriteUser);
    const QUrl url = QUrl::fromLocalFile(name);
669
    lst.append(url);
Laurent Montel's avatar
Laurent Montel committed
670

Laurent Montel's avatar
Laurent Montel committed
671
    auto job = new KIO::ApplicationLauncherJob(offer);
Laurent Montel's avatar
Laurent Montel committed
672
673
674
675
676
    job->setUrls({url});
    job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, mMainWindow));
    job->start();
    connect(job, &KJob::result, this, [url, job]() {
        if (job->error()) {
677
678
            QFile::remove(url.toLocalFile());
        }
Laurent Montel's avatar
Laurent Montel committed
679
    });
680
681
682
683
}

void ViewerPrivate::attachmentOpen(KMime::Content *node)
{
Laurent Montel's avatar
Laurent Montel committed
684
    const KService::Ptr offer = getServiceOffer(node);
685
686
687
688
689
690
691
    if (!offer) {
        qCDebug(MESSAGEVIEWER_LOG) << "got no offer";
        return;
    }
    attachmentOpenWith(node, offer);
}

692
693
bool ViewerPrivate::showEmoticons() const
{
694
    return mForceEmoticons;
695
696
}

697
HtmlWriter *ViewerPrivate::htmlWriter() const
698
699
700
701
702
703
{
    return mHtmlWriter;
}

CSSHelper *ViewerPrivate::cssHelper() const
{
704
    return mMessageViewerRenderer->cssHelper();
705
706
}

707
MimeTreeParser::NodeHelper *ViewerPrivate::nodeHelper() const
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
{
    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
729
    if (MessageViewer::MessageViewerSettings::self()->alwaysDecrypt()) {
730
        return true;
Laurent Montel's avatar
Laurent Montel committed
731
732
    } else {
        return mDecrytMessageOverwrite;
733
734
735
736
737
    }
}

void ViewerPrivate::displaySplashPage(const QString &message)
{
Laurent Montel's avatar
Laurent Montel committed
738
739
740
741
742
    displaySplashPage(QStringLiteral("status.html"),
                      {{QStringLiteral("icon"), QStringLiteral("kmail")},
                       {QStringLiteral("name"), i18n("KMail")},
                       {QStringLiteral("subtitle"), i18n("The KDE Mail Client")},
                       {QStringLiteral("message"), message}});
743
744
}

Laurent Montel's avatar
Laurent Montel committed
745
void ViewerPrivate::displaySplashPage(const QString &templateName, const QVariantHash &data, const QByteArray &domain)
746
{
Laurent Montel's avatar
Laurent Montel committed
747
748
749
750
    if (mViewer) {
        mMsgDisplay = false;
        adjustLayout();

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

void ViewerPrivate::enableMessageDisplay()
{
764
765
766
    if (mMsgDisplay) {
        return;
    }
767
768
769
770
771
772
773
774
775
776
777
    mMsgDisplay = true;
    adjustLayout();
}

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

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

    if (mMessageItem.hasAttribute<MessageViewer::MessageDisplayFormatAttribute>()) {
Laurent Montel's avatar
Laurent Montel committed
778
        const MessageViewer::MessageDisplayFormatAttribute *const attr = mMessageItem.attribute<MessageViewer::MessageDisplayFormatAttribute>();
779
780
781
782
        setHtmlLoadExtOverride(attr->remoteContent());
        setDisplayFormatMessageOverwrite(attr->messageFormat());
    }

Volker Krause's avatar
Volker Krause committed
783
    htmlWriter()->begin();
Laurent Montel's avatar
Laurent Montel committed
784
    htmlWriter()->write(cssHelper()->htmlHead(mUseFixedFont));
785
786
787
788
789
790
791

    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.
792
    mColorBar->setMode(MimeTreeParser::Util::Normal, HtmlStatusBar::NoUpdate);
793
794

    if (mMessageItem.hasAttribute<ErrorAttribute>()) {
Laurent Montel's avatar
Laurent Montel committed
795
        // TODO: Insert link to clear error so that message might be resent
796
797
        const ErrorAttribute *const attr = mMessageItem.attribute<ErrorAttribute>();
        Q_ASSERT(attr);
Laurent Montel's avatar
Laurent Montel committed
798
        initializeColorFromScheme();
799

Laurent Montel's avatar
Laurent Montel committed
800
801
        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
802
        htmlWriter()->write(QStringLiteral("<p></p>"));
803
804
805
806
807
808
    }

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

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

Volker Krause's avatar
Volker Krause committed
813
    htmlWriter()->end();
814
815
816
817
}

void ViewerPrivate::parseContent(KMime::Content *content)
{
Laurent Montel's avatar
Laurent Montel committed
818
    assert(content != nullptr);
819
    mNodeHelper->removeTempFiles();
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839

    // 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
840
    auto *message = dynamic_cast<KMime::Message *>(content);
841
    bool onlySingleNode = mMessage.data() != content;
842
843
844
845

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

848
    otp.setAllowAsync(!mPrinting);
849
    otp.parseObjectTree(content, onlySingleNode);
850
    htmlWriter()->setCodec(otp.plainTextContentCharset());
851
852
853
854
    if (message) {
        htmlWriter()->write(writeMessageHeader(message, hasVCard ? vCardContent : nullptr, true));
    }

855
    otpSource.render(otp.parsedPart(), onlySingleNode);
856

857
858
859
860
861
    // 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
862
863
    MimeTreeParser::KMMsgEncryptionState encryptionState = mNodeHelper->overallEncryptionState(content);
    MimeTreeParser::KMMsgSignatureState signatureState = mNodeHelper->overallSignatureState(content);
864
865
866
    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
867
    if (signatureState != MimeTreeParser::KMMsgNotSigned || mNodeHelper->signatureState(content) == MimeTreeParser::KMMsgSignatureStateUnknown) {
868
869
870
        mNodeHelper->setSignatureState(content, signatureState);
    }

871
872
873
874
875
    if (!onlySingleNode && isAutocryptEnabled(message)) {
        auto mixup = HeaderMixupNodeHelper(mNodeHelper, message);
        processAutocryptfromMail(mixup);
    }

876
877
878
    showHideMimeTree();
}

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

Laurent Montel's avatar
Laurent Montel committed
902
        style->setMessageStatus(status);
Laurent Montel's avatar
Laurent Montel committed
903
    } else {
Laurent Montel's avatar
Laurent Montel committed
904
        style->setReadOnlyMessage(true);
905
906
    }

Laurent Montel's avatar
Laurent Montel committed
907
    return style->format(aMsg);
908
909
910
911
912
913
}

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

Laurent Montel's avatar
Laurent Montel committed
914
    auto vcv = new VCardViewer(mMainWindow, vCard);
915
916
917
918
919
920
921
    vcv->setAttribute(Qt::WA_DeleteOnClose);
    vcv->show();
}

void ViewerPrivate::initHtmlWidget()
{
    if (!htmlWriter()) {
Laurent Montel's avatar
Laurent Montel committed
922
        mPartHtmlWriter = new WebEnginePartHtmlWriter(mViewer, nullptr);
923
924
        mHtmlWriter = mPartHtmlWriter;
    }
Laurent Montel's avatar
Laurent Montel committed
925
926
927
928
929
    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);
930
931
    connect(mViewer, &MailWebEngineView::formSubmittedForbidden, mSubmittedFormWarning, &SubmittedFormWarningWidget::showWarning);
    connect(mViewer, &MailWebEngineView::mailTrackingFound, mMailTrackingWarning, &MailTrackingWarningWidget::addTracker);
Laurent Montel's avatar
Laurent Montel committed
932
933
934
935
936
    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
937
938
939
940
941
    connect(mViewer, &MailWebEngineView::urlBlocked, this, &ViewerPrivate::slotUrlBlocked);
}

void ViewerPrivate::slotUrlBlocked(const QUrl &url)
{
Laurent Montel's avatar
Laurent Montel committed
942
    mRemoteContentMenu->appendUrl(url.adjusted(QUrl::RemovePath | QUrl::RemovePort | QUrl::RemoveQuery).toString());
Laurent Montel's avatar
Laurent Montel committed
943
944
945
946
947
}

RemoteContentMenu *ViewerPrivate::remoteContentMenu() const
{
    return mRemoteContentMenu;
948
949
}

Laurent Montel's avatar
Laurent Montel committed
950
void ViewerPrivate::applyZoomValue(qreal factor, bool saveConfig)
951
{
Laurent Montel's avatar
Laurent Montel committed
952
953
    if (mZoomActionMenu) {
        if (factor >= 10 && factor <= 300) {
Laurent Montel's avatar
Laurent Montel committed
954
            if (!qFuzzyCompare(mZoomActionMenu->zoomFactor(), factor)) {
Laurent Montel's avatar
Laurent Montel committed
955
956
957
958
959
960
                mZoomActionMenu->setZoomFactor(factor);
                mZoomActionMenu->setWebViewerZoomFactor(factor / 100.0);
                if (saveConfig) {
                    MessageViewer::MessageViewerSettings::self()->setZoomFactor(factor);
                }
            }
Laurent Montel's avatar
Laurent Montel committed
961
        }
962
963
964
    }
}

965
966
void ViewerPrivate::setWebViewZoomFactor(qreal factor)
{
Laurent Montel's avatar
Laurent Montel committed
967
    applyZoomValue(factor, false);
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
}

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

985
986
void ViewerPrivate::readConfig()
{
987
    mMessageViewerRenderer->setCurrentWidget(mViewer);
Laurent Montel's avatar
Laurent Montel committed
988
    recreateCssHelper();
989

990
991
992
993
    mForceEmoticons = MessageViewer::MessageViewerSettings::self()->showEmoticons();
    if (mDisableEmoticonAction) {
        mDisableEmoticonAction->setChecked(!mForceEmoticons);
    }
994
995
996
997
    if (headerStylePlugin()) {
        headerStylePlugin()->headerStyle()->setShowEmoticons(mForceEmoticons);
    }

998
999
1000
1001
1002
1003
1004
    mUseFixedFont = MessageViewer::MessageViewerSettings::self()->useFixedFont();
    if (mToggleFixFontAction) {
        mToggleFixFontAction->setChecked(mUseFixedFont);
    }

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

Laurent Montel's avatar
Laurent Montel committed
1005
    MessageViewer::Util::readGravatarConfig();
1006
1007
1008
1009
    if (mHeaderStyleMenuManager) {
        mHeaderStyleMenuManager->readConfig();
    }

Laurent Montel's avatar
Laurent Montel committed
1010
    setAttachmentStrategy(AttachmentStrategy::create(MessageViewer::MessageViewerSettings::self()->attachmentStrategy()));
1011
1012
1013
1014
1015
1016
1017
1018
    KToggleAction *raction = actionForAttachmentStrategy(attachmentStrategy());
    if (raction) {
        raction->setChecked(true);
    }

    adjustLayout();

    readGlobalOverrideCodec();
1019
    mViewer->readConfig();
Laurent Montel's avatar
Laurent Montel committed
1020
1021
    mViewer->settings()->setFontSize(QWebEngineSettings::MinimumFontSize, MessageViewer::MessageViewerSettings::self()->minimumFontSize());
    mViewer->settings()->setFontSize(QWebEngineSettings::MinimumLogicalFontSize, MessageViewer::MessageViewerSettings::self()->minimumFontSize());
1022
1023
1024
1025
    if (mMessage) {
        update();
    }
    mColorBar->update();
Laurent Montel's avatar
Laurent Montel committed
1026
    applyZoomValue(MessageViewer::MessageViewerSettings::self()->zoomFactor(), false);
1027
1028
}

Laurent Montel's avatar
Laurent Montel committed
1029
void ViewerPrivate::recreateCssHelper()
1030
{
1031
    mMessageViewerRenderer->recreateCssHelper();
Laurent Montel's avatar
Laurent Montel committed
1032
1033
}

<