-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gfx.cc
5414 lines (4923 loc) · 172 KB
/
Gfx.cc
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
//========================================================================
//
// Gfx.cc
//
// Copyright 1996-2013 Glyph & Cog, LLC
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2005 Jonathan Blandford <jrb@redhat.com>
// Copyright (C) 2005-2013, 2015-2022 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2006 Thorkild Stray <thorkild@ifi.uio.no>
// Copyright (C) 2006 Kristian Høgsberg <krh@redhat.com>
// Copyright (C) 2006-2011 Carlos Garcia Campos <carlosgc@gnome.org>
// Copyright (C) 2006, 2007 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2007, 2008 Brad Hards <bradh@kde.org>
// Copyright (C) 2007, 2011, 2017, 2021, 2023 Adrian Johnson <ajohnson@redneon.com>
// Copyright (C) 2007, 2008 Iñigo Martínez <inigomartinez@gmail.com>
// Copyright (C) 2007 Koji Otani <sho@bbr.jp>
// Copyright (C) 2007 Krzysztof Kowalczyk <kkowalczyk@gmail.com>
// Copyright (C) 2008 Pino Toscano <pino@kde.org>
// Copyright (C) 2008 Michael Vrable <mvrable@cs.ucsd.edu>
// Copyright (C) 2008 Hib Eris <hib@hiberis.nl>
// Copyright (C) 2009 M Joonas Pihlaja <jpihlaja@cc.helsinki.fi>
// Copyright (C) 2009-2016, 2020 Thomas Freitag <Thomas.Freitag@alfa.de>
// Copyright (C) 2009 William Bader <williambader@hotmail.com>
// Copyright (C) 2009, 2010 David Benjamin <davidben@mit.edu>
// Copyright (C) 2010 Nils Höglund <nils.hoglund@gmail.com>
// Copyright (C) 2010 Christian Feuersänger <cfeuersaenger@googlemail.com>
// Copyright (C) 2011 Axel Strübing <axel.struebing@freenet.de>
// Copyright (C) 2012 Even Rouault <even.rouault@mines-paris.org>
// Copyright (C) 2012, 2013 Fabio D'Urso <fabiodurso@hotmail.it>
// Copyright (C) 2012 Lu Wang <coolwanglu@gmail.com>
// Copyright (C) 2014 Jason Crain <jason@aquaticape.us>
// Copyright (C) 2017, 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>. Work sponsored by the LiMux project of the city of Munich
// Copyright (C) 2018, 2019 Adam Reichold <adam.reichold@t-online.de>
// Copyright (C) 2018 Denis Onishchenko <denis.onischenko@gmail.com>
// Copyright (C) 2019 LE GARREC Vincent <legarrec.vincent@gmail.com>
// Copyright (C) 2019-2022 Oliver Sander <oliver.sander@tu-dresden.de>
// Copyright (C) 2019 Volker Krause <vkrause@kde.org>
// Copyright (C) 2020 Philipp Knechtges <philipp-dev@knechtges.com>
// Copyright (C) 2021 Steve Rosenhamer <srosenhamer@me.com>
// Copyright (C) 2023 Anton Thomasson <antonthomasson@gmail.com>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#include <config.h>
#include <cstdlib>
#include <cstdio>
#include <cstddef>
#include <cstring>
#include <cmath>
#include <memory>
#include "goo/gmem.h"
#include "goo/GooTimer.h"
#include "GlobalParams.h"
#include "CharTypes.h"
#include "Object.h"
#include "PDFDoc.h"
#include "Array.h"
#include "Annot.h"
#include "Dict.h"
#include "Stream.h"
#include "Lexer.h"
#include "Parser.h"
#include "GfxFont.h"
#include "GfxState.h"
#include "OutputDev.h"
#include "Page.h"
#include "Annot.h"
#include "Error.h"
#include "Gfx.h"
#include "ProfileData.h"
#include "Catalog.h"
#include "OptionalContent.h"
// the MSVC math.h doesn't define this
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
//------------------------------------------------------------------------
// constants
//------------------------------------------------------------------------
// Max recursive depth for a function shading fill.
#define functionMaxDepth 6
// Max delta allowed in any color component for a function shading fill.
#define functionColorDelta (dblToCol(1 / 256.0))
// Max number of splits along the t axis for an axial shading fill.
#define axialMaxSplits 256
// Max delta allowed in any color component for an axial shading fill.
#define axialColorDelta (dblToCol(1 / 256.0))
// Max number of splits along the t axis for a radial shading fill.
#define radialMaxSplits 256
// Max delta allowed in any color component for a radial shading fill.
#define radialColorDelta (dblToCol(1 / 256.0))
// Max recursive depth for a Gouraud triangle shading fill.
//
// Triangles will be split at most gouraudMaxDepth times (each time into 4
// smaller ones). That makes pow(4,gouraudMaxDepth) many triangles for
// every triangle.
#define gouraudMaxDepth 6
// Max delta allowed in any color component for a Gouraud triangle
// shading fill.
#define gouraudColorDelta (dblToCol(3. / 256.0))
// Gouraud triangle: if the three color parameters differ by at more than this percend of
// the total color parameter range, the triangle will be refined
#define gouraudParameterizedColorDelta 5e-3
// Max recursive depth for a patch mesh shading fill.
#define patchMaxDepth 6
// Max delta allowed in any color component for a patch mesh shading
// fill.
#define patchColorDelta (dblToCol((3. / 256.0)))
//------------------------------------------------------------------------
// Operator table
//------------------------------------------------------------------------
const Operator Gfx::opTab[] = {
{ "\"", 3, { tchkNum, tchkNum, tchkString }, &Gfx::opMoveSetShowText },
{ "'", 1, { tchkString }, &Gfx::opMoveShowText },
{ "B", 0, { tchkNone }, &Gfx::opFillStroke },
{ "B*", 0, { tchkNone }, &Gfx::opEOFillStroke },
{ "BDC", 2, { tchkName, tchkProps }, &Gfx::opBeginMarkedContent },
{ "BI", 0, { tchkNone }, &Gfx::opBeginImage },
{ "BMC", 1, { tchkName }, &Gfx::opBeginMarkedContent },
{ "BT", 0, { tchkNone }, &Gfx::opBeginText },
{ "BX", 0, { tchkNone }, &Gfx::opBeginIgnoreUndef },
{ "CS", 1, { tchkName }, &Gfx::opSetStrokeColorSpace },
{ "DP", 2, { tchkName, tchkProps }, &Gfx::opMarkPoint },
{ "Do", 1, { tchkName }, &Gfx::opXObject },
{ "EI", 0, { tchkNone }, &Gfx::opEndImage },
{ "EMC", 0, { tchkNone }, &Gfx::opEndMarkedContent },
{ "ET", 0, { tchkNone }, &Gfx::opEndText },
{ "EX", 0, { tchkNone }, &Gfx::opEndIgnoreUndef },
{ "F", 0, { tchkNone }, &Gfx::opFill },
{ "G", 1, { tchkNum }, &Gfx::opSetStrokeGray },
{ "ID", 0, { tchkNone }, &Gfx::opImageData },
{ "J", 1, { tchkInt }, &Gfx::opSetLineCap },
{ "K", 4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opSetStrokeCMYKColor },
{ "M", 1, { tchkNum }, &Gfx::opSetMiterLimit },
{ "MP", 1, { tchkName }, &Gfx::opMarkPoint },
{ "Q", 0, { tchkNone }, &Gfx::opRestore },
{ "RG", 3, { tchkNum, tchkNum, tchkNum }, &Gfx::opSetStrokeRGBColor },
{ "S", 0, { tchkNone }, &Gfx::opStroke },
{ "SC", -4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opSetStrokeColor },
{ "SCN",
-33,
{ tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN,
tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN },
&Gfx::opSetStrokeColorN },
{ "T*", 0, { tchkNone }, &Gfx::opTextNextLine },
{ "TD", 2, { tchkNum, tchkNum }, &Gfx::opTextMoveSet },
{ "TJ", 1, { tchkArray }, &Gfx::opShowSpaceText },
{ "TL", 1, { tchkNum }, &Gfx::opSetTextLeading },
{ "Tc", 1, { tchkNum }, &Gfx::opSetCharSpacing },
{ "Td", 2, { tchkNum, tchkNum }, &Gfx::opTextMove },
{ "Tf", 2, { tchkName, tchkNum }, &Gfx::opSetFont },
{ "Tj", 1, { tchkString }, &Gfx::opShowText },
{ "Tm", 6, { tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opSetTextMatrix },
{ "Tr", 1, { tchkInt }, &Gfx::opSetTextRender },
{ "Ts", 1, { tchkNum }, &Gfx::opSetTextRise },
{ "Tw", 1, { tchkNum }, &Gfx::opSetWordSpacing },
{ "Tz", 1, { tchkNum }, &Gfx::opSetHorizScaling },
{ "W", 0, { tchkNone }, &Gfx::opClip },
{ "W*", 0, { tchkNone }, &Gfx::opEOClip },
{ "b", 0, { tchkNone }, &Gfx::opCloseFillStroke },
{ "b*", 0, { tchkNone }, &Gfx::opCloseEOFillStroke },
{ "c", 6, { tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opCurveTo },
{ "cm", 6, { tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opConcat },
{ "cs", 1, { tchkName }, &Gfx::opSetFillColorSpace },
{ "d", 2, { tchkArray, tchkNum }, &Gfx::opSetDash },
{ "d0", 2, { tchkNum, tchkNum }, &Gfx::opSetCharWidth },
{ "d1", 6, { tchkNum, tchkNum, tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opSetCacheDevice },
{ "f", 0, { tchkNone }, &Gfx::opFill },
{ "f*", 0, { tchkNone }, &Gfx::opEOFill },
{ "g", 1, { tchkNum }, &Gfx::opSetFillGray },
{ "gs", 1, { tchkName }, &Gfx::opSetExtGState },
{ "h", 0, { tchkNone }, &Gfx::opClosePath },
{ "i", 1, { tchkNum }, &Gfx::opSetFlat },
{ "j", 1, { tchkInt }, &Gfx::opSetLineJoin },
{ "k", 4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opSetFillCMYKColor },
{ "l", 2, { tchkNum, tchkNum }, &Gfx::opLineTo },
{ "m", 2, { tchkNum, tchkNum }, &Gfx::opMoveTo },
{ "n", 0, { tchkNone }, &Gfx::opEndPath },
{ "q", 0, { tchkNone }, &Gfx::opSave },
{ "re", 4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opRectangle },
{ "rg", 3, { tchkNum, tchkNum, tchkNum }, &Gfx::opSetFillRGBColor },
{ "ri", 1, { tchkName }, &Gfx::opSetRenderingIntent },
{ "s", 0, { tchkNone }, &Gfx::opCloseStroke },
{ "sc", -4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opSetFillColor },
{ "scn",
-33,
{ tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN,
tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN, tchkSCN },
&Gfx::opSetFillColorN },
{ "sh", 1, { tchkName }, &Gfx::opShFill },
{ "v", 4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opCurveTo1 },
{ "w", 1, { tchkNum }, &Gfx::opSetLineWidth },
{ "y", 4, { tchkNum, tchkNum, tchkNum, tchkNum }, &Gfx::opCurveTo2 },
};
#define numOps (sizeof(opTab) / sizeof(Operator))
static inline bool isSameGfxColor(const GfxColor &colorA, const GfxColor &colorB, unsigned int nComps, double delta)
{
for (unsigned int k = 0; k < nComps; ++k) {
if (abs(colorA.c[k] - colorB.c[k]) > delta) {
return false;
}
}
return true;
}
//------------------------------------------------------------------------
// GfxResources
//------------------------------------------------------------------------
GfxResources::GfxResources(XRef *xrefA, Dict *resDictA, GfxResources *nextA) : gStateCache(2), xref(xrefA)
{
Ref r;
if (resDictA) {
// build font dictionary
Dict *resDict = resDictA->copy(xref);
fonts = nullptr;
const Object &obj1 = resDict->lookupNF("Font");
if (obj1.isRef()) {
Object obj2 = obj1.fetch(xref);
if (obj2.isDict()) {
r = obj1.getRef();
fonts = new GfxFontDict(xref, &r, obj2.getDict());
}
} else if (obj1.isDict()) {
fonts = new GfxFontDict(xref, nullptr, obj1.getDict());
}
// get XObject dictionary
xObjDict = resDict->lookup("XObject");
// get color space dictionary
colorSpaceDict = resDict->lookup("ColorSpace");
// get pattern dictionary
patternDict = resDict->lookup("Pattern");
// get shading dictionary
shadingDict = resDict->lookup("Shading");
// get graphics state parameter dictionary
gStateDict = resDict->lookup("ExtGState");
// get properties dictionary
propertiesDict = resDict->lookup("Properties");
delete resDict;
} else {
fonts = nullptr;
xObjDict.setToNull();
colorSpaceDict.setToNull();
patternDict.setToNull();
shadingDict.setToNull();
gStateDict.setToNull();
propertiesDict.setToNull();
}
next = nextA;
}
GfxResources::~GfxResources()
{
delete fonts;
}
std::shared_ptr<GfxFont> GfxResources::doLookupFont(const char *name) const
{
const GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->fonts) {
if (std::shared_ptr<GfxFont> font = resPtr->fonts->lookup(name)) {
return font;
}
}
}
error(errSyntaxError, -1, "Unknown font tag '{0:s}'", name);
return nullptr;
}
std::shared_ptr<GfxFont> GfxResources::lookupFont(const char *name)
{
return doLookupFont(name);
}
std::shared_ptr<const GfxFont> GfxResources::lookupFont(const char *name) const
{
return doLookupFont(name);
}
Object GfxResources::lookupXObject(const char *name)
{
GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->xObjDict.isDict()) {
Object obj = resPtr->xObjDict.dictLookup(name);
if (!obj.isNull()) {
return obj;
}
}
}
error(errSyntaxError, -1, "XObject '{0:s}' is unknown", name);
return Object(objNull);
}
Object GfxResources::lookupXObjectNF(const char *name)
{
GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->xObjDict.isDict()) {
Object obj = resPtr->xObjDict.dictLookupNF(name).copy();
if (!obj.isNull()) {
return obj;
}
}
}
error(errSyntaxError, -1, "XObject '{0:s}' is unknown", name);
return Object(objNull);
}
Object GfxResources::lookupMarkedContentNF(const char *name)
{
GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->propertiesDict.isDict()) {
Object obj = resPtr->propertiesDict.dictLookupNF(name).copy();
if (!obj.isNull()) {
return obj;
}
}
}
error(errSyntaxError, -1, "Marked Content '{0:s}' is unknown", name);
return Object(objNull);
}
Object GfxResources::lookupColorSpace(const char *name)
{
GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->colorSpaceDict.isDict()) {
Object obj = resPtr->colorSpaceDict.dictLookup(name);
if (!obj.isNull()) {
return obj;
}
}
}
return Object(objNull);
}
GfxPattern *GfxResources::lookupPattern(const char *name, OutputDev *out, GfxState *state)
{
GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->patternDict.isDict()) {
Ref patternRef = Ref::INVALID();
Object obj = resPtr->patternDict.getDict()->lookup(name, &patternRef);
if (!obj.isNull()) {
return GfxPattern::parse(resPtr, &obj, out, state, patternRef.num);
}
}
}
error(errSyntaxError, -1, "Unknown pattern '{0:s}'", name);
return nullptr;
}
GfxShading *GfxResources::lookupShading(const char *name, OutputDev *out, GfxState *state)
{
GfxResources *resPtr;
GfxShading *shading;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->shadingDict.isDict()) {
Object obj = resPtr->shadingDict.dictLookup(name);
if (!obj.isNull()) {
shading = GfxShading::parse(resPtr, &obj, out, state);
return shading;
}
}
}
error(errSyntaxError, -1, "ExtGState '{0:s}' is unknown", name);
return nullptr;
}
Object GfxResources::lookupGState(const char *name)
{
Object obj = lookupGStateNF(name);
if (obj.isNull()) {
return Object(objNull);
}
if (!obj.isRef()) {
return obj;
}
const Ref ref = obj.getRef();
if (auto *item = gStateCache.lookup(ref)) {
return item->copy();
}
auto *item = new Object { xref->fetch(ref) };
gStateCache.put(ref, item);
return item->copy();
}
Object GfxResources::lookupGStateNF(const char *name)
{
GfxResources *resPtr;
for (resPtr = this; resPtr; resPtr = resPtr->next) {
if (resPtr->gStateDict.isDict()) {
Object obj = resPtr->gStateDict.dictLookupNF(name).copy();
if (!obj.isNull()) {
return obj;
}
}
}
error(errSyntaxError, -1, "ExtGState '{0:s}' is unknown", name);
return Object(objNull);
}
//------------------------------------------------------------------------
// Gfx
//------------------------------------------------------------------------
Gfx::Gfx(PDFDoc *docA, OutputDev *outA, int pageNum, Dict *resDict, double hDPI, double vDPI, const PDFRectangle *box, const PDFRectangle *cropBox, int rotate, bool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA, XRef *xrefA)
: printCommands(globalParams->getPrintCommands()), profileCommands(globalParams->getProfileCommands())
{
int i;
doc = docA;
xref = (xrefA == nullptr) ? doc->getXRef() : xrefA;
catalog = doc->getCatalog();
subPage = false;
mcStack = nullptr;
parser = nullptr;
// start the resource stack
res = new GfxResources(xref, resDict, nullptr);
// initialize
out = outA;
state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
out->initGfxState(state);
stackHeight = 1;
pushStateGuard();
fontChanged = false;
clip = clipNone;
ignoreUndef = 0;
out->startPage(pageNum, state, xref);
out->setDefaultCTM(state->getCTM());
out->updateAll(state);
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
displayDepth = 0;
ocState = true;
parser = nullptr;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
// set crop box
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
#ifdef USE_CMS
initDisplayProfile();
#endif
}
Gfx::Gfx(PDFDoc *docA, OutputDev *outA, Dict *resDict, const PDFRectangle *box, const PDFRectangle *cropBox, bool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA, Gfx *gfxA)
: printCommands(globalParams->getPrintCommands()), profileCommands(globalParams->getProfileCommands())
{
int i;
doc = docA;
if (gfxA) {
xref = gfxA->getXRef();
formsDrawing = gfxA->formsDrawing;
charProcDrawing = gfxA->charProcDrawing;
} else {
xref = doc->getXRef();
}
catalog = doc->getCatalog();
subPage = true;
mcStack = nullptr;
parser = nullptr;
// start the resource stack
res = new GfxResources(xref, resDict, nullptr);
// initialize
out = outA;
double hDPI = 72;
double vDPI = 72;
if (gfxA) {
hDPI = gfxA->getState()->getHDPI();
vDPI = gfxA->getState()->getVDPI();
}
state = new GfxState(hDPI, vDPI, box, 0, false);
stackHeight = 1;
pushStateGuard();
fontChanged = false;
clip = clipNone;
ignoreUndef = 0;
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
displayDepth = 0;
ocState = true;
parser = nullptr;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
// set crop box
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
#ifdef USE_CMS
initDisplayProfile();
#endif
}
#ifdef USE_CMS
# include <lcms2.h>
void Gfx::initDisplayProfile()
{
Object catDict = xref->getCatalog();
if (catDict.isDict()) {
Object outputIntents = catDict.dictLookup("OutputIntents");
if (outputIntents.isArray() && outputIntents.arrayGetLength() == 1) {
Object firstElement = outputIntents.arrayGet(0);
if (firstElement.isDict()) {
Object profile = firstElement.dictLookup("DestOutputProfile");
if (profile.isStream()) {
Stream *iccStream = profile.getStream();
const std::vector<unsigned char> profBuf = iccStream->toUnsignedChars(65536, 65536);
auto hp = make_GfxLCMSProfilePtr(cmsOpenProfileFromMem(profBuf.data(), profBuf.size()));
if (!hp) {
error(errSyntaxWarning, -1, "read ICCBased color space profile error");
} else {
state->setDisplayProfile(hp);
}
}
}
}
}
}
#endif
Gfx::~Gfx()
{
while (stateGuards.size()) {
popStateGuard();
}
if (!subPage) {
out->endPage();
}
// There shouldn't be more saves, but pop them if there were any
while (state->hasSaves()) {
error(errSyntaxError, -1, "Found state under last state guard. Popping.");
restoreState();
}
delete state;
while (res) {
popResources();
}
while (mcStack) {
popMarkedContent();
}
}
void Gfx::display(Object *obj, bool topLevel)
{
// check for excessive recursion
if (displayDepth > 100) {
return;
}
if (obj->isArray()) {
for (int i = 0; i < obj->arrayGetLength(); ++i) {
Object obj2 = obj->arrayGet(i);
if (!obj2.isStream()) {
error(errSyntaxError, -1, "Weird page contents");
return;
}
}
} else if (!obj->isStream()) {
error(errSyntaxError, -1, "Weird page contents");
return;
}
parser = new Parser(xref, obj, false);
go(topLevel);
delete parser;
parser = nullptr;
}
void Gfx::go(bool topLevel)
{
Object obj;
Object args[maxArgs];
int numArgs, i;
int lastAbortCheck;
// scan a sequence of objects
pushStateGuard();
updateLevel = 1; // make sure even empty pages trigger a call to dump()
lastAbortCheck = 0;
numArgs = 0;
obj = parser->getObj();
while (!obj.isEOF()) {
commandAborted = false;
// got a command - execute it
if (obj.isCmd()) {
if (printCommands) {
obj.print(stdout);
for (i = 0; i < numArgs; ++i) {
printf(" ");
args[i].print(stdout);
}
printf("\n");
fflush(stdout);
}
GooTimer *timer = nullptr;
if (unlikely(profileCommands)) {
timer = new GooTimer();
}
// Run the operation
execOp(&obj, args, numArgs);
// Update the profile information
if (unlikely(profileCommands)) {
if (auto *const hash = out->getProfileHash()) {
auto &data = (*hash)[obj.getCmd()];
data.addElement(timer->getElapsed());
}
delete timer;
}
for (i = 0; i < numArgs; ++i) {
args[i].setToNull(); // Free memory early
}
numArgs = 0;
// periodically update display
if (++updateLevel >= 20000) {
out->dump();
updateLevel = 0;
lastAbortCheck = 0;
}
// did the command throw an exception
if (commandAborted) {
// don't propogate; recursive drawing comes from Form XObjects which
// should probably be drawn in a separate context anyway for caching
commandAborted = false;
break;
}
// check for an abort
if (abortCheckCbk) {
if (updateLevel - lastAbortCheck > 10) {
if ((*abortCheckCbk)(abortCheckCbkData)) {
break;
}
lastAbortCheck = updateLevel;
}
}
// got an argument - save it
} else if (numArgs < maxArgs) {
args[numArgs++] = std::move(obj);
// too many arguments - something is wrong
} else {
error(errSyntaxError, getPos(), "Too many args in content stream");
if (printCommands) {
printf("throwing away arg: ");
obj.print(stdout);
printf("\n");
fflush(stdout);
}
}
// grab the next object
obj = parser->getObj();
}
// args at end with no command
if (numArgs > 0) {
error(errSyntaxError, getPos(), "Leftover args in content stream");
if (printCommands) {
printf("%d leftovers:", numArgs);
for (i = 0; i < numArgs; ++i) {
printf(" ");
args[i].print(stdout);
}
printf("\n");
fflush(stdout);
}
}
popStateGuard();
// update display
if (topLevel && updateLevel > 0) {
out->dump();
}
}
void Gfx::execOp(Object *cmd, Object args[], int numArgs)
{
const Operator *op;
Object *argPtr;
int i;
// find operator
const char *name = cmd->getCmd();
if (!(op = findOp(name))) {
if (ignoreUndef == 0) {
error(errSyntaxError, getPos(), "Unknown operator '{0:s}'", name);
}
return;
}
// type check args
argPtr = args;
if (op->numArgs >= 0) {
if (numArgs < op->numArgs) {
error(errSyntaxError, getPos(), "Too few ({0:d}) args to '{1:s}' operator", numArgs, name);
commandAborted = true;
return;
}
if (numArgs > op->numArgs) {
#if 0
error(errSyntaxWarning, getPos(),
"Too many ({0:d}) args to '{1:s}' operator", numArgs, name);
#endif
argPtr += numArgs - op->numArgs;
numArgs = op->numArgs;
}
} else {
if (numArgs > -op->numArgs) {
error(errSyntaxError, getPos(), "Too many ({0:d}) args to '{1:s}' operator", numArgs, name);
return;
}
}
for (i = 0; i < numArgs; ++i) {
if (!checkArg(&argPtr[i], op->tchk[i])) {
error(errSyntaxError, getPos(), "Arg #{0:d} to '{1:s}' operator is wrong type ({2:s})", i, name, argPtr[i].getTypeName());
return;
}
}
// do it
(this->*op->func)(argPtr, numArgs);
}
const Operator *Gfx::findOp(const char *name)
{
int a, b, m, cmp;
a = -1;
b = numOps;
cmp = 0; // make gcc happy
// invariant: opTab[a] < name < opTab[b]
while (b - a > 1) {
m = (a + b) / 2;
cmp = strcmp(opTab[m].name, name);
if (cmp < 0) {
a = m;
} else if (cmp > 0) {
b = m;
} else {
a = b = m;
}
}
if (cmp != 0) {
return nullptr;
}
return &opTab[a];
}
bool Gfx::checkArg(Object *arg, TchkType type)
{
switch (type) {
case tchkBool:
return arg->isBool();
case tchkInt:
return arg->isInt();
case tchkNum:
return arg->isNum();
case tchkString:
return arg->isString();
case tchkName:
return arg->isName();
case tchkArray:
return arg->isArray();
case tchkProps:
return arg->isDict() || arg->isName();
case tchkSCN:
return arg->isNum() || arg->isName();
case tchkNone:
return false;
}
return false;
}
Goffset Gfx::getPos()
{
return parser ? parser->getPos() : -1;
}
//------------------------------------------------------------------------
// graphics state operators
//------------------------------------------------------------------------
void Gfx::opSave(Object args[], int numArgs)
{
saveState();
}
void Gfx::opRestore(Object args[], int numArgs)
{
restoreState();
}
void Gfx::opConcat(Object args[], int numArgs)
{
state->concatCTM(args[0].getNum(), args[1].getNum(), args[2].getNum(), args[3].getNum(), args[4].getNum(), args[5].getNum());
out->updateCTM(state, args[0].getNum(), args[1].getNum(), args[2].getNum(), args[3].getNum(), args[4].getNum(), args[5].getNum());
fontChanged = true;
}
void Gfx::opSetDash(Object args[], int numArgs)
{
const Array *a = args[0].getArray();
int length = a->getLength();
std::vector<double> dash(length);
for (int i = 0; i < length; ++i) {
dash[i] = a->get(i).getNumWithDefaultValue(0);
}
state->setLineDash(std::move(dash), args[1].getNum());
out->updateLineDash(state);
}
void Gfx::opSetFlat(Object args[], int numArgs)
{
state->setFlatness((int)args[0].getNum());
out->updateFlatness(state);
}
void Gfx::opSetLineJoin(Object args[], int numArgs)
{
state->setLineJoin(args[0].getInt());
out->updateLineJoin(state);
}
void Gfx::opSetLineCap(Object args[], int numArgs)
{
state->setLineCap(args[0].getInt());
out->updateLineCap(state);
}
void Gfx::opSetMiterLimit(Object args[], int numArgs)
{
state->setMiterLimit(args[0].getNum());
out->updateMiterLimit(state);
}
void Gfx::opSetLineWidth(Object args[], int numArgs)
{
state->setLineWidth(args[0].getNum());
out->updateLineWidth(state);
}
void Gfx::opSetExtGState(Object args[], int numArgs)
{
Object obj1, obj2;
GfxBlendMode mode;
bool haveFillOP;
GfxColor backdropColor;
bool haveBackdropColor;
bool alpha;
double opac;
obj1 = res->lookupGState(args[0].getName());
if (obj1.isNull()) {
return;
}
if (!obj1.isDict()) {
error(errSyntaxError, getPos(), "ExtGState '{0:s}' is wrong type", args[0].getName());
return;
}
if (printCommands) {
printf(" gfx state dict: ");
obj1.print();
printf("\n");
}
// parameters that are also set by individual PDF operators
obj2 = obj1.dictLookup("LW");
if (obj2.isNum()) {
opSetLineWidth(&obj2, 1);
}
obj2 = obj1.dictLookup("LC");
if (obj2.isInt()) {
opSetLineCap(&obj2, 1);
}
obj2 = obj1.dictLookup("LJ");
if (obj2.isInt()) {
opSetLineJoin(&obj2, 1);
}
obj2 = obj1.dictLookup("ML");
if (obj2.isNum()) {
opSetMiterLimit(&obj2, 1);
}
obj2 = obj1.dictLookup("D");
if (obj2.isArray() && obj2.arrayGetLength() == 2) {
Object args2[2];
args2[0] = obj2.arrayGet(0);
args2[1] = obj2.arrayGet(1);
if (args2[0].isArray() && args2[1].isNum()) {
opSetDash(args2, 2);
}
}
#if 0 //~ need to add a new version of GfxResources::lookupFont() that
//~ takes an indirect ref instead of a name
if (obj1.dictLookup("Font", &obj2)->isArray() &&
obj2.arrayGetLength() == 2) {
obj2.arrayGet(0, &args2[0]);
obj2.arrayGet(1, &args2[1]);
if (args2[0].isDict() && args2[1].isNum()) {
opSetFont(args2, 2);
}
args2[0].free();
args2[1].free();
}
obj2.free();
#endif
obj2 = obj1.dictLookup("FL");
if (obj2.isNum()) {
opSetFlat(&obj2, 1);
}
// transparency support: blend mode, fill/stroke opacity