summaryrefslogtreecommitdiffstats
path: root/src/pdf/qpdfpagerenderer.cpp
blob: e90f667009f58c0b42a83ad3769ca5a083c9611f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/****************************************************************************
**
** Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Tobias König <tobias.koenig@kdab.com>
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtPDF module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qpdfpagerenderer.h"

#include <private/qobject_p.h>
#include <QMutex>
#include <QPdfDocument>
#include <QPointer>
#include <QThread>

QT_BEGIN_NAMESPACE

class RenderWorker : public QObject
{
    Q_OBJECT

public:
    RenderWorker();
    ~RenderWorker();

    void setDocument(QPdfDocument *document);

public Q_SLOTS:
    void requestPage(quint64 requestId, int page, QSize imageSize,
                     QPdfDocumentRenderOptions options);

Q_SIGNALS:
    void pageRendered(int page, QSize imageSize, const QImage &image,
                      QPdfDocumentRenderOptions options, quint64 requestId);

private:
    QPointer<QPdfDocument> m_document;
    QMutex m_mutex;
};

class QPdfPageRendererPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QPdfPageRenderer)

public:
    QPdfPageRendererPrivate();
    ~QPdfPageRendererPrivate();

    void handleNextRequest();
    void requestFinished(int page, QSize imageSize, const QImage &image,
                         QPdfDocumentRenderOptions options, quint64 requestId);

    QPdfPageRenderer::RenderMode m_renderMode = QPdfPageRenderer::SingleThreadedRenderMode;
    QPointer<QPdfDocument> m_document;

    struct PageRequest
    {
        quint64 id;
        int pageNumber;
        QSize imageSize;
        QPdfDocumentRenderOptions options;
    };

    QVector<PageRequest> m_requests;
    QVector<PageRequest> m_pendingRequests;
    quint64 m_requestIdCounter = 1;

    QThread *m_renderThread = nullptr;
    QScopedPointer<RenderWorker> m_renderWorker;
};

Q_DECLARE_TYPEINFO(QPdfPageRendererPrivate::PageRequest, Q_PRIMITIVE_TYPE);


RenderWorker::RenderWorker()
    : m_document(nullptr)
{
}

RenderWorker::~RenderWorker()
{
}

void RenderWorker::setDocument(QPdfDocument *document)
{
    const QMutexLocker locker(&m_mutex);

    if (m_document == document)
        return;

    m_document = document;
}

void RenderWorker::requestPage(quint64 requestId, int pageNumber, QSize imageSize,
                               QPdfDocumentRenderOptions options)
{
    const QMutexLocker locker(&m_mutex);

    if (!m_document || m_document->status() != QPdfDocument::Ready)
        return;

    const QImage image = m_document->render(pageNumber, imageSize, options);

    emit pageRendered(pageNumber, imageSize, image, options, requestId);
}


QPdfPageRendererPrivate::QPdfPageRendererPrivate()
    : QObjectPrivate()
    , m_renderWorker(new RenderWorker)
{
}

QPdfPageRendererPrivate::~QPdfPageRendererPrivate()
{
    if (m_renderThread) {
        m_renderThread->quit();
        m_renderThread->wait();
    }
}

void QPdfPageRendererPrivate::handleNextRequest()
{
    if (m_requests.isEmpty())
        return;

    const PageRequest request = m_requests.takeFirst();
    m_pendingRequests.append(request);

    QMetaObject::invokeMethod(m_renderWorker.data(), "requestPage", Qt::QueuedConnection,
                              Q_ARG(quint64, request.id), Q_ARG(int, request.pageNumber),
                              Q_ARG(QSize, request.imageSize), Q_ARG(QPdfDocumentRenderOptions,
                              request.options));
}

void QPdfPageRendererPrivate::requestFinished(int page, QSize imageSize, const QImage &image, QPdfDocumentRenderOptions options, quint64 requestId)
{
    const auto it = std::find_if(m_pendingRequests.begin(), m_pendingRequests.end(),
                                 [page, imageSize, options](const PageRequest &request){ return request.pageNumber == page && request.imageSize == imageSize && request.options == options; });

    if (it != m_pendingRequests.end())
        m_pendingRequests.erase(it);
}

/*!
    \class QPdfPageRenderer
    \since 5.11
    \inmodule QtPdf

    \brief The QPdfPageRenderer class encapsulates the rendering of pages of a PDF document.

    The QPdfPageRenderer contains a queue that collects all render requests that are invoked through
    requestPage(). Depending on the configured RenderMode the QPdfPageRenderer processes this queue
    in the main UI thread on next event loop invocation (SingleThreadedRenderMode) or in a separate worker thread
    (MultiThreadedRenderMode) and emits the result through the pageRendered() signal for each request once
    the rendering is done.

    \sa QPdfDocument
*/


/*!
    Constructs a page renderer object with parent object \a parent.
*/
QPdfPageRenderer::QPdfPageRenderer(QObject *parent)
    : QObject(*new QPdfPageRendererPrivate(), parent)
{
    Q_D(QPdfPageRenderer);

    qRegisterMetaType<QPdfDocumentRenderOptions>();

    connect(d->m_renderWorker.data(), &RenderWorker::pageRendered, this,
            [this,d](int page, QSize imageSize, const QImage &image, QPdfDocumentRenderOptions options, quint64 requestId) {
                d->requestFinished(page, imageSize, image, options, requestId);
                emit pageRendered(page, imageSize, image, options, requestId);
                d->handleNextRequest();
           });
}

/*!
    Destroys the page renderer object.
*/
QPdfPageRenderer::~QPdfPageRenderer()
{
}

/*!
    \enum QPdfPageRenderer::RenderMode

    This enum describes how the pages are rendered.

    \value MultiThreadedRenderMode All pages are rendered in a separate worker thread.
    \value SingleThreadedRenderMode All pages are rendered in the main UI thread (default).

    \sa renderMode(), setRenderMode()
*/

/*!
    \property QPdfPageRenderer::renderMode
    \brief The mode the renderer uses to render the pages.

    By default, this property is \c QPdfPageRenderer::SingleThreaded.

    \sa setRenderMode(), RenderMode
*/

/*!
    Returns the mode of how the pages are rendered.

    \sa RenderMode
*/
QPdfPageRenderer::RenderMode QPdfPageRenderer::renderMode() const
{
    Q_D(const QPdfPageRenderer);

    return d->m_renderMode;
}

/*!
    Sets the mode of how the pages are rendered to \a mode.

    \sa RenderMode
*/
void QPdfPageRenderer::setRenderMode(RenderMode mode)
{
    Q_D(QPdfPageRenderer);

    if (d->m_renderMode == mode)
        return;

    d->m_renderMode = mode;
    emit renderModeChanged(d->m_renderMode);

    if (d->m_renderMode == MultiThreadedRenderMode) {
        d->m_renderThread = new QThread;
        d->m_renderWorker->moveToThread(d->m_renderThread);
        d->m_renderThread->start();
    } else {
        d->m_renderThread->quit();
        d->m_renderThread->wait();
        delete d->m_renderThread;
        d->m_renderThread = nullptr;

        // pulling the object from another thread should be fine, once that thread is deleted
        d->m_renderWorker->moveToThread(this->thread());
    }
}

/*!
    \property QPdfPageRenderer::document
    \brief The document instance this object renders the pages from.

    By default, this property is \c nullptr.

    \sa document(), setDocument(), QPdfDocument
*/

/*!
    Returns the document this objects renders the pages from, or a \c nullptr
    if none has been set before.

    \sa QPdfDocument
*/
QPdfDocument* QPdfPageRenderer::document() const
{
    Q_D(const QPdfPageRenderer);

    return d->m_document;
}

/*!
    Sets the \a document this object renders the pages from.

    \sa QPdfDocument
*/
void QPdfPageRenderer::setDocument(QPdfDocument *document)
{
    Q_D(QPdfPageRenderer);

    if (d->m_document == document)
        return;

    d->m_document = document;
    emit documentChanged(d->m_document);

    d->m_renderWorker->setDocument(d->m_document);
}

/*!
    Requests the renderer to render the page \a pageNumber into a QImage of size \a imageSize
    according to the provided \a options.

    Once the rendering is done the pageRendered() signal is emitted with the result as parameters.

    The return value is an ID that uniquely identifies the render request. If a request with the
    same parameters is still in the queue, the ID of that queued request is returned.
*/
quint64 QPdfPageRenderer::requestPage(int pageNumber, QSize imageSize,
                                      QPdfDocumentRenderOptions options)
{
    Q_D(QPdfPageRenderer);

    if (!d->m_document || d->m_document->status() != QPdfDocument::Ready)
        return 0;

    for (const auto request : qAsConst(d->m_pendingRequests)) {
        if (request.pageNumber == pageNumber
            && request.imageSize == imageSize
            && request.options == options)
            return request.id;
    }

    const auto id = d->m_requestIdCounter++;

    QPdfPageRendererPrivate::PageRequest request;
    request.id = id;
    request.pageNumber = pageNumber;
    request.imageSize = imageSize;
    request.options = options;

    d->m_requests.append(request);

    d->handleNextRequest();

    return id;
}

QT_END_NAMESPACE

#include "qpdfpagerenderer.moc"