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

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

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

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

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

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

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

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

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

88
89
90
#include <KIdentityManagement/Identity>
#include <KIdentityManagement/IdentityManager>

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

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

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

#include <MessageCore/StringUtil>

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

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

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

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

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

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

static QAtomicInt _k_attributeInitialized;

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

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

Laurent Montel's avatar
Laurent Montel committed
171
ViewerPrivate::ViewerPrivate(Viewer *aParent, QWidget *mainWindow, KActionCollection *actionCollection)
Laurent Montel's avatar
Laurent Montel committed
172
173
174
175
176
177
    : QObject(aParent)
    , mNodeHelper(new MimeTreeParser::NodeHelper)
    , mOldGlobalOverrideEncoding(QStringLiteral("---"))
    , mMainWindow(mainWindow)
    , mActionCollection(actionCollection)
    , q(aParent)
Laurent Montel's avatar
Laurent Montel committed
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, this, &ViewerPrivate::slotCheckedUrlFinished);
Laurent Montel's avatar
Laurent Montel committed
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    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
209
    connect(&mResizeTimer, &QTimer::timeout, this, &ViewerPrivate::slotDelayedResize);
210
211

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    QMenu menu;
522

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

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

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

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

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

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

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

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

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

    menu->addSeparator();

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

Laurent Montel's avatar
Laurent Montel committed
600
void ViewerPrivate::prepareHandleAttachment(KMime::Content *node)
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
{
    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
618
        return KService::Ptr(nullptr);
619
620
621
622
    }

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

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

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

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

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

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

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

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

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

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

699
MimeTreeParser::NodeHelper *ViewerPrivate::nodeHelper() const
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
{
    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
721
    if (MessageViewer::MessageViewerSettings::self()->alwaysDecrypt()) {
722
        return true;
Laurent Montel's avatar
Laurent Montel committed
723
724
    } else {
        return mDecrytMessageOverwrite;
725
726
727
728
729
    }
}

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

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

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

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

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

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

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

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

    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.
784
    mColorBar->setMode(MimeTreeParser::Util::Normal, HtmlStatusBar::NoUpdate);
785
786

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

Laurent Montel's avatar
Laurent Montel committed
792
793
        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
794
        htmlWriter()->write(QStringLiteral("<p></p>"));
795
796
797
798
799
800
    }

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

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

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

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

    // 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
832
    auto *message = dynamic_cast<KMime::Message *>(content);
833
834
835
836

    // Pass control to the OTP now, which does the real work
    mNodeHelper->setNodeUnprocessed(mMessage.data(), true);
    MailViewerSource otpSource(this);
837
    MimeTreeParser::ObjectTreeParser otp(&otpSource, mNodeHelper);
Laurent Montel's avatar
Laurent Montel committed
838
    // TODO: needs to end up in renderer: mMessage.data() != content /* show only single node */);
839
    otp.setAllowAsync(!mPrinting);
840
    otp.parseObjectTree(content, mMessage.data() != content /* parse/show only single node */);
841
    htmlWriter()->setCodec(otp.plainTextContentCharset());
842
843
844
845
846
847
    if (message) {
        htmlWriter()->write(writeMessageHeader(message, hasVCard ? vCardContent : nullptr, true));
    }

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

848
849
850
851
852
    // 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
853
854
    MimeTreeParser::KMMsgEncryptionState encryptionState = mNodeHelper->overallEncryptionState(content);
    MimeTreeParser::KMMsgSignatureState signatureState = mNodeHelper->overallSignatureState(content);
855
856
857
    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
858
    if (signatureState != MimeTreeParser::KMMsgNotSigned || mNodeHelper->signatureState(content) == MimeTreeParser::KMMsgSignatureStateUnknown) {
859
860
861
862
863
864
        mNodeHelper->setSignatureState(content, signatureState);
    }

    showHideMimeTree();
}

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

Laurent Montel's avatar
Laurent Montel committed
888
        style->setMessageStatus(status);
Laurent Montel's avatar
Laurent Montel committed
889
    } else {
Laurent Montel's avatar
Laurent Montel committed
890
        style->setReadOnlyMessage(true);
891
892
    }

Laurent Montel's avatar
Laurent Montel committed
893
    return style->format(aMsg);
894
895
896
897
898
899
}

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

Laurent Montel's avatar
Laurent Montel committed
900
    auto vcv = new VCardViewer(mMainWindow, vCard);
901
902
903
904
905
906
907
    vcv->setAttribute(Qt::WA_DeleteOnClose);
    vcv->show();
}

void ViewerPrivate::initHtmlWidget()
{
    if (!htmlWriter()) {
Laurent Montel's avatar
Laurent Montel committed
908
        mPartHtmlWriter = new WebEnginePartHtmlWriter(mViewer, nullptr);
909
910
        mHtmlWriter = mPartHtmlWriter;
    }
Laurent Montel's avatar
Laurent Montel committed
911
912
913
914
915
    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);
916
917
    connect(mViewer, &MailWebEngineView::formSubmittedForbidden, mSubmittedFormWarning, &SubmittedFormWarningWidget::showWarning);
    connect(mViewer, &MailWebEngineView::mailTrackingFound, mMailTrackingWarning, &MailTrackingWarningWidget::addTracker);
Laurent Montel's avatar
Laurent Montel committed
918
919
920
921
922
    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);
923
924
}

Laurent Montel's avatar
Laurent Montel committed
925
void ViewerPrivate::applyZoomValue(qreal factor, bool saveConfig)
926
{
Laurent Montel's avatar
Laurent Montel committed
927
928
    if (mZoomActionMenu) {
        if (factor >= 10 && factor <= 300) {
Laurent Montel's avatar
Laurent Montel committed
929
930
931
932
933
934
935
            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
936
        }
937
938
939
    }
}

940
941
void ViewerPrivate::setWebViewZoomFactor(qreal factor)
{
Laurent Montel's avatar
Laurent Montel committed
942
    applyZoomValue(factor, false);
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
}

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

960
961
void ViewerPrivate::readConfig()
{
962
    mMessageViewerRenderer->setCurrentWidget(mViewer);
Laurent Montel's avatar
Laurent Montel committed
963
    recreateCssHelper();
964

965
966
967
968
    mForceEmoticons = MessageViewer::MessageViewerSettings::self()->showEmoticons();
    if (mDisableEmoticonAction) {
        mDisableEmoticonAction->setChecked(!mForceEmoticons);
    }
969
970
971
972
    if (headerStylePlugin()) {
        headerStylePlugin()->headerStyle()->setShowEmoticons(mForceEmoticons);
    }

973
974
975
976
977
978
979
    mUseFixedFont = MessageViewer::MessageViewerSettings::self()->useFixedFont();
    if (mToggleFixFontAction) {
        mToggleFixFontAction->setChecked(mUseFixedFont);
    }

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

Laurent Montel's avatar
Laurent Montel committed
980
    MessageViewer::Util::readGravatarConfig();
981
982
983
984
    if (mHeaderStyleMenuManager) {
        mHeaderStyleMenuManager->readConfig();
    }

Laurent Montel's avatar
Laurent Montel committed
985
    setAttachmentStrategy(AttachmentStrategy::create(MessageViewer::MessageViewerSettings::self()->attachmentStrategy()));
986
987
988
989
990
991
992
993
    KToggleAction *raction = actionForAttachmentStrategy(attachmentStrategy());
    if (raction) {
        raction->setChecked(true);
    }

    adjustLayout();

    readGlobalOverrideCodec();
994
    mViewer->readConfig();
Laurent Montel's avatar
Laurent Montel committed
995
996
    mViewer->settings()->setFontSize(QWebEngineSettings::MinimumFontSize, MessageViewer::MessageViewerSettings::self()->minimumFontSize());
    mViewer->settings()->setFontSize(QWebEngineSettings::MinimumLogicalFontSize, MessageViewer::MessageViewerSettings::self()->minimumFontSize());
997
998
999
1000
    if (mMessage) {
        update();
    }
    mColorBar->update();
Laurent Montel's avatar
Laurent Montel committed
1001
    applyZoomValue(MessageViewer::MessageViewerSettings::self()->zoomFactor(), false);
1002
1003
}

Laurent Montel's avatar
Laurent Montel committed
1004
void ViewerPrivate::recreateCssHelper()
1005
{
1006
    mMessageViewerRenderer->recreateCssHelper();
Laurent Montel's avatar
Laurent Montel committed
1007
1008
}

1009
1010
1011
1012
1013
void ViewerPrivate::hasMultiMessages(bool messages)
{
    mShowNextMessageWidget->setVisible(messages);
}

Laurent Montel's avatar
Laurent Montel committed
1014
1015
1016
void ViewerPrivate::slotGeneralFontChanged()
{
    recreateCssHelper();
1017
1018
1019
1020
1021
1022
1023
    if (mMessage) {
        update();
    }
}

void ViewerPrivate::writeConfig(bool sync)
{
1024
    MessageViewer::MessageViewerSettings::self()->setShowEmoticons(mForceEmoticons);
1025
1026
    MessageViewer::MessageViewerSettings::self()->setUseFixedFont(mUseFixedFont);
    if (attachmentStrategy()) {
Laurent Montel's avatar
Laurent Montel committed
1027
        MessageViewer::MessageViewerSettings::self()->setAttachmentStrategy(QLatin1String(attachmentStrategy()->name()));
1028
1029
1030
1031
1032
1033
1034
    }
    saveSplitterSizes();
    if (sync) {
        Q_EMIT requestConfigSync();
    }
}

1035
const AttachmentStrategy *ViewerPrivate::attachmentStrategy() const
1036
1037
1038
1039
{
    return mAttachmentStrategy;
}

1040
void ViewerPrivate::setAttachmentStrategy(const AttachmentStrategy *strategy)
1041
1042
1043
1044
{
    if (mAttachmentStrategy == strategy) {
        return;
    }