viewer_p.cpp 111 KB
Newer Older
1
/*
2
3
4
5
6
  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>
  SPDX-FileCopyrightText: 2011-2020 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
#include <kwidgetsaddons_version.h>
13

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

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

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

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

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

//Qt includes
#include <QClipboard>
#include <QItemSelectionModel>
#include <QSplitter>
#include <QTreeView>
#include <QPrinter>
#include <QPrintDialog>
#include <QMimeDatabase>
Laurent Montel's avatar
Laurent Montel committed
75
#include <QWheelEvent>
Laurent Montel's avatar
Laurent Montel committed
76
#include <WebEngineViewer/WebEngineExportHtmlPageJob>
77
//libkdepim
78
#include <PimCommon/BroadcastStatus>
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <MessageCore/AttachmentPropertiesDialog>

#include <AkonadiCore/collection.h>
#include <AkonadiCore/itemfetchjob.h>
#include <AkonadiCore/itemfetchscope.h>
#include <Akonadi/KMime/MessageStatus>
#include <AkonadiCore/attributefactory.h>
#include <Akonadi/KMime/MessageParts>

//own includes
#include "widgets/attachmentdialog.h"
#include "csshelper.h"
#include "settings/messageviewersettings.h"
#include "widgets/htmlstatusbar.h"
93
#include "viewer/attachmentstrategy.h"
94
95
96
#include "viewer/mimeparttree/mimetreemodel.h"
#include "viewer/urlhandlermanager.h"
#include "messageviewer/messageviewerutil.h"
97
#include "utils/messageviewerutil_p.h"
98
#include "widgets/vcardviewer.h"
99
#include "widgets/shownextmessagewidget.h"
100

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

111
#include <MimeTreeParser/BodyPart>
112
#include "interfaces/htmlwriter.h"
113
114
#include <MimeTreeParser/NodeHelper>
#include <MimeTreeParser/ObjectTreeParser>
115
116
117
118

#include <MessageCore/StringUtil>

#include <MessageCore/NodeHelper>
119
120
#include <MessageCore/MessageCoreSettings>

121
122
123
124
125
126
127
128
129
#include <AkonadiCore/agentinstance.h>
#include <AkonadiCore/agentmanager.h>
#include <AkonadiCore/CollectionFetchJob>
#include <AkonadiCore/collectionfetchscope.h>

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

137
#include <GrantleeTheme/GrantleeThemeManager>
Laurent Montel's avatar
Laurent Montel committed
138
#include <GrantleeTheme/GrantleeTheme>
139

140
#include "dkim-verify/dkimwidgetinfo.h"
141
#include "dkim-verify/dkimmanager.h"
Laurent Montel's avatar
Laurent Montel committed
142
#include "dkim-verify/dkimresultattribute.h"
Laurent Montel's avatar
Laurent Montel committed
143
#include "dkim-verify/dkimviewermenu.h"
Laurent Montel's avatar
Laurent Montel committed
144
#include "dkim-verify/dkimmanagerulesdialog.h"
145

146
147
148
149
150
151
152
using namespace boost;
using namespace MailTransport;
using namespace MessageViewer;
using namespace MessageCore;

static QAtomicInt _k_attributeInitialized;

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

template<typename Arg, typename R, typename C>
InvokeWrapper<Arg, R, C> invoke(R *receiver, void (C::*memberFun)(Arg))
{
    InvokeWrapper<Arg, R, C> wrapper = {receiver, memberFun};
    return wrapper;
}

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

185
    mDkimWidgetInfo = new MessageViewer::DKIMWidgetInfo(mMainWindow);
186
187
188
189
    if (_k_attributeInitialized.testAndSetAcquire(0, 1)) {
        Akonadi::AttributeFactory::registerAttribute<MessageViewer::MessageDisplayFormatAttribute>();
        Akonadi::AttributeFactory::registerAttribute<MessageViewer::ScamAttribute>();
    }
190
191
    mPhishingDatabase = new WebEngineViewer::LocalDataBaseManager(this);
    mPhishingDatabase->initialize();
Laurent Montel's avatar
Laurent Montel committed
192
    connect(mPhishingDatabase, &WebEngineViewer::LocalDataBaseManager::checkUrlFinished,
193
            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
210
211
212
213
214
215
216
    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);
    connect(&mResizeTimer, &QTimer::timeout,
            this, &ViewerPrivate::slotDelayedResize);

    mUpdateReaderWinTimer.setSingleShot(true);
    connect(&mUpdateReaderWinTimer, &QTimer::timeout,
            this, &ViewerPrivate::updateReaderWin);

217
218
219
    connect(mNodeHelper, &MimeTreeParser::NodeHelper::update,
            this, &ViewerPrivate::update);

220
221
222
223
224
    connect(mColorBar, &HtmlStatusBar::clicked,
            this, &ViewerPrivate::slotToggleHtmlMode);

    // 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
234
235
236
237
238
239
240
241
242
243
    mMonitor.setItemFetchScope(fs);
    connect(&mMonitor, &Akonadi::Monitor::itemChanged,
            this, &ViewerPrivate::slotItemChanged);
    connect(&mMonitor, &Akonadi::Monitor::itemRemoved,
            this, &ViewerPrivate::slotClear);
    connect(&mMonitor, &Akonadi::Monitor::itemMoved,
            this, &ViewerPrivate::slotItemMoved);
}

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

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

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

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

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

    if (!mimetype.isValid() || mimetype.name() == QLatin1String("application/octet-stream")) {
Laurent Montel's avatar
Laurent Montel committed
313
314
        mimetype = MimeTreeParser::Util::mimetype(
            url.isLocalFile() ? url.toLocalFile() : url.fileName());
315
    }
Laurent Montel's avatar
Laurent Montel committed
316
    KService::Ptr offer
Nicolas Fella's avatar
Nicolas Fella committed
317
        = KApplicationTrader::preferredService(mimetype.name());
318

319
    const QString filenameText = MimeTreeParser::NodeHelper::fileName(node);
320

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

    if (showWarning && KMessageBox::warningContinueCancel(mMainWindow,
Laurent Montel's avatar
Laurent Montel committed
365
366
367
368
369
370
371
372
                                                          i18n(
                                                              "Deleting an attachment might invalidate any digital signature on this message."),
                                                          i18n("Delete Attachment"),
                                                          KStandardGuiItem::del(),
                                                          KStandardGuiItem::cancel(),
                                                          QStringLiteral(
                                                              "DeleteAttachmentSignatureWarning"))
        != KMessageBox::Continue) {
373
374
375
376
377
378
379
        return false; //cancelled
    }
    //don't confuse the model
    mMimePartTree->clearModel();
    QString filename;
    QString name;
    QByteArray mimetype;
Laurent Montel's avatar
Laurent Montel committed
380
381
    if (auto cd = node->contentDisposition(false)) {
        filename = cd->filename();
382
383
    }

384
385
386
    if (auto ct = node->contentType(false)) {
        name = ct->name();
        mimetype = ct->mimeType();
387
388
389
    }

    // text/plain part:
Laurent Montel's avatar
Laurent Montel committed
390
    auto deletePart = new KMime::Content(parent);
Laurent Montel's avatar
Laurent Montel committed
391
392
393
    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
394
395
    deletePart->contentDisposition(true)->setDisposition(KMime::Headers::CDattachment);
    deletePart->contentDisposition(false)->setFilename(QStringLiteral("Deleted: %1").arg(name));
396

Laurent Montel's avatar
Laurent Montel committed
397
    deleteCt->setCharset("utf-8");
398
    deletePart->contentTransferEncoding()->setEncoding(KMime::Headers::CE7Bit);
Laurent Montel's avatar
Laurent Montel committed
399
400
    QByteArray bodyMessage = QByteArrayLiteral(
        "\nYou deleted an attachment from this message. The original MIME headers for the attachment were:");
401
402
403
404
405
406
407
408
409
410
411
    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
412
    auto job = new Akonadi::ItemModifyJob(mMessageItem, mSession);
413
414
415
416
417
418
419
420
421
422
    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 {
423
        setMessageItem(mMessageItem, MimeTreeParser::Force);
424
425
426
    }
}

Laurent Montel's avatar
Laurent Montel committed
427
void ViewerPrivate::scrollToAnchor(const QString &anchor)
428
{
Laurent Montel's avatar
Laurent Montel committed
429
    mViewer->scrollToAnchor(anchor);
430
431
}

Laurent Montel's avatar
Laurent Montel committed
432
void ViewerPrivate::createOpenWithMenu(QMenu *topMenu, const QString &contentTypeStr, bool fromCurrentContent)
433
{
Laurent Montel's avatar
Laurent Montel committed
434
435
    const KService::List offers = KFileItemActions::associatedApplications(
        QStringList() << contentTypeStr, QString());
436
437
    if (!offers.isEmpty()) {
        QMenu *menu = topMenu;
Laurent Montel's avatar
Laurent Montel committed
438
        auto actionGroup = new QActionGroup(menu);
439
440

        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
441
442
            connect(actionGroup, &QActionGroup::triggered, this,
                    &ViewerPrivate::slotOpenWithActionCurrentContent);
443
        } else {
Laurent Montel's avatar
Laurent Montel committed
444
445
            connect(actionGroup, &QActionGroup::triggered, this,
                    &ViewerPrivate::slotOpenWithAction);
446
447
448
449
450
451
452
        }

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

Laurent Montel's avatar
Laurent Montel committed
455
456
        for (const KService::Ptr &ser : offers) {
            QAction *act = MessageViewer::Util::createAppAction(ser,
Laurent Montel's avatar
Laurent Montel committed
457
458
                                                                // no submenu -> prefix single offer
                                                                menu == topMenu, actionGroup, menu);
459
460
461
462
463
464
465
466
467
468
            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
469
        auto openWithAct = new QAction(menu);
470
471
        openWithAct->setText(openWithActionName);
        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
472
473
            connect(openWithAct, &QAction::triggered, this,
                    &ViewerPrivate::slotOpenWithDialogCurrentContent);
474
475
476
477
478
479
        } else {
            connect(openWithAct, &QAction::triggered, this, &ViewerPrivate::slotOpenWithDialog);
        }

        menu->addAction(openWithAct);
    } else { // no app offers -> Open With...
Laurent Montel's avatar
Laurent Montel committed
480
        auto act = new QAction(topMenu);
481
482
        act->setText(i18nc("@title:menu", "&Open With..."));
        if (fromCurrentContent) {
Laurent Montel's avatar
Laurent Montel committed
483
484
            connect(act, &QAction::triggered, this,
                    &ViewerPrivate::slotOpenWithDialogCurrentContent);
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        } 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
502
    const auto contents = selectedContents();
503
504
505
506
507
508
509
510
511
512
    if (contents.count() == 1) {
        attachmentOpenWith(contents.first());
    }
}

void ViewerPrivate::slotOpenWithActionCurrentContent(QAction *act)
{
    if (!mCurrentContent) {
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
513
    const KService::Ptr app = act->data().value<KService::Ptr>();
514
515
516
517
518
    attachmentOpenWith(mCurrentContent, app);
}

void ViewerPrivate::slotOpenWithAction(QAction *act)
{
Laurent Montel's avatar
Laurent Montel committed
519
520
    const KService::Ptr app = act->data().value<KService::Ptr>();
    const auto contents = selectedContents();
521
522
523
524
525
    if (contents.count() == 1) {
        attachmentOpenWith(contents.first(), app);
    }
}

Laurent Montel's avatar
Laurent Montel committed
526
void ViewerPrivate::showAttachmentPopup(KMime::Content *node, const QString &name, const QPoint &globalPos)
527
{
Laurent Montel's avatar
Laurent Montel committed
528
    Q_UNUSED(name)
Laurent Montel's avatar
Laurent Montel committed
529
    prepareHandleAttachment(node);
530
    bool deletedAttachment = false;
Laurent Montel's avatar
Laurent Montel committed
531
532
533
    QString contentTypeStr;
    if (auto contentType = node->contentType(false)) {
        contentTypeStr = QLatin1String(contentType->mimeType());
534
    }
Laurent Montel's avatar
Laurent Montel committed
535
    deletedAttachment = (contentTypeStr == QStringLiteral("text/x-moz-deleted"));
536
537
538
539
540
541
    //Not necessary to show popup menu when attachment was removed
    if (deletedAttachment) {
        return;
    }

    QMenu menu;
542

Laurent Montel's avatar
Laurent Montel committed
543
    QAction *action
Laurent Montel's avatar
Laurent Montel committed
544
        = menu.addAction(QIcon::fromTheme(QStringLiteral("document-open")), i18nc("to open",
Laurent Montel's avatar
Laurent Montel committed
545
                                                                                  "Open"));
546
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
547
548
549
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Open);
    });
550
    if (!deletedAttachment) {
Laurent Montel's avatar
Laurent Montel committed
551
        createOpenWithMenu(&menu, contentTypeStr, true);
552
553
554
555
556
557
    }

    QMimeDatabase mimeDb;
    auto mimetype = mimeDb.mimeTypeForName(contentTypeStr);
    if (mimetype.isValid()) {
        const QStringList parentMimeType = mimetype.parentMimeTypes();
Laurent Montel's avatar
Laurent Montel committed
558
559
560
        if ((contentTypeStr == QLatin1String("text/plain"))
            || (contentTypeStr == QLatin1String("image/png"))
            || (contentTypeStr == QLatin1String("image/jpeg"))
Laurent Montel's avatar
Laurent Montel committed
561
562
563
            || parentMimeType.contains(QLatin1String("text/plain"))
            || parentMimeType.contains(QLatin1String("image/png"))
            || parentMimeType.contains(QLatin1String("image/jpeg"))
Laurent Montel's avatar
Laurent Montel committed
564
            ) {
Laurent Montel's avatar
Laurent Montel committed
565
            action = menu.addAction(i18nc("to view something", "View"));
566
            action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
567
568
569
            connect(action, &QAction::triggered, this, [this]() {
                slotHandleAttachment(Viewer::View);
            });
570
571
572
        }
    }

Laurent Montel's avatar
Laurent Montel committed
573
574
575
576
    action = menu.addAction(i18n("Scroll To"));
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ScrollTo);
    });
577

Laurent Montel's avatar
Laurent Montel committed
578
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("document-save-as")), i18n(
Laurent Montel's avatar
Laurent Montel committed
579
                                "Save As..."));
580
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
581
582
583
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Save);
    });
584

Laurent Montel's avatar
Laurent Montel committed
585
    action = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18n("Copy"));
586
    action->setEnabled(!deletedAttachment);
Laurent Montel's avatar
Laurent Montel committed
587
588
589
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Copy);
    });
590
591

    const bool isEncapsulatedMessage = node->parent() && node->parent()->bodyIsMessage();
Laurent Montel's avatar
Laurent Montel committed
592
593
594
595
    const bool canChange = mMessageItem.isValid() && mMessageItem.parentCollection().isValid()
                           && (mMessageItem.parentCollection().rights()
                               != Akonadi::Collection::ReadOnly)
                           && !isEncapsulatedMessage;
596

Laurent Montel's avatar
Laurent Montel committed
597
    action
Laurent Montel's avatar
Laurent Montel committed
598
        = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-delete")),
Laurent Montel's avatar
Laurent Montel committed
599
                         i18n("Delete Attachment"));
Laurent Montel's avatar
Laurent Montel committed
600
601
602
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Delete);
    });
Laurent Montel's avatar
Laurent Montel committed
603

604
    action->setEnabled(canChange && !deletedAttachment);
605
606
607
#if 0
    menu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
608
609
610
    action
        = menu->addAction(QIcon::fromTheme(QStringLiteral("mail-reply-sender")),
                          i18n("Reply To Author"));
Laurent Montel's avatar
Laurent Montel committed
611
612
613
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ReplyMessageToAuthor);
    });
Laurent Montel's avatar
Laurent Montel committed
614
615
616

    menu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
617
618
    action = menu->addAction(QIcon::fromTheme(QStringLiteral("mail-reply-all")), i18n(
                                 "Reply To All"));
Laurent Montel's avatar
Laurent Montel committed
619
620
621
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::ReplyMessageToAll);
    });
622
#endif
Laurent Montel's avatar
Laurent Montel committed
623
624
    menu.addSeparator();
    action = menu.addAction(i18n("Properties"));
Laurent Montel's avatar
Laurent Montel committed
625
626
627
    connect(action, &QAction::triggered, this, [this]() {
        slotHandleAttachment(Viewer::Properties);
    });
Laurent Montel's avatar
Laurent Montel committed
628
    menu.exec(globalPos);
629
630
}

Laurent Montel's avatar
Laurent Montel committed
631
void ViewerPrivate::prepareHandleAttachment(KMime::Content *node)
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
{
    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
649
        return KService::Ptr(nullptr);
650
651
652
653
    }

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

Laurent Montel's avatar
Laurent Montel committed
659
KMime::Content::List ViewerPrivate::selectedContents() const
660
661
662
663
664
665
666
667
{
    return mMimePartTree->selectedContents();
}

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

668
    // Make sure that it will not deleted when we switch from message.
Laurent Montel's avatar
Laurent Montel committed
669
    auto *tmpDir
Laurent Montel's avatar
Laurent Montel committed
670
        = new QTemporaryDir(QDir::tempPath() + QLatin1String("/messageviewer_attachment_XXXXXX"));
671
672
673
674
675
676
677
678
679
    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
680
            qCDebug(MESSAGEVIEWER_LOG) << " File was not able to copy: filename: " << name
Laurent Montel's avatar
Laurent Montel committed
681
                                       << " to " << path;
682
683
684
685
        } else {
            name = newPath;
        }
        f.close();
686
    } else {
687
        delete tmpDir;
688
689
    }

690
691
692
693
    QList<QUrl> lst;
    const QFileDevice::Permissions perms = QFile::permissions(name);
    QFile::setPermissions(name, perms | QFileDevice::ReadUser | QFileDevice::WriteUser);
    const QUrl url = QUrl::fromLocalFile(name);
694
    lst.append(url);
Laurent Montel's avatar
Laurent Montel committed
695

Laurent Montel's avatar
Laurent Montel committed
696
    auto job = new KIO::ApplicationLauncherJob(offer);
Laurent Montel's avatar
Laurent Montel committed
697
698
699
700
701
    job->setUrls({url});
    job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, mMainWindow));
    job->start();
    connect(job, &KJob::result, this, [url, job]() {
        if (job->error()) {
702
703
            QFile::remove(url.toLocalFile());
        }
Laurent Montel's avatar
Laurent Montel committed
704
    });
705
706
707
708
}

void ViewerPrivate::attachmentOpen(KMime::Content *node)
{
Laurent Montel's avatar
Laurent Montel committed
709
    const KService::Ptr offer = getServiceOffer(node);
710
711
712
713
714
715
716
    if (!offer) {
        qCDebug(MESSAGEVIEWER_LOG) << "got no offer";
        return;
    }
    attachmentOpenWith(node, offer);
}

717
718
bool ViewerPrivate::showEmoticons() const
{
719
    return mForceEmoticons;
720
721
}

722
HtmlWriter *ViewerPrivate::htmlWriter() const
723
724
725
726
727
728
{
    return mHtmlWriter;
}

CSSHelper *ViewerPrivate::cssHelper() const
{
729
    return mMessageViewerRenderer->cssHelper();
730
731
}

732
MimeTreeParser::NodeHelper *ViewerPrivate::nodeHelper() const
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
{
    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
754
    if (MessageViewer::MessageViewerSettings::self()->alwaysDecrypt()) {
755
        return true;
Laurent Montel's avatar
Laurent Montel committed
756
757
    } else {
        return mDecrytMessageOverwrite;
758
759
760
761
762
763
764
765
766
767
768
769
770
    }
}

void ViewerPrivate::displaySplashPage(const QString &message)
{
    displaySplashPage(QStringLiteral("status.html"), {
        { QStringLiteral("icon"), QStringLiteral("kmail") },
        { QStringLiteral("name"), i18n("KMail") },
        { QStringLiteral("subtitle"), i18n("The KDE Mail Client") },
        { QStringLiteral("message"), message }
    });
}

Laurent Montel's avatar
Laurent Montel committed
771
void ViewerPrivate::displaySplashPage(const QString &templateName, const QVariantHash &data, const QByteArray &domain)
772
{
Laurent Montel's avatar
Laurent Montel committed
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
    if (mViewer) {
        mMsgDisplay = false;
        adjustLayout();

        GrantleeTheme::ThemeManager manager(QStringLiteral("splashPage"),
                                            QStringLiteral("splash.theme"),
                                            nullptr,
                                            QStringLiteral("messageviewer/about/"));
        GrantleeTheme::Theme theme = manager.theme(QStringLiteral("default"));
        if (theme.isValid()) {
            mViewer->setHtml(theme.render(templateName, data, domain),
                             QUrl::fromLocalFile(theme.absolutePath() + QLatin1Char('/')));
        } else {
            qCDebug(MESSAGEVIEWER_LOG) << "Theme error: failed to find splash theme";
        }
        mViewer->show();
789
790
791
792
793
    }
}

void ViewerPrivate::enableMessageDisplay()
{
794
795
796
    if (mMsgDisplay) {
        return;
    }
797
798
799
800
801
802
803
804
805
806
807
    mMsgDisplay = true;
    adjustLayout();
}

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

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

    if (mMessageItem.hasAttribute<MessageViewer::MessageDisplayFormatAttribute>()) {
Laurent Montel's avatar
Laurent Montel committed
808
809
        const MessageViewer::MessageDisplayFormatAttribute *const attr
            = mMessageItem.attribute<MessageViewer::MessageDisplayFormatAttribute>();
810
811
812
813
        setHtmlLoadExtOverride(attr->remoteContent());
        setDisplayFormatMessageOverwrite(attr->messageFormat());
    }

Volker Krause's avatar
Volker Krause committed
814
    htmlWriter()->begin();
Laurent Montel's avatar
Laurent Montel committed
815
    htmlWriter()->write(cssHelper()->htmlHead(mUseFixedFont));
816
817
818
819
820
821
822

    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.
823
    mColorBar->setMode(MimeTreeParser::Util::Normal, HtmlStatusBar::NoUpdate);
824
825
826
827
828

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

Volker Krause's avatar
Volker Krause committed
831
        htmlWriter()->write(QStringLiteral(
Laurent Montel's avatar
Laurent Montel committed
832
833
834
                                "<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
835
        htmlWriter()->write(QStringLiteral("<p></p>"));
836
837
838
839
840
841
    }

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

Laurent Montel's avatar
Laurent Montel committed
842
    htmlWriter()->write(cssHelper()->endBodyHtml());
Laurent Montel's avatar
Laurent Montel committed
843
844
845
846
847
    connect(mViewer, &MailWebEngineView::loadFinished, this,
            &ViewerPrivate::executeCustomScriptsAfterLoading, Qt::UniqueConnection);
    connect(
        mPartHtmlWriter.data(), &WebEnginePartHtmlWriter::finished, this, &ViewerPrivate::slotMessageRendered,
        Qt::UniqueConnection);
848

Volker Krause's avatar
Volker Krause committed
849
    htmlWriter()->end();
850
851
852
853
}

void ViewerPrivate::parseContent(KMime::Content *content)
{
Laurent Montel's avatar
Laurent Montel committed
854
    assert(content != nullptr);
855
    mNodeHelper->removeTempFiles();
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875

    // 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
876
    auto *message = dynamic_cast<KMime::Message *>(content);
877
878
879
880

    // Pass control to the OTP now, which does the real work
    mNodeHelper->setNodeUnprocessed(mMessage.data(), true);
    MailViewerSource otpSource(this);
881
    MimeTreeParser::ObjectTreeParser otp(&otpSource, mNodeHelper);
Laurent Montel's avatar
Laurent Montel committed
882
    //TODO: needs to end up in renderer: mMessage.data() != content /* show only single node */);
883
    otp.setAllowAsync(!mPrinting);
884
    otp.parseObjectTree(content, mMessage.data() != content /* parse/show only single node */);
885
    htmlWriter()->setCodec(otp.plainTextContentCharset());
886
887
888
889
890
891
    if (message) {
        htmlWriter()->write(writeMessageHeader(message, hasVCard ? vCardContent : nullptr, true));
    }

    otpSource.render(otp.parsedPart(), mMessage.data() != content /* parse/show only single node */);

892
893
894
895
896
    // 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
897
898
899
900
    MimeTreeParser::KMMsgEncryptionState encryptionState = mNodeHelper->overallEncryptionState(
        content);
    MimeTreeParser::KMMsgSignatureState signatureState
        = mNodeHelper->overallSignatureState(content);
901
902
903
    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
904
905
    if (signatureState != MimeTreeParser::KMMsgNotSigned
        || mNodeHelper->signatureState(content) == MimeTreeParser::KMMsgSignatureStateUnknown) {
906
907
908
909
910
911
        mNodeHelper->setSignatureState(content, signatureState);
    }

    showHideMimeTree();
}

Laurent Montel's avatar
Laurent Montel committed
912
QString ViewerPrivate::writeMessageHeader(KMime::Message *aMsg, KMime::Content *vCardNode, bool topLevel)
913
914
{
    if (!headerStylePlugin()) {
Laurent Montel's avatar
Laurent Montel committed
915
        qCCritical(MESSAGEVIEWER_LOG) << "trying to writeMessageHeader() without a header style set!";
916
        return {};
917
    }
Laurent Montel's avatar
Laurent Montel committed
918
    HeaderStyle *style = headerStylePlugin()->headerStyle();
919
    if (vCardNode) {
Laurent Montel's avatar
Laurent Montel committed
920
        style->setVCardName(mNodeHelper->asHREF(vCardNode, QStringLiteral("body")));
921
922
    } else {
        style->setVCardName(QString());
Laurent Montel's avatar
Laurent Montel committed
923
924
925
926
927
928
929
930
    }
    style->setHeaderStrategy(headerStylePlugin()->headerStrategy());
    style->setPrinting(mPrinting);
    style->setTopLevel(topLevel);
    style->setAllowAsync(true);
    style->setSourceObject(this);
    style->setNodeHelper(mNodeHelper);
    style->setAttachmentHtml(attachmentHtml());
931
932
933
934
    if (mMessageItem.isValid()) {
        Akonadi::MessageStatus status;
        status.setStatusFromFlags(mMessageItem.flags());

Laurent Montel's avatar
Laurent Montel committed
935
        style->setMessageStatus(status);
Laurent Montel's avatar
Laurent Montel committed
936
    } else {
Laurent Montel's avatar
Laurent Montel committed
937
        style->setReadOnlyMessage(true);
938
939
    }

Laurent Montel's avatar
Laurent Montel committed
940
    return style->format(aMsg);
941
942
943
944
945
946
}

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

Laurent Montel's avatar
Laurent Montel committed
947
    auto vcv = new VCardViewer(mMainWindow, vCard);
948
949
950
951
952
953
954
    vcv->setAttribute(Qt::WA_DeleteOnClose);
    vcv->show();
}

void ViewerPrivate::initHtmlWidget()
{
    if (!htmlWriter()) {
Laurent Montel's avatar
Laurent Montel committed
955
        mPartHtmlWriter = new WebEnginePartHtmlWriter(mViewer, nullptr);
956
957
        mHtmlWriter = mPartHtmlWriter;
    }
Laurent Montel's avatar
Laurent Montel committed
958
    connect(mViewer->page(), &QWebEnginePage::linkHovered,
959
            this, &ViewerPrivate::slotUrlOn);
Laurent Montel's avatar
Laurent Montel committed
960
    connect(mViewer, &MailWebEngineView::openUrl,
961
962
963
            this, &ViewerPrivate::slotUrlOpen, Qt::QueuedConnection);
    connect(mViewer, &MailWebEngineView::popupMenu,
            this, &ViewerPrivate::slotUrlPopup);
964
965
    connect(mViewer, &MailWebEngineView::wheelZoomChanged,
            this, &ViewerPrivate::slotWheelZoomChanged);
Laurent Montel's avatar
Laurent Montel committed
966
967
    connect(mViewer, &MailWebEngineView::messageMayBeAScam, this,
            &ViewerPrivate::slotMessageMayBeAScam);
968
969
    connect(mViewer, &MailWebEngineView::formSubmittedForbidden, mSubmittedFormWarning, &SubmittedFormWarningWidget::showWarning);
    connect(mViewer, &MailWebEngineView::mailTrackingFound, mMailTrackingWarning, &MailTrackingWarningWidget::addTracker);
Laurent Montel's avatar
Laurent Montel committed
970
971
972
973
974
975
976
977
978
979
    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);
980
981
}

Laurent Montel's avatar
Laurent Montel committed
982
void ViewerPrivate::applyZoomValue(qreal factor, bool saveConfig)
983
{
Laurent Montel's avatar
Laurent Montel committed
984
985
    if (mZoomActionMenu) {
        if (factor >= 10 && factor <= 300) {
Laurent Montel's avatar
Laurent Montel committed
986
987
988
989
990
991
992
            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
993
        }
994
995
996
    }
}

997
998
void ViewerPrivate::setWebViewZoomFactor(qreal factor)
{
Laurent Montel's avatar
Laurent Montel committed
999
    applyZoomValue(factor, false);
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
}

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

1017
1018
void ViewerPrivate::readConfig()
{
1019
    mMessageViewerRenderer->setCurrentWidget(mViewer);
Laurent Montel's avatar
Laurent Montel committed
1020
    recreateCssHelper();
1021

1022
1023
1024
1025
    mForceEmoticons = MessageViewer::MessageViewerSettings::self()->showEmoticons();
    if (mDisableEmoticonAction) {
        mDisableEmoticonAction->setChecked(!mForceEmoticons);
    }
1026
1027
1028
1029
    if (headerStylePlugin()) {
        headerStylePlugin()->headerStyle()->setShowEmoticons(mForceEmoticons);
    }

1030
1031
1032
1033
1034
1035
1036
    mUseFixedFont = MessageViewer::MessageViewerSettings::self()->useFixedFont();
    if (mToggleFixFontAction) {
        mToggleFixFontAction->setChecked(mUseFixedFont);
    }

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

Laurent Montel's avatar
Laurent Montel committed
1037
    MessageViewer::Util::readGravatarConfig();
1038
1039
1040
1041
    if (mHeaderStyleMenuManager) {
        mHeaderStyleMenuManager->readConfig();
    }

1042
    setAttachmentStrategy(AttachmentStrategy::create(MessageViewer::
Laurent Montel's avatar
Laurent Montel committed
1043
1044
                                                     MessageViewerSettings::self()->
                                                     attachmentStrategy()));
1045
1046
1047
1048
1049
1050
1051
1052
    KToggleAction *raction = actionForAttachmentStrategy(attachmentStrategy());
    if (raction) {
        raction->setChecked(true);
    }

    adjustLayout();

    readGlobalOverrideCodec();
1053
    mViewer->readConfig();
Laurent Montel's avatar
Laurent Montel committed
1054
1055
1056
1057
    mViewer->settings()->setFontSize(QWebEngineSettings::MinimumFontSize,
                                     MessageViewer::MessageViewerSettings::self()->minimumFontSize());
    mViewer->settings()->setFontSize(QWebEngineSettings::MinimumLogicalFontSize,
                                     MessageViewer::MessageViewerSettings::self()->minimumFontSize());
1058
1059
1060
1061
    if (mMessage) {
        update();
    }
    mColorBar->update();
Laurent Montel's avatar
Laurent Montel committed
1062
    applyZoomValue(MessageViewer::MessageViewerSettings::self()->zoomFactor(), false);
1063
1064
}

Laurent Montel's avatar
Laurent Montel committed
1065
void ViewerPrivate::recreateCssHelper()
1066
{
1067
    mMessageViewerRenderer->recreateCssHelper();
Laurent Montel's avatar
Laurent Montel committed
1068
1069
}

1070
1071
1072
1073
1074
void ViewerPrivate::hasMultiMessages(bool messages)
{
    mShowNextMessageWidget->setVisible(messages);
}

Laurent Montel's avatar
Laurent Montel committed
1075
1076
1077
void ViewerPrivate::slotGeneralFontChanged()
{
    recreateCssHelper();
1078
1079
1080
1081
1082
1083
1084
    if (mMessage) {
        update();
    }
}

void ViewerPrivate::writeConfig(bool sync)
{
1085
    MessageViewer::MessageViewerSettings::self()->setShowEmoticons(mForceEmoticons);
1086
1087
    MessageViewer::MessageViewerSettings::self()->setUseFixedFont(mUseFixedFont);
    if (attachmentStrategy()) {
Laurent Montel's avatar
Laurent Montel committed
1088
1089
1090
        MessageViewer::MessageViewerSettings::self()->setAttachmentStrategy(QLatin1String(
                                                                                attachmentStrategy()
                                                                                ->name()));
1091
1092
1093
1094
1095
1096
1097
    }
    saveSplitterSizes();
    if (sync) {
        Q_EMIT requestConfigSync();
    }
}

1098
const AttachmentStrategy *ViewerPrivate::attachmentStrategy() const
1099
1100
1101
1102
{
    return mAttachmentStrategy;
}

1103
void ViewerPrivate::setAttachmentStrategy(const AttachmentStrategy *strategy)
1104
1105
1106
1107
{
    if (mAttachmentStrategy == strategy) {
        return;
    }
1108
    mAttachmentStrategy = strategy ? strategy : AttachmentStrategy::smart();
1109
    update(MimeTreeParser::Force);
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
}

QString ViewerPrivate::overrideEncoding() const
{
    return mOverrideEncoding;
}

void ViewerPrivate::setOverrideEncoding(const QString &encoding)
{
    if (encoding == mOverrideEncoding) {
        return;
    }

    mOverrideEncoding = encoding;
    if (mSelectEncodingAction) {
        if (encoding.isEmpty()) {
            mSelectEncodingAction->setCurrentItem(0);
        } else {
            const QStringList encodings = mSelectEncodingAction->items();
            int i = 0;
Laurent Montel's avatar
Laurent Montel committed
1130
1131
1132
            for (QStringList::const_iterator it = encodings.constBegin(),
                 end = encodings.constEnd();
                 it != end; ++it, ++i) {
1133
                if (MimeTreeParser::NodeHelper::encodingForName(*it) == encoding) {
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
                    mSelectEncodingAction->setCurrentItem(i);
                    break;
                }
            }
            if (i == encodings.size()) {
                // the value of encoding is unknown => use Auto
                qCWarning(MESSAGEVIEWER_LOG) << "Unknown override character encoding" << encoding
                                             << ". Using Auto instead.";
                mSelectEncodingAction->setCurrentItem(0);
                mOverrideEncoding.clear();
            }
        }
    }
1147
    update(MimeTreeParser::Force);
1148
1149
1150
1151