Gfx.cc 171 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1
2
3
4
//========================================================================
//
// Gfx.cc
//
Albert Astals Cid's avatar
Albert Astals Cid committed
5
// Copyright 1996-2013 Glyph & Cog, LLC
Kristian Høgsberg's avatar
Kristian Høgsberg committed
6
7
8
//
//========================================================================

9
10
11
12
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
13
14
15
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
16
// Copyright (C) 2005 Jonathan Blandford <jrb@redhat.com>
17
// Copyright (C) 2005-2013, 2015-2021 Albert Astals Cid <aacid@kde.org>
18
19
// Copyright (C) 2006 Thorkild Stray <thorkild@ifi.uio.no>
// Copyright (C) 2006 Kristian Høgsberg <krh@redhat.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
20
// Copyright (C) 2006-2011 Carlos Garcia Campos <carlosgc@gnome.org>
21
22
// Copyright (C) 2006, 2007 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2007, 2008 Brad Hards <bradh@kde.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
23
// Copyright (C) 2007, 2011, 2017 Adrian Johnson <ajohnson@redneon.com>
24
25
26
27
28
// 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>
29
// Copyright (C) 2008 Hib Eris <hib@hiberis.nl>
30
// Copyright (C) 2009 M Joonas Pihlaja <jpihlaja@cc.helsinki.fi>
Albert Astals Cid's avatar
Albert Astals Cid committed
31
// Copyright (C) 2009-2016, 2020 Thomas Freitag <Thomas.Freitag@alfa.de>
32
// Copyright (C) 2009 William Bader <williambader@hotmail.com>
33
// Copyright (C) 2009, 2010 David Benjamin <davidben@mit.edu>
34
// Copyright (C) 2010 Nils Höglund <nils.hoglund@gmail.com>
35
// Copyright (C) 2010 Christian Feuersänger <cfeuersaenger@googlemail.com>
36
// Copyright (C) 2011 Axel Strübing <axel.struebing@freenet.de>
37
// Copyright (C) 2012 Even Rouault <even.rouault@mines-paris.org>
38
// Copyright (C) 2012, 2013 Fabio D'Urso <fabiodurso@hotmail.it>
39
// Copyright (C) 2012 Lu Wang <coolwanglu@gmail.com>
40
// Copyright (C) 2014 Jason Crain <jason@aquaticape.us>
41
// 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
42
// Copyright (C) 2018, 2019 Adam Reichold <adam.reichold@t-online.de>
43
// Copyright (C) 2018 Denis Onishchenko <denis.onischenko@gmail.com>
44
// Copyright (C) 2019 LE GARREC Vincent <legarrec.vincent@gmail.com>
45
// Copyright (C) 2019, 2020 Oliver Sander <oliver.sander@tu-dresden.de>
46
// Copyright (C) 2019 Volker Krause <vkrause@kde.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
47
// Copyright (C) 2020 Philipp Knechtges <philipp-dev@knechtges.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
48
// Copyright (C) 2021 Steve Rosenhamer <srosenhamer@me.com>
49
50
51
52
53
54
//
// 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
//
//========================================================================

Kristian Høgsberg's avatar
Kristian Høgsberg committed
55
56
#include <config.h>

57
58
59
60
61
#include <cstdlib>
#include <cstdio>
#include <cstddef>
#include <cstring>
#include <cmath>
62
#include <memory>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
63
#include "goo/gmem.h"
64
#include "goo/GooTimer.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
65
66
67
#include "GlobalParams.h"
#include "CharTypes.h"
#include "Object.h"
68
#include "PDFDoc.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
69
#include "Array.h"
70
#include "Annot.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
71
72
73
74
75
76
77
78
#include "Dict.h"
#include "Stream.h"
#include "Lexer.h"
#include "Parser.h"
#include "GfxFont.h"
#include "GfxState.h"
#include "OutputDev.h"
#include "Page.h"
79
#include "Annot.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
80
81
#include "Error.h"
#include "Gfx.h"
82
#include "ProfileData.h"
83
84
#include "Catalog.h"
#include "OptionalContent.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
85
86
87

// the MSVC math.h doesn't define this
#ifndef M_PI
Albert Astals Cid's avatar
Albert Astals Cid committed
88
#    define M_PI 3.14159265358979323846
Kristian Høgsberg's avatar
Kristian Høgsberg committed
89
90
91
92
93
94
95
96
97
98
#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.
99
#define functionColorDelta (dblToCol(1 / 256.0))
Kristian Høgsberg's avatar
Kristian Høgsberg committed
100
101
102
103
104

// 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.
105
#define axialColorDelta (dblToCol(1 / 256.0))
Kristian Høgsberg's avatar
Kristian Høgsberg committed
106
107
108
109
110

// 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.
111
112
113
#define radialColorDelta (dblToCol(1 / 256.0))

// Max recursive depth for a Gouraud triangle shading fill.
114
115
116
117
//
// Triangles will be split at most gouraudMaxDepth times (each time into 4
// smaller ones). That makes pow(4,gouraudMaxDepth) many triangles for
// every triangle.
118
#define gouraudMaxDepth 6
119
120
121

// Max delta allowed in any color component for a Gouraud triangle
// shading fill.
122
123
#define gouraudColorDelta (dblToCol(3. / 256.0))

Albert Astals Cid's avatar
Albert Astals Cid committed
124
// Gouraud triangle: if the three color parameters differ by at more than this percend of
125
126
// the total color parameter range, the triangle will be refined
#define gouraudParameterizedColorDelta 5e-3
127
128
129
130
131
132

// 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.
133
#define patchColorDelta (dblToCol((3. / 256.0)))
Kristian Høgsberg's avatar
Kristian Høgsberg committed
134
135
136
137
138

//------------------------------------------------------------------------
// Operator table
//------------------------------------------------------------------------

139
const Operator Gfx::opTab[] = {
Albert Astals Cid's avatar
Albert Astals Cid committed
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
    { "\"", 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 },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
221
222
223
224
};

#define numOps (sizeof(opTab) / sizeof(Operator))

Albert Astals Cid's avatar
Albert Astals Cid committed
225
226
227
228
229
230
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;
        }
231
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
232
    return true;
233
234
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
235
236
237
238
//------------------------------------------------------------------------
// GfxResources
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
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
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();
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
287

Albert Astals Cid's avatar
Albert Astals Cid committed
288
    next = nextA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
289
290
}

Albert Astals Cid's avatar
Albert Astals Cid committed
291
292
293
GfxResources::~GfxResources()
{
    delete fonts;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
294
295
}

296
297
GfxFont *GfxResources::doLookupFont(const char *name) const
{
Albert Astals Cid's avatar
Albert Astals Cid committed
298
299
    GfxFont *font;
    const GfxResources *resPtr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
300

Albert Astals Cid's avatar
Albert Astals Cid committed
301
302
303
304
305
    for (resPtr = this; resPtr; resPtr = resPtr->next) {
        if (resPtr->fonts) {
            if ((font = resPtr->fonts->lookup(name)))
                return font;
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
306
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
307
308
    error(errSyntaxError, -1, "Unknown font tag '{0:s}'", name);
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
309
310
}

Albert Astals Cid's avatar
Albert Astals Cid committed
311
312
313
GfxFont *GfxResources::lookupFont(const char *name)
{
    return doLookupFont(name);
314
315
}

Albert Astals Cid's avatar
Albert Astals Cid committed
316
317
318
const GfxFont *GfxResources::lookupFont(const char *name) const
{
    return doLookupFont(name);
319
320
}

Albert Astals Cid's avatar
Albert Astals Cid committed
321
322
323
Object GfxResources::lookupXObject(const char *name)
{
    GfxResources *resPtr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
324

Albert Astals Cid's avatar
Albert Astals Cid committed
325
326
327
328
329
330
    for (resPtr = this; resPtr; resPtr = resPtr->next) {
        if (resPtr->xObjDict.isDict()) {
            Object obj = resPtr->xObjDict.dictLookup(name);
            if (!obj.isNull())
                return obj;
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
331
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
332
333
    error(errSyntaxError, -1, "XObject '{0:s}' is unknown", name);
    return Object(objNull);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
334
335
}

Albert Astals Cid's avatar
Albert Astals Cid committed
336
337
338
Object GfxResources::lookupXObjectNF(const char *name)
{
    GfxResources *resPtr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
339

Albert Astals Cid's avatar
Albert Astals Cid committed
340
341
342
343
344
345
    for (resPtr = this; resPtr; resPtr = resPtr->next) {
        if (resPtr->xObjDict.isDict()) {
            Object obj = resPtr->xObjDict.dictLookupNF(name).copy();
            if (!obj.isNull())
                return obj;
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
346
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
347
348
    error(errSyntaxError, -1, "XObject '{0:s}' is unknown", name);
    return Object(objNull);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
349
350
}

Albert Astals Cid's avatar
Albert Astals Cid committed
351
352
353
Object GfxResources::lookupMarkedContentNF(const char *name)
{
    GfxResources *resPtr;
354

Albert Astals Cid's avatar
Albert Astals Cid committed
355
356
357
358
359
360
    for (resPtr = this; resPtr; resPtr = resPtr->next) {
        if (resPtr->propertiesDict.isDict()) {
            Object obj = resPtr->propertiesDict.dictLookupNF(name).copy();
            if (!obj.isNull())
                return obj;
        }
361
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
362
363
    error(errSyntaxError, -1, "Marked Content '{0:s}' is unknown", name);
    return Object(objNull);
364
365
}

Albert Astals Cid's avatar
Albert Astals Cid committed
366
367
368
Object GfxResources::lookupColorSpace(const char *name)
{
    GfxResources *resPtr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
369

Albert Astals Cid's avatar
Albert Astals Cid committed
370
371
372
373
374
375
376
    for (resPtr = this; resPtr; resPtr = resPtr->next) {
        if (resPtr->colorSpaceDict.isDict()) {
            Object obj = resPtr->colorSpaceDict.dictLookup(name);
            if (!obj.isNull()) {
                return obj;
            }
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
377
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
378
    return Object(objNull);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
379
380
}

Albert Astals Cid's avatar
Albert Astals Cid committed
381
382
383
384
385
386
387
388
389
390
391
392
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);
            }
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
393
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
394
395
    error(errSyntaxError, -1, "Unknown pattern '{0:s}'", name);
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
396
397
}

Albert Astals Cid's avatar
Albert Astals Cid committed
398
399
400
401
402
403
404
405
406
407
408
409
410
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;
            }
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
411
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
412
413
    error(errSyntaxError, -1, "ExtGState '{0:s}' is unknown", name);
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
414
415
}

Albert Astals Cid's avatar
Albert Astals Cid committed
416
417
418
419
420
Object GfxResources::lookupGState(const char *name)
{
    Object obj = lookupGStateNF(name);
    if (obj.isNull())
        return Object(objNull);
421

Albert Astals Cid's avatar
Albert Astals Cid committed
422
423
    if (!obj.isRef())
        return obj;
424

Albert Astals Cid's avatar
Albert Astals Cid committed
425
    const Ref ref = obj.getRef();
426

Albert Astals Cid's avatar
Albert Astals Cid committed
427
428
429
430
431
432
433
    if (auto *item = gStateCache.lookup(ref)) {
        return item->copy();
    }

    auto *item = new Object { xref->fetch(ref) };
    gStateCache.put(ref, item);
    return item->copy();
434
435
}

Albert Astals Cid's avatar
Albert Astals Cid committed
436
437
438
Object GfxResources::lookupGStateNF(const char *name)
{
    GfxResources *resPtr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
439

Albert Astals Cid's avatar
Albert Astals Cid committed
440
441
442
443
444
445
446
    for (resPtr = this; resPtr; resPtr = resPtr->next) {
        if (resPtr->gStateDict.isDict()) {
            Object obj = resPtr->gStateDict.dictLookupNF(name).copy();
            if (!obj.isNull()) {
                return obj;
            }
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
447
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
448
449
    error(errSyntaxError, -1, "ExtGState '{0:s}' is unknown", name);
    return Object(objNull);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
450
451
452
453
454
455
}

//------------------------------------------------------------------------
// Gfx
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
456
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)
457
    : printCommands(globalParams->getPrintCommands()), profileCommands(globalParams->getProfileCommands())
Albert Astals Cid's avatar
Albert Astals Cid committed
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
{
    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];
    }
486
    displayDepth = 0;
Albert Astals Cid's avatar
Albert Astals Cid committed
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    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();
    }
503
#ifdef USE_CMS
Albert Astals Cid's avatar
Albert Astals Cid committed
504
    initDisplayProfile();
505
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
506
507
}

Albert Astals Cid's avatar
Albert Astals Cid committed
508
Gfx::Gfx(PDFDoc *docA, OutputDev *outA, Dict *resDict, const PDFRectangle *box, const PDFRectangle *cropBox, bool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA, Gfx *gfxA)
509
    : printCommands(globalParams->getPrintCommands()), profileCommands(globalParams->getProfileCommands())
510
{
Albert Astals Cid's avatar
Albert Astals Cid committed
511
    int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
512

Albert Astals Cid's avatar
Albert Astals Cid committed
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
    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;
531
532
533
534
535
536
537
    double hDPI = 72;
    double vDPI = 72;
    if (gfxA) {
        hDPI = gfxA->getState()->getHDPI();
        vDPI = gfxA->getState()->getVDPI();
    }
    state = new GfxState(hDPI, vDPI, box, 0, false);
Albert Astals Cid's avatar
Albert Astals Cid committed
538
539
540
541
542
543
544
545
    stackHeight = 1;
    pushStateGuard();
    fontChanged = false;
    clip = clipNone;
    ignoreUndef = 0;
    for (i = 0; i < 6; ++i) {
        baseMatrix[i] = state->getCTM()[i];
    }
546
    displayDepth = 0;
Albert Astals Cid's avatar
Albert Astals Cid committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
    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();
    }
563
#ifdef USE_CMS
Albert Astals Cid's avatar
Albert Astals Cid committed
564
    initDisplayProfile();
565
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
566
567
}

568
569
#ifdef USE_CMS

Albert Astals Cid's avatar
Albert Astals Cid committed
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#    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();
                    int length = 0;
                    unsigned char *profBuf = iccStream->toUnsignedChars(&length, 65536, 65536);
                    auto hp = make_GfxLCMSProfilePtr(cmsOpenProfileFromMem(profBuf, length));
                    if (!hp) {
                        error(errSyntaxWarning, -1, "read ICCBased color space profile error");
                    } else {
                        state->setDisplayProfile(hp);
                    }
                    gfree(profBuf);
592
                }
Albert Astals Cid's avatar
Albert Astals Cid committed
593
594
595
            }
        }
    }
596
597
598
599
}

#endif

Albert Astals Cid's avatar
Albert Astals Cid committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
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();
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
620
621
}

Albert Astals Cid's avatar
Albert Astals Cid committed
622
623
void Gfx::display(Object *obj, bool topLevel)
{
624
625
626
627
    // check for excessive recursion
    if (displayDepth > 100) {
        return;
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
628
629

    if (obj->isArray()) {
630
        for (int i = 0; i < obj->arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
631
632
633
634
635
636
637
638
639
            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;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
640
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
641
642
643
644
645
    parser = new Parser(xref, obj, false);
    go(topLevel);
    delete parser;
    parser = nullptr;
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
646

Albert Astals Cid's avatar
Albert Astals Cid committed
647
648
649
650
651
652
653
654
655
656
657
658
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;
Albert Astals Cid's avatar
Albert Astals Cid committed
659
    obj = parser->getObj();
Albert Astals Cid's avatar
Albert Astals Cid committed
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
    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;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
675

Albert Astals Cid's avatar
Albert Astals Cid committed
676
677
678
            if (unlikely(profileCommands)) {
                timer = new GooTimer();
            }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
679

Albert Astals Cid's avatar
Albert Astals Cid committed
680
681
            // Run the operation
            execOp(&obj, args, numArgs);
682

Albert Astals Cid's avatar
Albert Astals Cid committed
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
            // 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;
            }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
701

Albert Astals Cid's avatar
Albert Astals Cid committed
702
703
704
705
706
707
708
            // 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;
            }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
709

Albert Astals Cid's avatar
Albert Astals Cid committed
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
            // 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();
    }
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
759

Albert Astals Cid's avatar
Albert Astals Cid committed
760
761
762
763
764
765
766
767
768
769
770
771
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;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
772
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
773
774
775
776
777
778
779
780
781
782

    // 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) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
783
#if 0
784
785
      error(errSyntaxWarning, getPos(),
	    "Too many ({0:d}) args to '{1:s}' operator", numArgs, name);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
786
#endif
Albert Astals Cid's avatar
Albert Astals Cid committed
787
788
789
790
791
792
793
794
            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;
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
795
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
796
797
798
799
800
    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;
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
801
802
    }

Albert Astals Cid's avatar
Albert Astals Cid committed
803
804
    // do it
    (this->*op->func)(argPtr, numArgs);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
805
806
}

Albert Astals Cid's avatar
Albert Astals Cid committed
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
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;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
853
854
}

Albert Astals Cid's avatar
Albert Astals Cid committed
855
856
857
Goffset Gfx::getPos()
{
    return parser ? parser->getPos() : -1;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
858
859
860
861
862
863
}

//------------------------------------------------------------------------
// graphics state operators
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
864
865
866
void Gfx::opSave(Object args[], int numArgs)
{
    saveState();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
867
868
}

Albert Astals Cid's avatar
Albert Astals Cid committed
869
870
871
void Gfx::opRestore(Object args[], int numArgs)
{
    restoreState();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
872
873
}

Albert Astals Cid's avatar
Albert Astals Cid committed
874
875
876
877
878
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;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
879
880
}

Albert Astals Cid's avatar
Albert Astals Cid committed
881
882
883
884
885
886
void Gfx::opSetDash(Object args[], int numArgs)
{
    Array *a;
    int length;
    double *dash;
    int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
887

Albert Astals Cid's avatar
Albert Astals Cid committed
888
889
890
891
892
893
894
895
896
    a = args[0].getArray();
    length = a->getLength();
    if (length == 0) {
        dash = nullptr;
    } else {
        dash = (double *)gmallocn(length, sizeof(double));
        for (i = 0; i < length; ++i) {
            dash[i] = a->get(i).getNumWithDefaultValue(0);
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
897
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
898
899
    state->setLineDash(dash, length, args[1].getNum());
    out->updateLineDash(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
900
901
}

Albert Astals Cid's avatar
Albert Astals Cid committed
902
903
904
905
void Gfx::opSetFlat(Object args[], int numArgs)
{
    state->setFlatness((int)args[0].getNum());
    out->updateFlatness(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
906
907
}

Albert Astals Cid's avatar
Albert Astals Cid committed
908
909
910
911
void Gfx::opSetLineJoin(Object args[], int numArgs)
{
    state->setLineJoin(args[0].getInt());
    out->updateLineJoin(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
912
913
}

Albert Astals Cid's avatar
Albert Astals Cid committed
914
915
916
917
void Gfx::opSetLineCap(Object args[], int numArgs)
{
    state->setLineCap(args[0].getInt());
    out->updateLineCap(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
918
919
}

Albert Astals Cid's avatar
Albert Astals Cid committed
920
921
922
923
void Gfx::opSetMiterLimit(Object args[], int numArgs)
{
    state->setMiterLimit(args[0].getNum());
    out->updateMiterLimit(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
924
925
}

Albert Astals Cid's avatar
Albert Astals Cid committed
926
927
928
929
void Gfx::opSetLineWidth(Object args[], int numArgs)
{
    state->setLineWidth(args[0].getNum());
    out->updateLineWidth(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
930
931
}

Albert Astals Cid's avatar
Albert Astals Cid committed
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
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);
        }
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
    }
#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
Albert Astals Cid's avatar
Albert Astals Cid committed
996
997
998
    obj2 = obj1.dictLookup("FL");
    if (obj2.isNum()) {
        opSetFlat(&obj2, 1);
999
1000
    }

Albert Astals Cid's avatar
Albert Astals Cid committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
    // transparency support: blend mode, fill/stroke opacity
    obj2 = obj1.dictLookup("BM");
    if (!obj2.isNull()) {
        if (state->parseBlendMode(&obj2, &mode)) {
            state->setBlendMode(mode);
            out->updateBlendMode(state);
        } else {
            error(errSyntaxError, getPos(), "Invalid blend mode in ExtGState");
        }
1010
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
    obj2 = obj1.dictLookup("ca");
    if (obj2.isNum()) {
        opac = obj2.getNum();
        state->setFillOpacity(opac < 0 ? 0 : opac > 1 ? 1 : opac);
        out->updateFillOpacity(state);
    }
    obj2 = obj1.dictLookup("CA");
    if (obj2.isNum()) {
        opac = obj2.getNum();
        state->setStrokeOpacity(opac < 0 ? 0 : opac > 1 ? 1 : opac);
        out->updateStrokeOpacity(state);
    }

    // fill/stroke overprint, overprint mode
    obj2 = obj1.dictLookup("op");
    if ((haveFillOP = obj2.isBool())) {
        state->setFillOverprint(obj2.getBool());
        out->updateFillOverprint(state);
    }
    obj2 = obj1.dictLookup("OP");
    if (obj2.isBool()) {
        state->setStrokeOverprint(obj2.getBool());
        out->updateStrokeOverprint(state);
        if (!haveFillOP) {
            state->setFillOverprint(obj2.getBool());
            out->updateFillOverprint(state);
        }
1038
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
    obj2 = obj1.dictLookup("OPM");
    if (obj2.isInt()) {
        state->setOverprintMode(obj2.getInt());
        out->updateOverprintMode(state);
    }

    // stroke adjust
    obj2 = obj1.dictLookup("SA");
    if (obj2.isBool()) {
        state->setStrokeAdjust(obj2.getBool());
        out->updateStrokeAdjust(state);
    }

    // transfer function
    obj2 = obj1.dictLookup("TR2");
    if (obj2.isNull()) {
        obj2 = obj1.dictLookup("TR");
    }
    if (obj2.isName("Default") || obj2.isName("Identity")) {
1058
        Function *funcs[4] = { nullptr, nullptr, nullptr, nullptr };
Albert Astals Cid's avatar
Albert Astals Cid committed
1059
1060
1061
        state->setTransfer(funcs);
        out->updateTransfer(state);
    } else if (obj2.isArray() && obj2.arrayGetLength() == 4) {
1062
1063
        Function *funcs[4] = { nullptr, nullptr, nullptr, nullptr };
        for (int i = 0; i < 4; ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1064
1065
1066
1067
1068
1069
            Object obj3 = obj2.arrayGet(i);
            funcs[i] = Function::parse(&obj3);
            if (!funcs[i]) {
                break;
            }
        }
1070
        if (funcs[0] && funcs[1] && funcs[2] && funcs[3]) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1071
1072
            state->setTransfer(funcs);
            out->updateTransfer(state);
1073
1074
1075
1076
        } else {
            for (Function *f : funcs) {
                delete f;
            }
Albert Astals Cid's avatar
Albert Astals Cid committed
1077
1078
        }
    } else if (obj2.isName() || obj2.isDict() || obj2.isStream()) {
1079
        Function *funcs[4];
Albert Astals Cid's avatar
Albert Astals Cid committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
        if ((funcs[0] = Function::parse(&obj2))) {
            funcs[1] = funcs[2] = funcs[3] = nullptr;
            state->setTransfer(funcs);
            out->updateTransfer(state);
        }
    } else if (!obj2.isNull()) {
        error(errSyntaxError, getPos(), "Invalid transfer function in ExtGState");
    }

    // alpha is shape
    obj2 = obj1.dictLookup("AIS");
    if (obj2.isBool()) {
        state->setAlphaIsShape(obj2.getBool());
        out->updateAlphaIsShape(state);
    }

    // text knockout
    obj2 = obj1.dictLookup("TK");
    if (obj2.isBool()) {
        state->setTextKnockout(obj2.getBool());
        out->updateTextKnockout(state);
    }

    // soft mask
    obj2 = obj1.dictLookup("SMask");
    if (!obj2.isNull()) {
        if (obj2.isName("None")) {
            out->clearSoftMask(state);
        } else if (obj2.isDict()) {
            Object obj3 = obj2.dictLookup("S");
            if (obj3.isName("Alpha")) {
                alpha = true;
            } else { // "Luminosity"
                alpha = false;
            }
1115
            Function *softMaskTransferFunc = nullptr;
Albert Astals Cid's avatar
Albert Astals Cid committed
1116
1117
1118
            obj3 = obj2.dictLookup("TR");
            if (!obj3.isNull()) {
                if (obj3.isName("Default") || obj3.isName("Identity")) {
1119
                    // nothing
Albert Astals Cid's avatar
Albert Astals Cid committed
1120
                } else {
1121
1122
                    softMaskTransferFunc = Function::parse(&obj3);
                    if (softMaskTransferFunc == nullptr || softMaskTransferFunc->getInputSize() != 1 || softMaskTransferFunc->getOutputSize() != 1) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1123
                        error(errSyntaxError, getPos(), "Invalid transfer function in soft mask in ExtGState");
1124
1125
                        delete softMaskTransferFunc;
                        softMaskTransferFunc = nullptr;
Albert Astals Cid's avatar
Albert Astals Cid committed
1126
1127
1128
1129
1130
                    }
                }
            }
            obj3 = obj2.dictLookup("BC");
            if ((haveBackdropColor = obj3.isArray())) {
1131
1132
                for (int &c : backdropColor.c) {
                    c = 0;
Albert Astals Cid's avatar
Albert Astals Cid committed
1133
                }
1134
                for (int i = 0; i < obj3.arrayGetLength() && i < gfxColorMaxComps; ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
                    Object obj4 = obj3.arrayGet(i);
                    if (obj4.isNum()) {
                        backdropColor.c[i] = dblToCol(obj4.getNum());
                    }
                }
            }
            obj3 = obj2.dictLookup("G");
            if (obj3.isStream()) {
                Object obj4 = obj3.streamGetDict()->lookup("Group");
                if (obj4.isDict()) {
                    GfxColorSpace *blendingColorSpace = nullptr;
                    Object obj5 = obj4.dictLookup("CS");
                    if (!obj5.isNull()) {
                        blendingColorSpace = GfxColorSpace::parse(res, &obj5, out, state);
                    }
                    const bool isolated = obj4.dictLookup("I").getBoolWithDefaultValue(false);
                    const bool knockout = obj4.dictLookup("K").getBoolWithDefaultValue(false);
                    if (!haveBackdropColor) {
                        if (blendingColorSpace) {
                            blendingColorSpace->getDefaultColor(&backdropColor);
                        } else {
                            //~ need to get the parent or default color space (?)
1157
1158
                            for (int &c : backdropColor.c) {
                                c = 0;
Albert Astals Cid's avatar
Albert Astals Cid committed
1159
1160
1161
                            }
                        }
                    }
1162
                    doSoftMask(&obj3, alpha, blendingColorSpace, isolated, knockout, softMaskTransferFunc, &backdropColor);
Albert Astals Cid's avatar
Albert Astals Cid committed
1163
1164
1165
1166
1167
1168
1169
                    delete blendingColorSpace;
                } else {
                    error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group");
                }
            } else {
                error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group");
            }
1170
            delete softMaskTransferFunc;
Albert Astals Cid's avatar
Albert Astals Cid committed
1171
1172
1173
        } else if (!obj2.isNull()) {
            error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState");
        }
1174
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
    obj2 = obj1.dictLookup("Font");
    if (obj2.isArray()) {
        GfxFont *font;
        if (obj2.arrayGetLength() == 2) {
            const Object &fargs0 = obj2.arrayGetNF(0);
            Object fargs1 = obj2.arrayGet(1);
            if (fargs0.isRef() && fargs1.isNum()) {
                Object fobj = fargs0.fetch(xref);
                if (fobj.isDict()) {
                    Ref r = fargs0.getRef();
                    font = GfxFont::makeFont(xref, args[0].getName(), r, fobj.getDict());
                    state->setFont(font, fargs1.getNum());
                    fontChanged = true;
                }
            }
        } else {
            error(errSyntaxError, getPos(), "Number of args mismatch for /Font in ExtGState");
        }
    }
    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()) {
        if (obj2.arrayGetLength() == 2) {
            Object dargs[2];

            dargs[0] = obj2.arrayGetNF(0).copy();
            dargs[1] = obj2.arrayGet(1);
            if (dargs[0].isArray() && dargs[1].isInt()) {
                opSetDash(dargs, 2);
            }
        } else {
            error(errSyntaxError, getPos(), "Number of args mismatch for /D in ExtGState");
        }
    }
    obj2 = obj1.dictLookup("RI");
    if (obj2.isName()) {
        opSetRenderingIntent(&obj2, 1);
    }
    obj2 = obj1.dictLookup("FL");
    if (obj2.isNum()) {
        opSetFlat(&obj2, 1);
1231
    }
1232
1233
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1234
1235
1236
1237
1238
1239
void Gfx::doSoftMask(Object *str, bool alpha, GfxColorSpace *blendingColorSpace, bool isolated, bool knockout, Function *transferFunc, GfxColor *backdropColor)
{
    Dict *dict, *resDict;
    double m[6], bbox[4];
    Object obj1;
    int i;
1240

Albert Astals Cid's avatar
Albert Astals Cid committed
1241
1242
    // get stream dict
    dict = str->streamGetDict();
1243

Albert Astals Cid's avatar
Albert Astals Cid committed
1244
1245
1246
1247
1248
    // check form type
    obj1 = dict->lookup("FormType");
    if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) {
        error(errSyntaxError, getPos(), "Unknown form type");
    }
1249

Albert Astals Cid's avatar
Albert Astals Cid committed
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
    // get bounding box
    obj1 = dict->lookup("BBox");
    if (!obj1.isArray()) {
        error(errSyntaxError, getPos(), "Bad form bounding box");
        return;
    }
    for (i = 0; i < 4; ++i) {
        Object obj2 = obj1.arrayGet(i);
        if (likely(obj2.isNum()))
            bbox[i] = obj2.getNum();
        else {
            error(errSyntaxError, getPos(), "Bad form bounding box (non number)");
            return;
        }
1264
    }
1265

Albert Astals Cid's avatar
Albert Astals Cid committed
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
    // get matrix
    obj1 = dict->lookup("Matrix");
    if (obj1.isArray()) {
        for (i = 0; i < 6; ++i) {
            Object obj2 = obj1.arrayGet(i);
            if (likely(obj2.isNum()))
                m[i] = obj2.getNum();
            else
                m[i] = 0;
        }
    } else {
        m[0] = 1;
        m[1] = 0;
        m[2] = 0;
        m[3] = 1;
        m[4] = 0;
        m[5] = 0;
    }
1284

Albert Astals Cid's avatar
Albert Astals Cid committed
1285
1286
1287
    // get resources
    obj1 = dict->lookup("Resources");
    resDict = obj1.isDict() ? obj1.getDict() : nullptr;
1288

Albert Astals Cid's avatar
Albert Astals Cid committed
1289
1290
    // draw it
    drawForm(str, resDict, m, bbox, true, true, blendingColorSpace, isolated, knockout, alpha, transferFunc, backdropColor);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1291
1292
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1293
1294
1295
void Gfx::opSetRenderingIntent(Object args[], int numArgs)
{
    state->setRenderingIntent(args[0].getName());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1296
1297
1298
1299
1300
1301
}

//------------------------------------------------------------------------
// color operators
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
1302
1303
1304
1305
void Gfx::opSetFillGray(Object args[], int numArgs)
{
    GfxColor color;
    GfxColorSpace *colorSpace = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1306

Albert Astals Cid's avatar
Albert Astals Cid committed
1307
1308
1309
1310
1311
    state->setFillPattern(nullptr);
    Object obj = res->lookupColorSpace("DefaultGray");
    if (!obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
1312
    if (colorSpace == nullptr || colorSpace->getNComps() > 1) {
1313
        delete colorSpace;
1314
        colorSpace = state->copyDefaultGrayColorSpace();
Albert Astals Cid's avatar
Albert Astals Cid committed
1315
1316
1317
1318
1319
1320
    }
    state->setFillColorSpace(colorSpace);
    out->updateFillColorSpace(state);
    color.c[0] = dblToCol(args[0].getNum());
    state->setFillColor(&color);
    out->updateFillColor(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1321
1322
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1323
1324
1325
1326
void Gfx::opSetStrokeGray(Object args[], int numArgs)
{
    GfxColor color;
    GfxColorSpace *colorSpace = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1327

Albert Astals Cid's avatar
Albert Astals Cid committed
1328
1329
1330
1331
1332
1333
    state->setStrokePattern(nullptr);
    Object obj = res->lookupColorSpace("DefaultGray");
    if (!obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
    if (colorSpace == nullptr) {
1334
        colorSpace = state->copyDefaultGrayColorSpace();
Albert Astals Cid's avatar
Albert Astals Cid committed
1335
1336
1337
1338
1339
1340
    }
    state->setStrokeColorSpace(colorSpace);
    out->updateStrokeColorSpace(state);
    color.c[0] = dblToCol(args[0].getNum());
    state->setStrokeColor(&color);
    out->updateStrokeColor(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1341
1342
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1343
1344
1345
1346
1347
void Gfx::opSetFillCMYKColor(Object args[], int numArgs)
{
    GfxColor color;
    GfxColorSpace *colorSpace = nullptr;
    int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1348

Albert Astals Cid's avatar
Albert Astals Cid committed
1349
1350
1351
1352
1353
    Object obj = res->lookupColorSpace("DefaultCMYK");
    if (!obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
    if (colorSpace == nullptr) {
1354
        colorSpace = state->copyDefaultCMYKColorSpace();
Albert Astals Cid's avatar
Albert Astals Cid committed
1355
1356
1357
1358
1359
1360
1361
1362
1363
    }
    state->setFillPattern(nullptr);
    state->setFillColorSpace(colorSpace);
    out->updateFillColorSpace(state);
    for (i = 0; i < 4; ++i) {
        color.c[i] = dblToCol(args[i].getNum());
    }
    state->setFillColor(&color);
    out->updateFillColor(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1364
1365
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1366
1367
1368
1369
1370
void Gfx::opSetStrokeCMYKColor(Object args[], int numArgs)
{
    GfxColor color;
    GfxColorSpace *colorSpace = nullptr;
    int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1371

Albert Astals Cid's avatar
Albert Astals Cid committed
1372
1373
1374
1375
1376
1377
    state->setStrokePattern(nullptr);
    Object obj = res->lookupColorSpace("DefaultCMYK");
    if (!obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
    if (colorSpace == nullptr) {
1378
        colorSpace = state->copyDefaultCMYKColorSpace();
Albert Astals Cid's avatar
Albert Astals Cid committed
1379
1380
1381
1382
1383
1384
1385
1386
    }
    state->setStrokeColorSpace(colorSpace);
    out->updateStrokeColorSpace(state);
    for (i = 0; i < 4; ++i) {
        color.c[i] = dblToCol(args[i].getNum());
    }
    state->setStrokeColor(&color);
    out->updateStrokeColor(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1387
1388
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1389
1390
1391
1392
1393
void Gfx::opSetFillRGBColor(Object args[], int numArgs)
{
    GfxColorSpace *colorSpace = nullptr;
    GfxColor color;
    int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1394

1395
    state->setFillPattern(nullptr);
Albert Astals Cid's avatar
Albert Astals Cid committed
1396
1397
1398
1399
    Object obj = res->lookupColorSpace("DefaultRGB");
    if (!obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
1400
1401
    if (colorSpace == nullptr || colorSpace->getNComps() > 3) {
        delete colorSpace;
1402
        colorSpace = state->copyDefaultRGBColorSpace();
Albert Astals Cid's avatar
Albert Astals Cid committed
1403
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1404
    state->setFillColorSpace(colorSpace);
1405
    out->updateFillColorSpace(state);
Albert Astals Cid's avatar
Albert Astals Cid committed
1406
1407
1408
    for (i = 0; i < 3; ++i) {
        color.c[i] = dblToCol(args[i].getNum());
    }
1409
1410
    state->setFillColor(&color);
    out->updateFillColor(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1411
1412
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1413
1414
1415
1416
1417
void Gfx::opSetStrokeRGBColor(Object args[], int numArgs)
{
    GfxColorSpace *colorSpace = nullptr;
    GfxColor color;
    int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1418

Albert Astals Cid's avatar
Albert Astals Cid committed
1419
1420
1421
1422
1423
1424
    state->setStrokePattern(nullptr);
    Object obj = res->lookupColorSpace("DefaultRGB");
    if (!obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
    if (colorSpace == nullptr) {
1425
        colorSpace = state->copyDefaultRGBColorSpace();
Albert Astals Cid's avatar
Albert Astals Cid committed
1426
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1427
    state->setStrokeColorSpace(colorSpace);
1428
    out->updateStrokeColorSpace(state);
Albert Astals Cid's avatar
Albert Astals Cid committed
1429
1430
1431
    for (i = 0; i < 3; ++i) {
        color.c[i] = dblToCol(args[i].getNum());
    }
1432
1433
    state->setStrokeColor(&color);
    out->updateStrokeColor(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1434
1435
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1436
1437
1438
1439
void Gfx::opSetFillColorSpace(Object args[], int numArgs)
{
    GfxColorSpace *colorSpace;
    GfxColor color;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1440

Albert Astals Cid's avatar
Albert Astals Cid committed
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    Object obj = res->lookupColorSpace(args[0].getName());
    if (obj.isNull()) {
        colorSpace = GfxColorSpace::parse(res, &args[0], out, state);
    } else {
        colorSpace = GfxColorSpace::parse(res, &obj, out, state);
    }
    if (colorSpace) {
        state->setFillPattern(nullptr);
        state->setFillColorSpace(colorSpace);
        out->updateFillColorSpace(state);
        colorSpace->getDefaultColor(&color);
        state->setFillColor(&color);
        out->updateFillColor(state);
    } else {
        error(errSyntaxError, getPos(), "Bad color space (fill)");
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1457
1458
}

Albert Astals Cid's avatar
Albert Astals Cid committed
1459
1460
1461
1462
void Gfx::opSetStrokeColorSpace(Object args[], int numArgs)
{
    GfxColorSpace *colorSpace;
    GfxColor color;