Debian Codegraph @

qt6/src/poppler-page.cc

raw
1 /* poppler-page.cc: qt interface to poppler
2 * Copyright (C) 2005, Net Integration Technologies, Inc.
3 * Copyright (C) 2005, Brad Hards <[email protected]>
4 * Copyright (C) 2005-2022, 2024-2026, Albert Astals Cid <[email protected]>
5 * Copyright (C) 2005, Stefan Kebekus <[email protected]>
6 * Copyright (C) 2006-2011, Pino Toscano <[email protected]>
7 * Copyright (C) 2008 Carlos Garcia Campos <[email protected]>
8 * Copyright (C) 2009 Shawn Rutledge <[email protected]>
9 * Copyright (C) 2010, 2012, Guillermo Amaral <[email protected]>
10 * Copyright (C) 2010 Suzuki Toshiya <[email protected]>
11 * Copyright (C) 2010 Matthias Fauconneau <[email protected]>
12 * Copyright (C) 2010 Hib Eris <[email protected]>
13 * Copyright (C) 2012 Tobias Koenig <[email protected]>
14 * Copyright (C) 2012 Fabio D'Urso <[email protected]>
15 * Copyright (C) 2012, 2015 Adam Reichold <[email protected]>
16 * Copyright (C) 2012, 2013 Thomas Freitag <[email protected]>
17 * Copyright (C) 2015 William Bader <[email protected]>
18 * Copyright (C) 2016 Arseniy Lartsev <[email protected]>
19 * Copyright (C) 2016, Hanno Meyer-Thurow <[email protected]>
20 * Copyright (C) 2017-2021, Oliver Sander <[email protected]>
21 * Copyright (C) 2017 Adrian Johnson <[email protected]>
22 * Copyright (C) 2017, 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <[email protected]>. Work sponsored by the LiMux project of the city of Munich
23 * Copyright (C) 2018 Intevation GmbH <[email protected]>
24 * Copyright (C) 2018, Tobias Deiminger <[email protected]>
25 * Copyright (C) 2018, 2021 Nelson Benítez León <[email protected]>
26 * Copyright (C) 2020 Philipp Knechtges <[email protected]>
27 * Copyright (C) 2021 Hubert Figuiere <[email protected]>
28 * Copyright (C) 2021 Thomas Huxhorn <[email protected]>
29 * Copyright (C) 2023 Kevin Ottens <[email protected]>. Work sponsored by De Bortoli Wines
30 * Copyright (C) 2024, 2025 Stefan Brüns <[email protected]>
31 * Copyright (C) 2024 Pratham Gandhi <[email protected]>
32 * Copyright (C) 2024, 2026 g10 Code GmbH, Author: Sune Stolborg Vuorela <[email protected]>
33 *
34 * This program is free software; you can redistribute it and/or modify
35 * it under the terms of the GNU General Public License as published by
36 * the Free Software Foundation; either version 2, or (at your option)
37 * any later version.
38 *
39 * This program is distributed in the hope that it will be useful,
40 * but WITHOUT ANY WARRANTY; without even the implied warranty of
41 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 * GNU General Public License for more details.
43 *
44 * You should have received a copy of the GNU General Public License
45 * along with this program; if not, write to the Free Software
46 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
47 */
48
49 #include <poppler-qt6.h>
50
51 #include <QtCore/QHash>
52 #include <QtCore/QMap>
53 #include <QtCore/QVarLengthArray>
54 #include <QtGui/QImage>
55 #include <QtGui/QPainter>
56 #include <QDebug>
57
58 #include <config.h>
59 #include <cfloat>
60 #include <poppler-config.h>
61 #include <PDFDoc.h>
62 #include <Catalog.h>
63 #include <Form.h>
64 #include <ErrorCodes.h>
65 #include <TextOutputDev.h>
66 #include <Annot.h>
67 #include <Link.h>
68 #include <QPainterOutputDev.h>
69 #include <Rendition.h>
70 #include <SplashOutputDev.h>
71 #include <goo/gmem.h>
72 #include <splash/SplashBitmap.h>
73
74 #include "poppler-private.h"
75 #include "poppler-page-transition-private.h"
76 #include "poppler-page-private.h"
77 #include "poppler-link-extractor-private.h"
78 #include "poppler-link-private.h"
79 #include "poppler-annotation-private.h"
80 #include "poppler-form.h"
81 #include "poppler-media.h"
82
83 namespace Poppler {
84
85 class TextExtractionAbortHelper
86 {
87 public:
88 TextExtractionAbortHelper(Page::ShouldAbortQueryFunc shouldAbortCallback, const QVariant &payloadA)
89 {
90 shouldAbortExtractionCallback = shouldAbortCallback;
91 payload = payloadA;
92 }
93
94 Page::ShouldAbortQueryFunc shouldAbortExtractionCallback = nullptr;
95 QVariant payload;
96 };
97
98 class OutputDevCallbackHelper
99 {
100 public:
101 void setCallbacks(Page::RenderToImagePartialUpdateFunc callback, Page::ShouldRenderToImagePartialQueryFunc shouldDoCallback, Page::ShouldAbortQueryFunc shouldAbortCallback, const QVariant &payloadA)
102 {
103 partialUpdateCallback = callback;
104 shouldDoPartialUpdateCallback = shouldDoCallback;
105 shouldAbortRenderCallback = shouldAbortCallback;
106 payload = payloadA;
107 }
108
109 Page::RenderToImagePartialUpdateFunc partialUpdateCallback = nullptr;
110 Page::ShouldRenderToImagePartialQueryFunc shouldDoPartialUpdateCallback = nullptr;
111 Page::ShouldAbortQueryFunc shouldAbortRenderCallback = nullptr;
112 QVariant payload;
113 };
114
115 class Qt6SplashOutputDev : public SplashOutputDev, public OutputDevCallbackHelper
116 {
117 public:
118 Qt6SplashOutputDev(SplashColorMode colorModeA, int bitmapRowPadA, bool reverseVideoA, bool ignorePaperColorA, SplashColorPtr paperColorA, bool bitmapTopDownA, SplashThinLineMode thinLineMode, bool overprintPreviewA)
119 : SplashOutputDev(colorModeA, bitmapRowPadA, reverseVideoA, paperColorA, bitmapTopDownA, thinLineMode, overprintPreviewA), ignorePaperColor(ignorePaperColorA)
120 {
121 }
122
123 ~Qt6SplashOutputDev() override;
124
125 void dump() override
126 {
127 if (partialUpdateCallback && shouldDoPartialUpdateCallback && shouldDoPartialUpdateCallback(payload)) {
128 partialUpdateCallback(getXBGRImage(false /* takeImageData */), payload);
129 }
130 }
131
132 QImage getXBGRImage(bool takeImageData)
133 {
134 SplashBitmap *b = getBitmap();
135
136 // If we use DeviceN8, convert to XBGR8.
137 // If requested, also transfer Splash's internal alpha channel.
138 const SplashBitmap::ConversionMode mode = ignorePaperColor ? SplashBitmap::conversionAlphaPremultiplied : SplashBitmap::conversionOpaque;
139
140 const QImage::Format format = ignorePaperColor ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
141
142 if (b->convertToXBGR(mode)) {
143 const int bw = b->getWidth();
144 const int bh = b->getHeight();
145 const int brs = b->getRowSize();
146
147 SplashColorPtr data = takeImageData ? b->takeData() : b->getDataPtr();
148
149 if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
150 // Convert byte order from RGBX to XBGR.
151 for (int i = 0; i < bh; ++i) {
152 for (int j = 0; j < bw; ++j) {
153 SplashColorPtr pixel = &data[i * brs + j];
154
155 qSwap(pixel[0], pixel[3]);
156 qSwap(pixel[1], pixel[2]);
157 }
158 }
159 }
160
161 if (takeImageData) {
162 // Construct a Qt image holding (and also owning) the raw bitmap data.
163 QImage i(data, bw, bh, brs, format, gfree, data);
164 if (i.isNull()) {
165 gfree(data);
166 }
167 return i;
168 } else {
169 return QImage(data, bw, bh, brs, format).copy();
170 }
171 }
172
173 return QImage();
174 }
175
176 private:
177 bool ignorePaperColor;
178 };
179
180 Qt6SplashOutputDev::~Qt6SplashOutputDev() = default;
181
182 class QImageDumpingQPainterOutputDev : public QPainterOutputDev, public OutputDevCallbackHelper
183 {
184 public:
185 QImageDumpingQPainterOutputDev(QPainter *painter, QImage *i) : QPainterOutputDev(painter), image(i) { }
186 ~QImageDumpingQPainterOutputDev() override;
187
188 void dump() override
189 {
190 if (partialUpdateCallback && shouldDoPartialUpdateCallback && shouldDoPartialUpdateCallback(payload)) {
191 partialUpdateCallback(*image, payload);
192 }
193 }
194
195 private:
196 QImage *image;
197 };
198
199 QImageDumpingQPainterOutputDev::~QImageDumpingQPainterOutputDev() = default;
200
201 std::unique_ptr<Link> PageData::convertLinkActionToLink(::LinkAction *a, const QRectF &linkArea)
202 {
203 return convertLinkActionToLink(a, parentDoc, linkArea);
204 }
205
206 std::unique_ptr<Link> PageData::convertLinkActionToLink(::LinkAction *a, DocumentData *parentDoc, const QRectF &linkArea)
207 {
208 if (!a) {
209 return nullptr;
210 }
211
212 std::unique_ptr<Link> popplerLink;
213 switch (a->getKind()) {
214 case actionGoTo: {
215 LinkGoTo *g = (LinkGoTo *)a;
216 const LinkDestinationData ldd(g->getDest(), g->getNamedDest(), parentDoc, false);
217 // create link: no ext file, namedDest, object pointer
218 popplerLink = std::make_unique<LinkGoto>(linkArea, QString(), LinkDestination(ldd));
219 } break;
220
221 case actionGoToR: {
222 LinkGoToR *g = (LinkGoToR *)a;
223 // copy link file
224 const QString fileName = UnicodeParsedString(g->getFileName());
225 const LinkDestinationData ldd(g->getDest(), g->getNamedDest(), parentDoc, !fileName.isEmpty());
226 // create link: fileName, namedDest, object pointer
227 popplerLink = std::make_unique<LinkGoto>(linkArea, fileName, LinkDestination(ldd));
228 } break;
229
230 case actionLaunch: {
231 LinkLaunch *e = (LinkLaunch *)a;
232 const GooString *p = e->getParams();
233 popplerLink = std::make_unique<LinkExecute>(linkArea, UnicodeParsedString(e->getFileName()), p ? QString::fromStdString(p->toStr()) : QString {});
234 } break;
235
236 case actionNamed: {
237 const std::string &name = ((LinkNamed *)a)->getName();
238 if (name == "NextPage") {
239 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::PageNext);
240 } else if (name == "PrevPage") {
241 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::PagePrev);
242 } else if (name == "FirstPage") {
243 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::PageFirst);
244 } else if (name == "LastPage") {
245 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::PageLast);
246 } else if (name == "GoBack") {
247 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::HistoryBack);
248 } else if (name == "GoForward") {
249 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::HistoryForward);
250 } else if (name == "Quit") {
251 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::Quit);
252 } else if (name == "GoToPage") {
253 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::GoToPage);
254 } else if (name == "Find") {
255 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::Find);
256 } else if (name == "FullScreen") {
257 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::Presentation);
258 } else if (name == "Print") {
259 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::Print);
260 } else if (name == "Close") {
261 // acroread closes the document always, doesn't care whether
262 // its presentation mode or not
263 // popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::EndPresentation);
264 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::Close);
265 } else if (name == "SaveAs") {
266 popplerLink = std::make_unique<LinkAction>(linkArea, LinkAction::SaveAs);
267 } else {
268 qWarning() << "Unhandled action name" << name.c_str();
269 }
270 } break;
271
272 case actionURI: {
273 popplerLink = std::make_unique<LinkBrowse>(linkArea, QString::fromStdString(((LinkURI *)a)->getURI()));
274 } break;
275
276 case actionSound: {
277 ::LinkSound *ls = (::LinkSound *)a;
278 popplerLink = std::make_unique<LinkSound>(linkArea, ls->getVolume(), ls->getSynchronous(), ls->getRepeat(), ls->getMix(), new SoundObject(ls->getSound()));
279 } break;
280
281 case actionJavaScript: {
282 ::LinkJavaScript *ljs = (::LinkJavaScript *)a;
283 popplerLink = std::make_unique<LinkJavaScript>(linkArea, UnicodeParsedString(ljs->getScript()));
284 } break;
285
286 case actionMovie: {
287 ::LinkMovie *lm = (::LinkMovie *)a;
288
289 const QString title = (lm->hasAnnotTitle() ? UnicodeParsedString(lm->getAnnotTitle()) : QString());
290
291 Ref reference = Ref::INVALID();
292 if (lm->hasAnnotRef()) {
293 reference = *lm->getAnnotRef();
294 }
295
296 LinkMovie::Operation operation = LinkMovie::Play;
297 switch (lm->getOperation()) {
298 case ::LinkMovie::operationTypePlay:
299 operation = LinkMovie::Play;
300 break;
301 case ::LinkMovie::operationTypePause:
302 operation = LinkMovie::Pause;
303 break;
304 case ::LinkMovie::operationTypeResume:
305 operation = LinkMovie::Resume;
306 break;
307 case ::LinkMovie::operationTypeStop:
308 operation = LinkMovie::Stop;
309 break;
310 };
311
312 popplerLink = std::make_unique<LinkMovie>(linkArea, operation, title, reference);
313 } break;
314
315 case actionRendition: {
316 ::LinkRendition *lrn = (::LinkRendition *)a;
317
318 Ref reference = Ref::INVALID();
319 if (lrn->hasScreenAnnot()) {
320 reference = lrn->getScreenAnnot();
321 }
322
323 popplerLink = std::make_unique<LinkRendition>(linkArea, lrn->getMedia() ? lrn->getMedia()->copy() : std::unique_ptr<::MediaRendition> {}, lrn->getOperation(), UnicodeParsedString(lrn->getScript()), reference);
324 } break;
325
326 case actionOCGState: {
327 ::LinkOCGState *plocg = (::LinkOCGState *)a;
328
329 LinkOCGStatePrivate *locgp = new LinkOCGStatePrivate(linkArea, plocg->getStateList(), plocg->getPreserveRB());
330 popplerLink = std::make_unique<LinkOCGState>(locgp);
331 } break;
332
333 case actionHide: {
334 ::LinkHide *lh = (::LinkHide *)a;
335
336 LinkHidePrivate *lhp = new LinkHidePrivate(linkArea, lh->hasTargetName() ? UnicodeParsedString(lh->getTargetName()) : QString(), lh->isShowAction());
337 popplerLink = std::make_unique<LinkHide>(lhp);
338 } break;
339
340 case actionResetForm: {
341 ::LinkResetForm *lrf = (::LinkResetForm *)a;
342 std::vector<std::string> stdStringFields = lrf->getFields();
343 QStringList qStringFields;
344 for (const std::string &str : stdStringFields) {
345 qStringFields << QString::fromStdString(str);
346 }
347 LinkResetFormPrivate *lrfp = new LinkResetFormPrivate(linkArea, qStringFields, lrf->getExclude());
348 popplerLink = std::make_unique<LinkResetForm>(lrfp);
349 } break;
350
351 case actionSubmitForm: {
352 ::LinkSubmitForm *lsf = (::LinkSubmitForm *)a;
353 const std::vector<std::string> &stdStringFields = lsf->getFields();
354 QVector<int> fieldIds;
355 fieldIds.reserve(stdStringFields.size());
356 Form *form = parentDoc->doc->getCatalog()->getForm();
357 for (const std::string &fieldStr : stdStringFields) {
358 ::FormField *field = form->findFieldByFullyQualifiedNameOrRef(fieldStr);
359 if (field && !field->getNoExport()) {
360 int numWidgets = field->getNumWidgets();
361 for (int i = 0; i < numWidgets; i++) {
362 ::FormWidget *widget = field->getWidget(i);
363 if (widget) {
364 fieldIds.append(field->getWidget(i)->getID());
365 }
366 }
367 }
368 }
369 QString qStringUrl = QString::fromStdString(lsf->getUrl());
370 LinkSubmitForm::SubmitFormFlags qFlags = static_cast<LinkSubmitForm::SubmitFormFlags>(lsf->getFlags());
371 LinkSubmitFormPrivate *lsfp = new LinkSubmitFormPrivate(linkArea, fieldIds, qStringUrl, qFlags);
372 popplerLink = std::make_unique<LinkSubmitForm>(lsfp);
373 } break;
374
375 case actionUnknown:
376 break;
377 }
378
379 if (popplerLink) {
380 std::vector<std::unique_ptr<Link>> links;
381 for (const std::unique_ptr<::LinkAction> &nextAction : a->nextActions()) {
382 links.push_back(convertLinkActionToLink(nextAction.get(), parentDoc, linkArea));
383 }
384 LinkPrivate::get(popplerLink.get())->nextLinks = std::move(links);
385 }
386
387 return popplerLink;
388 }
389
390 inline TextPage *PageData::prepareTextSearch(const QString &text, Page::Rotation rotate, QVector<Unicode> *u)
391 {
392 *u = text.toUcs4();
393
394 const int rotation = (int)rotate * 90;
395
396 // fetch ourselves a textpage
397 TextOutputDev td(nullptr, true, 0, false, false);
398 parentDoc->doc->displayPage(&td, index + 1, 72, 72, rotation, false, true, false, nullptr, nullptr, nullptr, nullptr, true);
399 TextPage *textPage = td.takeText();
400
401 return textPage;
402 }
403
404 inline bool PageData::performSingleTextSearch(TextPage *textPage, QVector<Unicode> &u, double &sLeft, double &sTop, double &sRight, double &sBottom, Page::SearchDirection direction, bool sCase, bool sWords, bool sDiacritics,
405 bool sAcrossLines)
406 {
407 if (direction == Page::FromTop) {
408 return textPage->findText(u.data(), u.size(), true, true, false, false, sCase, sDiacritics, sAcrossLines, false, sWords, &sLeft, &sTop, &sRight, &sBottom, nullptr, nullptr);
409 } else if (direction == Page::NextResult) {
410 return textPage->findText(u.data(), u.size(), false, true, true, false, sCase, sDiacritics, sAcrossLines, false, sWords, &sLeft, &sTop, &sRight, &sBottom, nullptr, nullptr);
411 } else if (direction == Page::PreviousResult) {
412 return textPage->findText(u.data(), u.size(), false, true, true, false, sCase, sDiacritics, sAcrossLines, true, sWords, &sLeft, &sTop, &sRight, &sBottom, nullptr, nullptr);
413 }
414
415 return false;
416 }
417
418 inline QList<QRectF> PageData::performMultipleTextSearch(TextPage *textPage, QVector<Unicode> &u, bool sCase, bool sWords, bool sDiacritics, bool sAcrossLines)
419 {
420 QList<QRectF> results;
421 double sLeft = 0.0, sTop = 0.0, sRight = 0.0, sBottom = 0.0;
422 bool sIgnoredHyphen = false;
423 PDFRectangle continueMatch;
424 continueMatch.x1 = DBL_MAX; // we use this to detect valid return values
425
426 while (textPage->findText(u.data(), u.size(), false, true, true, false, sCase, sDiacritics, sAcrossLines, false, sWords, &sLeft, &sTop, &sRight, &sBottom, &continueMatch, &sIgnoredHyphen)) {
427 QRectF result;
428
429 result.setLeft(sLeft);
430 result.setTop(sTop);
431 result.setRight(sRight);
432 result.setBottom(sBottom);
433
434 results.append(result);
435
436 if (sAcrossLines && continueMatch.x1 != DBL_MAX) {
437 QRectF resultN;
438
439 resultN.setLeft(continueMatch.x1);
440 resultN.setTop(continueMatch.y1);
441 resultN.setRight(continueMatch.x2);
442 resultN.setBottom(continueMatch.y1);
443
444 results.append(resultN);
445 continueMatch.x1 = DBL_MAX;
446 }
447 }
448
449 return results;
450 }
451
452 Page::Page(DocumentData *doc, int index)
453 {
454 m_page = new PageData();
455 m_page->index = index;
456 m_page->parentDoc = doc;
457 m_page->page = doc->doc->getPage(m_page->index + 1);
458 m_page->transition = nullptr;
459 }
460
461 Page::~Page()
462 {
463 delete m_page->transition;
464 delete m_page;
465 }
466
467 // Callback that filters out everything but form fields
468 static auto annotDisplayDecideCbk = [](Annot *annot, void * /*user_data*/) {
469 // Hide everything but forms
470 return (annot->getType() == Annot::typeWidget);
471 };
472
473 // A nullptr, but with the type of a function pointer
474 // Needed to make the ternary operator happy.
475 static bool (*nullAnnotCallBack)(Annot *annot, void *user_data) = nullptr;
476
477 static auto shouldAbortRenderInternalCallback = [](void *user_data) {
478 OutputDevCallbackHelper *helper = reinterpret_cast<OutputDevCallbackHelper *>(user_data);
479 return helper->shouldAbortRenderCallback(helper->payload);
480 };
481
482 static auto shouldAbortExtractionInternalCallback = [](void *user_data) {
483 TextExtractionAbortHelper *helper = reinterpret_cast<TextExtractionAbortHelper *>(user_data);
484 return helper->shouldAbortExtractionCallback(helper->payload);
485 };
486
487 // A nullptr, but with the type of a function pointer
488 // Needed to make the ternary operator happy.
489 static bool (*nullAbortCallBack)(void *user_data) = nullptr;
490
491 static bool renderToQPainter(QImageDumpingQPainterOutputDev *qpainter_output, QPainter *painter, PageData *page, double xres, double yres, int x, int y, int w, int h, Page::Rotation rotate, Page::PainterFlags flags)
492 {
493 const bool savePainter = !(flags & Page::DontSaveAndRestore);
494 if (savePainter) {
495 painter->save();
496 }
497 if (page->parentDoc->m_hints & Document::Antialiasing) {
498 painter->setRenderHint(QPainter::Antialiasing);
499 }
500 if (page->parentDoc->m_hints & Document::TextAntialiasing) {
501 painter->setRenderHint(QPainter::TextAntialiasing);
502 }
503 painter->translate(x == -1 ? 0 : -x, y == -1 ? 0 : -y);
504
505 qpainter_output->startDoc(page->parentDoc->doc);
506
507 const bool hideAnnotations = page->parentDoc->m_hints & Document::HideAnnotations;
508
509 OutputDevCallbackHelper *abortHelper = qpainter_output;
510 page->parentDoc->doc->displayPageSlice(qpainter_output, page->index + 1, xres, yres, (int)rotate * 90, false, true, false, x, y, w, h, abortHelper->shouldAbortRenderCallback ? shouldAbortRenderInternalCallback : nullAbortCallBack,
511 abortHelper, (hideAnnotations) ? annotDisplayDecideCbk : nullAnnotCallBack, nullptr, true);
512 if (savePainter) {
513 painter->restore();
514 }
515 return true;
516 }
517
518 QImage Page::renderToImage(double xres, double yres, int x, int y, int w, int h, Rotation rotate) const
519 {
520 return renderToImage(xres, yres, x, y, w, h, rotate, nullptr, nullptr, QVariant());
521 }
522
523 QImage Page::renderToImage(double xres, double yres, int x, int y, int w, int h, Rotation rotate, RenderToImagePartialUpdateFunc partialUpdateCallback, ShouldRenderToImagePartialQueryFunc shouldDoPartialUpdateCallback,
524 const QVariant &payload) const
525 {
526 return renderToImage(xres, yres, x, y, w, h, rotate, partialUpdateCallback, shouldDoPartialUpdateCallback, nullptr, payload);
527 }
528
529 // Translate the text hinting settings from poppler-speak to Qt-speak
530 static QFont::HintingPreference QFontHintingFromPopplerHinting(int renderHints)
531 {
532 QFont::HintingPreference result = QFont::PreferNoHinting;
533
534 if (renderHints & Document::TextHinting) {
535 result = (renderHints & Document::TextSlightHinting) ? QFont::PreferVerticalHinting : QFont::PreferFullHinting;
536 }
537
538 return result;
539 }
540
541 QImage Page::renderToImage(double xres, double yres, int xPos, int yPos, int w, int h, Rotation rotate, RenderToImagePartialUpdateFunc partialUpdateCallback, ShouldRenderToImagePartialQueryFunc shouldDoPartialUpdateCallback,
542 ShouldAbortQueryFunc shouldAbortRenderCallback, const QVariant &payload) const
543 {
544 int rotation = (int)rotate * 90;
545 QImage img;
546 switch (m_page->parentDoc->m_backend) {
547 case Poppler::Document::SplashBackend: {
548 SplashColor bgColor;
549 const bool overprintPreview = m_page->parentDoc->m_hints & Document::OverprintPreview ? true : false;
550 if (overprintPreview) {
551 unsigned char c, m, y, k;
552
553 c = 255 - m_page->parentDoc->paperColor.blue();
554 m = 255 - m_page->parentDoc->paperColor.red();
555 y = 255 - m_page->parentDoc->paperColor.green();
556 k = c;
557 if (m < k) {
558 k = m;
559 }
560 if (y < k) {
561 k = y;
562 }
563 bgColor[0] = c - k;
564 bgColor[1] = m - k;
565 bgColor[2] = y - k;
566 bgColor[3] = k;
567 for (int i = 4; i < SPOT_NCOMPS + 4; i++) {
568 bgColor[i] = 0;
569 }
570 } else {
571 bgColor[0] = m_page->parentDoc->paperColor.blue();
572 bgColor[1] = m_page->parentDoc->paperColor.green();
573 bgColor[2] = m_page->parentDoc->paperColor.red();
574 }
575
576 const SplashColorMode colorMode = overprintPreview ? splashModeDeviceN8 : splashModeXBGR8;
577
578 SplashThinLineMode thinLineMode = splashThinLineDefault;
579 if (m_page->parentDoc->m_hints & Document::ThinLineShape) {
580 thinLineMode = splashThinLineShape;
581 }
582 if (m_page->parentDoc->m_hints & Document::ThinLineSolid) {
583 thinLineMode = splashThinLineSolid;
584 }
585
586 const bool ignorePaperColor = m_page->parentDoc->m_hints & Document::IgnorePaperColor;
587
588 Qt6SplashOutputDev splash_output(colorMode, 4, false, ignorePaperColor, ignorePaperColor ? nullptr : bgColor, true, thinLineMode, overprintPreview);
589
590 splash_output.setCallbacks(partialUpdateCallback, shouldDoPartialUpdateCallback, shouldAbortRenderCallback, payload);
591
592 splash_output.setFontAntialias(m_page->parentDoc->m_hints & Document::TextAntialiasing ? true : false);
593 splash_output.setVectorAntialias(m_page->parentDoc->m_hints & Document::Antialiasing ? true : false);
594 splash_output.setFreeTypeHinting(m_page->parentDoc->m_hints & Document::TextHinting ? true : false, m_page->parentDoc->m_hints & Document::TextSlightHinting ? true : false);
595
596 #if USE_CMS
597 splash_output.setDisplayProfile(m_page->parentDoc->m_displayProfile);
598 #endif
599
600 splash_output.startDoc(m_page->parentDoc->doc);
601
602 const bool hideAnnotations = m_page->parentDoc->m_hints & Document::HideAnnotations;
603
604 OutputDevCallbackHelper *abortHelper = &splash_output;
605 m_page->parentDoc->doc->displayPageSlice(&splash_output, m_page->index + 1, xres, yres, rotation, false, true, false, xPos, yPos, w, h, shouldAbortRenderCallback ? shouldAbortRenderInternalCallback : nullAbortCallBack, abortHelper,
606 (hideAnnotations) ? annotDisplayDecideCbk : nullAnnotCallBack, nullptr, true);
607
608 img = splash_output.getXBGRImage(true /* takeImageData */);
609 break;
610 }
611 case Poppler::Document::QPainterBackend: {
612 QSize size = pageSize();
613 QImage tmpimg(w == -1 ? qRound(size.width() * xres / 72.0) : w, h == -1 ? qRound(size.height() * yres / 72.0) : h, QImage::Format_ARGB32);
614
615 QColor bgColor(m_page->parentDoc->paperColor.red(), m_page->parentDoc->paperColor.green(), m_page->parentDoc->paperColor.blue(), m_page->parentDoc->paperColor.alpha());
616
617 tmpimg.fill(bgColor);
618
619 QPainter painter(&tmpimg);
620 QImageDumpingQPainterOutputDev qpainter_output(&painter, &tmpimg);
621
622 qpainter_output.setHintingPreference(QFontHintingFromPopplerHinting(m_page->parentDoc->m_hints));
623
624 #if USE_CMS
625 qpainter_output.setDisplayProfile(m_page->parentDoc->m_displayProfile);
626 #endif
627
628 qpainter_output.setCallbacks(partialUpdateCallback, shouldDoPartialUpdateCallback, shouldAbortRenderCallback, payload);
629 renderToQPainter(&qpainter_output, &painter, m_page, xres, yres, xPos, yPos, w, h, rotate, DontSaveAndRestore);
630 painter.end();
631 img = tmpimg;
632 break;
633 }
634 }
635
636 if (shouldAbortRenderCallback && shouldAbortRenderCallback(payload)) {
637 return QImage();
638 }
639
640 return img;
641 }
642
643 bool Page::renderToPainter(QPainter *painter, double xres, double yres, int x, int y, int w, int h, Rotation rotate, PainterFlags flags) const
644 {
645 if (!painter) {
646 return false;
647 }
648
649 switch (m_page->parentDoc->m_backend) {
650 case Poppler::Document::SplashBackend:
651 return false;
652 case Poppler::Document::QPainterBackend: {
653 QImageDumpingQPainterOutputDev qpainter_output(painter, nullptr);
654
655 qpainter_output.setHintingPreference(QFontHintingFromPopplerHinting(m_page->parentDoc->m_hints));
656
657 return renderToQPainter(&qpainter_output, painter, m_page, xres, yres, x, y, w, h, rotate, flags);
658 }
659 }
660 return false;
661 }
662
663 QImage Page::thumbnail() const
664 {
665 unsigned char *data = nullptr;
666 int w = 0;
667 int h = 0;
668 int rowstride = 0;
669 bool r = m_page->page->loadThumb(&data, &w, &h, &rowstride);
670 QImage ret;
671 if (r) {
672 // first construct a temporary image with the data got,
673 // then force a copy of it so we can free the raw thumbnail data
674 ret = QImage(data, w, h, rowstride, QImage::Format_RGB888).copy();
675 gfree(data);
676 }
677 return ret;
678 }
679
680 QString Page::text(const QRectF &r, TextLayout textLayout) const
681 {
682 TextOutputDev *output_dev;
683 GooString s;
684 QString result;
685
686 const bool rawOrder = textLayout == RawOrderLayout;
687 const bool physLayout = textLayout == PhysicalLayout;
688 output_dev = new TextOutputDev(nullptr, physLayout, 0, rawOrder, false);
689 m_page->parentDoc->doc->displayPageSlice(output_dev, m_page->index + 1, 72, 72, 0, false, true, false, -1, -1, -1, -1, nullptr, nullptr, nullptr, nullptr, true);
690 if (r.isNull()) {
691 const PDFRectangle *rect = m_page->page->getCropBox();
692 if (orientation() == Orientation::Portrait || orientation() == Orientation::UpsideDown) {
693 s = output_dev->getText(*rect);
694 } else {
695 s = output_dev->getText(PDFRectangle { rect->y1, rect->x1, rect->y2, rect->x2 });
696 }
697 } else {
698 if (textLayout == ReadingOrder) {
699 qWarning() << "ReadingOrder is not supported with non null rect";
700 return {};
701 }
702 s = output_dev->getText(PDFRectangle { r.left(), r.top(), r.right(), r.bottom() });
703 }
704
705 result = QString::fromStdString(s.toStr());
706
707 delete output_dev;
708 return result;
709 }
710
711 QString Page::text(const QRectF &r) const
712 {
713 return text(r, PhysicalLayout);
714 }
715
716 bool Page::search(const QString &text, double &sLeft, double &sTop, double &sRight, double &sBottom, SearchDirection direction, SearchFlags flags, Rotation rotate) const
717 {
718 const bool sCase = flags.testFlag(IgnoreCase) ? false : true;
719 const bool sWords = flags.testFlag(WholeWords) ? true : false;
720 const bool sDiacritics = flags.testFlag(IgnoreDiacritics) ? true : false;
721 const bool sAcrossLines = flags.testFlag(AcrossLines) ? true : false;
722
723 QVector<Unicode> u;
724 TextPage *textPage = m_page->prepareTextSearch(text, rotate, &u);
725
726 const bool found = m_page->performSingleTextSearch(textPage, u, sLeft, sTop, sRight, sBottom, direction, sCase, sWords, sDiacritics, sAcrossLines);
727
728 textPage->decRefCnt();
729
730 return found;
731 }
732
733 QList<QRectF> Page::search(const QString &text, SearchFlags flags, Rotation rotate) const
734 {
735 const bool sCase = flags.testFlag(IgnoreCase) ? false : true;
736 const bool sWords = flags.testFlag(WholeWords) ? true : false;
737 const bool sDiacritics = flags.testFlag(IgnoreDiacritics) ? true : false;
738 const bool sAcrossLines = flags.testFlag(AcrossLines) ? true : false;
739
740 QVector<Unicode> u;
741 TextPage *textPage = m_page->prepareTextSearch(text, rotate, &u);
742
743 QList<QRectF> results = m_page->performMultipleTextSearch(textPage, u, sCase, sWords, sDiacritics, sAcrossLines);
744
745 textPage->decRefCnt();
746
747 return results;
748 }
749
750 std::vector<std::unique_ptr<TextBox>> Page::textList(Rotation rotate) const
751 {
752 return textList(rotate, nullptr, QVariant());
753 }
754
755 std::vector<std::unique_ptr<TextBox>> Page::textList(Rotation rotate, ShouldAbortQueryFunc shouldAbortExtractionCallback, const QVariant &closure) const
756 {
757 std::vector<std::unique_ptr<TextBox>> output_list;
758
759 TextOutputDev output_dev(nullptr, false, 0, false, false);
760
761 int rotation = (int)rotate * 90;
762
763 TextExtractionAbortHelper abortHelper(shouldAbortExtractionCallback, closure);
764 m_page->parentDoc->doc->displayPageSlice(&output_dev, m_page->index + 1, 72, 72, rotation, false, false, false, -1, -1, -1, -1, shouldAbortExtractionCallback ? shouldAbortExtractionInternalCallback : nullAbortCallBack, &abortHelper,
765 nullptr, nullptr, true);
766
767 std::unique_ptr<TextWordList> word_list = output_dev.makeWordList();
768
769 if (shouldAbortExtractionCallback && shouldAbortExtractionCallback(closure)) {
770 return output_list;
771 }
772
773 QHash<const TextWord *, TextBox *> wordBoxMap;
774
775 const std::vector<TextWord *> &words = word_list->getWords();
776 output_list.reserve(words.size());
777 for (const TextWord *word : words) {
778 const std::unique_ptr<std::string> wordText = word->getText();
779 const QString string = QString::fromUtf8(wordText->c_str());
780 double xMin, yMin, xMax, yMax;
781 word->getBBox(&xMin, &yMin, &xMax, &yMax);
782
783 auto text_box = std::make_unique<TextBox>(string, QRectF(xMin, yMin, xMax - xMin, yMax - yMin));
784 text_box->m_data->hasSpaceAfter = word->hasSpaceAfter() == true;
785 text_box->m_data->charBBoxes.reserve(word->getLength());
786 for (int j = 0; j < word->getLength(); ++j) {
787 word->getCharBBox(j, &xMin, &yMin, &xMax, &yMax);
788 text_box->m_data->charBBoxes.append(QRectF(xMin, yMin, xMax - xMin, yMax - yMin));
789 }
790
791 wordBoxMap.insert(word, text_box.get());
792
793 output_list.push_back(std::move(text_box));
794 }
795
796 for (const TextWord *word : words) {
797 TextBox *text_box = wordBoxMap.value(word);
798 text_box->m_data->nextWord = wordBoxMap.value(word->nextWord());
799 }
800
801 return output_list;
802 }
803
804 PageTransition *Page::transition() const
805 {
806 if (!m_page->transition) {
807 Object o = m_page->page->getTrans();
808 PageTransitionParams params;
809 params.dictObj = &o;
810 if (params.dictObj->isDict()) {
811 m_page->transition = new PageTransition(params);
812 }
813 }
814 return m_page->transition;
815 }
816
817 std::unique_ptr<Link> Page::action(PageAction act) const
818 {
819 if (act == Page::Opening || act == Page::Closing) {
820 Object o = m_page->page->getActions();
821 if (!o.isDict()) {
822 return nullptr;
823 }
824 Dict *dict = o.getDict();
825 const char *key = act == Page::Opening ? "O" : "C";
826 Object o2 = dict->lookup((char *)key);
827 std::unique_ptr<::LinkAction> lact = ::LinkAction::parseAction(&o2, m_page->parentDoc->doc->getCatalog()->getBaseURI());
828 if (lact != nullptr) {
829 return m_page->convertLinkActionToLink(lact.get(), QRectF());
830 }
831 }
832 return nullptr;
833 }
834
835 QSizeF Page::pageSizeF() const
836 {
837 Page::Orientation orient = orientation();
838 if ((Page::Landscape == orient) || (Page::Seascape == orient)) {
839 return QSizeF(m_page->page->getCropHeight(), m_page->page->getCropWidth());
840 } else {
841 return QSizeF(m_page->page->getCropWidth(), m_page->page->getCropHeight());
842 }
843 }
844
845 QSize Page::pageSize() const
846 {
847 return pageSizeF().toSize();
848 }
849
850 Page::Orientation Page::orientation() const
851 {
852 const int rotation = m_page->page->getRotate();
853 switch (rotation) {
854 case 90:
855 return Page::Landscape;
856 break;
857 case 180:
858 return Page::UpsideDown;
859 break;
860 case 270:
861 return Page::Seascape;
862 break;
863 default:
864 return Page::Portrait;
865 }
866 }
867
868 void Page::defaultCTM(double *CTM, double dpiX, double dpiY, int rotate, bool upsideDown)
869 {
870 m_page->page->getDefaultCTM(CTM, dpiX, dpiY, rotate, false, upsideDown);
871 }
872
873 std::vector<std::unique_ptr<Link>> Page::links() const
874 {
875 LinkExtractorOutputDev link_dev(m_page);
876 m_page->parentDoc->doc->processLinks(&link_dev, m_page->index + 1);
877 return link_dev.links();
878 }
879
880 std::vector<std::unique_ptr<Annotation>> Page::annotations() const
881 {
882 return AnnotationPrivate::findAnnotations(m_page->page, m_page->parentDoc, QSet<Annotation::SubType>());
883 }
884
885 std::vector<std::unique_ptr<Annotation>> Page::annotations(const QSet<Annotation::SubType> &subtypes) const
886 {
887 return AnnotationPrivate::findAnnotations(m_page->page, m_page->parentDoc, subtypes);
888 }
889
890 void Page::addAnnotation(const Annotation *ann)
891 {
892 AnnotationPrivate::addAnnotationToPage(m_page->page, m_page->parentDoc, ann);
893 }
894
895 void Page::removeAnnotation(const Annotation *ann)
896 {
897 AnnotationPrivate::removeAnnotationFromPage(m_page->page, ann);
898 }
899
900 std::vector<std::unique_ptr<FormField>> Page::formFields() const
901 {
902 std::vector<std::unique_ptr<FormField>> fields;
903 ::Page *p = m_page->page;
904 const std::unique_ptr<FormPageWidgets> form = p->getFormWidgets();
905 int formcount = form->getNumWidgets();
906 for (int i = 0; i < formcount; ++i) {
907 ::FormWidget *fm = form->getWidget(i);
908 std::unique_ptr<FormField> ff;
909 switch (fm->getType()) {
910 case formButton: {
911 ff = std::make_unique<FormFieldButton>(m_page->parentDoc, p, static_cast<FormWidgetButton *>(fm));
912 } break;
913
914 case formText: {
915 ff = std::make_unique<FormFieldText>(m_page->parentDoc, p, static_cast<FormWidgetText *>(fm));
916 } break;
917
918 case formChoice: {
919 ff = std::make_unique<FormFieldChoice>(m_page->parentDoc, p, static_cast<FormWidgetChoice *>(fm));
920 } break;
921
922 case formSignature: {
923 ff = std::make_unique<FormFieldSignature>(m_page->parentDoc, p, static_cast<FormWidgetSignature *>(fm));
924 } break;
925
926 default:;
927 }
928
929 if (ff) {
930 fields.push_back(std::move(ff));
931 }
932 }
933
934 return fields;
935 }
936
937 double Page::duration() const
938 {
939 return m_page->page->getDuration();
940 }
941
942 QString Page::label() const
943 {
944 GooString goo;
945 if (!m_page->parentDoc->doc->getCatalog()->indexToLabel(m_page->index, &goo)) {
946 return QString();
947 }
948
949 return UnicodeParsedString(&goo);
950 }
951
952 int Page::index() const
953 {
954 return m_page->index;
955 }
956
957 }