aboutsummaryrefslogtreecommitdiffhomepage
path: root/experimental/PdfViewer/SkPdfParser.h
blob: c156004f601ec8f6765cc7612e17be2b74e76d3d (plain)
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
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "podofo.h"
#include "SkPdfHeaders_autogen.h"
#include "SkPdfPodofoMapper_autogen.h"

#ifndef SkPdfParser_DEFINED
#define SkPdfParser_DEFINED


enum SkPdfTokenType {
    kKeyword_TokenType,
    kObject_TokenType,
    kImageData_TokenType,  // TODO(edisonn): inline images seem to work without it
};

struct PdfToken {
    const char*      fKeyword;
    SkPdfObject*     fObject;
    SkPdfTokenType   fType;

    PdfToken() : fKeyword(NULL), fObject(NULL) {}
};

class SkPdfTokenizer {
    PdfMemDocument* fDoc;
    PdfContentsTokenizer* fTokenizer;

    char* fUncompressedStream;
    pdf_long fUncompressedStreamLength;

    bool fEmpty;
    bool fHasPutBack;
    PdfToken fPutBack;

public:
    SkPdfTokenizer(PdfMemDocument* doc = NULL, PdfContentsTokenizer* tokenizer = NULL) : fDoc(doc), fTokenizer(tokenizer), fUncompressedStream(NULL), fUncompressedStreamLength(0),  fEmpty(false), fHasPutBack(false) {}
    SkPdfTokenizer(const SkPdfObject* objWithStream) : fDoc(NULL), fTokenizer(NULL), fEmpty(false), fHasPutBack(false) {
        fUncompressedStream = NULL;
        fUncompressedStreamLength = 0;

        fDoc = NULL;


        try {
            objWithStream->podofo()->GetStream()->GetFilteredCopy(&fUncompressedStream, &fUncompressedStreamLength);
            if (fUncompressedStream != NULL && fUncompressedStreamLength != 0) {
                fTokenizer = new PdfContentsTokenizer(fUncompressedStream, fUncompressedStreamLength);
            } else {
                fEmpty = true;
            }
        } catch (PdfError& e) {
            fEmpty = true;
        }

    }

    SkPdfTokenizer(const char* buffer, int len) : fDoc(NULL), fTokenizer(NULL), fUncompressedStream(NULL), fUncompressedStreamLength(0), fEmpty(false), fHasPutBack(false) {
        try {
            fTokenizer = new PdfContentsTokenizer(buffer, len);
        } catch (PdfError& e) {
            fEmpty = true;
        }
    }

    ~SkPdfTokenizer() {
        free(fUncompressedStream);
    }

    void PutBack(PdfToken token) {
        SkASSERT(!fHasPutBack);
        fHasPutBack = true;
        fPutBack = token;
    }

    bool readToken(PdfToken* token) {
        if (fHasPutBack) {
            *token = fPutBack;
            fHasPutBack = false;
            return true;
        }

        if (fEmpty) {
            return false;
        }

        PdfVariant var;
        EPdfContentsType type;

        token->fKeyword = NULL;
        token->fObject = NULL;

        bool ret = fTokenizer->ReadNext(type, token->fKeyword, var);

        if (!ret) return ret;

        switch (type) {
            case ePdfContentsType_Keyword:
                token->fType = kKeyword_TokenType;
                break;

            case ePdfContentsType_Variant: {
                    token->fType = kObject_TokenType;
                    PdfObject* obj = new PdfObject(var);
                    mapObject(*fDoc, *obj, &token->fObject);
                }
                break;

            case ePdfContentsType_ImageData:
                token->fType = kImageData_TokenType;
                // TODO(edisonn): inline images seem to work without it
                break;
        }
#ifdef PDF_TRACE
        std::string str;
        if (token->fObject) {
            token->fObject->podofo()->ToString(str);
        }
        printf("%s %s\n", token->fType == kKeyword_TokenType ? "Keyword" : token->fType == kObject_TokenType ? "Object" : "ImageData", token->fKeyword ? token->fKeyword : str.c_str());
#endif
        return ret;
    }
};

extern "C" PdfContext* gPdfContext;
extern "C" SkBitmap* gDumpBitmap;
extern "C" SkCanvas* gDumpCanvas;

// TODO(edisonn): move in trace util.
#ifdef PDF_TRACE
static void SkTraceMatrix(const SkMatrix& matrix, const char* sz = "") {
    printf("SkMatrix %s ", sz);
    for (int i = 0 ; i < 9 ; i++) {
        printf("%f ", SkScalarToDouble(matrix.get(i)));
    }
    printf("\n");
}

static void SkTraceRect(const SkRect& rect, const char* sz = "") {
    printf("SkRect %s ", sz);
    printf("x = %f ", SkScalarToDouble(rect.x()));
    printf("y = %f ", SkScalarToDouble(rect.y()));
    printf("w = %f ", SkScalarToDouble(rect.width()));
    printf("h = %f ", SkScalarToDouble(rect.height()));
    printf("\n");
}

#else
#define SkTraceMatrix(a,b)
#define SkTraceRect(a,b)
#endif

// TODO(edisonn): Document PdfTokenLooper and subclasses.
class PdfTokenLooper {
protected:
    PdfTokenLooper* fParent;
    SkPdfTokenizer* fTokenizer;
    PdfContext* fPdfContext;
    SkCanvas* fCanvas;

public:
    PdfTokenLooper(PdfTokenLooper* parent,
                   SkPdfTokenizer* tokenizer,
                   PdfContext* pdfContext,
                   SkCanvas* canvas)
        : fParent(parent), fTokenizer(tokenizer), fPdfContext(pdfContext), fCanvas(canvas) {}

    virtual PdfResult consumeToken(PdfToken& token) = 0;
    virtual void loop() = 0;

    void setUp(PdfTokenLooper* parent) {
        fParent = parent;
        fTokenizer = parent->fTokenizer;
        fPdfContext = parent->fPdfContext;
        fCanvas = parent->fCanvas;
    }
};

class PdfMainLooper : public PdfTokenLooper {
public:
    PdfMainLooper(PdfTokenLooper* parent,
                  SkPdfTokenizer* tokenizer,
                  PdfContext* pdfContext,
                  SkCanvas* canvas)
        : PdfTokenLooper(parent, tokenizer, pdfContext, canvas) {}

    virtual PdfResult consumeToken(PdfToken& token);
    virtual void loop();
};

class PdfInlineImageLooper : public PdfTokenLooper {
public:
    PdfInlineImageLooper()
        : PdfTokenLooper(NULL, NULL, NULL, NULL) {}

    virtual PdfResult consumeToken(PdfToken& token);
    virtual void loop();
    PdfResult done();
};

class PdfCompatibilitySectionLooper : public PdfTokenLooper {
public:
    PdfCompatibilitySectionLooper()
        : PdfTokenLooper(NULL, NULL, NULL, NULL) {}

    virtual PdfResult consumeToken(PdfToken& token);
    virtual void loop();
};

class SkPdfDoc {
    PdfMemDocument fDoc;
public:

    PdfMemDocument& podofo() {return fDoc;}

    SkPdfDoc(const char* path) : fDoc(path) {}

    int pages() {
        return fDoc.GetPageCount();
    }

    double width(int n) {
        PdfRect rect = fDoc.GetPage(n)->GetMediaBox();
        return rect.GetWidth() + rect.GetLeft();
    }

    double height(int n) {
        PdfRect rect = fDoc.GetPage(n)->GetMediaBox();
        return rect.GetHeight() + rect.GetBottom();
    }

    // Can return NULL
    SkPdfPageObjectDictionary* page(int n) {
        SkPdfPageObjectDictionary* page = NULL;
        mapPageObjectDictionary(fDoc, *fDoc.GetPage(n)->GetObject(), &page);
        return page;
    }

    SkRect MediaBox(int n) {
        PdfRect rect = fDoc.GetPage(n)->GetMediaBox();
        SkRect skrect = SkRect::MakeLTRB(SkDoubleToScalar(rect.GetLeft()),
                                         SkDoubleToScalar(rect.GetBottom()),
                                         SkDoubleToScalar(rect.GetLeft() + rect.GetWidth()),
                                         SkDoubleToScalar(rect.GetBottom() + rect.GetHeight()));
        return skrect;
    }

    void drawPage(int n, SkCanvas* canvas) {
        SkPdfPageObjectDictionary* pg = page(n);
        SkPdfTokenizer* tokenizer = tokenizerOfPage(n);

        PdfContext pdfContext(this);
        pdfContext.fOriginalMatrix = SkMatrix::I();
        pdfContext.fGraphicsState.fResources = NULL;
        mapResourceDictionary(*pg->Resources(), &pdfContext.fGraphicsState.fResources);

        gPdfContext = &pdfContext;
        gDumpCanvas = canvas;

        // TODO(edisonn): get matrix stuff right.
        // TODO(edisonn): add DPI/scale/zoom.
        SkScalar z = SkIntToScalar(0);
        SkRect rect = MediaBox(n);
        SkScalar w = rect.width();
        SkScalar h = rect.height();

        SkPoint pdfSpace[4] = {SkPoint::Make(z, z), SkPoint::Make(w, z), SkPoint::Make(w, h), SkPoint::Make(z, h)};
//                SkPoint skiaSpace[4] = {SkPoint::Make(z, h), SkPoint::Make(w, h), SkPoint::Make(w, z), SkPoint::Make(z, z)};

        // TODO(edisonn): add flag for this app to create sourunding buffer zone
        // TODO(edisonn): add flagg for no clipping.
        // Use larger image to make sure we do not draw anything outside of page
        // could be used in tests.

#ifdef PDF_DEBUG_3X
        SkPoint skiaSpace[4] = {SkPoint::Make(w+z, h+h), SkPoint::Make(w+w, h+h), SkPoint::Make(w+w, h+z), SkPoint::Make(w+z, h+z)};
#else
        SkPoint skiaSpace[4] = {SkPoint::Make(z, h), SkPoint::Make(w, h), SkPoint::Make(w, z), SkPoint::Make(z, z)};
#endif
        //SkPoint pdfSpace[2] = {SkPoint::Make(z, z), SkPoint::Make(w, h)};
        //SkPoint skiaSpace[2] = {SkPoint::Make(w, z), SkPoint::Make(z, h)};

        //SkPoint pdfSpace[2] = {SkPoint::Make(z, z), SkPoint::Make(z, h)};
        //SkPoint skiaSpace[2] = {SkPoint::Make(z, h), SkPoint::Make(z, z)};

        //SkPoint pdfSpace[3] = {SkPoint::Make(z, z), SkPoint::Make(z, h), SkPoint::Make(w, h)};
        //SkPoint skiaSpace[3] = {SkPoint::Make(z, h), SkPoint::Make(z, z), SkPoint::Make(w, 0)};

        SkAssertResult(pdfContext.fOriginalMatrix.setPolyToPoly(pdfSpace, skiaSpace, 4));
        SkTraceMatrix(pdfContext.fOriginalMatrix, "Original matrix");


        pdfContext.fGraphicsState.fMatrix = pdfContext.fOriginalMatrix;
        pdfContext.fGraphicsState.fMatrixTm = pdfContext.fGraphicsState.fMatrix;
        pdfContext.fGraphicsState.fMatrixTlm = pdfContext.fGraphicsState.fMatrix;

        canvas->setMatrix(pdfContext.fOriginalMatrix);

#ifndef PDF_DEBUG_NO_PAGE_CLIPING
        canvas->clipRect(SkRect::MakeXYWH(z, z, w, h), SkRegion::kIntersect_Op, true);
#endif

// erase with red before?
//        SkPaint paint;
//        paint.setColor(SK_ColorRED);
//        canvas->drawRect(rect, paint);

        PdfMainLooper looper(NULL, tokenizer, &pdfContext, canvas);
        looper.loop();

        delete tokenizer;


        canvas->flush();
    }

    SkPdfTokenizer* tokenizerOfPage(int n) {
        PdfContentsTokenizer* t = new PdfContentsTokenizer(fDoc.GetPage(n));
        return new SkPdfTokenizer(&fDoc, t);
    }
};

// TODO(edisonn): move in another file
class SkPdfViewer : public SkRefCnt {
public:

  bool load(const SkString inputFileName, SkPicture* out);
  bool write(void*) const { return false; }
};

void reportPdfRenderStats();

#endif  // SkPdfParser_DEFINED