Messagelib

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

KDE's Doxygen guidelines are available online.