/
generator_pdf.cpp
1931 lines (1657 loc) · 73.4 KB
/
generator_pdf.cpp
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (C) 2004-2008 by Albert Astals Cid <aacid@kde.org> *
* Copyright (C) 2004 by Enrico Ros <eros.kde@email.it> *
* Copyright (C) 2012 by Guillermo A. Amaral B. <gamaral@kde.org> *
* Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group *
* company, info@kdab.com. Work sponsored by the *
* LiMux project of the city of Munich *
* Copyright (C) 2019 by Oliver Sander <oliver.sander@tu-dresden.de> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include <memory>
#include "generator_pdf.h"
// qt/kde includes
#include <QCheckBox>
#include <QColor>
#include <QComboBox>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QImage>
#include <QLayout>
#include <QMutex>
#include <QPainter>
#include <QPrinter>
#include <QStack>
#include <QTemporaryFile>
#include <QTextStream>
#include <QTimer>
#include <KAboutData>
#include <KConfigDialog>
#include <KConfigDialogManager>
#include <KLocalizedString>
#include <core/action.h>
#include <core/annotations.h>
#include <core/fileprinter.h>
#include <core/movie.h>
#include <core/page.h>
#include <core/pagetransition.h>
#include <core/signatureutils.h>
#include <core/sound.h>
#include <core/sourcereference.h>
#include <core/textpage.h>
#include <core/utils.h>
#include "pdfsettings.h"
#include <config-okular-poppler.h>
#include <poppler-media.h>
#include <poppler-version.h>
#include "annots.h"
#include "debug_pdf.h"
#include "formfields.h"
#include "pdfsettingswidget.h"
#include "pdfsignatureutils.h"
#include "popplerembeddedfile.h"
Q_DECLARE_METATYPE(Poppler::Annotation *)
Q_DECLARE_METATYPE(Poppler::FontInfo)
Q_DECLARE_METATYPE(const Poppler::LinkMovie *)
Q_DECLARE_METATYPE(const Poppler::LinkRendition *)
Q_DECLARE_METATYPE(const Poppler::LinkOCGState *)
#define POPPLER_VERSION_MACRO ((POPPLER_VERSION_MAJOR << 16) | (POPPLER_VERSION_MINOR << 8) | (POPPLER_VERSION_MICRO))
static const int defaultPageWidth = 595;
static const int defaultPageHeight = 842;
class PDFOptionsPage : public Okular::PrintOptionsWidget
{
Q_OBJECT
public:
enum ScaleMode { FitToPrintableArea, FitToPage, None };
Q_ENUM(ScaleMode)
PDFOptionsPage()
{
setWindowTitle(i18n("PDF Options"));
QVBoxLayout *layout = new QVBoxLayout(this);
m_printAnnots = new QCheckBox(i18n("Print annotations"), this);
m_printAnnots->setToolTip(i18n("Include annotations in the printed document"));
m_printAnnots->setWhatsThis(i18n("Includes annotations in the printed document. You can disable this if you want to print the original unannotated document."));
layout->addWidget(m_printAnnots);
m_forceRaster = new QCheckBox(i18n("Force rasterization"), this);
m_forceRaster->setToolTip(i18n("Rasterize into an image before printing"));
m_forceRaster->setWhatsThis(i18n("Forces the rasterization of each page into an image before printing it. This usually gives somewhat worse results, but is useful when printing documents that appear to print incorrectly."));
layout->addWidget(m_forceRaster);
QWidget *formWidget = new QWidget(this);
QFormLayout *printBackendLayout = new QFormLayout(formWidget);
m_scaleMode = new QComboBox;
m_scaleMode->insertItem(FitToPrintableArea, i18n("Fit to printable area"), FitToPrintableArea);
m_scaleMode->insertItem(FitToPage, i18n("Fit to full page"), FitToPage);
m_scaleMode->insertItem(None, i18n("None; print original size"), None);
m_scaleMode->setToolTip(i18n("Scaling mode for the printed pages"));
printBackendLayout->addRow(i18n("Scale mode:"), m_scaleMode);
layout->addWidget(formWidget);
layout->addStretch(1);
setPrintAnnots(true); // Default value
}
bool ignorePrintMargins() const override
{
return scaleMode() == FitToPage;
}
bool printAnnots()
{
return m_printAnnots->isChecked();
}
void setPrintAnnots(bool printAnnots)
{
m_printAnnots->setChecked(printAnnots);
}
bool printForceRaster()
{
return m_forceRaster->isChecked();
}
void setPrintForceRaster(bool forceRaster)
{
m_forceRaster->setChecked(forceRaster);
}
ScaleMode scaleMode() const
{
return m_scaleMode->currentData().value<ScaleMode>();
}
private:
QCheckBox *m_printAnnots;
QCheckBox *m_forceRaster;
QComboBox *m_scaleMode;
};
static void fillViewportFromLinkDestination(Okular::DocumentViewport &viewport, const Poppler::LinkDestination &destination)
{
viewport.pageNumber = destination.pageNumber() - 1;
if (!viewport.isValid())
return;
// get destination position
// TODO add other attributes to the viewport (taken from link)
// switch ( destination->getKind() )
// {
// case destXYZ:
if (destination.isChangeLeft() || destination.isChangeTop()) {
// TODO remember to change this if we implement DPI and/or rotation
double left, top;
left = destination.left();
top = destination.top();
viewport.rePos.normalizedX = left;
viewport.rePos.normalizedY = top;
viewport.rePos.enabled = true;
viewport.rePos.pos = Okular::DocumentViewport::TopLeft;
}
/* TODO
if ( dest->getChangeZoom() )
make zoom change*/
/* break;
default:
// implement the others cases
break;*/
// }
}
Okular::Sound *createSoundFromPopplerSound(const Poppler::SoundObject *popplerSound)
{
Okular::Sound *sound = popplerSound->soundType() == Poppler::SoundObject::Embedded ? new Okular::Sound(popplerSound->data()) : new Okular::Sound(popplerSound->url());
sound->setSamplingRate(popplerSound->samplingRate());
sound->setChannels(popplerSound->channels());
sound->setBitsPerSample(popplerSound->bitsPerSample());
switch (popplerSound->soundEncoding()) {
case Poppler::SoundObject::Raw:
sound->setSoundEncoding(Okular::Sound::Raw);
break;
case Poppler::SoundObject::Signed:
sound->setSoundEncoding(Okular::Sound::Signed);
break;
case Poppler::SoundObject::muLaw:
sound->setSoundEncoding(Okular::Sound::muLaw);
break;
case Poppler::SoundObject::ALaw:
sound->setSoundEncoding(Okular::Sound::ALaw);
break;
}
return sound;
}
Okular::Movie *createMovieFromPopplerMovie(const Poppler::MovieObject *popplerMovie)
{
Okular::Movie *movie = new Okular::Movie(popplerMovie->url());
movie->setSize(popplerMovie->size());
movie->setRotation((Okular::Rotation)(popplerMovie->rotation() / 90));
movie->setShowControls(popplerMovie->showControls());
movie->setPlayMode((Okular::Movie::PlayMode)popplerMovie->playMode());
movie->setAutoPlay(false); // will be triggered by external MovieAnnotation
movie->setShowPosterImage(popplerMovie->showPosterImage());
movie->setPosterImage(popplerMovie->posterImage());
return movie;
}
Okular::Movie *createMovieFromPopplerScreen(const Poppler::LinkRendition *popplerScreen)
{
Poppler::MediaRendition *rendition = popplerScreen->rendition();
Okular::Movie *movie = nullptr;
if (rendition->isEmbedded())
movie = new Okular::Movie(rendition->fileName(), rendition->data());
else
movie = new Okular::Movie(rendition->fileName());
movie->setSize(rendition->size());
movie->setShowControls(rendition->showControls());
if (rendition->repeatCount() == 0) {
movie->setPlayMode(Okular::Movie::PlayRepeat);
} else {
movie->setPlayMode(Okular::Movie::PlayLimited);
movie->setPlayRepetitions(rendition->repeatCount());
}
movie->setAutoPlay(rendition->autoPlay());
return movie;
}
QPair<Okular::Movie *, Okular::EmbeddedFile *> createMovieFromPopplerRichMedia(const Poppler::RichMediaAnnotation *popplerRichMedia)
{
const QPair<Okular::Movie *, Okular::EmbeddedFile *> emptyResult(nullptr, nullptr);
/**
* To convert a Flash/Video based RichMedia annotation to a movie, we search for the first
* Flash/Video richmedia instance and parse the flashVars parameter for the 'source' identifier.
* That identifier is then used to find the associated embedded file through the assets
* mapping.
*/
const Poppler::RichMediaAnnotation::Content *content = popplerRichMedia->content();
if (!content)
return emptyResult;
const QList<Poppler::RichMediaAnnotation::Configuration *> configurations = content->configurations();
if (configurations.isEmpty())
return emptyResult;
const Poppler::RichMediaAnnotation::Configuration *configuration = configurations[0];
const QList<Poppler::RichMediaAnnotation::Instance *> instances = configuration->instances();
if (instances.isEmpty())
return emptyResult;
const Poppler::RichMediaAnnotation::Instance *instance = instances[0];
if ((instance->type() != Poppler::RichMediaAnnotation::Instance::TypeFlash) && (instance->type() != Poppler::RichMediaAnnotation::Instance::TypeVideo))
return emptyResult;
const Poppler::RichMediaAnnotation::Params *params = instance->params();
if (!params)
return emptyResult;
QString sourceId;
bool playbackLoops = false;
const QStringList flashVars = params->flashVars().split(QLatin1Char('&'));
for (const QString &flashVar : flashVars) {
const int pos = flashVar.indexOf(QLatin1Char('='));
if (pos == -1)
continue;
const QString key = flashVar.left(pos);
const QString value = flashVar.mid(pos + 1);
if (key == QLatin1String("source"))
sourceId = value;
else if (key == QLatin1String("loop"))
playbackLoops = (value == QLatin1String("true") ? true : false);
}
if (sourceId.isEmpty())
return emptyResult;
const QList<Poppler::RichMediaAnnotation::Asset *> assets = content->assets();
if (assets.isEmpty())
return emptyResult;
Poppler::RichMediaAnnotation::Asset *matchingAsset = nullptr;
for (Poppler::RichMediaAnnotation::Asset *asset : assets) {
if (asset->name() == sourceId) {
matchingAsset = asset;
break;
}
}
if (!matchingAsset)
return emptyResult;
Poppler::EmbeddedFile *embeddedFile = matchingAsset->embeddedFile();
if (!embeddedFile)
return emptyResult;
Okular::EmbeddedFile *pdfEmbeddedFile = new PDFEmbeddedFile(embeddedFile);
Okular::Movie *movie = new Okular::Movie(embeddedFile->name(), embeddedFile->data());
movie->setPlayMode(playbackLoops ? Okular::Movie::PlayRepeat : Okular::Movie::PlayLimited);
if (popplerRichMedia && popplerRichMedia->settings() && popplerRichMedia->settings()->activation()) {
if (popplerRichMedia->settings()->activation()->condition() == Poppler::RichMediaAnnotation::Activation::PageOpened ||
popplerRichMedia->settings()->activation()->condition() == Poppler::RichMediaAnnotation::Activation::PageVisible) {
movie->setAutoPlay(true);
} else {
movie->setAutoPlay(false);
}
} else {
movie->setAutoPlay(false);
}
return qMakePair(movie, pdfEmbeddedFile);
}
/**
* Note: the function will take ownership of the popplerLink object.
*/
Okular::Action *createLinkFromPopplerLink(const Poppler::Link *popplerLink, bool deletePopplerLink = true)
{
if (!popplerLink)
return nullptr;
Okular::Action *link = nullptr;
const Poppler::LinkGoto *popplerLinkGoto;
const Poppler::LinkExecute *popplerLinkExecute;
const Poppler::LinkBrowse *popplerLinkBrowse;
const Poppler::LinkAction *popplerLinkAction;
const Poppler::LinkSound *popplerLinkSound;
const Poppler::LinkJavaScript *popplerLinkJS;
const Poppler::LinkMovie *popplerLinkMovie;
const Poppler::LinkRendition *popplerLinkRendition;
Okular::DocumentViewport viewport;
switch (popplerLink->linkType()) {
case Poppler::Link::None:
break;
case Poppler::Link::Goto: {
popplerLinkGoto = static_cast<const Poppler::LinkGoto *>(popplerLink);
const Poppler::LinkDestination dest = popplerLinkGoto->destination();
const QString destName = dest.destinationName();
if (destName.isEmpty()) {
fillViewportFromLinkDestination(viewport, dest);
link = new Okular::GotoAction(popplerLinkGoto->fileName(), viewport);
} else {
link = new Okular::GotoAction(popplerLinkGoto->fileName(), destName);
}
} break;
case Poppler::Link::Execute:
popplerLinkExecute = static_cast<const Poppler::LinkExecute *>(popplerLink);
link = new Okular::ExecuteAction(popplerLinkExecute->fileName(), popplerLinkExecute->parameters());
break;
case Poppler::Link::Browse:
popplerLinkBrowse = static_cast<const Poppler::LinkBrowse *>(popplerLink);
link = new Okular::BrowseAction(QUrl(popplerLinkBrowse->url()));
break;
case Poppler::Link::Action:
popplerLinkAction = static_cast<const Poppler::LinkAction *>(popplerLink);
link = new Okular::DocumentAction((Okular::DocumentAction::DocumentActionType)popplerLinkAction->actionType());
break;
case Poppler::Link::Sound: {
popplerLinkSound = static_cast<const Poppler::LinkSound *>(popplerLink);
Poppler::SoundObject *popplerSound = popplerLinkSound->sound();
Okular::Sound *sound = createSoundFromPopplerSound(popplerSound);
link = new Okular::SoundAction(popplerLinkSound->volume(), popplerLinkSound->synchronous(), popplerLinkSound->repeat(), popplerLinkSound->mix(), sound);
} break;
case Poppler::Link::JavaScript: {
popplerLinkJS = static_cast<const Poppler::LinkJavaScript *>(popplerLink);
link = new Okular::ScriptAction(Okular::JavaScript, popplerLinkJS->script());
} break;
case Poppler::Link::Rendition: {
if (!deletePopplerLink) {
// If links should not be deleted it probably means that they
// are part of a nextActions chain. There is no support
// to resolveMediaLinkReferences on nextActions. It would also
// be necessary to ensure that resolveMediaLinkReferences does
// not delete the Links which are part of a nextActions list
// to avoid a double deletion.
qCDebug(OkularPdfDebug) << "parsing rendition link without deletion is not supported. Action chain might be broken.";
break;
}
deletePopplerLink = false; // we'll delete it inside resolveMediaLinkReferences() after we have resolved all references
popplerLinkRendition = static_cast<const Poppler::LinkRendition *>(popplerLink);
Okular::RenditionAction::OperationType operation = Okular::RenditionAction::None;
switch (popplerLinkRendition->action()) {
case Poppler::LinkRendition::NoRendition:
operation = Okular::RenditionAction::None;
break;
case Poppler::LinkRendition::PlayRendition:
operation = Okular::RenditionAction::Play;
break;
case Poppler::LinkRendition::StopRendition:
operation = Okular::RenditionAction::Stop;
break;
case Poppler::LinkRendition::PauseRendition:
operation = Okular::RenditionAction::Pause;
break;
case Poppler::LinkRendition::ResumeRendition:
operation = Okular::RenditionAction::Resume;
break;
};
Okular::Movie *movie = nullptr;
if (popplerLinkRendition->rendition())
movie = createMovieFromPopplerScreen(popplerLinkRendition);
Okular::RenditionAction *renditionAction = new Okular::RenditionAction(operation, movie, Okular::JavaScript, popplerLinkRendition->script());
renditionAction->setNativeId(QVariant::fromValue(popplerLinkRendition));
link = renditionAction;
} break;
case Poppler::Link::Movie: {
if (!deletePopplerLink) {
// See comment above in Link::Rendition
qCDebug(OkularPdfDebug) << "parsing movie link without deletion is not supported. Action chain might be broken.";
break;
}
deletePopplerLink = false; // we'll delete it inside resolveMediaLinkReferences() after we have resolved all references
popplerLinkMovie = static_cast<const Poppler::LinkMovie *>(popplerLink);
Okular::MovieAction::OperationType operation = Okular::MovieAction::Play;
switch (popplerLinkMovie->operation()) {
case Poppler::LinkMovie::Play:
operation = Okular::MovieAction::Play;
break;
case Poppler::LinkMovie::Stop:
operation = Okular::MovieAction::Stop;
break;
case Poppler::LinkMovie::Pause:
operation = Okular::MovieAction::Pause;
break;
case Poppler::LinkMovie::Resume:
operation = Okular::MovieAction::Resume;
break;
};
Okular::MovieAction *movieAction = new Okular::MovieAction(operation);
movieAction->setNativeId(QVariant::fromValue(popplerLinkMovie));
link = movieAction;
} break;
case Poppler::Link::Hide: {
const Poppler::LinkHide *l = static_cast<const Poppler::LinkHide *>(popplerLink);
QStringList scripts;
const QVector<QString> targets = l->targets();
for (const QString &target : targets) {
scripts << QStringLiteral("getField(\"%1\").hidden = %2;").arg(target).arg(l->isShowAction() ? QLatin1String("false") : QLatin1String("true"));
}
link = new Okular::ScriptAction(Okular::JavaScript, scripts.join(QLatin1Char('\n')));
} break;
case Poppler::Link::OCGState:
link = new Okular::BackendOpaqueAction();
link->setNativeId(QVariant::fromValue(static_cast<const Poppler::LinkOCGState *>(popplerLink)));
deletePopplerLink = false;
break;
}
if (link) {
QVector<Okular::Action *> nextActions;
const QVector<Poppler::Link *> nextLinks = popplerLink->nextLinks();
for (const Poppler::Link *nl : nextLinks) {
nextActions << createLinkFromPopplerLink(nl, false);
}
link->setNextActions(nextActions);
}
if (deletePopplerLink)
delete popplerLink;
return link;
}
/**
* Note: the function will take ownership of the popplerLink objects.
*/
static QLinkedList<Okular::ObjectRect *> generateLinks(const QList<Poppler::Link *> &popplerLinks)
{
QLinkedList<Okular::ObjectRect *> links;
for (const Poppler::Link *popplerLink : popplerLinks) {
QRectF linkArea = popplerLink->linkArea();
double nl = linkArea.left(), nt = linkArea.top(), nr = linkArea.right(), nb = linkArea.bottom();
// create the rect using normalized coords and attach the Okular::Link to it
Okular::ObjectRect *rect = new Okular::ObjectRect(nl, nt, nr, nb, false, Okular::ObjectRect::Action, createLinkFromPopplerLink(popplerLink));
// add the ObjectRect to the container
links.push_front(rect);
}
return links;
}
/** NOTES on threading:
* internal: thread race prevention is done via the 'docLock' mutex. the
* mutex is needed only because we have the asynchronous thread; else
* the operations are all within the 'gui' thread, scheduled by the
* Qt scheduler and no mutex is needed.
* external: dangerous operations are all locked via mutex internally, and the
* only needed external thing is the 'canGeneratePixmap' method
* that tells if the generator is free (since we don't want an
* internal queue to store PixmapRequests). A generatedPixmap call
* without the 'ready' flag set, results in undefined behavior.
* So, as example, printing while generating a pixmap asynchronously is safe,
* it might only block the gui thread by 1) waiting for the mutex to unlock
* in async thread and 2) doing the 'heavy' print operation.
*/
OKULAR_EXPORT_PLUGIN(PDFGenerator, "libokularGenerator_poppler.json")
static void PDFGeneratorPopplerDebugFunction(const QString &message, const QVariant &closure)
{
Q_UNUSED(closure);
qCDebug(OkularPdfDebug) << "[Poppler]" << message;
}
PDFGenerator::PDFGenerator(QObject *parent, const QVariantList &args)
: Generator(parent, args)
, pdfdoc(nullptr)
, docSynopsisDirty(true)
, docEmbeddedFilesDirty(true)
, nextFontPage(0)
, annotProxy(nullptr)
, certStore(nullptr)
{
setFeature(Threaded);
setFeature(TextExtraction);
setFeature(FontInfo);
#ifdef Q_OS_WIN32
setFeature(PrintNative);
#else
setFeature(PrintPostscript);
#endif
if (Okular::FilePrinter::ps2pdfAvailable())
setFeature(PrintToFile);
setFeature(ReadRawData);
setFeature(TiledRendering);
setFeature(SwapBackingFile);
setFeature(SupportsCancelling);
// You only need to do it once not for each of the documents but it is cheap enough
// so doing it all the time won't hurt either
Poppler::setDebugErrorFunction(PDFGeneratorPopplerDebugFunction, QVariant());
#ifdef HAVE_POPPLER_SIGNING
if (!PDFSettings::useDefaultCertDB()) {
Poppler::setNSSDir(QUrl(PDFSettings::dBCertificatePath()).toLocalFile());
}
#endif
}
PDFGenerator::~PDFGenerator()
{
delete pdfOptionsPage;
delete certStore;
}
// BEGIN Generator inherited functions
Okular::Document::OpenResult PDFGenerator::loadDocumentWithPassword(const QString &filePath, QVector<Okular::Page *> &pagesVector, const QString &password)
{
#ifndef NDEBUG
if (pdfdoc) {
qCDebug(OkularPdfDebug) << "PDFGenerator: multiple calls to loadDocument. Check it.";
return Okular::Document::OpenError;
}
#endif
// create PDFDoc for the given file
pdfdoc = Poppler::Document::load(filePath, nullptr, nullptr);
return init(pagesVector, password);
}
Okular::Document::OpenResult PDFGenerator::loadDocumentFromDataWithPassword(const QByteArray &fileData, QVector<Okular::Page *> &pagesVector, const QString &password)
{
#ifndef NDEBUG
if (pdfdoc) {
qCDebug(OkularPdfDebug) << "PDFGenerator: multiple calls to loadDocument. Check it.";
return Okular::Document::OpenError;
}
#endif
// create PDFDoc for the given file
pdfdoc = Poppler::Document::loadFromData(fileData, nullptr, nullptr);
return init(pagesVector, password);
}
Okular::Document::OpenResult PDFGenerator::init(QVector<Okular::Page *> &pagesVector, const QString &password)
{
if (!pdfdoc)
return Okular::Document::OpenError;
if (pdfdoc->isLocked()) {
pdfdoc->unlock(password.toLatin1(), password.toLatin1());
if (pdfdoc->isLocked()) {
delete pdfdoc;
pdfdoc = nullptr;
return Okular::Document::OpenNeedsPassword;
}
}
// build Pages (currentPage was set -1 by deletePages)
int pageCount = pdfdoc->numPages();
if (pageCount < 0) {
delete pdfdoc;
pdfdoc = nullptr;
return Okular::Document::OpenError;
}
pagesVector.resize(pageCount);
rectsGenerated.fill(false, pageCount);
annotationsOnOpenHash.clear();
loadPages(pagesVector, 0, false);
// update the configuration
reparseConfig();
// create annotation proxy
annotProxy = new PopplerAnnotationProxy(pdfdoc, userMutex(), &annotationsOnOpenHash);
// the file has been loaded correctly
return Okular::Document::OpenSuccess;
}
PDFGenerator::SwapBackingFileResult PDFGenerator::swapBackingFile(QString const &newFileName, QVector<Okular::Page *> &newPagesVector)
{
const QBitArray oldRectsGenerated = rectsGenerated;
doCloseDocument();
auto openResult = loadDocumentWithPassword(newFileName, newPagesVector, QString());
if (openResult != Okular::Document::OpenSuccess)
return SwapBackingFileError;
// Recreate links if needed since they are done on image() and image() is not called when swapping the file
// since the page is already rendered
if (oldRectsGenerated.count() == rectsGenerated.count()) {
for (int i = 0; i < oldRectsGenerated.count(); ++i) {
if (oldRectsGenerated[i]) {
Okular::Page *page = newPagesVector[i];
Poppler::Page *pp = pdfdoc->page(i);
if (pp) {
page->setObjectRects(generateLinks(pp->links()));
rectsGenerated[i] = true;
resolveMediaLinkReferences(page);
delete pp;
}
}
}
}
return SwapBackingFileReloadInternalData;
}
bool PDFGenerator::doCloseDocument()
{
// remove internal objects
userMutex()->lock();
delete annotProxy;
annotProxy = nullptr;
delete pdfdoc;
pdfdoc = nullptr;
userMutex()->unlock();
docSynopsisDirty = true;
docSyn.clear();
docEmbeddedFilesDirty = true;
qDeleteAll(docEmbeddedFiles);
docEmbeddedFiles.clear();
nextFontPage = 0;
rectsGenerated.clear();
return true;
}
void PDFGenerator::loadPages(QVector<Okular::Page *> &pagesVector, int rotation, bool clear)
{
// TODO XPDF 3.01 check
const int count = pagesVector.count();
double w = 0, h = 0;
for (int i = 0; i < count; i++) {
// get xpdf page
Poppler::Page *p = pdfdoc->page(i);
Okular::Page *page;
if (p) {
const QSizeF pSize = p->pageSizeF();
w = pSize.width() / 72.0 * dpi().width();
h = pSize.height() / 72.0 * dpi().height();
Okular::Rotation orientation = Okular::Rotation0;
switch (p->orientation()) {
case Poppler::Page::Landscape:
orientation = Okular::Rotation90;
break;
case Poppler::Page::UpsideDown:
orientation = Okular::Rotation180;
break;
case Poppler::Page::Seascape:
orientation = Okular::Rotation270;
break;
case Poppler::Page::Portrait:
orientation = Okular::Rotation0;
break;
}
if (rotation % 2 == 1)
qSwap(w, h);
// init a Okular::page, add transition and annotation information
page = new Okular::Page(i, w, h, orientation);
addTransition(p, page);
if (true) // TODO real check
addAnnotations(p, page);
Poppler::Link *tmplink = p->action(Poppler::Page::Opening);
if (tmplink) {
page->setPageAction(Okular::Page::Opening, createLinkFromPopplerLink(tmplink));
}
tmplink = p->action(Poppler::Page::Closing);
if (tmplink) {
page->setPageAction(Okular::Page::Closing, createLinkFromPopplerLink(tmplink));
}
page->setDuration(p->duration());
page->setLabel(p->label());
QLinkedList<Okular::FormField *> okularFormFields;
#if POPPLER_VERSION_MACRO >= QT_VERSION_CHECK(0, 89, 0)
if (i > 0) // for page 0 we handle the form fields at the end
okularFormFields = getFormFields(p);
#else
okularFormFields = getFormFields(p);
#endif
if (!okularFormFields.isEmpty())
page->setFormFields(okularFormFields);
// kWarning(PDFDebug).nospace() << page->width() << "x" << page->height();
#ifdef PDFGENERATOR_DEBUG
qCDebug(OkularPdfDebug) << "load page" << i << "with rotation" << rotation << "and orientation" << orientation;
#endif
delete p;
if (clear && pagesVector[i])
delete pagesVector[i];
} else {
page = new Okular::Page(i, defaultPageWidth, defaultPageHeight, Okular::Rotation0);
}
// set the Okular::page at the right position in document's pages vector
pagesVector[i] = page;
}
// Once we've added the signatures to all pages except page 0, we add all the missing signatures there
// we do that because there's signatures that don't belong to any page, but okular needs a page<->signature mapping
if (count > 0) {
#if POPPLER_VERSION_MACRO >= QT_VERSION_CHECK(0, 89, 0)
const QVector<Poppler::FormFieldSignature *> allSignatures = pdfdoc->signatures();
std::unique_ptr<Poppler::Page> page0(pdfdoc->page(0));
QLinkedList<Okular::FormField *> page0FormFields = getFormFields(page0.get());
for (Poppler::FormFieldSignature *s : allSignatures) {
bool createSignature = true;
const QString fullyQualifiedName = s->fullyQualifiedName();
auto compareSignatureByFullyQualifiedName = [&fullyQualifiedName](const Okular::FormField *off) { return off->fullyQualifiedName() == fullyQualifiedName; };
// See if the signature is in one of the already loaded page (i.e. 1 to end)
for (Okular::Page *p : qAsConst(pagesVector)) {
const QLinkedList<Okular::FormField *> pageFormFields = p->formFields();
if (std::find_if(pageFormFields.begin(), pageFormFields.end(), compareSignatureByFullyQualifiedName) != pageFormFields.end()) {
delete s;
createSignature = false;
break;
}
}
// See if the signature is in page 0
if (createSignature && std::find_if(page0FormFields.constBegin(), page0FormFields.constEnd(), compareSignatureByFullyQualifiedName) != page0FormFields.constEnd()) {
delete s;
createSignature = false;
}
// Otherwise it's a page-less signature, add it to page 0
if (createSignature) {
Okular::FormField *of = new PopplerFormFieldSignature(std::unique_ptr<Poppler::FormFieldSignature>(s));
page0FormFields.append(of);
}
}
if (!page0FormFields.isEmpty())
pagesVector[0]->setFormFields(page0FormFields);
#endif
}
}
Okular::DocumentInfo PDFGenerator::generateDocumentInfo(const QSet<Okular::DocumentInfo::Key> &keys) const
{
Okular::DocumentInfo docInfo;
docInfo.set(Okular::DocumentInfo::MimeType, QStringLiteral("application/pdf"));
userMutex()->lock();
if (pdfdoc) {
// compile internal structure reading properties from PDFDoc
if (keys.contains(Okular::DocumentInfo::Title))
docInfo.set(Okular::DocumentInfo::Title, pdfdoc->info(QStringLiteral("Title")));
if (keys.contains(Okular::DocumentInfo::Subject))
docInfo.set(Okular::DocumentInfo::Subject, pdfdoc->info(QStringLiteral("Subject")));
if (keys.contains(Okular::DocumentInfo::Author))
docInfo.set(Okular::DocumentInfo::Author, pdfdoc->info(QStringLiteral("Author")));
if (keys.contains(Okular::DocumentInfo::Keywords))
docInfo.set(Okular::DocumentInfo::Keywords, pdfdoc->info(QStringLiteral("Keywords")));
if (keys.contains(Okular::DocumentInfo::Creator))
docInfo.set(Okular::DocumentInfo::Creator, pdfdoc->info(QStringLiteral("Creator")));
if (keys.contains(Okular::DocumentInfo::Producer))
docInfo.set(Okular::DocumentInfo::Producer, pdfdoc->info(QStringLiteral("Producer")));
if (keys.contains(Okular::DocumentInfo::CreationDate))
docInfo.set(Okular::DocumentInfo::CreationDate, QLocale().toString(pdfdoc->date(QStringLiteral("CreationDate")), QLocale::LongFormat));
if (keys.contains(Okular::DocumentInfo::ModificationDate))
docInfo.set(Okular::DocumentInfo::ModificationDate, QLocale().toString(pdfdoc->date(QStringLiteral("ModDate")), QLocale::LongFormat));
if (keys.contains(Okular::DocumentInfo::CustomKeys)) {
int major, minor;
pdfdoc->getPdfVersion(&major, &minor);
docInfo.set(QStringLiteral("format"), i18nc("PDF v. <version>", "PDF v. %1.%2", major, minor), i18n("Format"));
docInfo.set(QStringLiteral("encryption"), pdfdoc->isEncrypted() ? i18n("Encrypted") : i18n("Unencrypted"), i18n("Security"));
docInfo.set(QStringLiteral("optimization"), pdfdoc->isLinearized() ? i18n("Yes") : i18n("No"), i18n("Optimized"));
}
docInfo.set(Okular::DocumentInfo::Pages, QString::number(pdfdoc->numPages()));
}
userMutex()->unlock();
return docInfo;
}
const Okular::DocumentSynopsis *PDFGenerator::generateDocumentSynopsis()
{
if (!docSynopsisDirty)
return &docSyn;
if (!pdfdoc)
return nullptr;
userMutex()->lock();
const QVector<Poppler::OutlineItem> outline = pdfdoc->outline();
userMutex()->unlock();
if (outline.isEmpty())
return nullptr;
addSynopsisChildren(outline, &docSyn);
docSynopsisDirty = false;
return &docSyn;
}
static Okular::FontInfo::FontType convertPopplerFontInfoTypeToOkularFontInfoType(Poppler::FontInfo::Type type)
{
switch (type) {
case Poppler::FontInfo::Type1:
return Okular::FontInfo::Type1;
break;
case Poppler::FontInfo::Type1C:
return Okular::FontInfo::Type1C;
break;
case Poppler::FontInfo::Type3:
return Okular::FontInfo::Type3;
break;
case Poppler::FontInfo::TrueType:
return Okular::FontInfo::TrueType;
break;
case Poppler::FontInfo::CIDType0:
return Okular::FontInfo::CIDType0;
break;
case Poppler::FontInfo::CIDType0C:
return Okular::FontInfo::CIDType0C;
break;
case Poppler::FontInfo::CIDTrueType:
return Okular::FontInfo::CIDTrueType;
break;
case Poppler::FontInfo::Type1COT:
return Okular::FontInfo::Type1COT;
break;
case Poppler::FontInfo::TrueTypeOT:
return Okular::FontInfo::TrueTypeOT;
break;
case Poppler::FontInfo::CIDType0COT:
return Okular::FontInfo::CIDType0COT;
break;
case Poppler::FontInfo::CIDTrueTypeOT:
return Okular::FontInfo::CIDTrueTypeOT;
break;
case Poppler::FontInfo::unknown:
default:;
}
return Okular::FontInfo::Unknown;
}
static Okular::FontInfo::EmbedType embedTypeForPopplerFontInfo(const Poppler::FontInfo &fi)
{
Okular::FontInfo::EmbedType ret = Okular::FontInfo::NotEmbedded;
if (fi.isEmbedded()) {
if (fi.isSubset()) {
ret = Okular::FontInfo::EmbeddedSubset;
} else {
ret = Okular::FontInfo::FullyEmbedded;
}
}
return ret;
}
Okular::FontInfo::List PDFGenerator::fontsForPage(int page)
{
Okular::FontInfo::List list;
if (page != nextFontPage)
return list;
QList<Poppler::FontInfo> fonts;
userMutex()->lock();
Poppler::FontIterator *it = pdfdoc->newFontIterator(page);
if (it->hasNext()) {
fonts = it->next();
}
delete it;
userMutex()->unlock();
for (const Poppler::FontInfo &font : qAsConst(fonts)) {
Okular::FontInfo of;
of.setName(font.name());
of.setSubstituteName(font.substituteName());
of.setType(convertPopplerFontInfoTypeToOkularFontInfoType(font.type()));
of.setEmbedType(embedTypeForPopplerFontInfo(font));
of.setFile(font.file());
of.setCanBeExtracted(of.embedType() != Okular::FontInfo::NotEmbedded);
QVariant nativeId;
nativeId.setValue(font);
of.setNativeId(nativeId);
list.append(of);
}
++nextFontPage;
return list;
}
const QList<Okular::EmbeddedFile *> *PDFGenerator::embeddedFiles() const
{
if (docEmbeddedFilesDirty) {
userMutex()->lock();
const QList<Poppler::EmbeddedFile *> &popplerFiles = pdfdoc->embeddedFiles();
for (Poppler::EmbeddedFile *pef : popplerFiles) {
docEmbeddedFiles.append(new PDFEmbeddedFile(pef));
}
userMutex()->unlock();
docEmbeddedFilesDirty = false;
}
return &docEmbeddedFiles;
}
QAbstractItemModel *PDFGenerator::layersModel() const
{
return pdfdoc->hasOptionalContent() ? pdfdoc->optionalContentModel() : nullptr;
}
void PDFGenerator::opaqueAction(const Okular::BackendOpaqueAction *action)
{
const Poppler::LinkOCGState *popplerLink = action->nativeId().value<const Poppler::LinkOCGState *>();
pdfdoc->optionalContentModel()->applyLink(const_cast<Poppler::LinkOCGState *>(popplerLink));
}
bool PDFGenerator::isAllowed(Okular::Permission permission) const
{
bool b = true;
switch (permission) {
case Okular::AllowModify:
b = pdfdoc->okToChange();
break;
case Okular::AllowCopy:
b = pdfdoc->okToCopy();
break;