Messagelib

webengineexporthtmlpagejob.cpp
1 /*
2  SPDX-FileCopyrightText: 2016-2021 Laurent Montel <[email protected]>
3 
4  SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6 
7 #include "webengineexporthtmlpagejob.h"
8 #include <QTemporaryFile>
9 #include <QWebEngineView>
10 
11 using namespace WebEngineViewer;
12 template<typename Arg, typename R, typename C> struct InvokeWrapper {
13  R *receiver;
14  void (C::*memberFun)(Arg);
15  void operator()(Arg result)
16  {
17  (receiver->*memberFun)(result);
18  }
19 };
20 
21 template<typename Arg, typename R, typename C>
22 InvokeWrapper<Arg, R, C> invokeWebEngineExportHtml(R *receiver, void (C::*memberFun)(Arg))
23 {
24  InvokeWrapper<Arg, R, C> wrapper = {receiver, memberFun};
25  return wrapper;
26 }
27 
28 WebEngineExportHtmlPageJob::WebEngineExportHtmlPageJob(QObject *parent)
29  : QObject(parent)
30 {
31 }
32 
33 WebEngineExportHtmlPageJob::~WebEngineExportHtmlPageJob() = default;
34 
35 void WebEngineExportHtmlPageJob::start()
36 {
37  if (!mEngineView) {
38  Q_EMIT failed();
39  deleteLater();
40  return;
41  }
42  mEngineView->page()->toHtml(invokeWebEngineExportHtml(this, &WebEngineExportHtmlPageJob::slotSaveHtmlToPage));
43 }
44 
45 void WebEngineExportHtmlPageJob::slotSaveHtmlToPage(const QString &text)
46 {
47  QTemporaryFile temporaryFile;
48  temporaryFile.setAutoRemove(false);
49  if (!temporaryFile.open()) {
50  Q_EMIT failed();
51  deleteLater();
52  return;
53  }
54  QTextStream stream(&temporaryFile);
55 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
56  stream.setCodec("UTF-8");
57 #endif
58  QString newText = text;
59  newText.replace(QLatin1String("<head>"), QLatin1String("<head><meta charset=\"UTF-8\">"));
60  stream << newText;
61  temporaryFile.close();
62  // We need to remove this temporary file
63  Q_EMIT success(temporaryFile.fileName());
64  deleteLater();
65 }
66 
67 QWebEngineView *WebEngineExportHtmlPageJob::engineView() const
68 {
69  return mEngineView;
70 }
71 
72 void WebEngineExportHtmlPageJob::setEngineView(QWebEngineView *engineView)
73 {
74  mEngineView = engineView;
75 }
void setAutoRemove(bool b)
void deleteLater()
virtual QString fileName() const const override
QString & replace(int position, int n, QChar after)
virtual void close() override
Q_EMITQ_EMIT
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Sat Dec 4 2021 23:12:55 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.