Debian Codegraph @

qt5/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-2020, 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 Oliver Sander <[email protected]>
27 * Copyright (C) 2020 Philipp Knechtges <[email protected]>
28 * Copyright (C) 2021 Hubert Figuiere <[email protected]>
29 * Copyright (C) 2021 Thomas Huxhorn <[email protected]>
30 * Copyright (C) 2023 Kevin Ottens <[email protected]>. Work sponsored by De Bortoli Wines
31 * Copyright (C) 2024, 2025 Stefan Brüns <[email protected]>
32 * Copyright (C) 2024 Pratham Gandhi <[email protected]>
33 * Copyright (C) 2024, 2026 g10 Code GmbH, Author: Sune Stolborg Vuorela <[email protected]>
34 *
35 * This program is free software; you can redistribute it and/or modify
36 * it under the terms of the GNU General Public License as published by
37 * the Free Software Foundation; either version 2, or (at your option)
38 * any later version.
39 *
40 * This program is distributed in the hope that it will be useful,
41 * but WITHOUT ANY WARRANTY; without even the implied warranty of
42 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 * GNU General Public License for more details.
44 *
45 * You should have received a copy of the GNU General Public License
46 * along with this program; if not, write to the Free Software
47 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
48 */
49
50 #include <poppler-qt5.h>
51
52 #include <QtCore/QHash>
53 #include <QtCore/QMap>
54 #include <QtCore/QVarLengthArray>
55 #include <QtGui/QImage>
56 #include <QtGui/QPainter>
57 #include <QDebug>
58
59 #include <config.h>
60 #include <cfloat>
61 #include <poppler-config.h>
62 #include <PDFDoc.h>
63 #include <Catalog.h>
64 #include <Form.h>
65 #include <ErrorCodes.h>
66 #include <TextOutputDev.h>
67 #include <Annot.h>
68 #include <Link.h>
69 #include <QPainterOutputDev.h>
70 #include <Rendition.h>
71 #include <SplashOutputDev.h>
72 #include <goo/gmem.h>
73 #include <splash/SplashBitmap.h>
74
75 #include "poppler-private.h"
76 #include "poppler-page-transition-private.h"
77 #include "poppler-page-private.h"
78 #include "poppler-link-extractor-private.h"
79 #include "poppler-link-private.h"
80 #include "poppler-annotation-private.h"
81 #include "poppler-form.h"
82 #include "poppler-media.h"
83
84 namespace Poppler {
85
86 class TextExtractionAbortHelper
87 {
88 public:
89 TextExtractionAbortHelper(Page::ShouldAbortQueryFunc shouldAbortCallback, const QVariant &payloadA)
90 {
91 shouldAbortExtractionCallback = shouldAbortCallback;
92 payload = payloadA;
93 }
94
95 Page::ShouldAbortQueryFunc shouldAbortExtractionCallback = nullptr;
96 QVariant payload;
97 };
98
99 class OutputDevCallbackHelper
100 {
101 public:
102 void setCallbacks(Page::RenderToImagePartialUpdateFunc callback, Page::ShouldRenderToImagePartialQueryFunc shouldDoCallback, Page::ShouldAbortQueryFunc shouldAbortCallback, const QVariant &payloadA)
103 {
104 partialUpdateCallback = callback;
105 shouldDoPartialUpdateCallback = shouldDoCallback;
106 shouldAbortRenderCallback = shouldAbortCallback;
107 payload = payloadA;
108 }
109
110 Page::RenderToImagePartialUpdateFunc partialUpdateCallback = nullptr;
111 Page::ShouldRenderToImagePartialQueryFunc shouldDoPartialUpdateCallback = nullptr;
112 Page::ShouldAbortQueryFunc shouldAbortRenderCallback = nullptr;
113 QVariant payload;
114 };
115
116 class Qt5SplashOutputDev : public SplashOutputDev, public OutputDevCallbackHelper
117 {
118 public:
119 Qt5SplashOutputDev(SplashColorMode colorModeA, int bitmapRowPadA, bool reverseVideoA, bool ignorePaperColorA, SplashColorPtr paperColorA, bool bitmapTopDownA, SplashThinLineMode thinLineMode, bool overprintPreviewA)
120 : SplashOutputDev(colorModeA, bitmapRowPadA, reverseVideoA, paperColorA, bitmapTopDownA, thinLineMode, overprintPreviewA), ignorePaperColor(ignorePaperColorA)
121 {
122 }
123
124 ~Qt5SplashOutputDev() override;
125
126 void dump() override
127 {
128 if (partialUpdateCallback && shouldDoPartialUpdateCallback && shouldDoPartialUpdateCallback(payload)) {
129 partialUpdateCallback(getXBGRImage(false /* takeImageData */), payload);
130 }
131 }
132
133 QImage getXBGRImage(bool takeImageData)
134 {
135 SplashBitmap *b = getBitmap();
136
137 // If we use DeviceN8, convert to XBGR8.
138 // If requested, also transfer Splash's internal alpha channel.
139 const SplashBitmap::ConversionMode mode = ignorePaperColor ? SplashBitmap::conversionAlphaPremultiplied : SplashBitmap::conversionOpaque;
140
141 const QImage::Format format = ignorePaperColor ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
142
143 if (b->convertToXBGR(mode)) {
144 const int bw = b->getWidth();
145 const int bh = b->getHeight();
146 const int brs = b->getRowSize();
147
148 SplashColorPtr data = takeImageData ? b->takeData() : b->getDataPtr();
149
150 if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
151 // Convert byte order from RGBX to XBGR.
152 for (int i = 0; i < bh; ++i) {
153 for (int j = 0; j < bw; ++j) {
154 SplashColorPtr pixel = &data[i * brs + j];
155
156 qSwap(pixel[0], pixel[3]);
157 qSwap(pixel[1], pixel[2]);
158 }
159 }
160 }
161
162 if (takeImageData) {
163 // Construct a Qt image holding (and also owning) the raw bitmap data.
164 QImage i(data, bw, bh, brs, format, gfree, data);
165 if (i.isNull()) {
166 gfree(data);
167 }
168 return i;
169 } else {
170 return QImage(data, bw, bh, brs, format).copy();
171 }
172 }
173
174 return QImage();
175 }
176
177 private:
178 bool ignorePaperColor;
179 };
180
181 Qt5SplashOutputDev::~Qt5SplashOutputDev() = default;
182
183 class QImageDumpingQPainterOutputDev : public QPainterOutputDev, public OutputDevCallbackHelper
184 {
185 public:
186 QImageDumpingQPainterOutputDev(QPainter *painter, QImage *i) : QPainterOutputDev(painter), image(i) { }
187 ~QImageDumpingQPainterOutputDev() override;
188
189 void dump() override
190 {
191 if (partialUpdateCallback && shouldDoPartialUpdateCallback && shouldDoPartialUpdateCallback(payload)) {
192 partialUpdateCallback(*image, payload);
193 }
194 }
195
196 private:
197 QImage *image;
198 };
199
200 QImageDumpingQPainterOutputDev::~QImageDumpingQPainterOutputDev() = default;
201
202 Link *PageData::convertLinkActionToLink(::LinkAction *a, const QRectF &linkArea)
203 {
204 return convertLinkActionToLink(a, parentDoc, linkArea);
205 }
206
207 Link *PageData::convertLinkActionToLink(::LinkAction *a, DocumentData *parentDoc, const QRectF &linkArea)
208 {
209 if (!a) {
210 return nullptr;
211 }
212
213 Link *popplerLink = nullptr;
214 switch (a->getKind()) {
215 case actionGoTo: {
216 LinkGoTo *g = (LinkGoTo *)a;
217 const LinkDestinationData ldd(g->getDest(), g->getNamedDest(), parentDoc, false);
218 // create link: no ext file, namedDest, object pointer
219 popplerLink = new LinkGoto(linkArea, QString(), LinkDestination(ldd));
220 } break;
221
222 case actionGoToR: {
223 LinkGoToR *g = (LinkGoToR *)a;
224 // copy link file
225 const QString fileName = UnicodeParsedString(g->getFileName());
226 const LinkDestinationData ldd(g->getDest(), g->getNamedDest(), parentDoc, !fileName.isEmpty());
227 // create link: fileName, namedDest, object pointer
228 popplerLink = new LinkGoto(linkArea, fileName, LinkDestination(ldd));
229 } break;
230
231 case actionLaunch: {
232 LinkLaunch *e = (LinkLaunch *)a;
233 const GooString *p = e->getParams();
234 popplerLink = new LinkExecute(linkArea, UnicodeParsedString(e->getFileName()), p ? QString::fromStdString(p->toStr()) : QString {});
235 } break;
236
237 case actionNamed: {
238 const std::string &name = ((LinkNamed *)a)->getName();
239 if (name == "NextPage") {
240 popplerLink = new LinkAction(linkArea, LinkAction::PageNext);
241 } else if (name == "PrevPage") {
242 popplerLink = new LinkAction(linkArea, LinkAction::PagePrev);
243 } else if (name == "FirstPage") {
244 popplerLink = new LinkAction(linkArea, LinkAction::PageFirst);
245 } else if (name == "LastPage") {
246 popplerLink = new LinkAction(linkArea, LinkAction::PageLast);
247 } else if (name == "GoBack") {
248 popplerLink = new LinkAction(linkArea, LinkAction::HistoryBack);
249 } else if (name == "GoForward") {
250 popplerLink = new LinkAction(linkArea, LinkAction::HistoryForward);
251 } else if (name == "Quit") {
252 popplerLink = new LinkAction(linkArea, LinkAction::Quit);
253 } else if (name == "GoToPage") {
254 popplerLink = new LinkAction(linkArea, LinkAction::GoToPage);
255 } else if (name == "Find") {
256 popplerLink = new LinkAction(linkArea, LinkAction::Find);
257 } else if (name == "FullScreen") {
258 popplerLink = new LinkAction(linkArea, LinkAction::Presentation);
259 } else if (name == "Print") {
260 popplerLink = new LinkAction(linkArea, LinkAction::Print);
261 } else if (name == "Close") {
262 // acroread closes the document always, doesnt care whether
263 // its presentation mode or not
264 // popplerLink = new LinkAction( linkArea, LinkAction::EndPresentation );
265 popplerLink = new LinkAction(linkArea, LinkAction::Close);
266 } else if (name == "SaveAs") {
267 popplerLink = new LinkAction(linkArea, LinkAction::SaveAs);
268 } else {
269 qWarning() << "Unhandled action name" << name.c_str();
270 }
271 } break;
272
273 case actionURI: {
274 popplerLink = new LinkBrowse(linkArea, QString::fromStdString(((LinkURI *)a)->getURI()));
275 } break;
276
277 case actionSound: {
278 ::LinkSound *ls = (::LinkSound *)a;
279 popplerLink = new LinkSound(linkArea, ls->getVolume(), ls->getSynchronous(), ls->getRepeat(), ls->getMix(), new SoundObject(ls->getSound()));
280 } break;
281
282 case actionJavaScript: {
283 ::LinkJavaScript *ljs = (::LinkJavaScript *)a;
284 popplerLink = new LinkJavaScript(linkArea, UnicodeParsedString(ljs->getScript()));
285 } break;
286
287 case actionMovie: {
288 ::LinkMovie *lm = (::LinkMovie *)a;
289
290 const QString title = (lm->hasAnnotTitle() ? UnicodeParsedString(lm->getAnnotTitle()) : QString());
291
292 Ref reference = Ref::INVALID();
293 if (lm->hasAnnotRef()) {
294 reference = *lm->getAnnotRef();
295 }
296
297 LinkMovie::Operation operation = LinkMovie::Play;
298 switch (lm->getOperation()) {
299 case ::LinkMovie::operationTypePlay:
300 operation = LinkMovie::Play;
301 break;
302 case ::LinkMovie::operationTypePause:
303 operation = LinkMovie::Pause;
304 break;
305 case ::LinkMovie::operationTypeResume:
306 operation = LinkMovie::Resume;
307 break;
308 case ::LinkMovie::operationTypeStop:
309 operation = LinkMovie::Stop;
310 break;
311 };
312
313 popplerLink = new LinkMovie(linkArea, operation, title, reference);
314 } break;
315
316 case actionRendition: {
317 ::LinkRendition *lrn = (::LinkRendition *)a;
318
319 Ref reference = Ref::INVALID();
320 if (lrn->hasScreenAnnot()) {
321 reference = lrn->getScreenAnnot();
322 }
323
324 popplerLink = new LinkRendition(linkArea, lrn->getMedia() ? lrn->getMedia()->copy() : std::unique_ptr<::MediaRendition> {}, lrn->getOperation(), UnicodeParsedString(lrn->getScript()), reference);
325 } break;
326
327 case actionOCGState: {
328 ::LinkOCGState *plocg = (::LinkOCGState *)a;
329
330 LinkOCGStatePrivate *locgp = new LinkOCGStatePrivate(linkArea, plocg->getStateList(), plocg->getPreserveRB());
331 popplerLink = new LinkOCGState(locgp);
332 } break;
333
334 case actionHide: {
335 ::LinkHide *lh = (::LinkHide *)a;
336
337 LinkHidePrivate *lhp = new LinkHidePrivate(linkArea, lh->hasTargetName() ? UnicodeParsedString(lh->getTargetName()) : QString(), lh->isShowAction());
338 popplerLink = new LinkHide(lhp);
339 } break;
340
341 case actionResetForm: {
342 ::LinkResetForm *lrf = (::LinkResetForm *)a;
343 std::vector<std::string> stdStringFields = lrf->getFields();
344 QStringList qStringFields;
345 for (const std::string &str : stdStringFields) {
346 qStringFields << QString::fromStdString(str);
347 }
348 LinkResetFormPrivate *lrfp = new LinkResetFormPrivate(linkArea, qStringFields, lrf->getExclude());
349 popplerLink = new LinkResetForm(lrfp);
350 } break;
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 = new LinkSubmitForm(lsfp);
373 } break;
374
375 case actionUnknown:
376 break;
377 }
378
379 if (popplerLink) {
380 QVector<Link *> links;
381 for (const std::unique_ptr<::LinkAction> &nextAction : a->nextActions()) {
382 links << convertLinkActionToLink(nextAction.get(), parentDoc, linkArea);
383 }
384 LinkPrivate::get(popplerLink)->nextLinks = 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 Qt5SplashOutputDev 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, SearchMode caseSensitive, Rotation rotate) const
717 {
718 const bool sCase = caseSensitive == Page::CaseSensitive ? true : false;
719
720 QVector<Unicode> u;
721 TextPage *textPage = m_page->prepareTextSearch(text, rotate, &u);
722
723 const bool found = m_page->performSingleTextSearch(textPage, u, sLeft, sTop, sRight, sBottom, direction, sCase, false, false, false);
724
725 textPage->decRefCnt();
726
727 return found;
728 }
729
730 bool Page::search(const QString &text, double &sLeft, double &sTop, double &sRight, double &sBottom, SearchDirection direction, SearchFlags flags, Rotation rotate) const
731 {
732 const bool sCase = flags.testFlag(IgnoreCase) ? false : true;
733 const bool sWords = flags.testFlag(WholeWords) ? true : false;
734 const bool sDiacritics = flags.testFlag(IgnoreDiacritics) ? true : false;
735 const bool sAcrossLines = flags.testFlag(AcrossLines) ? true : false;
736
737 QVector<Unicode> u;
738 TextPage *textPage = m_page->prepareTextSearch(text, rotate, &u);
739
740 const bool found = m_page->performSingleTextSearch(textPage, u, sLeft, sTop, sRight, sBottom, direction, sCase, sWords, sDiacritics, sAcrossLines);
741
742 textPage->decRefCnt();
743
744 return found;
745 }
746
747 QList<QRectF> Page::search(const QString &text, SearchMode caseSensitive, Rotation rotate) const
748 {
749 const bool sCase = caseSensitive == Page::CaseSensitive ? true : false;
750
751 QVector<Unicode> u;
752 TextPage *textPage = m_page->prepareTextSearch(text, rotate, &u);
753
754 const QList<QRectF> results = m_page->performMultipleTextSearch(textPage, u, sCase, false, false, false);
755
756 textPage->decRefCnt();
757
758 return results;
759 }
760
761 QList<QRectF> Page::search(const QString &text, SearchFlags flags, Rotation rotate) const
762 {
763 const bool sCase = flags.testFlag(IgnoreCase) ? false : true;
764 const bool sWords = flags.testFlag(WholeWords) ? true : false;
765 const bool sDiacritics = flags.testFlag(IgnoreDiacritics) ? true : false;
766 const bool sAcrossLines = flags.testFlag(AcrossLines) ? true : false;
767
768 QVector<Unicode> u;
769 TextPage *textPage = m_page->prepareTextSearch(text, rotate, &u);
770
771 const QList<QRectF> results = m_page->performMultipleTextSearch(textPage, u, sCase, sWords, sDiacritics, sAcrossLines);
772
773 textPage->decRefCnt();
774
775 return results;
776 }
777
778 QList<TextBox *> Page::textList(Rotation rotate) const
779 {
780 return textList(rotate, nullptr, QVariant());
781 }
782
783 QList<TextBox *> Page::textList(Rotation rotate, ShouldAbortQueryFunc shouldAbortExtractionCallback, const QVariant &closure) const
784 {
785 QList<TextBox *> output_list;
786
787 TextOutputDev output_dev(nullptr, false, 0, false, false);
788
789 int rotation = (int)rotate * 90;
790
791 TextExtractionAbortHelper abortHelper(shouldAbortExtractionCallback, closure);
792 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,
793 nullptr, nullptr, true);
794
795 std::unique_ptr<TextWordList> word_list = output_dev.makeWordList();
796
797 if (shouldAbortExtractionCallback && shouldAbortExtractionCallback(closure)) {
798 return output_list;
799 }
800
801 QHash<const TextWord *, TextBox *> wordBoxMap;
802
803 const std::vector<TextWord *> &words = word_list->getWords();
804 output_list.reserve(words.size());
805 for (const TextWord *word : words) {
806 const std::unique_ptr<std::string> wordText = word->getText();
807 const QString string = QString::fromUtf8(wordText->c_str());
808 double xMin, yMin, xMax, yMax;
809 word->getBBox(&xMin, &yMin, &xMax, &yMax);
810
811 TextBox *text_box = new TextBox(string, QRectF(xMin, yMin, xMax - xMin, yMax - yMin));
812 text_box->m_data->hasSpaceAfter = word->hasSpaceAfter() == true;
813 text_box->m_data->charBBoxes.reserve(word->getLength());
814 for (int j = 0; j < word->getLength(); ++j) {
815 word->getCharBBox(j, &xMin, &yMin, &xMax, &yMax);
816 text_box->m_data->charBBoxes.append(QRectF(xMin, yMin, xMax - xMin, yMax - yMin));
817 }
818
819 wordBoxMap.insert(word, text_box);
820
821 output_list.append(text_box);
822 }
823
824 for (const TextWord *word : words) {
825 TextBox *text_box = wordBoxMap.value(word);
826 text_box->m_data->nextWord = wordBoxMap.value(word->nextWord());
827 }
828
829 return output_list;
830 }
831
832 PageTransition *Page::transition() const
833 {
834 if (!m_page->transition) {
835 Object o = m_page->page->getTrans();
836 PageTransitionParams params;
837 params.dictObj = &o;
838 if (params.dictObj->isDict()) {
839 m_page->transition = new PageTransition(params);
840 }
841 }
842 return m_page->transition;
843 }
844
845 Link *Page::action(PageAction act) const
846 {
847 if (act == Page::Opening || act == Page::Closing) {
848 Object o = m_page->page->getActions();
849 if (!o.isDict()) {
850 return nullptr;
851 }
852 Dict *dict = o.getDict();
853 const char *key = act == Page::Opening ? "O" : "C";
854 Object o2 = dict->lookup((char *)key);
855 std::unique_ptr<::LinkAction> lact = ::LinkAction::parseAction(&o2, m_page->parentDoc->doc->getCatalog()->getBaseURI());
856 Link *popplerLink = nullptr;
857 if (lact != nullptr) {
858 popplerLink = m_page->convertLinkActionToLink(lact.get(), QRectF());
859 }
860 return popplerLink;
861 }
862 return nullptr;
863 }
864
865 QSizeF Page::pageSizeF() const
866 {
867 Page::Orientation orient = orientation();
868 if ((Page::Landscape == orient) || (Page::Seascape == orient)) {
869 return QSizeF(m_page->page->getCropHeight(), m_page->page->getCropWidth());
870 } else {
871 return QSizeF(m_page->page->getCropWidth(), m_page->page->getCropHeight());
872 }
873 }
874
875 QSize Page::pageSize() const
876 {
877 return pageSizeF().toSize();
878 }
879
880 Page::Orientation Page::orientation() const
881 {
882 const int rotation = m_page->page->getRotate();
883 switch (rotation) {
884 case 90:
885 return Page::Landscape;
886 break;
887 case 180:
888 return Page::UpsideDown;
889 break;
890 case 270:
891 return Page::Seascape;
892 break;
893 default:
894 return Page::Portrait;
895 }
896 }
897
898 void Page::defaultCTM(double *CTM, double dpiX, double dpiY, int rotate, bool upsideDown)
899 {
900 m_page->page->getDefaultCTM(CTM, dpiX, dpiY, rotate, false, upsideDown);
901 }
902
903 QList<Link *> Page::links() const
904 {
905 LinkExtractorOutputDev link_dev(m_page);
906 m_page->parentDoc->doc->processLinks(&link_dev, m_page->index + 1);
907 QList<Link *> popplerLinks = link_dev.links();
908
909 return popplerLinks;
910 }
911
912 QList<Annotation *> Page::annotations() const
913 {
914 return AnnotationPrivate::findAnnotations(m_page->page, m_page->parentDoc, QSet<Annotation::SubType>());
915 }
916
917 QList<Annotation *> Page::annotations(const QSet<Annotation::SubType> &subtypes) const
918 {
919 return AnnotationPrivate::findAnnotations(m_page->page, m_page->parentDoc, subtypes);
920 }
921
922 void Page::addAnnotation(const Annotation *ann)
923 {
924 AnnotationPrivate::addAnnotationToPage(m_page->page, m_page->parentDoc, ann);
925 }
926
927 void Page::removeAnnotation(const Annotation *ann)
928 {
929 AnnotationPrivate::removeAnnotationFromPage(m_page->page, ann);
930 }
931
932 QList<FormField *> Page::formFields() const
933 {
934 QList<FormField *> fields;
935 ::Page *p = m_page->page;
936 const std::unique_ptr<FormPageWidgets> form = p->getFormWidgets();
937 int formcount = form->getNumWidgets();
938 for (int i = 0; i < formcount; ++i) {
939 ::FormWidget *fm = form->getWidget(i);
940 FormField *ff = nullptr;
941 switch (fm->getType()) {
942 case formButton: {
943 ff = new FormFieldButton(m_page->parentDoc, p, static_cast<FormWidgetButton *>(fm));
944 } break;
945
946 case formText: {
947 ff = new FormFieldText(m_page->parentDoc, p, static_cast<FormWidgetText *>(fm));
948 } break;
949
950 case formChoice: {
951 ff = new FormFieldChoice(m_page->parentDoc, p, static_cast<FormWidgetChoice *>(fm));
952 } break;
953
954 case formSignature: {
955 ff = new FormFieldSignature(m_page->parentDoc, p, static_cast<FormWidgetSignature *>(fm));
956 } break;
957
958 default:;
959 }
960
961 if (ff) {
962 fields.append(ff);
963 }
964 }
965
966 return fields;
967 }
968
969 double Page::duration() const
970 {
971 return m_page->page->getDuration();
972 }
973
974 QString Page::label() const
975 {
976 GooString goo;
977 if (!m_page->parentDoc->doc->getCatalog()->indexToLabel(m_page->index, &goo)) {
978 return QString();
979 }
980
981 return UnicodeParsedString(&goo);
982 }
983
984 int Page::index() const
985 {
986 return m_page->index;
987 }
988
989 }