blob: 2c6c4235d53c79d2b2687393fcfb13c198939c11 [file] [log] [blame]
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001/*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkCanvas.h"
9#include "SkDevice.h"
10#include "SkGraphics.h"
11#include "SkImageDecoder.h"
12#include "SkImageEncoder.h"
13#include "SkOSFile.h"
14#include "SkPicture.h"
15#include "SkStream.h"
16#include "SkTypeface.h"
17#include "SkTArray.h"
18#include "picture_utils.h"
19
20#include <iostream>
21#include <cstdio>
22#include <stack>
23
24#include "podofo.h"
edisonn@google.comaf3daa02013-06-12 19:07:45 +000025using namespace PoDoFo;
26
edisonn@google.com59543d32013-06-18 22:00:40 +000027const PdfObject* resolveReferenceObject(const PdfMemDocument* pdfDoc,
28 const PdfObject* obj,
29 bool resolveOneElementArrays = false);
30
edisonn@google.comaf3daa02013-06-12 19:07:45 +000031bool LongFromDictionary(const PdfMemDocument* pdfDoc,
32 const PdfDictionary& dict,
33 const char* key,
34 const char* abr,
35 long* data);
36
edisonn@google.coma2fab9d2013-06-14 19:22:19 +000037bool DoubleFromDictionary(const PdfMemDocument* pdfDoc,
38 const PdfDictionary& dict,
39 const char* key,
40 const char* abr,
41 double* data);
42
edisonn@google.comaf3daa02013-06-12 19:07:45 +000043bool BoolFromDictionary(const PdfMemDocument* pdfDoc,
44 const PdfDictionary& dict,
45 const char* key,
46 const char* abr,
47 bool* data);
48
49bool NameFromDictionary(const PdfMemDocument* pdfDoc,
50 const PdfDictionary& dict,
51 const char* key,
52 const char* abr,
53 std::string* data);
54
edisonn@google.coma2fab9d2013-06-14 19:22:19 +000055bool StringFromDictionary(const PdfMemDocument* pdfDoc,
56 const PdfDictionary& dict,
57 const char* key,
58 const char* abr,
59 std::string* data);
60
61class SkPdfDictionary;
62bool DictionaryFromDictionary(const PdfMemDocument* pdfDoc,
63 const PdfDictionary& dict,
64 const char* key,
65 const char* abr,
66 SkPdfDictionary** data);
67
edisonn@google.com68d15c82013-06-17 20:46:27 +000068template <typename T>
69bool DictionaryFromDictionary2(const PdfMemDocument* pdfDoc,
70 const PdfDictionary& dict,
71 const char* key,
72 const char* abr,
73 T** data);
74
edisonn@google.coma2fab9d2013-06-14 19:22:19 +000075class SkPdfObject;
76bool ObjectFromDictionary(const PdfMemDocument* pdfDoc,
77 const PdfDictionary& dict,
78 const char* key,
79 const char* abr,
80 SkPdfObject** data);
edisonn@google.comaf3daa02013-06-12 19:07:45 +000081
82
edisonn@google.com1277cf02013-06-17 23:36:45 +000083struct SkPdfFileSpec {};
84class SkPdfArray;
85struct SkPdfStream {};
86struct SkPdfDate {};
87struct SkPdfTree {};
88struct SkPdfFunction {};
89
90bool ArrayFromDictionary(const PdfMemDocument* pdfDoc,
91 const PdfDictionary& dict,
92 const char* key,
93 const char* abr,
94 SkPdfArray* data);
95
96
97bool FileSpecFromDictionary(const PdfMemDocument* pdfDoc,
98 const PdfDictionary& dict,
99 const char* key,
100 const char* abr,
101 SkPdfFileSpec* data);
102
103
104bool StreamFromDictionary(const PdfMemDocument* pdfDoc,
105 const PdfDictionary& dict,
106 const char* key,
107 const char* abr,
108 SkPdfStream* data);
109
110bool TreeFromDictionary(const PdfMemDocument* pdfDoc,
111 const PdfDictionary& dict,
112 const char* key,
113 const char* abr,
114 SkPdfTree** data);
115
116bool DateFromDictionary(const PdfMemDocument* pdfDoc,
117 const PdfDictionary& dict,
118 const char* key,
119 const char* abr,
120 SkPdfDate* data);
121
122bool SkRectFromDictionary(const PdfMemDocument* pdfDoc,
123 const PdfDictionary& dict,
124 const char* key,
125 const char* abr,
126 SkRect* data);
127
128bool FunctionFromDictionary(const PdfMemDocument* pdfDoc,
129 const PdfDictionary& dict,
130 const char* key,
131 const char* abr,
132 SkPdfFunction* data);
133
134
edisonn@google.com59543d32013-06-18 22:00:40 +0000135#include "SkPdfHeaders_autogen.h"
136#include "SkPdfPodofoMapper_autogen.h"
137#include "SkPdfParser.h"
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000138
edisonn@google.com1277cf02013-06-17 23:36:45 +0000139bool ArrayFromDictionary(const PdfMemDocument* pdfDoc,
140 const PdfDictionary& dict,
141 const char* key,
142 const char* abr,
143 SkPdfArray* data) {return false;}
144
145bool FileSpecFromDictionary(const PdfMemDocument* pdfDoc,
146 const PdfDictionary& dict,
147 const char* key,
148 const char* abr,
149 SkPdfFileSpec* data) {return false;}
150
151bool StreamFromDictionary(const PdfMemDocument* pdfDoc,
152 const PdfDictionary& dict,
153 const char* key,
154 const char* abr,
155 SkPdfStream* data) {return false;}
156
157bool TreeFromDictionary(const PdfMemDocument* pdfDoc,
158 const PdfDictionary& dict,
159 const char* key,
160 const char* abr,
161 SkPdfTree** data) {return false;}
162
163bool DateFromDictionary(const PdfMemDocument* pdfDoc,
164 const PdfDictionary& dict,
165 const char* key,
166 const char* abr,
167 SkPdfDate* data) {return false;}
168
edisonn@google.com1277cf02013-06-17 23:36:45 +0000169bool FunctionFromDictionary(const PdfMemDocument* pdfDoc,
170 const PdfDictionary& dict,
171 const char* key,
172 const char* abr,
173 SkPdfFunction* data) {return false;}
174
175
176
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000177/*
edisonn@google.com68d15c82013-06-17 20:46:27 +0000178 * TODO(edisonn):
179 * - encapsulate podofo in the pdf api so the skpdf does not know anything about podofo
180 * - ASAP so skp -> pdf -> png looks great
181 * - load gs/ especially smask and already known prop (skp)
182 * - use transparency (I think ca and CA ops) (skp)
183 * - all font types
184 * - word spacing
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000185 * - load font for baidu.pdf
186 * - load font for youtube.pdf
187*/
188
edisonn@google.come4d11be2013-06-12 19:53:42 +0000189//#define PDF_TRACE
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000190//#define PDF_TRACE_DIFF_IN_PNG
191//#define PDF_DEBUG_NO_CLIPING
192//#define PDF_DEBUG_NO_PAGE_CLIPING
193//#define PDF_DEBUG_3X
194
195// TODO(edisonn): move in trace util.
196#ifdef PDF_TRACE
197static void SkTraceMatrix(const SkMatrix& matrix, const char* sz = "") {
198 printf("SkMatrix %s ", sz);
199 for (int i = 0 ; i < 9 ; i++) {
200 printf("%f ", SkScalarToDouble(matrix.get(i)));
201 }
202 printf("\n");
203}
204#else
205#define SkTraceMatrix(a,b)
206#endif
207
208using namespace std;
209using namespace PoDoFo;
210
211// Utilities
212static void setup_bitmap(SkBitmap* bitmap, int width, int height, SkColor color = SK_ColorWHITE) {
213 bitmap->setConfig(SkBitmap::kARGB_8888_Config, width, height);
214
215 bitmap->allocPixels();
216 bitmap->eraseColor(color);
217}
218
219// TODO(edisonn): synonyms? DeviceRGB and RGB ...
220int GetColorSpaceComponents(const std::string& colorSpace) {
221 if (colorSpace == "DeviceCMYK") {
222 return 4;
223 } else if (colorSpace == "DeviceGray" ||
224 colorSpace == "CalGray" ||
225 colorSpace == "Indexed") {
226 return 1;
227 } else if (colorSpace == "DeviceRGB" ||
228 colorSpace == "CalRGB" ||
229 colorSpace == "Lab") {
230 return 3;
231 } else {
232 return 0;
233 }
234}
235
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000236const PdfObject* resolveReferenceObject(const PdfMemDocument* pdfDoc,
237 const PdfObject* obj,
edisonn@google.com59543d32013-06-18 22:00:40 +0000238 bool resolveOneElementArrays) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000239 while (obj && (obj->IsReference() || (resolveOneElementArrays &&
240 obj->IsArray() &&
241 obj->GetArray().GetSize() == 1))) {
242 if (obj->IsReference()) {
243 // We need to force the non const, the only update we will do is for recurssion checks.
244 PdfReference& ref = (PdfReference&)obj->GetReference();
245 obj = pdfDoc->GetObjects().GetObject(ref);
246 } else {
247 obj = &obj->GetArray()[0];
248 }
249 }
250
251 return obj;
252}
253
254static SkMatrix SkMatrixFromPdfMatrix(double array[6]) {
255 SkMatrix matrix;
256 matrix.setAll(SkDoubleToScalar(array[0]),
257 SkDoubleToScalar(array[2]),
258 SkDoubleToScalar(array[4]),
259 SkDoubleToScalar(array[1]),
260 SkDoubleToScalar(array[3]),
261 SkDoubleToScalar(array[5]),
262 SkDoubleToScalar(0),
263 SkDoubleToScalar(0),
264 SkDoubleToScalar(1));
265
266 return matrix;
267}
268
269// TODO(edisonn): better class design.
270struct PdfColorOperator {
271 std::string fColorSpace; // TODO(edisonn): use SkString
272 SkColor fColor;
273 // TODO(edisonn): add here other color space options.
274
275 void setRGBColor(SkColor color) {
276 // TODO(edisonn): ASSERT DeviceRGB is the color space.
277 fColor = color;
278 }
279 // TODO(edisonn): double check the default values for all fields.
280 PdfColorOperator() : fColor(SK_ColorBLACK) {}
281};
282
283// TODO(edisonn): better class design.
284struct PdfGraphicsState {
285 SkMatrix fMatrix;
286 SkMatrix fMatrixTm;
287 SkMatrix fMatrixTlm;
288
289 double fCurPosX;
290 double fCurPosY;
291
292 double fCurFontSize;
293 bool fTextBlock;
294 PdfFont* fCurFont;
295 SkPath fPath;
296 bool fPathClosed;
297
298 // Clip that is applied after the drawing is done!!!
299 bool fHasClipPathToApply;
300 SkPath fClipPath;
301
302 PdfColorOperator fStroking;
303 PdfColorOperator fNonStroking;
304
305 double fLineWidth;
306 double fTextLeading;
307 double fWordSpace;
308 double fCharSpace;
309
edisonn@google.com59543d32013-06-18 22:00:40 +0000310 SkPdfResourceDictionary* fResources;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000311
312 SkBitmap fSMask;
313
314 PdfGraphicsState() {
315 fCurPosX = 0.0;
316 fCurPosY = 0.0;
317 fCurFontSize = 0.0;
318 fTextBlock = false;
319 fCurFont = NULL;
320 fMatrix = SkMatrix::I();
321 fMatrixTm = SkMatrix::I();
322 fMatrixTlm = SkMatrix::I();
323 fPathClosed = true;
324 fLineWidth = 0;
325 fTextLeading = 0;
326 fWordSpace = 0;
327 fCharSpace = 0;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000328 fHasClipPathToApply = false;
edisonn@google.com59543d32013-06-18 22:00:40 +0000329 fResources = NULL;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000330 }
331};
332
333// TODO(edisonn): better class design.
334struct PdfInlineImage {
335 std::map<std::string, std::string> fKeyValuePairs;
336 std::string fImageData;
337
338};
339
340// TODO(edisonn): better class design.
341struct PdfContext {
edisonn@google.com59543d32013-06-18 22:00:40 +0000342 std::stack<SkPdfObject*> fObjectStack;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000343 std::stack<PdfGraphicsState> fStateStack;
344 PdfGraphicsState fGraphicsState;
edisonn@google.com59543d32013-06-18 22:00:40 +0000345 SkPdfDoc& fPdfDoc;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000346 SkMatrix fOriginalMatrix;
347
348 PdfInlineImage fInlineImage;
349
edisonn@google.com59543d32013-06-18 22:00:40 +0000350 PdfContext(SkPdfDoc& doc) : fPdfDoc(doc) {}
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000351
352};
353
354// TODO(edisonn): temporary code, to report how much of the PDF we actually think we rendered.
355enum PdfResult {
356 kOK_PdfResult,
357 kPartial_PdfResult,
358 kNYI_PdfResult,
359 kIgnoreError_PdfResult,
360 kError_PdfResult,
361 kUnsupported_PdfResult,
362
363 kCount_PdfResult
364};
365
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000366PdfContext* gPdfContext = NULL;
367SkBitmap* gDumpBitmap = NULL;
368SkCanvas* gDumpCanvas = NULL;
369char gLastKeyword[100] = "";
370int gLastOpKeyword = -1;
edisonn@google.com59543d32013-06-18 22:00:40 +0000371char allOpWithVisualEffects[100] = ",S,s,f,F,f*,B,B*,b,b*,n,Tj,TJ,\',\",d0,d1,sh,EI,Do,EX,";
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000372int gReadOp = 0;
373
374
375
376bool hasVisualEffect(const char* pdfOp) {
377 return true;
378 if (*pdfOp == '\0') return false;
379
380 char markedPdfOp[100] = ",";
381 strcat(markedPdfOp, pdfOp);
382 strcat(markedPdfOp, ",");
383
384 return (strstr(allOpWithVisualEffects, markedPdfOp) != NULL);
385}
386
387// TODO(edisonn): Pass PdfContext and SkCanvasd only with the define for instrumentation.
edisonn@google.com59543d32013-06-18 22:00:40 +0000388static bool readToken(SkPdfTokenizer fTokenizer, PdfToken* token) {
389 bool ret = fTokenizer.readToken(token);
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000390
391 gReadOp++;
392
393#ifdef PDF_TRACE_DIFF_IN_PNG
394 // TODO(edisonn): compare with old bitmap, and save only new bits are available, and save
395 // the numbar and name of last operation, so the file name will reflect op that changed.
396 if (hasVisualEffect(gLastKeyword)) { // TODO(edisonn): and has dirty bits.
397 gDumpCanvas->flush();
398
399 SkBitmap bitmap;
400 setup_bitmap(&bitmap, gDumpBitmap->width(), gDumpBitmap->height());
401
402 memcpy(bitmap.getPixels(), gDumpBitmap->getPixels(), gDumpBitmap->getSize());
403
404 SkAutoTUnref<SkDevice> device(SkNEW_ARGS(SkDevice, (bitmap)));
405 SkCanvas canvas(device);
406
407 // draw context stuff here
408 SkPaint blueBorder;
409 blueBorder.setColor(SK_ColorBLUE);
410 blueBorder.setStyle(SkPaint::kStroke_Style);
411 blueBorder.setTextSize(SkDoubleToScalar(20));
412
413 SkString str;
414
415 const SkClipStack* clipStack = gDumpCanvas->getClipStack();
416 if (clipStack) {
417 SkClipStack::Iter iter(*clipStack, SkClipStack::Iter::kBottom_IterStart);
418 const SkClipStack::Element* elem;
419 double y = 0;
420 int total = 0;
421 while (elem = iter.next()) {
422 total++;
423 y += 30;
424
425 switch (elem->getType()) {
426 case SkClipStack::Element::kRect_Type:
427 canvas.drawRect(elem->getRect(), blueBorder);
428 canvas.drawText("Rect Clip", strlen("Rect Clip"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
429 break;
430 case SkClipStack::Element::kPath_Type:
431 canvas.drawPath(elem->getPath(), blueBorder);
432 canvas.drawText("Path Clip", strlen("Path Clip"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
433 break;
434 case SkClipStack::Element::kEmpty_Type:
435 canvas.drawText("Empty Clip!!!", strlen("Empty Clip!!!"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
436 break;
437 default:
438 canvas.drawText("Unkown Clip!!!", strlen("Unkown Clip!!!"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
439 break;
440 }
441 }
442
443 y += 30;
444 str.printf("Number of clips in stack: %i", total);
445 canvas.drawText(str.c_str(), str.size(), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
446 }
447
448 const SkRegion& clipRegion = gDumpCanvas->getTotalClip();
449 SkPath clipPath;
450 if (clipRegion.getBoundaryPath(&clipPath)) {
451 SkPaint redBorder;
452 redBorder.setColor(SK_ColorRED);
453 redBorder.setStyle(SkPaint::kStroke_Style);
454 canvas.drawPath(clipPath, redBorder);
455 }
456
457 canvas.flush();
458
459 SkString out;
460
461 // TODO(edisonn): get the image, and overlay on top of it, the clip , grafic state, teh stack,
462 // ... and other properties, to be able to debug th code easily
463
464 out.appendf("/usr/local/google/home/edisonn/log_view2/step-%i-%s.png", gLastOpKeyword, gLastKeyword);
465 SkImageEncoder::EncodeFile(out.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100);
466 }
467
edisonn@google.com59543d32013-06-18 22:00:40 +0000468 if (token->fType == kKeyword_TokenType) {
469 strcpy(gLastKeyword, token->fKeyword);
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000470 gLastOpKeyword = gReadOp;
471 } else {
472 strcpy(gLastKeyword, "");
473 }
474#endif
475
476 return ret;
477}
478
479// TODO(edisonn): Document PdfTokenLooper and subclasses.
480class PdfTokenLooper {
481protected:
482 PdfTokenLooper* fParent;
edisonn@google.com59543d32013-06-18 22:00:40 +0000483 SkPdfTokenizer fTokenizer;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000484 PdfContext* fPdfContext;
485 SkCanvas* fCanvas;
486
487public:
488 PdfTokenLooper(PdfTokenLooper* parent,
edisonn@google.com59543d32013-06-18 22:00:40 +0000489 SkPdfTokenizer tokenizer,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000490 PdfContext* pdfContext,
491 SkCanvas* canvas)
492 : fParent(parent), fTokenizer(tokenizer), fPdfContext(pdfContext), fCanvas(canvas) {}
493
494 virtual PdfResult consumeToken(PdfToken& token) = 0;
495 virtual void loop() = 0;
496
497 void setUp(PdfTokenLooper* parent) {
498 fParent = parent;
499 fTokenizer = parent->fTokenizer;
500 fPdfContext = parent->fPdfContext;
501 fCanvas = parent->fCanvas;
502 }
503};
504
505class PdfMainLooper : public PdfTokenLooper {
506public:
507 PdfMainLooper(PdfTokenLooper* parent,
edisonn@google.com59543d32013-06-18 22:00:40 +0000508 SkPdfTokenizer tokenizer,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000509 PdfContext* pdfContext,
510 SkCanvas* canvas)
511 : PdfTokenLooper(parent, tokenizer, pdfContext, canvas) {}
512
513 virtual PdfResult consumeToken(PdfToken& token);
514 virtual void loop();
515};
516
517class PdfInlineImageLooper : public PdfTokenLooper {
518public:
519 PdfInlineImageLooper()
edisonn@google.com59543d32013-06-18 22:00:40 +0000520 : PdfTokenLooper(NULL, SkPdfTokenizer(), NULL, NULL) {}
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000521
522 virtual PdfResult consumeToken(PdfToken& token);
523 virtual void loop();
524 PdfResult done();
525};
526
527class PdfCompatibilitySectionLooper : public PdfTokenLooper {
528public:
529 PdfCompatibilitySectionLooper()
edisonn@google.com59543d32013-06-18 22:00:40 +0000530 : PdfTokenLooper(NULL, SkPdfTokenizer(), NULL, NULL) {}
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000531
532 virtual PdfResult consumeToken(PdfToken& token);
533 virtual void loop();
534};
535
536typedef PdfResult (*PdfOperatorRenderer)(PdfContext*, SkCanvas*, PdfTokenLooper**);
537
538map<std::string, PdfOperatorRenderer> gPdfOps;
539
540map<std::string, int> gRenderStats[kCount_PdfResult];
541
542char* gRenderStatsNames[kCount_PdfResult] = {
543 "Success",
544 "Partially implemented",
545 "Not yet implemented",
546 "Ignore Error",
547 "Error",
548 "Unsupported/Unknown"
549};
550
551struct SkPdfStandardFont {
552 const char* fName;
553 bool fIsBold;
554 bool fIsItalic;
555};
556
557static map<std::string, SkPdfStandardFont>& getStandardFonts() {
558 static std::map<std::string, SkPdfStandardFont> gPdfStandardFonts;
559
560 // TODO (edisonn): , vs - ? what does it mean?
561 // TODO (edisonn): MT, PS, Oblique=italic?, ... what does it mean?
562 if (gPdfStandardFonts.empty()) {
563 gPdfStandardFonts["Arial"] = {"Arial", false, false};
564 gPdfStandardFonts["Arial,Bold"] = {"Arial", true, false};
565 gPdfStandardFonts["Arial,BoldItalic"] = {"Arial", true, true};
566 gPdfStandardFonts["Arial,Italic"] = {"Arial", false, true};
567 gPdfStandardFonts["Arial-Bold"] = {"Arial", true, false};
568 gPdfStandardFonts["Arial-BoldItalic"] = {"Arial", true, true};
569 gPdfStandardFonts["Arial-BoldItalicMT"] = {"Arial", true, true};
570 gPdfStandardFonts["Arial-BoldMT"] = {"Arial", true, false};
571 gPdfStandardFonts["Arial-Italic"] = {"Arial", false, true};
572 gPdfStandardFonts["Arial-ItalicMT"] = {"Arial", false, true};
573 gPdfStandardFonts["ArialMT"] = {"Arial", false, false};
574 gPdfStandardFonts["Courier"] = {"Courier New", false, false};
575 gPdfStandardFonts["Courier,Bold"] = {"Courier New", true, false};
576 gPdfStandardFonts["Courier,BoldItalic"] = {"Courier New", true, true};
577 gPdfStandardFonts["Courier,Italic"] = {"Courier New", false, true};
578 gPdfStandardFonts["Courier-Bold"] = {"Courier New", true, false};
579 gPdfStandardFonts["Courier-BoldOblique"] = {"Courier New", true, true};
580 gPdfStandardFonts["Courier-Oblique"] = {"Courier New", false, true};
581 gPdfStandardFonts["CourierNew"] = {"Courier New", false, false};
582 gPdfStandardFonts["CourierNew,Bold"] = {"Courier New", true, false};
583 gPdfStandardFonts["CourierNew,BoldItalic"] = {"Courier New", true, true};
584 gPdfStandardFonts["CourierNew,Italic"] = {"Courier New", false, true};
585 gPdfStandardFonts["CourierNew-Bold"] = {"Courier New", true, false};
586 gPdfStandardFonts["CourierNew-BoldItalic"] = {"Courier New", true, true};
587 gPdfStandardFonts["CourierNew-Italic"] = {"Courier New", false, true};
588 gPdfStandardFonts["CourierNewPS-BoldItalicMT"] = {"Courier New", true, true};
589 gPdfStandardFonts["CourierNewPS-BoldMT"] = {"Courier New", true, false};
590 gPdfStandardFonts["CourierNewPS-ItalicMT"] = {"Courier New", false, true};
591 gPdfStandardFonts["CourierNewPSMT"] = {"Courier New", false, false};
592 gPdfStandardFonts["Helvetica"] = {"Helvetica", false, false};
593 gPdfStandardFonts["Helvetica,Bold"] = {"Helvetica", true, false};
594 gPdfStandardFonts["Helvetica,BoldItalic"] = {"Helvetica", true, true};
595 gPdfStandardFonts["Helvetica,Italic"] = {"Helvetica", false, true};
596 gPdfStandardFonts["Helvetica-Bold"] = {"Helvetica", true, false};
597 gPdfStandardFonts["Helvetica-BoldItalic"] = {"Helvetica", true, true};
598 gPdfStandardFonts["Helvetica-BoldOblique"] = {"Helvetica", true, true};
599 gPdfStandardFonts["Helvetica-Italic"] = {"Helvetica", false, true};
600 gPdfStandardFonts["Helvetica-Oblique"] = {"Helvetica", false, true};
601 gPdfStandardFonts["Times-Bold"] = {"Times", true, false};
602 gPdfStandardFonts["Times-BoldItalic"] = {"Times", true, true};
603 gPdfStandardFonts["Times-Italic"] = {"Times", false, true};
604 gPdfStandardFonts["Times-Roman"] = {"Times New Roman", false, false};
605 gPdfStandardFonts["TimesNewRoman"] = {"Times New Roman", false, false};
606 gPdfStandardFonts["TimesNewRoman,Bold"] = {"Times New Roman", true, false};
607 gPdfStandardFonts["TimesNewRoman,BoldItalic"] = {"Times New Roman", true, true};
608 gPdfStandardFonts["TimesNewRoman,Italic"] = {"Times New Roman", false, true};
609 gPdfStandardFonts["TimesNewRoman-Bold"] = {"Times New Roman", true, false};
610 gPdfStandardFonts["TimesNewRoman-BoldItalic"] = {"Times New Roman", true, true};
611 gPdfStandardFonts["TimesNewRoman-Italic"] = {"Times New Roman", false, true};
612 gPdfStandardFonts["TimesNewRomanPS"] = {"Times New Roman", false, false};
613 gPdfStandardFonts["TimesNewRomanPS-Bold"] = {"Times New Roman", true, false};
614 gPdfStandardFonts["TimesNewRomanPS-BoldItalic"] = {"Times New Roman", true, true};
615 gPdfStandardFonts["TimesNewRomanPS-BoldItalicMT"] = {"Times New Roman", true, true};
616 gPdfStandardFonts["TimesNewRomanPS-BoldMT"] = {"Times New Roman", true, false};
617 gPdfStandardFonts["TimesNewRomanPS-Italic"] = {"Times New Roman", false, true};
618 gPdfStandardFonts["TimesNewRomanPS-ItalicMT"] = {"Times New Roman", false, true};
619 gPdfStandardFonts["TimesNewRomanPSMT"] = {"Times New Roman", false, false};
620 }
621
622 return gPdfStandardFonts;
623}
624
625static SkTypeface* SkTypefaceFromPdfStandardFont(const char* fontName, bool bold, bool italic) {
626 map<std::string, SkPdfStandardFont>& standardFontMap = getStandardFonts();
627
628 if (standardFontMap.find(fontName) != standardFontMap.end()) {
629 SkPdfStandardFont fontData = standardFontMap[fontName];
630
631 // TODO(edisonn): How does the bold/italic specified in standard definition combines with
632 // the one in /font key? use OR for now.
633 bold = bold || fontData.fIsBold;
634 italic = italic || fontData.fIsItalic;
635
636 SkTypeface* typeface = SkTypeface::CreateFromName(
637 fontData.fName,
638 SkTypeface::Style((bold ? SkTypeface::kBold : 0) |
639 (italic ? SkTypeface::kItalic : 0)));
640 if (typeface) {
641 typeface->ref();
642 }
643 return typeface;
644 }
645 return NULL;
646}
647
648static SkTypeface* SkTypefaceFromPdfFont(PdfFont* font) {
649 PdfObject* fontObject = font->GetObject();
650
651 PdfObject* pBaseFont = NULL;
652 // TODO(edisonn): warning, PoDoFo has a bug in PdfFont constructor, does not call InitVars()
653 // for now fixed locally.
654 pBaseFont = fontObject->GetIndirectKey( "BaseFont" );
655 const char* pszBaseFontName = pBaseFont->GetName().GetName().c_str();
656
657#ifdef PDF_TRACE
658 std::string str;
659 fontObject->ToString(str);
660 printf("Base Font Name: %s\n", pszBaseFontName);
661 printf("Font Object Data: %s\n", str.c_str());
662#endif
663
664 SkTypeface* typeface = SkTypefaceFromPdfStandardFont(pszBaseFontName, font->IsBold(), font->IsItalic());
665
666 if (typeface != NULL) {
667 return typeface;
668 }
669
670 char name[1000];
671 // HACK
672 strncpy(name, pszBaseFontName, 1000);
673 char* comma = strstr(name, ",");
674 char* dash = strstr(name, "-");
675 if (comma) *comma = '\0';
676 if (dash) *dash = '\0';
677
678 typeface = SkTypeface::CreateFromName(
679 name,
680 SkTypeface::Style((font->IsBold() ? SkTypeface::kBold : 0) |
681 (font->IsItalic() ? SkTypeface::kItalic : 0)));
682
683 if (typeface != NULL) {
684#ifdef PDF_TRACE
685 printf("HACKED FONT found %s\n", name);
686#endif
687 return typeface;
688 }
689
690#ifdef PDF_TRACE
691 printf("FONT_NOT_FOUND %s\n", pszBaseFontName);
692#endif
693
694 // TODO(edisonn): Report Warning, NYI
695 return SkTypeface::CreateFromName(
696 "Times New Roman",
697 SkTypeface::Style((font->IsBold() ? SkTypeface::kBold : 0) |
698 (font->IsItalic() ? SkTypeface::kItalic : 0)));
699}
700
701// TODO(edisonn): move this code in podofo, so we don't have to fix the font.
702// This logic needs to be moved in PdfEncodingObjectFactory::CreateEncoding
703std::map<PdfFont*, PdfCMapEncoding*> gFontsFixed;
704PdfEncoding* FixPdfFont(PdfContext* pdfContext, PdfFont* fCurFont) {
705 // TODO(edisonn): and is Identity-H
706 if (gFontsFixed.find(fCurFont) == gFontsFixed.end()) {
707 if (fCurFont->GetObject()->IsDictionary() && fCurFont->GetObject()->GetDictionary().HasKey(PdfName("ToUnicode"))) {
708 PdfCMapEncoding* enc = new PdfCMapEncoding(
709 fCurFont->GetObject(),
edisonn@google.com59543d32013-06-18 22:00:40 +0000710 (PdfObject*)resolveReferenceObject(&pdfContext->fPdfDoc.podofo(),
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000711 fCurFont->GetObject()->GetDictionary().GetKey(PdfName("ToUnicode"))),
712 PdfCMapEncoding::eBaseEncoding_Identity); // todo, read the base encoding
713 gFontsFixed[fCurFont] = enc;
714 return enc;
715 }
716
717 return NULL;
718 }
719
720 return gFontsFixed[fCurFont];
721}
722
723PdfResult DrawText(PdfContext* pdfContext,
724 PdfFont* fCurFont,
725 const PdfString& rString,
726 SkCanvas* canvas)
727{
728 if (!fCurFont)
729 {
730 // TODO(edisonn): ignore the error, use the default font?
731 return kError_PdfResult;
732 }
733
734 const PdfEncoding* enc = FixPdfFont(pdfContext, fCurFont);
735 bool cMapUnicodeFont = enc != NULL;
736 if (!enc) enc = fCurFont->GetEncoding();
737 if (!enc)
738 {
739 // TODO(edisonn): Can we recover from this error?
740 return kError_PdfResult;
741 }
742
743 PdfString r2 = rString;
744 PdfString unicode;
745
746 if (cMapUnicodeFont) {
747 r2 = PdfString((pdf_utf16be*)rString.GetString(), rString.GetLength() / 2);
748 }
749
750 unicode = enc->ConvertToUnicode( r2, fCurFont );
751
752#ifdef PDF_TRACE
753 printf("%i %i ? %c rString.len = %i\n", (int)rString.GetString()[0], (int)rString.GetString()[1], (int)rString.GetString()[1], rString.GetLength());
754 printf("%i %i %i %i %c unicode.len = %i\n", (int)unicode.GetString()[0], (int)unicode.GetString()[1], (int)unicode.GetString()[2], (int)unicode.GetString()[3], (int)unicode.GetString()[0], unicode.GetLength());
755#endif
756
757 SkPaint paint;
758 // TODO(edisonn): when should fCurFont->GetFontSize() used? When cur is fCurFontSize == 0?
759 // Or maybe just not call setTextSize at all?
760 if (pdfContext->fGraphicsState.fCurFontSize != 0) {
761 paint.setTextSize(SkDoubleToScalar(pdfContext->fGraphicsState.fCurFontSize));
762 }
763 if (fCurFont->GetFontScale() != 0) {
764 paint.setTextScaleX(SkFloatToScalar(fCurFont->GetFontScale() / 100.0));
765 }
766 paint.setColor(pdfContext->fGraphicsState.fNonStroking.fColor);
767
768 paint.setTypeface(SkTypefaceFromPdfFont(fCurFont));
769
770 paint.setAntiAlias(true);
771 // TODO(edisonn): paint.setStyle(...);
772
773 canvas->save();
774 SkMatrix matrix = pdfContext->fGraphicsState.fMatrixTm;
775
776#if 0
777 // Reverse now the space, otherwise the text is upside down.
778 SkScalar z = SkIntToScalar(0);
779 SkScalar one = SkIntToScalar(1);
780
781 SkPoint normalSpace1[4] = {SkPoint::Make(z, z), SkPoint::Make(one, z), SkPoint::Make(one, one), SkPoint::Make(z, one)};
782 SkPoint mirrorSpace1[4];
783 pdfContext->fGraphicsState.fMatrixTm.mapPoints(mirrorSpace1, normalSpace1, 4);
784
785 SkPoint normalSpace2[4] = {SkPoint::Make(z, z), SkPoint::Make(one, z), SkPoint::Make(one, -one), SkPoint::Make(z, -one)};
786 SkPoint mirrorSpace2[4];
787 pdfContext->fGraphicsState.fMatrixTm.mapPoints(mirrorSpace2, normalSpace2, 4);
788
789#ifdef PDF_TRACE
790 printf("mirror1[0], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[0].x()), SkScalarToDouble(mirrorSpace1[0].y()));
791 printf("mirror1[1], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[1].x()), SkScalarToDouble(mirrorSpace1[1].y()));
792 printf("mirror1[2], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[2].x()), SkScalarToDouble(mirrorSpace1[2].y()));
793 printf("mirror1[3], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[3].x()), SkScalarToDouble(mirrorSpace1[3].y()));
794 printf("mirror2[0], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[0].x()), SkScalarToDouble(mirrorSpace2[0].y()));
795 printf("mirror2[1], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[1].x()), SkScalarToDouble(mirrorSpace2[1].y()));
796 printf("mirror2[2], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[2].x()), SkScalarToDouble(mirrorSpace2[2].y()));
797 printf("mirror2[3], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[3].x()), SkScalarToDouble(mirrorSpace2[3].y()));
798#endif
799
800 SkMatrix mirror;
801 SkASSERT(mirror.setPolyToPoly(mirrorSpace1, mirrorSpace2, 4));
802
803 // TODO(edisonn): text positioning wrong right now. Need to get matrix operations right.
804 matrix.preConcat(mirror);
805 canvas->setMatrix(matrix);
806#endif
807
808 SkPoint point1;
809 pdfContext->fGraphicsState.fMatrixTm.mapXY(SkIntToScalar(0), SkIntToScalar(0), &point1);
810
811 SkMatrix mirror;
812 mirror.setTranslate(0, -point1.y());
813 // TODO(edisonn): fix rotated text, and skewed too
814 mirror.postScale(SK_Scalar1, -SK_Scalar1);
815 // TODO(edisonn): post rotate, skew
816 mirror.postTranslate(0, point1.y());
817
818 matrix.postConcat(mirror);
819
820 canvas->setMatrix(matrix);
821
822 SkTraceMatrix(matrix, "mirrored");
823
824#ifdef PDF_TRACE
825 SkPoint point;
826 pdfContext->fGraphicsState.fMatrixTm.mapXY(SkDoubleToScalar(0), SkDoubleToScalar(0), &point);
827 printf("Original SkCanvas resolved coordinates, x = %f y = %f\n", SkScalarToDouble(point.x()), SkScalarToDouble(point.y()));
828 matrix.mapXY(SkDoubleToScalar(0), SkDoubleToScalar(0), &point);
829 printf("Mirored SkCanvas resolved coordinates, x = %f y = %f\n", SkScalarToDouble(point.x()), SkScalarToDouble(point.y()));
830#endif
831
832 // TODO(edisonn): remove this call once we load the font properly
833 // The extra * will show that we got at least the text positioning right
834 // even if font failed to be loaded
835// canvas->drawText(".", 1, SkDoubleToScalar(-5.0), SkDoubleToScalar(0.0), paint);
836
837
838
839 // TODO(edisonn): use character and word spacing .. add utility function
840 if (cMapUnicodeFont) {
841 paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
842 SkScalar textWidth = paint.measureText(unicode.GetString(), unicode.GetLength());
843 pdfContext->fGraphicsState.fMatrixTm.preTranslate(textWidth, SkDoubleToScalar(0.0));
844 canvas->drawText(unicode.GetString(), unicode.GetLength(), SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), paint);
845 }
846 else {
847 paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
848 SkScalar textWidth = paint.measureText(unicode.GetStringUtf8().c_str(), strlen(unicode.GetStringUtf8().c_str()));
849 pdfContext->fGraphicsState.fMatrixTm.preTranslate(textWidth, SkDoubleToScalar(0.0));
850 canvas->drawText(unicode.GetStringUtf8().c_str(), strlen(unicode.GetStringUtf8().c_str()), SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), paint);
851 }
852
853// paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
854// unsigned char ch = *(unicode.GetString() + 3);
855// if ((ch & 0xC0) != 0x80 && ch < 0x80) {
856// printf("x%i", ch);
857// SkScalar textWidth = paint.measureText(&ch, 1);
858// pdfContext->fGraphicsState.fMatrixTm.preTranslate(textWidth, SkDoubleToScalar(0.0));
859// canvas->drawText(&ch, 1, SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), paint);
860// }
861
862 canvas->restore();
863
864
865 return kPartial_PdfResult;
866}
867
868// TODO(edisonn): create header files with declarations!
869PdfResult PdfOp_q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
870PdfResult PdfOp_Q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
871PdfResult PdfOp_Tw(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
872PdfResult PdfOp_Tc(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
873
874// TODO(edisonn): deal with synonyms (/BPC == /BitsPerComponent), here or in GetKey?
875// Always pass long form in key, and have a map of long -> short key
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000876bool LongFromDictionary(const PdfMemDocument* pdfDoc,
877 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000878 const char* key,
879 long* data) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000880 const PdfObject* value = resolveReferenceObject(pdfDoc,
881 dict.GetKey(PdfName(key)));
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000882
883 if (value == NULL || !value->IsNumber()) {
884 return false;
885 }
886
887 *data = value->GetNumber();
888 return true;
889}
890
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000891bool LongFromDictionary(const PdfMemDocument* pdfDoc,
892 const PdfDictionary& dict,
893 const char* key,
894 const char* abr,
895 long* data) {
896 if (LongFromDictionary(pdfDoc, dict, key, data)) return true;
897 if (abr == NULL || *abr == '\0') return false;
898 return LongFromDictionary(pdfDoc, dict, abr, data);
899}
900
edisonn@google.coma2fab9d2013-06-14 19:22:19 +0000901bool DoubleFromDictionary(const PdfMemDocument* pdfDoc,
902 const PdfDictionary& dict,
903 const char* key,
904 double* data) {
905 const PdfObject* value = resolveReferenceObject(pdfDoc,
906 dict.GetKey(PdfName(key)));
907
908 if (value == NULL || !value->IsReal()) {
909 return false;
910 }
911
912 *data = value->GetReal();
913 return true;
914}
915
916bool DoubleFromDictionary(const PdfMemDocument* pdfDoc,
917 const PdfDictionary& dict,
918 const char* key,
919 const char* abr,
920 double* data) {
921 if (DoubleFromDictionary(pdfDoc, dict, key, data)) return true;
922 if (abr == NULL || *abr == '\0') return false;
923 return DoubleFromDictionary(pdfDoc, dict, abr, data);
924}
925
926
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000927bool BoolFromDictionary(const PdfMemDocument* pdfDoc,
928 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000929 const char* key,
930 bool* data) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000931 const PdfObject* value = resolveReferenceObject(pdfDoc,
932 dict.GetKey(PdfName(key)));
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000933
934 if (value == NULL || !value->IsBool()) {
935 return false;
936 }
937
938 *data = value->GetBool();
939 return true;
940}
941
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000942bool BoolFromDictionary(const PdfMemDocument* pdfDoc,
943 const PdfDictionary& dict,
944 const char* key,
945 const char* abr,
946 bool* data) {
947 if (BoolFromDictionary(pdfDoc, dict, key, data)) return true;
948 if (abr == NULL || *abr == '\0') return false;
949 return BoolFromDictionary(pdfDoc, dict, abr, data);
950}
951
952bool NameFromDictionary(const PdfMemDocument* pdfDoc,
953 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000954 const char* key,
955 std::string* data) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000956 const PdfObject* value = resolveReferenceObject(pdfDoc,
957 dict.GetKey(PdfName(key)),
958 true);
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000959 if (value == NULL || !value->IsName()) {
960 return false;
961 }
962
963 *data = value->GetName().GetName();
964 return true;
965}
966
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000967bool NameFromDictionary(const PdfMemDocument* pdfDoc,
968 const PdfDictionary& dict,
969 const char* key,
970 const char* abr,
971 std::string* data) {
972 if (NameFromDictionary(pdfDoc, dict, key, data)) return true;
973 if (abr == NULL || *abr == '\0') return false;
974 return NameFromDictionary(pdfDoc, dict, abr, data);
975}
976
edisonn@google.coma2fab9d2013-06-14 19:22:19 +0000977bool StringFromDictionary(const PdfMemDocument* pdfDoc,
978 const PdfDictionary& dict,
979 const char* key,
980 std::string* data) {
981 const PdfObject* value = resolveReferenceObject(pdfDoc,
982 dict.GetKey(PdfName(key)),
983 true);
984 if (value == NULL || (!value->IsString() && !value->IsHexString())) {
985 return false;
986 }
987
988 *data = value->GetString().GetString();
989 return true;
990}
991
992bool StringFromDictionary(const PdfMemDocument* pdfDoc,
993 const PdfDictionary& dict,
994 const char* key,
995 const char* abr,
996 std::string* data) {
997 if (StringFromDictionary(pdfDoc, dict, key, data)) return true;
998 if (abr == NULL || *abr == '\0') return false;
999 return StringFromDictionary(pdfDoc, dict, abr, data);
1000}
1001
1002bool DictionaryFromDictionary(const PdfMemDocument* pdfDoc,
1003 const PdfDictionary& dict,
1004 const char* key,
1005 SkPdfDictionary** data) {
1006 const PdfObject* value = resolveReferenceObject(pdfDoc,
1007 dict.GetKey(PdfName(key)),
1008 true);
1009 if (value == NULL || !value->IsDictionary()) {
1010 return false;
1011 }
1012
edisonn@google.com68d15c82013-06-17 20:46:27 +00001013 return PodofoMapper::map(*pdfDoc, *value, (SkPdfObject**)data);
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001014}
1015
1016bool DictionaryFromDictionary(const PdfMemDocument* pdfDoc,
1017 const PdfDictionary& dict,
1018 const char* key,
1019 const char* abr,
1020 SkPdfDictionary** data) {
1021 if (DictionaryFromDictionary(pdfDoc, dict, key, data)) return true;
1022 if (abr == NULL || *abr == '\0') return false;
1023 return DictionaryFromDictionary(pdfDoc, dict, abr, data);
1024}
1025
edisonn@google.com68d15c82013-06-17 20:46:27 +00001026template <typename T>
1027bool DictionaryFromDictionary2(const PdfMemDocument* pdfDoc,
1028 const PdfDictionary& dict,
1029 const char* key,
1030 SkPdfDictionary** data) {
1031 const PdfObject* value = resolveReferenceObject(pdfDoc,
1032 dict.GetKey(PdfName(key)),
1033 true);
1034 if (value == NULL || !value->IsDictionary()) {
1035 return false;
1036 }
1037
1038 return PodofoMapper::map(*pdfDoc, *value, (T**)data);
1039}
1040
1041template <typename T>
1042bool DictionaryFromDictionary2(const PdfMemDocument* pdfDoc,
1043 const PdfDictionary& dict,
1044 const char* key,
1045 const char* abr,
1046 T** data) {
1047 if (DictionaryFromDictionary2<T>(pdfDoc, dict, key, data)) return true;
1048 if (abr == NULL || *abr == '\0') return false;
1049 return DictionaryFromDictionary2<T>(pdfDoc, dict, abr, data);
1050}
1051
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001052bool ObjectFromDictionary(const PdfMemDocument* pdfDoc,
1053 const PdfDictionary& dict,
1054 const char* key,
1055 SkPdfObject** data) {
1056 const PdfObject* value = resolveReferenceObject(pdfDoc,
1057 dict.GetKey(PdfName(key)),
1058 true);
1059 if (value == NULL) {
1060 return false;
1061 }
edisonn@google.com68d15c82013-06-17 20:46:27 +00001062 return PodofoMapper::map(*pdfDoc, *value, data);
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001063}
1064
1065bool ObjectFromDictionary(const PdfMemDocument* pdfDoc,
1066 const PdfDictionary& dict,
1067 const char* key,
1068 const char* abr,
1069 SkPdfObject** data) {
1070 if (ObjectFromDictionary(pdfDoc, dict, key, data)) return true;
1071 if (abr == NULL || *abr == '\0') return false;
1072 return ObjectFromDictionary(pdfDoc, dict, abr, data);
1073}
1074
1075
edisonn@google.com68d15c82013-06-17 20:46:27 +00001076
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001077// TODO(edisonn): perf!!!
1078
1079static SkColorTable* getGrayColortable() {
1080 static SkColorTable* grayColortable = NULL;
1081 if (grayColortable == NULL) {
1082 SkPMColor* colors = new SkPMColor[256];
1083 for (int i = 0 ; i < 256; i++) {
1084 colors[i] = SkPreMultiplyARGB(255, i, i, i);
1085 }
1086 grayColortable = new SkColorTable(colors, 256);
1087 }
1088 return grayColortable;
1089}
1090
1091SkBitmap transferImageStreamToBitmap(unsigned char* uncompressedStream, pdf_long uncompressedStreamLength,
1092 int width, int height, int bytesPerLine,
1093 int bpc, const std::string& colorSpace,
1094 bool transparencyMask) {
1095 SkBitmap bitmap;
1096
1097 int components = GetColorSpaceComponents(colorSpace);
1098//#define MAX_COMPONENTS 10
1099
1100 int bitsPerLine = width * components * bpc;
1101 // TODO(edisonn): assume start of lines are aligned at 32 bits?
1102 // Is there a faster way to load the uncompressed stream into a bitmap?
1103
1104 // minimal support for now
1105 if ((colorSpace == "DeviceRGB" || colorSpace == "RGB") && bpc == 8) {
1106 SkColor* uncompressedStreamArgb = (SkColor*)malloc(width * height * sizeof(SkColor));
1107
1108 for (int h = 0 ; h < height; h++) {
1109 long i = width * (height - 1 - h);
1110 for (int w = 0 ; w < width; w++) {
1111 uncompressedStreamArgb[i] = SkColorSetRGB(uncompressedStream[3 * w],
1112 uncompressedStream[3 * w + 1],
1113 uncompressedStream[3 * w + 2]);
1114 i++;
1115 }
1116 uncompressedStream += bytesPerLine;
1117 }
1118
1119 bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
1120 bitmap.setPixels(uncompressedStreamArgb);
1121 }
1122 else if ((colorSpace == "DeviceGray" || colorSpace == "Gray") && bpc == 8) {
1123 unsigned char* uncompressedStreamA8 = (unsigned char*)malloc(width * height);
1124
1125 for (int h = 0 ; h < height; h++) {
1126 long i = width * (height - 1 - h);
1127 for (int w = 0 ; w < width; w++) {
1128 uncompressedStreamA8[i] = transparencyMask ? 255 - uncompressedStream[w] :
1129 uncompressedStream[w];
1130 i++;
1131 }
1132 uncompressedStream += bytesPerLine;
1133 }
1134
1135 bitmap.setConfig(transparencyMask ? SkBitmap::kA8_Config : SkBitmap::kIndex8_Config,
1136 width, height);
1137 bitmap.setPixels(uncompressedStreamA8, transparencyMask ? NULL : getGrayColortable());
1138 }
1139
1140 // TODO(edisonn): Report Warning, NYI, or error
1141 return bitmap;
1142}
1143
1144bool transferImageStreamToARGB(unsigned char* uncompressedStream, pdf_long uncompressedStreamLength,
1145 int width, int bytesPerLine,
1146 int bpc, const std::string& colorSpace,
1147 SkColor** uncompressedStreamArgb,
1148 pdf_long* uncompressedStreamLengthInBytesArgb) {
1149 int components = GetColorSpaceComponents(colorSpace);
1150//#define MAX_COMPONENTS 10
1151
1152 int bitsPerLine = width * components * bpc;
1153 // TODO(edisonn): assume start of lines are aligned at 32 bits?
1154 int height = uncompressedStreamLength / bytesPerLine;
1155
1156 // minimal support for now
1157 if ((colorSpace == "DeviceRGB" || colorSpace == "RGB") && bpc == 8) {
1158 *uncompressedStreamLengthInBytesArgb = width * height * 4;
1159 *uncompressedStreamArgb = (SkColor*)malloc(*uncompressedStreamLengthInBytesArgb);
1160
1161 for (int h = 0 ; h < height; h++) {
1162 long i = width * (height - 1 - h);
1163 for (int w = 0 ; w < width; w++) {
1164 (*uncompressedStreamArgb)[i] = SkColorSetRGB(uncompressedStream[3 * w],
1165 uncompressedStream[3 * w + 1],
1166 uncompressedStream[3 * w + 2]);
1167 i++;
1168 }
1169 uncompressedStream += bytesPerLine;
1170 }
1171 return true;
1172 }
1173
1174 if ((colorSpace == "DeviceGray" || colorSpace == "Gray") && bpc == 8) {
1175 *uncompressedStreamLengthInBytesArgb = width * height * 4;
1176 *uncompressedStreamArgb = (SkColor*)malloc(*uncompressedStreamLengthInBytesArgb);
1177
1178 for (int h = 0 ; h < height; h++) {
1179 long i = width * (height - 1 - h);
1180 for (int w = 0 ; w < width; w++) {
1181 (*uncompressedStreamArgb)[i] = SkColorSetRGB(uncompressedStream[w],
1182 uncompressedStream[w],
1183 uncompressedStream[w]);
1184 i++;
1185 }
1186 uncompressedStream += bytesPerLine;
1187 }
1188 return true;
1189 }
1190
1191 return false;
1192}
1193
1194// utils
1195
1196// TODO(edisonn): add cache, or put the bitmap property directly on the PdfObject
1197// TODO(edisonn): deal with colorSpaces, we could add them to SkBitmap::Config
1198// TODO(edisonn): preserve A1 format that skia knows, + fast convert from 111, 222, 444 to closest
1199// skia format, through a table
1200
1201// this functions returns the image, it does not look at the smask.
1202
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001203SkBitmap getImageFromObject(PdfContext* pdfContext, const SkPdfImageDictionary* image, bool transparencyMask) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001204 if (image == NULL || !image->valid()) {
1205 // TODO(edisonn): report warning to be used in testing.
1206 return SkBitmap();
1207 }
1208
1209 // TODO (edisonn): Fast Jpeg(DCTDecode) draw, or fast PNG(FlateDecode) draw ...
1210// PdfObject* value = resolveReferenceObject(pdfContext->fPdfDoc,
1211// obj.GetDictionary().GetKey(PdfName("Filter")));
1212// if (value && value->IsArray() && value->GetArray().GetSize() == 1) {
1213// value = resolveReferenceObject(pdfContext->fPdfDoc,
1214// &value->GetArray()[0]);
1215// }
1216// if (value && value->IsName() && value->GetName().GetName() == "DCTDecode") {
1217// SkStream stream = SkStream::
1218// SkImageDecoder::Factory()
1219// }
1220
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001221 long bpc = image->BitsPerComponent();
1222 long width = image->Width();
1223 long height = image->Height();
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001224 std::string colorSpace = "DeviceRGB";
edisonn@google.com1277cf02013-06-17 23:36:45 +00001225
1226 // TODO(edisonn): color space can be an array too!
1227 if (image->isColorSpaceAName()) {
1228 colorSpace = image->getColorSpaceAsName();
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001229 }
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001230
1231/*
1232 bool imageMask = image->imageMask();
1233
1234 if (imageMask) {
1235 if (bpc != 0 && bpc != 1) {
1236 // TODO(edisonn): report warning to be used in testing.
1237 return SkBitmap();
1238 }
1239 bpc = 1;
1240 }
1241*/
1242
1243 const PdfObject* obj = image->podofo();
1244
1245 char* uncompressedStream = NULL;
1246 pdf_long uncompressedStreamLength = 0;
1247
1248 PdfResult ret = kPartial_PdfResult;
1249 // TODO(edisonn): get rid of try/catch exceptions! We should not throw on user data!
1250 try {
1251 obj->GetStream()->GetFilteredCopy(&uncompressedStream, &uncompressedStreamLength);
1252 } catch (PdfError& e) {
1253 // TODO(edisonn): report warning to be used in testing.
1254 return SkBitmap();
1255 }
1256
1257 int bytesPerLine = uncompressedStreamLength / height;
1258#ifdef PDF_TRACE
1259 if (uncompressedStreamLength % height != 0) {
1260 printf("Warning uncompressedStreamLength % height != 0 !!!\n");
1261 }
1262#endif
1263
1264 SkBitmap bitmap = transferImageStreamToBitmap(
1265 (unsigned char*)uncompressedStream, uncompressedStreamLength,
1266 width, height, bytesPerLine,
1267 bpc, colorSpace,
1268 transparencyMask);
1269
1270 free(uncompressedStream);
1271
1272 return bitmap;
1273}
1274
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001275SkBitmap getSmaskFromObject(PdfContext* pdfContext, const SkPdfImageDictionary* obj) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001276 const PdfObject* sMask = resolveReferenceObject(&pdfContext->fPdfDoc.podofo(),
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001277 obj->podofo()->GetDictionary().GetKey(PdfName("SMask")));
1278
1279#ifdef PDF_TRACE
1280 std::string str;
1281 if (sMask) {
1282 sMask->ToString(str);
1283 printf("/SMask of /Subtype /Image: %s\n", str.c_str());
1284 }
1285#endif
1286
1287 if (sMask) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001288 SkPdfImageDictionary skxobjmask(&pdfContext->fPdfDoc.podofo(), sMask);
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001289 return getImageFromObject(pdfContext, &skxobjmask, true);
1290 }
1291
1292 // TODO(edisonn): implement GS SMask. Default to empty right now.
1293 return pdfContext->fGraphicsState.fSMask;
1294}
1295
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001296PdfResult doXObject_Image(PdfContext* pdfContext, SkCanvas* canvas, const SkPdfImageDictionary* skpdfimage) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001297 if (skpdfimage == NULL || !skpdfimage->valid()) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001298 return kIgnoreError_PdfResult;
1299 }
1300
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001301 SkBitmap image = getImageFromObject(pdfContext, skpdfimage, false);
1302 SkBitmap sMask = getSmaskFromObject(pdfContext, skpdfimage);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001303
1304 canvas->save();
1305 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1306 SkRect dst = SkRect::MakeXYWH(SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), SkDoubleToScalar(1.0), SkDoubleToScalar(1.0));
1307
1308 if (sMask.empty()) {
1309 canvas->drawBitmapRect(image, dst, NULL);
1310 } else {
1311 canvas->saveLayer(&dst, NULL);
1312 canvas->drawBitmapRect(image, dst, NULL);
1313 SkPaint xfer;
1314 xfer.setXfermodeMode(SkXfermode::kSrcOut_Mode); // SkXfermode::kSdtOut_Mode
1315 canvas->drawBitmapRect(sMask, dst, &xfer);
1316 canvas->restore();
1317 }
1318
1319 canvas->restore();
1320
1321 return kPartial_PdfResult;
1322}
1323
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001324bool SkMatrixFromDictionary(PdfContext* pdfContext,
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001325 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001326 const char* key,
1327 SkMatrix* matrix) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001328 const PdfObject* value = resolveReferenceObject(&pdfContext->fPdfDoc.podofo(),
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001329 dict.GetKey(PdfName(key)));
1330
1331 if (value == NULL || !value->IsArray()) {
1332 return false;
1333 }
1334
1335 if (value->GetArray().GetSize() != 6) {
1336 return false;
1337 }
1338
1339 double array[6];
1340 for (int i = 0; i < 6; i++) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001341 const PdfObject* elem = resolveReferenceObject(&pdfContext->fPdfDoc.podofo(), &value->GetArray()[i]);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001342 if (elem == NULL || (!elem->IsReal() && !elem->IsNumber())) {
1343 return false;
1344 }
1345 array[i] = elem->GetReal();
1346 }
1347
1348 *matrix = SkMatrixFromPdfMatrix(array);
1349 return true;
1350}
1351
edisonn@google.com59543d32013-06-18 22:00:40 +00001352bool SkRectFromDictionary(const PdfMemDocument* pdfDoc,
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001353 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001354 const char* key,
1355 SkRect* rect) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001356 const PdfObject* value = resolveReferenceObject(pdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001357 dict.GetKey(PdfName(key)));
1358
1359 if (value == NULL || !value->IsArray()) {
1360 return false;
1361 }
1362
1363 if (value->GetArray().GetSize() != 4) {
1364 return false;
1365 }
1366
1367 double array[4];
1368 for (int i = 0; i < 4; i++) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001369 const PdfObject* elem = resolveReferenceObject(pdfDoc, &value->GetArray()[i]);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001370 if (elem == NULL || (!elem->IsReal() && !elem->IsNumber())) {
1371 return false;
1372 }
1373 array[i] = elem->GetReal();
1374 }
1375
1376 *rect = SkRect::MakeLTRB(SkDoubleToScalar(array[0]),
1377 SkDoubleToScalar(array[1]),
1378 SkDoubleToScalar(array[2]),
1379 SkDoubleToScalar(array[3]));
1380 return true;
1381}
1382
edisonn@google.com59543d32013-06-18 22:00:40 +00001383bool SkRectFromDictionary(const PdfMemDocument* pdfDoc,
1384 const PdfDictionary& dict,
1385 const char* key,
1386 const char* abr,
1387 SkRect* data) {
1388 if (SkRectFromDictionary(pdfDoc, dict, key, data)) return true;
1389 if (abr == NULL || *abr == '\0') return false;
1390 return SkRectFromDictionary(pdfDoc, dict, abr, data);
1391
1392}
1393
1394
edisonn@google.com68d15c82013-06-17 20:46:27 +00001395SkPdfObject* get(const SkPdfObject* obj, const char* key, const char* abr = "") {
1396 SkPdfObject* ret = NULL;
1397 if (obj == NULL) return NULL;
1398 const SkPdfDictionary* dict = obj->asDictionary();
1399 if (dict == NULL) return NULL;
1400 if (!dict->podofo()->IsDictionary()) return NULL;
1401 ObjectFromDictionary(dict->doc(), dict->podofo()->GetDictionary(), key, abr, &ret);
1402 return ret;
1403}
1404
1405PdfResult doXObject_Form(PdfContext* pdfContext, SkCanvas* canvas, SkPdfType1FormDictionary* skobj) {
1406 if (!skobj || !skobj->podofo() || !skobj->podofo()->HasStream() || skobj->podofo()->GetStream() == NULL || skobj->podofo()->GetStream()->GetLength() == 0) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001407 return kOK_PdfResult;
1408 }
1409
1410 PdfOp_q(pdfContext, canvas, NULL);
1411 canvas->save();
1412
edisonn@google.com68d15c82013-06-17 20:46:27 +00001413 if (get(skobj, "Resources")) {
1414 SkPdfResourceDictionary* res = NULL;
1415
1416 PodofoMapper::map(*get(skobj, "Resources"), &res);
1417
1418 if (res) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001419 pdfContext->fGraphicsState.fResources = res;
edisonn@google.com68d15c82013-06-17 20:46:27 +00001420 }
1421 }
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001422
1423 SkTraceMatrix(pdfContext->fGraphicsState.fMatrix, "Current matrix");
1424
1425 SkMatrix matrix;
edisonn@google.com68d15c82013-06-17 20:46:27 +00001426 if (SkMatrixFromDictionary(pdfContext, skobj->podofo()->GetDictionary(), "Matrix", &matrix)) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001427 pdfContext->fGraphicsState.fMatrix.preConcat(matrix);
1428 pdfContext->fGraphicsState.fMatrixTm = pdfContext->fGraphicsState.fMatrix;
1429 pdfContext->fGraphicsState.fMatrixTlm = pdfContext->fGraphicsState.fMatrix;
1430 // TODO(edisonn) reset matrixTm and matricTlm also?
1431 }
1432
1433 SkTraceMatrix(pdfContext->fGraphicsState.fMatrix, "Total matrix");
1434
1435 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1436
1437 SkRect bbox;
edisonn@google.com59543d32013-06-18 22:00:40 +00001438 if (SkRectFromDictionary(&pdfContext->fPdfDoc.podofo(), skobj->podofo()->GetDictionary(), "BBox", &bbox)) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001439 canvas->clipRect(bbox, SkRegion::kIntersect_Op, true); // TODO(edisonn): AA from settings.
1440 }
1441
1442 // TODO(edisonn): iterate smart on the stream even if it is compressed, tokenize it as we go.
1443 // For this PdfContentsTokenizer needs to be extended.
1444
1445 char* uncompressedStream = NULL;
1446 pdf_long uncompressedStreamLength = 0;
1447
1448 PdfResult ret = kPartial_PdfResult;
1449
1450 // TODO(edisonn): get rid of try/catch exceptions! We should not throw on user data!
1451 try {
edisonn@google.com68d15c82013-06-17 20:46:27 +00001452 skobj->podofo()->GetStream()->GetFilteredCopy(&uncompressedStream, &uncompressedStreamLength);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001453 if (uncompressedStream != NULL && uncompressedStreamLength != 0) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001454 SkPdfTokenizer tokenizer = pdfContext->fPdfDoc.tokenizerOfStream(uncompressedStream, uncompressedStreamLength);
1455 PdfMainLooper looper(NULL, tokenizer, pdfContext, canvas);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001456 looper.loop();
1457 }
1458 free(uncompressedStream);
1459 } catch (PdfError& e) {
1460 ret = kIgnoreError_PdfResult;
1461 }
1462
1463 // TODO(edisonn): should we restore the variable stack at the same state?
1464 // There could be operands left, that could be consumed by a parent tokenizer when we pop.
1465 canvas->restore();
1466 PdfOp_Q(pdfContext, canvas, NULL);
1467 return ret;
1468}
1469
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001470PdfResult doXObject_PS(PdfContext* pdfContext, SkCanvas* canvas, const PdfObject& obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001471 return kNYI_PdfResult;
1472}
1473
edisonn@google.com59543d32013-06-18 22:00:40 +00001474// TODO(edisonn): faster, have the property on the SkPdfObject itself?
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001475std::set<const PdfObject*> gInRendering;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001476
1477class CheckRecursiveRendering {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001478 const PdfObject& fObj;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001479public:
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001480 CheckRecursiveRendering(const PdfObject& obj) : fObj(obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001481 gInRendering.insert(&obj);
1482 }
1483
1484 ~CheckRecursiveRendering() {
1485 //SkASSERT(fObj.fInRendering);
1486 gInRendering.erase(&fObj);
1487 }
1488
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001489 static bool IsInRendering(const PdfObject& obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001490 return gInRendering.find(&obj) != gInRendering.end();
1491 }
1492};
1493
edisonn@google.com59543d32013-06-18 22:00:40 +00001494PdfResult doXObject(PdfContext* pdfContext, SkCanvas* canvas, const SkPdfObject& obj) {
1495 if (CheckRecursiveRendering::IsInRendering(*obj.podofo())) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001496 // Oops, corrupt PDF!
1497 return kIgnoreError_PdfResult;
1498 }
1499
edisonn@google.com59543d32013-06-18 22:00:40 +00001500 CheckRecursiveRendering checkRecursion(*obj.podofo());
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001501
1502 // TODO(edisonn): check type
edisonn@google.com68d15c82013-06-17 20:46:27 +00001503 SkPdfXObjectDictionary* skobj = NULL;
edisonn@google.com59543d32013-06-18 22:00:40 +00001504 if (!PodofoMapper::map(obj, &skobj)) return kIgnoreError_PdfResult;
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001505
1506 if (!skobj || !skobj->valid()) return kIgnoreError_PdfResult;
1507
1508 PdfResult ret = kIgnoreError_PdfResult;
1509 switch (skobj->getType())
1510 {
edisonn@google.com59543d32013-06-18 22:00:40 +00001511 case kImageDictionary_SkPdfObjectType:
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00001512 ret = doXObject_Image(pdfContext, canvas, skobj->asImageDictionary());
edisonn@google.come4d11be2013-06-12 19:53:42 +00001513 break;
edisonn@google.com59543d32013-06-18 22:00:40 +00001514 case kType1FormDictionary_SkPdfObjectType:
edisonn@google.com68d15c82013-06-17 20:46:27 +00001515 ret = doXObject_Form(pdfContext, canvas, skobj->asType1FormDictionary());
edisonn@google.come4d11be2013-06-12 19:53:42 +00001516 break;
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001517 //case kObjectDictionaryXObjectPS_SkPdfObjectType:
1518 //return doXObject_PS(skxobj.asPS());
1519 }
1520
1521 delete skobj;
1522 return ret;
1523}
1524
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001525PdfResult PdfOp_q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1526 pdfContext->fStateStack.push(pdfContext->fGraphicsState);
1527 canvas->save();
1528 return kOK_PdfResult;
1529}
1530
1531PdfResult PdfOp_Q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1532 pdfContext->fGraphicsState = pdfContext->fStateStack.top();
1533 pdfContext->fStateStack.pop();
1534 canvas->restore();
1535 return kOK_PdfResult;
1536}
1537
1538PdfResult PdfOp_cm(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1539 double array[6];
1540 for (int i = 0 ; i < 6 ; i++) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001541 array[5 - i] = pdfContext->fObjectStack.top()->asNumber()->value();
1542 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001543 }
1544
1545 // a b
1546 // c d
1547 // e f
1548
1549 // 0 1
1550 // 2 3
1551 // 4 5
1552
1553 // sx ky
1554 // kx sy
1555 // tx ty
1556 SkMatrix matrix = SkMatrixFromPdfMatrix(array);
1557
1558 pdfContext->fGraphicsState.fMatrix.preConcat(matrix);
1559
1560#ifdef PDF_TRACE
1561 printf("cm ");
1562 for (int i = 0 ; i < 6 ; i++) {
1563 printf("%f ", array[i]);
1564 }
1565 printf("\n");
1566 SkTraceMatrix(pdfContext->fGraphicsState.fMatrix);
1567#endif
1568
1569 return kOK_PdfResult;
1570}
1571
1572//leading TL Set the text leading, Tl
1573//, to leading, which is a number expressed in unscaled text
1574//space units. Text leading is used only by the T*, ', and " operators. Initial value: 0.
1575PdfResult PdfOp_TL(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001576 double ty = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001577
1578 pdfContext->fGraphicsState.fTextLeading = ty;
1579
1580 return kOK_PdfResult;
1581}
1582
1583PdfResult PdfOp_Td(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001584 double ty = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1585 double tx = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001586
1587 double array[6] = {1, 0, 0, 1, tx, ty};
1588 SkMatrix matrix = SkMatrixFromPdfMatrix(array);
1589
1590 pdfContext->fGraphicsState.fMatrixTm.preConcat(matrix);
1591 pdfContext->fGraphicsState.fMatrixTlm.preConcat(matrix);
1592
1593 return kPartial_PdfResult;
1594}
1595
1596PdfResult PdfOp_TD(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001597 double ty = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1598 double tx = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001599
edisonn@google.com59543d32013-06-18 22:00:40 +00001600 PdfObject _ty(PdfVariant(-ty));
1601 pdfContext->fObjectStack.push(new SkPdfNumber(&pdfContext->fPdfDoc.podofo(), &_ty));
1602
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001603 PdfOp_TL(pdfContext, canvas, looper);
1604
edisonn@google.com59543d32013-06-18 22:00:40 +00001605 PdfObject vtx(PdfVariant(-(-tx))); // TODO(edisonn) Hmm, the compiler thinks I have here a function pointer if we use (tx), but not -(-tx)
1606 pdfContext->fObjectStack.push(new SkPdfNumber(&pdfContext->fPdfDoc.podofo(), &vtx));
1607
1608 PdfObject vty(PdfVariant(-(-ty)));
1609 pdfContext->fObjectStack.push(new SkPdfNumber(&pdfContext->fPdfDoc.podofo(), &vty));
1610
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001611 return PdfOp_Td(pdfContext, canvas, looper);
1612}
1613
1614PdfResult PdfOp_Tm(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001615 double f = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1616 double e = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1617 double d = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1618 double c = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1619 double b = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1620 double a = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001621
1622 double array[6];
1623 array[0] = a;
1624 array[1] = b;
1625 array[2] = c;
1626 array[3] = d;
1627 array[4] = e;
1628 array[5] = f;
1629
1630 SkMatrix matrix = SkMatrixFromPdfMatrix(array);
1631 matrix.postConcat(pdfContext->fGraphicsState.fMatrix);
1632
1633 // TODO(edisonn): Text positioning.
1634 pdfContext->fGraphicsState.fMatrixTm = matrix;
1635 pdfContext->fGraphicsState.fMatrixTlm = matrix;;
1636
1637 return kPartial_PdfResult;
1638}
1639
1640//— T* Move to the start of the next line. This operator has the same effect as the code
1641//0 Tl Td
1642//where Tl is the current leading parameter in the text state
1643PdfResult PdfOp_T_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001644 PdfObject zero(PdfVariant(0.0));
1645 PdfObject tl(PdfVariant(-(-pdfContext->fGraphicsState.fTextLeading)));
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001646
edisonn@google.com59543d32013-06-18 22:00:40 +00001647 pdfContext->fObjectStack.push(new SkPdfNumber(&pdfContext->fPdfDoc.podofo(), &zero));
1648 pdfContext->fObjectStack.push(new SkPdfNumber(&pdfContext->fPdfDoc.podofo(), &tl));
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001649 return PdfOp_Td(pdfContext, canvas, looper);
1650}
1651
1652PdfResult PdfOp_m(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1653 if (pdfContext->fGraphicsState.fPathClosed) {
1654 pdfContext->fGraphicsState.fPath.reset();
1655 pdfContext->fGraphicsState.fPathClosed = false;
1656 }
1657
edisonn@google.com59543d32013-06-18 22:00:40 +00001658 pdfContext->fGraphicsState.fCurPosY = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1659 pdfContext->fGraphicsState.fCurPosX = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001660
1661 pdfContext->fGraphicsState.fPath.moveTo(SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosX),
1662 SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosY));
1663
1664 return kOK_PdfResult;
1665}
1666
1667PdfResult PdfOp_l(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1668 if (pdfContext->fGraphicsState.fPathClosed) {
1669 pdfContext->fGraphicsState.fPath.reset();
1670 pdfContext->fGraphicsState.fPathClosed = false;
1671 }
1672
edisonn@google.com59543d32013-06-18 22:00:40 +00001673 pdfContext->fGraphicsState.fCurPosY = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1674 pdfContext->fGraphicsState.fCurPosX = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001675
1676 pdfContext->fGraphicsState.fPath.lineTo(SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosX),
1677 SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosY));
1678
1679 return kOK_PdfResult;
1680}
1681
1682PdfResult PdfOp_c(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1683 if (pdfContext->fGraphicsState.fPathClosed) {
1684 pdfContext->fGraphicsState.fPath.reset();
1685 pdfContext->fGraphicsState.fPathClosed = false;
1686 }
1687
edisonn@google.com59543d32013-06-18 22:00:40 +00001688 double y3 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1689 double x3 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1690 double y2 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1691 double x2 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1692 double y1 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1693 double x1 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001694
1695 pdfContext->fGraphicsState.fPath.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
1696 SkDoubleToScalar(x2), SkDoubleToScalar(y2),
1697 SkDoubleToScalar(x3), SkDoubleToScalar(y3));
1698
1699 pdfContext->fGraphicsState.fCurPosX = x3;
1700 pdfContext->fGraphicsState.fCurPosY = y3;
1701
1702 return kOK_PdfResult;
1703}
1704
1705PdfResult PdfOp_v(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1706 if (pdfContext->fGraphicsState.fPathClosed) {
1707 pdfContext->fGraphicsState.fPath.reset();
1708 pdfContext->fGraphicsState.fPathClosed = false;
1709 }
1710
edisonn@google.com59543d32013-06-18 22:00:40 +00001711 double y3 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1712 double x3 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1713 double y2 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1714 double x2 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001715 double y1 = pdfContext->fGraphicsState.fCurPosY;
1716 double x1 = pdfContext->fGraphicsState.fCurPosX;
1717
1718 pdfContext->fGraphicsState.fPath.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
1719 SkDoubleToScalar(x2), SkDoubleToScalar(y2),
1720 SkDoubleToScalar(x3), SkDoubleToScalar(y3));
1721
1722 pdfContext->fGraphicsState.fCurPosX = x3;
1723 pdfContext->fGraphicsState.fCurPosY = y3;
1724
1725 return kOK_PdfResult;
1726}
1727
1728PdfResult PdfOp_y(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1729 if (pdfContext->fGraphicsState.fPathClosed) {
1730 pdfContext->fGraphicsState.fPath.reset();
1731 pdfContext->fGraphicsState.fPathClosed = false;
1732 }
1733
edisonn@google.com59543d32013-06-18 22:00:40 +00001734 double y3 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1735 double x3 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001736 double y2 = pdfContext->fGraphicsState.fCurPosY;
1737 double x2 = pdfContext->fGraphicsState.fCurPosX;
edisonn@google.com59543d32013-06-18 22:00:40 +00001738 double y1 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1739 double x1 = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001740
1741 pdfContext->fGraphicsState.fPath.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
1742 SkDoubleToScalar(x2), SkDoubleToScalar(y2),
1743 SkDoubleToScalar(x3), SkDoubleToScalar(y3));
1744
1745 pdfContext->fGraphicsState.fCurPosX = x3;
1746 pdfContext->fGraphicsState.fCurPosY = y3;
1747
1748 return kOK_PdfResult;
1749}
1750
1751PdfResult PdfOp_re(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1752 if (pdfContext->fGraphicsState.fPathClosed) {
1753 pdfContext->fGraphicsState.fPath.reset();
1754 pdfContext->fGraphicsState.fPathClosed = false;
1755 }
1756
edisonn@google.com59543d32013-06-18 22:00:40 +00001757 double height = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1758 double width = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1759 double y = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1760 double x = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001761
1762 pdfContext->fGraphicsState.fPath.addRect(SkDoubleToScalar(x), SkDoubleToScalar(y),
1763 SkDoubleToScalar(x + width), SkDoubleToScalar(y + height));
1764
1765 pdfContext->fGraphicsState.fCurPosX = x;
1766 pdfContext->fGraphicsState.fCurPosY = y + height;
1767
1768 return kOK_PdfResult;
1769}
1770
1771PdfResult PdfOp_h(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1772 pdfContext->fGraphicsState.fPath.close();
1773 pdfContext->fGraphicsState.fPathClosed = true;
1774 return kOK_PdfResult;
1775}
1776
1777PdfResult PdfOp_fillAndStroke(PdfContext* pdfContext, SkCanvas* canvas, bool fill, bool stroke, bool close, bool evenOdd) {
1778 SkPath path = pdfContext->fGraphicsState.fPath;
1779
1780 if (close) {
1781 path.close();
1782 }
1783
1784 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1785
1786 SkPaint paint;
1787
1788 // TODO(edisonn): get this from pdfContext->options,
1789 // or pdfContext->addPaintOptions(&paint);
1790 paint.setAntiAlias(true);
1791
1792 // TODO(edisonn): dashing, miter, ...
1793
1794// path.transform(pdfContext->fGraphicsState.fMatrix);
1795// path.transform(pdfContext->fOriginalMatrix);
1796
1797 SkPoint line[2];
1798 if (fill && !stroke && path.isLine(line)) {
1799 paint.setStyle(SkPaint::kStroke_Style);
1800 paint.setColor(pdfContext->fGraphicsState.fNonStroking.fColor);
1801 paint.setStrokeWidth(SkDoubleToScalar(0));
1802 canvas->drawPath(path, paint);
1803 } else {
1804 if (fill) {
1805 paint.setStyle(SkPaint::kFill_Style);
1806 if (evenOdd) {
1807 path.setFillType(SkPath::kEvenOdd_FillType);
1808 }
1809 paint.setColor(pdfContext->fGraphicsState.fNonStroking.fColor);
1810 canvas->drawPath(path, paint);
1811 }
1812
1813 if (stroke) {
1814 paint.setStyle(SkPaint::kStroke_Style);
1815 paint.setColor(pdfContext->fGraphicsState.fStroking.fColor);
1816 paint.setStrokeWidth(SkDoubleToScalar(pdfContext->fGraphicsState.fLineWidth));
1817 path.setFillType(SkPath::kWinding_FillType); // reset it, just in case it messes up the stroke
1818 canvas->drawPath(path, paint);
1819 }
1820 }
1821
1822 pdfContext->fGraphicsState.fPath.reset();
1823 // todo zoom ... other stuff ?
1824
1825 if (pdfContext->fGraphicsState.fHasClipPathToApply) {
1826#ifndef PDF_DEBUG_NO_CLIPING
1827 canvas->clipPath(pdfContext->fGraphicsState.fClipPath, SkRegion::kIntersect_Op, true);
1828#endif
1829 }
1830
1831 //pdfContext->fGraphicsState.fClipPath.reset();
1832 pdfContext->fGraphicsState.fHasClipPathToApply = false;
1833
1834 return kPartial_PdfResult;
1835
1836}
1837
1838PdfResult PdfOp_S(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1839 return PdfOp_fillAndStroke(pdfContext, canvas, false, true, false, false);
1840}
1841
1842PdfResult PdfOp_s(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1843 return PdfOp_fillAndStroke(pdfContext, canvas, false, true, true, false);
1844}
1845
1846PdfResult PdfOp_F(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1847 return PdfOp_fillAndStroke(pdfContext, canvas, true, false, false, false);
1848}
1849
1850PdfResult PdfOp_f(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1851 return PdfOp_fillAndStroke(pdfContext, canvas, true, false, false, false);
1852}
1853
1854PdfResult PdfOp_f_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1855 return PdfOp_fillAndStroke(pdfContext, canvas, true, false, false, true);
1856}
1857
1858PdfResult PdfOp_B(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1859 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, false, false);
1860}
1861
1862PdfResult PdfOp_B_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1863 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, false, true);
1864}
1865
1866PdfResult PdfOp_b(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1867 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, true, false);
1868}
1869
1870PdfResult PdfOp_b_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1871 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, true, true);
1872}
1873
1874PdfResult PdfOp_n(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1875 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1876 if (pdfContext->fGraphicsState.fHasClipPathToApply) {
1877#ifndef PDF_DEBUG_NO_CLIPING
1878 canvas->clipPath(pdfContext->fGraphicsState.fClipPath, SkRegion::kIntersect_Op, true);
1879#endif
1880 }
1881
1882 //pdfContext->fGraphicsState.fClipPath.reset();
1883 pdfContext->fGraphicsState.fHasClipPathToApply = false;
1884
1885 pdfContext->fGraphicsState.fPathClosed = true;
1886
1887 return kOK_PdfResult;
1888}
1889
1890PdfResult PdfOp_BT(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1891 pdfContext->fGraphicsState.fTextBlock = true;
1892 pdfContext->fGraphicsState.fMatrixTm = pdfContext->fGraphicsState.fMatrix;
1893 pdfContext->fGraphicsState.fMatrixTlm = pdfContext->fGraphicsState.fMatrix;
1894
1895 return kPartial_PdfResult;
1896}
1897
1898PdfResult PdfOp_ET(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1899 if (!pdfContext->fGraphicsState.fTextBlock) {
1900 return kIgnoreError_PdfResult;
1901 }
1902 // TODO(edisonn): anything else to be done once we are done with draw text? Like restore stack?
1903 return kPartial_PdfResult;
1904}
1905
1906//font size Tf Set the text font, Tf
1907//, to font and the text font size, Tfs, to size. font is the name of a
1908//font resource in the Fontsubdictionary of the current resource dictionary; size is
1909//a number representing a scale factor. There is no initial value for either font or
1910//size; they must be specified explicitly using Tf before any text is shown.
1911PdfResult PdfOp_Tf(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00001912 pdfContext->fGraphicsState.fCurFontSize = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
1913 std::string fontName = pdfContext->fObjectStack.top()->asName()->value(); pdfContext->fObjectStack.pop();
1914
1915#ifdef PDF_TRACE
1916 printf("font name: %s\n", fontName.c_str());
1917 std::string str;
1918 pdfContext->fGraphicsState.fResources->podofo()->ToString(str);
1919 printf("Print Tf font Resources: %s\n", str.c_str());
1920#endif
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001921
1922 // TODO(edisonn): Load font from pdfContext->fGraphicsState.fObjectWithResources ?
edisonn@google.com59543d32013-06-18 22:00:40 +00001923 const PdfObject* pFont = resolveReferenceObject(&pdfContext->fPdfDoc.podofo(),
1924 pdfContext->fGraphicsState.fResources->Font()->get(fontName.c_str()).podofo());
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001925 if( !pFont )
1926 {
1927 // TODO(edisonn): try to ignore the error, make sure we do not crash.
1928 return kIgnoreError_PdfResult;
1929 }
1930
edisonn@google.com59543d32013-06-18 22:00:40 +00001931 pdfContext->fGraphicsState.fCurFont = pdfContext->fPdfDoc.podofo().GetFont( (PdfObject*)pFont );
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001932 if( !pdfContext->fGraphicsState.fCurFont )
1933 {
1934 // TODO(edisonn): check ~/crasing, for one of the files PoDoFo throws exception
1935 // when calling pFont->Reference(), with Linked list corruption.
1936 return kIgnoreError_PdfResult;
1937 }
1938
1939 return kPartial_PdfResult;
1940}
1941
1942PdfResult PdfOp_Tj(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1943 if (!pdfContext->fGraphicsState.fTextBlock) {
1944 // TODO(edisonn): try to recover and draw it any way?
1945 return kIgnoreError_PdfResult;
1946 }
1947
1948 PdfResult ret = DrawText(pdfContext,
1949 pdfContext->fGraphicsState.fCurFont,
edisonn@google.com59543d32013-06-18 22:00:40 +00001950 pdfContext->fObjectStack.top()->podofo()->GetString(),
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001951 canvas);
edisonn@google.com59543d32013-06-18 22:00:40 +00001952 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001953
1954 return ret;
1955}
1956
1957PdfResult PdfOp_quote(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1958 if (!pdfContext->fGraphicsState.fTextBlock) {
1959 // TODO(edisonn): try to recover and draw it any way?
1960 return kIgnoreError_PdfResult;
1961 }
1962
1963 PdfOp_T_star(pdfContext, canvas, looper);
1964 // Do not pop, and push, just transfer the param to Tj
1965 return PdfOp_Tj(pdfContext, canvas, looper);
1966}
1967
1968PdfResult PdfOp_doublequote(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1969 if (!pdfContext->fGraphicsState.fTextBlock) {
1970 // TODO(edisonn): try to recover and draw it any way?
1971 return kIgnoreError_PdfResult;
1972 }
1973
edisonn@google.com59543d32013-06-18 22:00:40 +00001974 SkPdfObject* str = pdfContext->fObjectStack.top(); pdfContext->fObjectStack.pop();
1975 SkPdfObject* ac = pdfContext->fObjectStack.top(); pdfContext->fObjectStack.pop();
1976 SkPdfObject* aw = pdfContext->fObjectStack.top(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001977
edisonn@google.com59543d32013-06-18 22:00:40 +00001978 pdfContext->fObjectStack.push(aw);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001979 PdfOp_Tw(pdfContext, canvas, looper);
1980
edisonn@google.com59543d32013-06-18 22:00:40 +00001981 pdfContext->fObjectStack.push(ac);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001982 PdfOp_Tc(pdfContext, canvas, looper);
1983
edisonn@google.com59543d32013-06-18 22:00:40 +00001984 pdfContext->fObjectStack.push(str);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001985 PdfOp_quote(pdfContext, canvas, looper);
1986
1987 return kPartial_PdfResult;
1988}
1989
1990PdfResult PdfOp_TJ(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1991 if (!pdfContext->fGraphicsState.fTextBlock) {
1992 // TODO(edisonn): try to recover and draw it any way?
1993 return kIgnoreError_PdfResult;
1994 }
1995
edisonn@google.com59543d32013-06-18 22:00:40 +00001996 SkPdfArray* array = pdfContext->fObjectStack.top()->asArray();
1997 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001998
edisonn@google.com59543d32013-06-18 22:00:40 +00001999 for( int i=0; i<static_cast<int>(array->size()); i++ )
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002000 {
edisonn@google.com59543d32013-06-18 22:00:40 +00002001 if( (*array)[i].asString()) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002002 DrawText(pdfContext,
2003 pdfContext->fGraphicsState.fCurFont,
edisonn@google.com59543d32013-06-18 22:00:40 +00002004 (*array)[i].podofo()->GetString(),
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002005 canvas);
edisonn@google.com59543d32013-06-18 22:00:40 +00002006 } else if ((*array)[i].asInteger() || (*array)[i].asNumber()) {
2007 double dx = (*array)[i].asNumber()->value();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002008 SkMatrix matrix;
2009 matrix.setAll(SkDoubleToScalar(1),
2010 SkDoubleToScalar(0),
2011 // TODO(edisonn): use writing mode, vertical/horizontal.
2012 SkDoubleToScalar(-dx), // amount is substracted!!!
2013 SkDoubleToScalar(0),
2014 SkDoubleToScalar(1),
2015 SkDoubleToScalar(0),
2016 SkDoubleToScalar(0),
2017 SkDoubleToScalar(0),
2018 SkDoubleToScalar(1));
2019
2020 pdfContext->fGraphicsState.fMatrixTm.preConcat(matrix);
2021 }
2022 }
2023 return kPartial_PdfResult; // TODO(edisonn): Implement fully DrawText before returing OK.
2024}
2025
2026PdfResult PdfOp_CS_cs(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002027 colorOperator->fColorSpace = pdfContext->fObjectStack.top()->asName()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002028 return kOK_PdfResult;
2029}
2030
2031PdfResult PdfOp_CS(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2032 return PdfOp_CS_cs(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
2033}
2034
2035PdfResult PdfOp_cs(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2036 return PdfOp_CS_cs(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
2037}
2038
2039PdfResult PdfOp_SC_sc(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
2040 double c[4];
2041 pdf_int64 v[4];
2042
2043 int n = GetColorSpaceComponents(colorOperator->fColorSpace);
2044
2045 bool doubles = true;
2046 if (colorOperator->fColorSpace == "Indexed") {
2047 doubles = false;
2048 }
2049
2050#ifdef PDF_TRACE
2051 printf("color space = %s, N = %i\n", colorOperator->fColorSpace.c_str(), n);
2052#endif
2053
2054 for (int i = n - 1; i >= 0 ; i--) {
2055 if (doubles) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002056 c[i] = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002057 } else {
edisonn@google.com59543d32013-06-18 22:00:40 +00002058 v[i] = pdfContext->fObjectStack.top()->asInteger()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002059 }
2060 }
2061
2062 // TODO(edisonn): Now, set that color. Only DeviceRGB supported.
2063 if (colorOperator->fColorSpace == "DeviceRGB") {
2064 colorOperator->setRGBColor(SkColorSetRGB(255*c[0], 255*c[1], 255*c[2]));
2065 }
2066 return kPartial_PdfResult;
2067}
2068
2069PdfResult PdfOp_SC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2070 return PdfOp_SC_sc(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
2071}
2072
2073PdfResult PdfOp_sc(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2074 return PdfOp_SC_sc(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
2075}
2076
2077PdfResult PdfOp_SCN_scn(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
2078 PdfString name;
2079
edisonn@google.com59543d32013-06-18 22:00:40 +00002080 if (pdfContext->fObjectStack.top()->asName()) {
2081 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002082 }
2083
2084 // TODO(edisonn): SCN supports more color spaces than SCN. Read and implement spec.
2085 PdfOp_SC_sc(pdfContext, canvas, colorOperator);
2086
2087 return kPartial_PdfResult;
2088}
2089
2090PdfResult PdfOp_SCN(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2091 return PdfOp_SCN_scn(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
2092}
2093
2094PdfResult PdfOp_scn(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2095 return PdfOp_SCN_scn(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
2096}
2097
2098PdfResult PdfOp_G_g(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002099 double gray = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002100 return kNYI_PdfResult;
2101}
2102
2103PdfResult PdfOp_G(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2104 return PdfOp_G_g(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
2105}
2106
2107PdfResult PdfOp_g(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2108 return PdfOp_G_g(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
2109}
2110
2111PdfResult PdfOp_RG_rg(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002112 double b = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
2113 double g = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
2114 double r = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002115
2116 colorOperator->fColorSpace = "DeviceRGB";
2117 colorOperator->setRGBColor(SkColorSetRGB(255*r, 255*g, 255*b));
2118 return kOK_PdfResult;
2119}
2120
2121PdfResult PdfOp_RG(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2122 return PdfOp_RG_rg(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
2123}
2124
2125PdfResult PdfOp_rg(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2126 return PdfOp_RG_rg(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
2127}
2128
2129PdfResult PdfOp_K_k(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
2130 // TODO(edisonn): spec has some rules about overprint, implement them.
edisonn@google.com59543d32013-06-18 22:00:40 +00002131 double k = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
2132 double y = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
2133 double m = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
2134 double c = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002135
2136 colorOperator->fColorSpace = "DeviceCMYK";
2137 // TODO(edisonn): Set color.
2138 return kNYI_PdfResult;
2139}
2140
2141PdfResult PdfOp_K(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2142 return PdfOp_K_k(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
2143}
2144
2145PdfResult PdfOp_k(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2146 return PdfOp_K_k(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
2147}
2148
2149PdfResult PdfOp_W(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2150 pdfContext->fGraphicsState.fClipPath = pdfContext->fGraphicsState.fPath;
2151 pdfContext->fGraphicsState.fHasClipPathToApply = true;
2152
2153 return kOK_PdfResult;
2154}
2155
2156PdfResult PdfOp_W_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2157 pdfContext->fGraphicsState.fClipPath = pdfContext->fGraphicsState.fPath;
2158
2159#ifdef PDF_TRACE
2160 if (pdfContext->fGraphicsState.fClipPath.isRect(NULL)) {
2161 printf("CLIP IS RECT\n");
2162 }
2163#endif
2164
2165 // TODO(edisonn): there seem to be a bug with clipPath of a rect with even odd.
2166 pdfContext->fGraphicsState.fClipPath.setFillType(SkPath::kEvenOdd_FillType);
2167 pdfContext->fGraphicsState.fHasClipPathToApply = true;
2168
2169 return kPartial_PdfResult;
2170}
2171
2172PdfResult PdfOp_BX(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2173 *looper = new PdfCompatibilitySectionLooper();
2174 return kOK_PdfResult;
2175}
2176
2177PdfResult PdfOp_EX(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2178#ifdef ASSERT_BAD_PDF_OPS
2179 SkASSERT(false); // EX must be consumed by PdfCompatibilitySectionLooper, but let's
2180 // have the assert when testing good pdfs.
2181#endif
2182 return kIgnoreError_PdfResult;
2183}
2184
2185PdfResult PdfOp_BI(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2186 *looper = new PdfInlineImageLooper();
2187 return kOK_PdfResult;
2188}
2189
2190PdfResult PdfOp_ID(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2191#ifdef ASSERT_BAD_PDF_OPS
2192 SkASSERT(false); // must be processed in inline image looper, but let's
2193 // have the assert when testing good pdfs.
2194#endif
2195 return kIgnoreError_PdfResult;
2196}
2197
2198PdfResult PdfOp_EI(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2199#ifdef ASSERT_BAD_PDF_OPS
2200 SkASSERT(false); // must be processed in inline image looper, but let's
2201 // have the assert when testing good pdfs.
2202#endif
2203 return kIgnoreError_PdfResult;
2204}
2205
2206//lineWidth w Set the line width in the graphics state (see “Line Width” on page 152).
2207PdfResult PdfOp_w(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002208 double lineWidth = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002209 pdfContext->fGraphicsState.fLineWidth = lineWidth;
2210
2211 return kOK_PdfResult;
2212}
2213
2214//lineCap J Set the line cap style in the graphics state (see “Line Cap Style” on page 153).
2215PdfResult PdfOp_J(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002216 pdfContext->fObjectStack.pop();
2217 //double lineCap = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002218
2219 return kNYI_PdfResult;
2220}
2221
2222//lineJoin j Set the line join style in the graphics state (see “Line Join Style” on page 153).
2223PdfResult PdfOp_j(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002224 pdfContext->fObjectStack.pop();
2225 //double lineJoin = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002226
2227 return kNYI_PdfResult;
2228}
2229
2230//miterLimit M Set the miter limit in the graphics state (see “Miter Limit” on page 153).
2231PdfResult PdfOp_M(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002232 pdfContext->fObjectStack.pop();
2233 //double miterLimit = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002234
2235 return kNYI_PdfResult;
2236}
2237
2238//dashArray dashPhase d Set the line dash pattern in the graphics state (see “Line Dash Pattern” on
2239//page 155).
2240PdfResult PdfOp_d(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002241 pdfContext->fObjectStack.pop();
2242 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002243
2244 return kNYI_PdfResult;
2245}
2246
2247//intent ri (PDF 1.1) Set the color rendering intent in the graphics state (see “Rendering Intents” on page 197).
2248PdfResult PdfOp_ri(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002249 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002250
2251 return kNYI_PdfResult;
2252}
2253
2254//flatness i Set the flatness tolerance in the graphics state (see Section 6.5.1, “Flatness
2255//Tolerance”). flatness is a number in the range 0 to 100; a value of 0 speci-
2256//fies the output device’s default flatness tolerance.
2257PdfResult PdfOp_i(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002258 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002259
2260 return kNYI_PdfResult;
2261}
2262
2263//dictName gs (PDF 1.2) Set the specified parameters in the graphics state. dictName is
2264//the name of a graphics state parameter dictionary in the ExtGState subdictionary of the current resource dictionary (see the next section).
2265PdfResult PdfOp_gs(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002266 std::string name = pdfContext->fObjectStack.top()->asName()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002267
edisonn@google.coma2fab9d2013-06-14 19:22:19 +00002268#ifdef PDF_TRACE
2269 std::string str;
2270#endif
2271
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002272 //Next, get the ExtGState Dictionary from the Resource Dictionary:
edisonn@google.com59543d32013-06-18 22:00:40 +00002273 const SkPdfDictionary* extGStateDictionary = pdfContext->fGraphicsState.fResources->ExtGState();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002274
2275 if (extGStateDictionary == NULL) {
2276#ifdef PDF_TRACE
2277 printf("ExtGState is NULL!\n");
2278#endif
2279 return kIgnoreError_PdfResult;
2280 }
2281
edisonn@google.com59543d32013-06-18 22:00:40 +00002282 SkPdfObject value = extGStateDictionary->get(name.c_str());
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002283
2284#ifdef PDF_TRACE
edisonn@google.com59543d32013-06-18 22:00:40 +00002285// value->ToString(str);
2286// printf("gs object value: %s\n", str.c_str());
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002287#endif
2288
edisonn@google.com59543d32013-06-18 22:00:40 +00002289 SkPdfGraphicsStateDictionary* gs = NULL;
2290 PodofoMapper::map(value, &gs);
edisonn@google.com68d15c82013-06-17 20:46:27 +00002291
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002292 // TODO(edisonn): now load all those properties in graphic state.
2293
2294 return kNYI_PdfResult;
2295}
2296
2297//charSpace Tc Set the character spacing, Tc
2298//, to charSpace, which is a number expressed in unscaled text space units. Character spacing is used by the Tj, TJ, and ' operators.
2299//Initial value: 0.
2300PdfResult PdfOp_Tc(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002301 double charSpace = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002302 pdfContext->fGraphicsState.fCharSpace = charSpace;
2303
2304 return kOK_PdfResult;
2305}
2306
2307//wordSpace Tw Set the word spacing, T
2308//w
2309//, to wordSpace, which is a number expressed in unscaled
2310//text space units. Word spacing is used by the Tj, TJ, and ' operators. Initial
2311//value: 0.
2312PdfResult PdfOp_Tw(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002313 double wordSpace = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002314 pdfContext->fGraphicsState.fWordSpace = wordSpace;
2315
2316 return kOK_PdfResult;
2317}
2318
2319//scale Tz Set the horizontal scaling, Th
2320//, to (scale ˜ 100). scale is a number specifying the
2321//percentage of the normal width. Initial value: 100 (normal width).
2322PdfResult PdfOp_Tz(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002323 double scale = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002324
2325 return kNYI_PdfResult;
2326}
2327
2328//render Tr Set the text rendering mode, T
2329//mode, to render, which is an integer. Initial value: 0.
2330PdfResult PdfOp_Tr(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002331 double render = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002332
2333 return kNYI_PdfResult;
2334}
2335
2336//rise Ts Set the text rise, Trise, to rise, which is a number expressed in unscaled text space
2337//units. Initial value: 0.
2338PdfResult PdfOp_Ts(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002339 double rise = pdfContext->fObjectStack.top()->asNumber()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002340
2341 return kNYI_PdfResult;
2342}
2343
2344//wx wy d0
2345PdfResult PdfOp_d0(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002346 pdfContext->fObjectStack.pop();
2347 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002348
2349 return kNYI_PdfResult;
2350}
2351
2352//wx wy llx lly urx ury d1
2353PdfResult PdfOp_d1(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002354 pdfContext->fObjectStack.pop();
2355 pdfContext->fObjectStack.pop();
2356 pdfContext->fObjectStack.pop();
2357 pdfContext->fObjectStack.pop();
2358 pdfContext->fObjectStack.pop();
2359 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002360
2361 return kNYI_PdfResult;
2362}
2363
2364//name sh
2365PdfResult PdfOp_sh(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002366 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002367
2368 return kNYI_PdfResult;
2369}
2370
2371//name Do
2372PdfResult PdfOp_Do(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002373 std::string name = pdfContext->fObjectStack.top()->asName()->value(); pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002374
edisonn@google.com59543d32013-06-18 22:00:40 +00002375 SkPdfDictionary* xObject = pdfContext->fGraphicsState.fResources->XObject();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002376
edisonn@google.com59543d32013-06-18 22:00:40 +00002377 if (xObject == NULL) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002378#ifdef PDF_TRACE
2379 printf("XObject is NULL!\n");
2380#endif
2381 return kIgnoreError_PdfResult;
2382 }
2383
edisonn@google.com59543d32013-06-18 22:00:40 +00002384 SkPdfObject value = xObject->get(name.c_str());
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002385
2386#ifdef PDF_TRACE
edisonn@google.com59543d32013-06-18 22:00:40 +00002387// value->ToString(str);
2388// printf("Do object value: %s\n", str.c_str());
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002389#endif
2390
edisonn@google.com59543d32013-06-18 22:00:40 +00002391 return doXObject(pdfContext, canvas, value);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002392}
2393
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002394//tag MP Designate a marked-content point. tag is a name object indicating the role or
2395//significance of the point.
2396PdfResult PdfOp_MP(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002397 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002398
2399 return kNYI_PdfResult;
2400}
2401
2402//tag properties DP Designate a marked-content point with an associated property list. tag is a
2403//name object indicating the role or significance of the point; properties is
2404//either an inline dictionary containing the property list or a name object
2405//associated with it in the Properties subdictionary of the current resource
2406//dictionary (see Section 9.5.1, “Property Lists”).
2407PdfResult PdfOp_DP(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002408 pdfContext->fObjectStack.pop();
2409 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002410
2411 return kNYI_PdfResult;
2412}
2413
2414//tag BMC Begin a marked-content sequence terminated by a balancing EMC operator.
2415//tag is a name object indicating the role or significance of the sequence.
2416PdfResult PdfOp_BMC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002417 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002418
2419 return kNYI_PdfResult;
2420}
2421
2422//tag properties BDC Begin a marked-content sequence with an associated property list, terminated
2423//by a balancing EMCoperator. tag is a name object indicating the role or significance of the sequence; propertiesis either an inline dictionary containing the
2424//property list or a name object associated with it in the Properties subdictionary of the current resource dictionary (see Section 9.5.1, “Property Lists”).
2425PdfResult PdfOp_BDC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002426 pdfContext->fObjectStack.pop();
2427 pdfContext->fObjectStack.pop();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002428
2429 return kNYI_PdfResult;
2430}
2431
2432//— EMC End a marked-content sequence begun by a BMC or BDC operator.
2433PdfResult PdfOp_EMC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2434 return kNYI_PdfResult;
2435}
2436
2437void initPdfOperatorRenderes() {
2438 static bool gInitialized = false;
2439 if (gInitialized) {
2440 return;
2441 }
2442
2443 gPdfOps["q"] = PdfOp_q;
2444 gPdfOps["Q"] = PdfOp_Q;
2445 gPdfOps["cm"] = PdfOp_cm;
2446
2447 gPdfOps["TD"] = PdfOp_TD;
2448 gPdfOps["Td"] = PdfOp_Td;
2449 gPdfOps["Tm"] = PdfOp_Tm;
2450 gPdfOps["T*"] = PdfOp_T_star;
2451
2452 gPdfOps["m"] = PdfOp_m;
2453 gPdfOps["l"] = PdfOp_l;
2454 gPdfOps["c"] = PdfOp_c;
2455 gPdfOps["v"] = PdfOp_v;
2456 gPdfOps["y"] = PdfOp_y;
2457 gPdfOps["h"] = PdfOp_h;
2458 gPdfOps["re"] = PdfOp_re;
2459
2460 gPdfOps["S"] = PdfOp_S;
2461 gPdfOps["s"] = PdfOp_s;
2462 gPdfOps["f"] = PdfOp_f;
2463 gPdfOps["F"] = PdfOp_F;
2464 gPdfOps["f*"] = PdfOp_f_star;
2465 gPdfOps["B"] = PdfOp_B;
2466 gPdfOps["B*"] = PdfOp_B_star;
2467 gPdfOps["b"] = PdfOp_b;
2468 gPdfOps["b*"] = PdfOp_b_star;
2469 gPdfOps["n"] = PdfOp_n;
2470
2471 gPdfOps["BT"] = PdfOp_BT;
2472 gPdfOps["ET"] = PdfOp_ET;
2473
2474 gPdfOps["Tj"] = PdfOp_Tj;
2475 gPdfOps["'"] = PdfOp_quote;
2476 gPdfOps["\""] = PdfOp_doublequote;
2477 gPdfOps["TJ"] = PdfOp_TJ;
2478
2479 gPdfOps["CS"] = PdfOp_CS;
2480 gPdfOps["cs"] = PdfOp_cs;
2481 gPdfOps["SC"] = PdfOp_SC;
2482 gPdfOps["SCN"] = PdfOp_SCN;
2483 gPdfOps["sc"] = PdfOp_sc;
2484 gPdfOps["scn"] = PdfOp_scn;
2485 gPdfOps["G"] = PdfOp_G;
2486 gPdfOps["g"] = PdfOp_g;
2487 gPdfOps["RG"] = PdfOp_RG;
2488 gPdfOps["rg"] = PdfOp_rg;
2489 gPdfOps["K"] = PdfOp_K;
2490 gPdfOps["k"] = PdfOp_k;
2491
2492 gPdfOps["W"] = PdfOp_W;
2493 gPdfOps["W*"] = PdfOp_W_star;
2494
2495 gPdfOps["BX"] = PdfOp_BX;
2496 gPdfOps["EX"] = PdfOp_EX;
2497
2498 gPdfOps["BI"] = PdfOp_BI;
2499 gPdfOps["ID"] = PdfOp_ID;
2500 gPdfOps["EI"] = PdfOp_EI;
2501
2502 gPdfOps["w"] = PdfOp_w;
2503 gPdfOps["J"] = PdfOp_J;
2504 gPdfOps["j"] = PdfOp_j;
2505 gPdfOps["M"] = PdfOp_M;
2506 gPdfOps["d"] = PdfOp_d;
2507 gPdfOps["ri"] = PdfOp_ri;
2508 gPdfOps["i"] = PdfOp_i;
2509 gPdfOps["gs"] = PdfOp_gs;
2510
2511 gPdfOps["Tc"] = PdfOp_Tc;
2512 gPdfOps["Tw"] = PdfOp_Tw;
2513 gPdfOps["Tz"] = PdfOp_Tz;
2514 gPdfOps["TL"] = PdfOp_TL;
2515 gPdfOps["Tf"] = PdfOp_Tf;
2516 gPdfOps["Tr"] = PdfOp_Tr;
2517 gPdfOps["Ts"] = PdfOp_Ts;
2518
2519 gPdfOps["d0"] = PdfOp_d0;
2520 gPdfOps["d1"] = PdfOp_d1;
2521
2522 gPdfOps["sh"] = PdfOp_sh;
2523
2524 gPdfOps["Do"] = PdfOp_Do;
2525
2526 gPdfOps["MP"] = PdfOp_MP;
2527 gPdfOps["DP"] = PdfOp_DP;
2528 gPdfOps["BMC"] = PdfOp_BMC;
2529 gPdfOps["BDC"] = PdfOp_BDC;
2530 gPdfOps["EMC"] = PdfOp_EMC;
2531
2532 gInitialized = true;
2533}
2534
2535void reportPdfRenderStats() {
2536 std::map<std::string, int>::iterator iter;
2537
2538 for (int i = 0 ; i < kCount_PdfResult; i++) {
2539 for (iter = gRenderStats[i].begin(); iter != gRenderStats[i].end(); ++iter) {
2540 printf("%s: %s -> count %i\n", gRenderStatsNames[i], iter->first.c_str(), iter->second);
2541 }
2542 }
2543}
2544
2545PdfResult PdfMainLooper::consumeToken(PdfToken& token) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002546 if (token.fType == kKeyword_TokenType)
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002547 {
2548 // TODO(edisonn): log trace flag (verbose, error, info, warning, ...)
2549#ifdef PDF_TRACE
edisonn@google.com59543d32013-06-18 22:00:40 +00002550 printf("KEYWORD: %s\n", token.fKeyword);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002551#endif
edisonn@google.com59543d32013-06-18 22:00:40 +00002552 PdfOperatorRenderer pdfOperatorRenderer = gPdfOps[token.fKeyword];
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002553 if (pdfOperatorRenderer) {
2554 // caller, main work is done by pdfOperatorRenderer(...)
2555 PdfTokenLooper* childLooper = NULL;
edisonn@google.com59543d32013-06-18 22:00:40 +00002556 gRenderStats[pdfOperatorRenderer(fPdfContext, fCanvas, &childLooper)][token.fKeyword]++;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002557
2558 if (childLooper) {
2559 childLooper->setUp(this);
2560 childLooper->loop();
2561 delete childLooper;
2562 }
2563 } else {
edisonn@google.com59543d32013-06-18 22:00:40 +00002564 gRenderStats[kUnsupported_PdfResult][token.fKeyword]++;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002565 }
2566 }
edisonn@google.com59543d32013-06-18 22:00:40 +00002567 else if (token.fType == kObject_TokenType)
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002568 {
2569#ifdef PDF_TRACE
2570 std::string _var;
edisonn@google.com59543d32013-06-18 22:00:40 +00002571 token.fObject->podofo()->ToString(_var);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002572 printf("var: %s\n", _var.c_str());
2573#endif
edisonn@google.com59543d32013-06-18 22:00:40 +00002574 fPdfContext->fObjectStack.push( token.fObject );
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002575 }
edisonn@google.com59543d32013-06-18 22:00:40 +00002576 else if ( token.fType == kImageData_TokenType) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002577 // TODO(edisonn): implement inline image.
2578 }
2579 else {
2580 return kIgnoreError_PdfResult;
2581 }
2582 return kOK_PdfResult;
2583}
2584
2585void PdfMainLooper::loop() {
2586 PdfToken token;
2587 while (readToken(fTokenizer, &token)) {
2588 consumeToken(token);
2589 }
2590}
2591
2592PdfResult PdfInlineImageLooper::consumeToken(PdfToken& token) {
2593 //pdfContext.fInlineImage.fKeyValuePairs[key] = value;
2594 return kNYI_PdfResult;
2595}
2596
2597void PdfInlineImageLooper::loop() {
2598 PdfToken token;
2599 while (readToken(fTokenizer, &token)) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002600 if (token.fType == kKeyword_TokenType && strcmp(token.fKeyword, "BX") == 0) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002601 PdfTokenLooper* looper = new PdfCompatibilitySectionLooper();
2602 looper->setUp(this);
2603 looper->loop();
2604 } else {
edisonn@google.com59543d32013-06-18 22:00:40 +00002605 if (token.fType == kKeyword_TokenType && strcmp(token.fKeyword, "EI") == 0) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002606 done();
2607 return;
2608 }
2609
2610 consumeToken(token);
2611 }
2612 }
2613 // TODO(edisonn): report error/warning, EOF without EI.
2614}
2615
2616PdfResult PdfInlineImageLooper::done() {
2617
2618 // TODO(edisonn): long to short names
2619 // TODO(edisonn): set properties in a map
2620 // TODO(edisonn): extract bitmap stream, check if PoDoFo has public utilities to uncompress
2621 // the stream.
2622
2623 SkBitmap bitmap;
2624 setup_bitmap(&bitmap, 50, 50, SK_ColorRED);
2625
2626 // TODO(edisonn): matrix use.
2627 // Draw dummy red square, to show the prezence of the inline image.
2628 fCanvas->drawBitmap(bitmap,
2629 SkDoubleToScalar(0),
2630 SkDoubleToScalar(0),
2631 NULL);
2632 return kNYI_PdfResult;
2633}
2634
2635PdfResult PdfCompatibilitySectionLooper::consumeToken(PdfToken& token) {
2636 return fParent->consumeToken(token);
2637}
2638
2639void PdfCompatibilitySectionLooper::loop() {
2640 // TODO(edisonn): save stacks position, or create a new stack?
2641 // TODO(edisonn): what happens if we pop out more variables then when we started?
2642 // restore them? fail? We could create a new operands stack for every new BX/EX section,
2643 // pop-ing too much will not affect outside the section.
2644 PdfToken token;
2645 while (readToken(fTokenizer, &token)) {
edisonn@google.com59543d32013-06-18 22:00:40 +00002646 if (token.fType == kKeyword_TokenType && strcmp(token.fKeyword, "BX") == 0) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002647 PdfTokenLooper* looper = new PdfCompatibilitySectionLooper();
2648 looper->setUp(this);
2649 looper->loop();
2650 delete looper;
2651 } else {
edisonn@google.com59543d32013-06-18 22:00:40 +00002652 if (token.fType == kKeyword_TokenType && strcmp(token.fKeyword, "EX") == 0) break;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002653 fParent->consumeToken(token);
2654 }
2655 }
2656 // TODO(edisonn): restore stack.
2657}
2658
2659// TODO(edisonn): fix PoDoFo load ~/crashing/Shading.pdf
2660// TODO(edisonn): Add API for Forms viewing and editing
2661// e.g. SkBitmap getPage(int page);
2662// int formsCount();
2663// SkForm getForm(int formID); // SkForm(SkRect, .. other data)
2664// TODO (edisonn): Add intend when loading pdf, for example: for viewing, parsing all content, ...
2665// if we load the first page, and we zoom to fit to screen horizontally, then load only those
2666// resources needed, so the preview is fast.
2667// TODO (edisonn): hide parser/tokenizer behind and interface and a query language, and resolve
2668// references automatically.
2669class SkPdfViewer : public SkRefCnt {
2670public:
2671
2672 bool load(const SkString inputFileName, SkPicture* out) {
2673
2674 initPdfOperatorRenderes();
2675
2676 try
2677 {
2678 std::cout << "Init: " << inputFileName.c_str() << std::endl;
2679
edisonn@google.com59543d32013-06-18 22:00:40 +00002680 SkPdfDoc doc(inputFileName.c_str());
2681 if( !doc.pages() )
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002682 {
2683 std::cout << "ERROR: Empty Document" << inputFileName.c_str() << std::endl;
2684 return false;
2685 } else {
2686
edisonn@google.com59543d32013-06-18 22:00:40 +00002687 for (int pn = 0; pn < doc.pages(); ++pn) {
2688 SkPdfPageObjectDictionary* page = doc.page(pn);
2689
2690 // TODO(edisonn): implement inheritance properties as per PDF spec
2691 //SkRect rect = page->MediaBox();
2692 SkRect rect = doc.MediaBox(pn);
2693
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002694#ifdef PDF_TRACE
edisonn@google.com59543d32013-06-18 22:00:40 +00002695 printf("Page Width: %f, Page Height: %f\n", SkScalarToDouble(rect.width()), SkScalarToDouble(rect.height()));
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002696#endif
2697
2698 // TODO(edisonn): page->GetCropBox(), page->GetTrimBox() ... how to use?
2699
2700 SkBitmap bitmap;
2701#ifdef PDF_DEBUG_3X
edisonn@google.com59543d32013-06-18 22:00:40 +00002702 setup_bitmap(&bitmap, 3 * (int)SkScalarToDouble(rect.width()), 3 * (int)SkScalarToDouble(rect.height()))
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002703#else
edisonn@google.com59543d32013-06-18 22:00:40 +00002704 setup_bitmap(&bitmap, (int)SkScalarToDouble(rect.width()), (int)SkScalarToDouble(rect.height()));
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002705#endif
2706 SkAutoTUnref<SkDevice> device(SkNEW_ARGS(SkDevice, (bitmap)));
2707 SkCanvas canvas(device);
2708
edisonn@google.com59543d32013-06-18 22:00:40 +00002709 SkPdfTokenizer tokenizer = doc.tokenizerOfPage(pn);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002710
edisonn@google.com59543d32013-06-18 22:00:40 +00002711 PdfContext pdfContext(doc);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002712 pdfContext.fOriginalMatrix = SkMatrix::I();
edisonn@google.com59543d32013-06-18 22:00:40 +00002713 pdfContext.fGraphicsState.fResources = NULL;
2714 PodofoMapper::map(*page->Resources(), &pdfContext.fGraphicsState.fResources);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002715
2716 gPdfContext = &pdfContext;
2717 gDumpBitmap = &bitmap;
2718 gDumpCanvas = &canvas;
2719
2720
2721 // TODO(edisonn): get matrix stuff right.
2722 // TODO(edisonn): add DPI/scale/zoom.
2723 SkScalar z = SkIntToScalar(0);
edisonn@google.com59543d32013-06-18 22:00:40 +00002724 SkScalar w = rect.width();
2725 SkScalar h = rect.height();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002726
2727 SkPoint pdfSpace[4] = {SkPoint::Make(z, z), SkPoint::Make(w, z), SkPoint::Make(w, h), SkPoint::Make(z, h)};
2728// SkPoint skiaSpace[4] = {SkPoint::Make(z, h), SkPoint::Make(w, h), SkPoint::Make(w, z), SkPoint::Make(z, z)};
2729
2730 // TODO(edisonn): add flag for this app to create sourunding buffer zone
2731 // TODO(edisonn): add flagg for no clipping.
2732 // Use larger image to make sure we do not draw anything outside of page
2733 // could be used in tests.
2734
2735#ifdef PDF_DEBUG_3X
2736 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)};
2737#else
2738 SkPoint skiaSpace[4] = {SkPoint::Make(z, h), SkPoint::Make(w, h), SkPoint::Make(w, z), SkPoint::Make(z, z)};
2739#endif
2740 //SkPoint pdfSpace[2] = {SkPoint::Make(z, z), SkPoint::Make(w, h)};
2741 //SkPoint skiaSpace[2] = {SkPoint::Make(w, z), SkPoint::Make(z, h)};
2742
2743 //SkPoint pdfSpace[2] = {SkPoint::Make(z, z), SkPoint::Make(z, h)};
2744 //SkPoint skiaSpace[2] = {SkPoint::Make(z, h), SkPoint::Make(z, z)};
2745
2746 //SkPoint pdfSpace[3] = {SkPoint::Make(z, z), SkPoint::Make(z, h), SkPoint::Make(w, h)};
2747 //SkPoint skiaSpace[3] = {SkPoint::Make(z, h), SkPoint::Make(z, z), SkPoint::Make(w, 0)};
2748
2749 SkAssertResult(pdfContext.fOriginalMatrix.setPolyToPoly(pdfSpace, skiaSpace, 4));
2750 SkTraceMatrix(pdfContext.fOriginalMatrix, "Original matrix");
2751
2752
2753 pdfContext.fGraphicsState.fMatrix = pdfContext.fOriginalMatrix;
2754 pdfContext.fGraphicsState.fMatrixTm = pdfContext.fGraphicsState.fMatrix;
2755 pdfContext.fGraphicsState.fMatrixTlm = pdfContext.fGraphicsState.fMatrix;
2756
2757 canvas.setMatrix(pdfContext.fOriginalMatrix);
2758
2759#ifndef PDF_DEBUG_NO_PAGE_CLIPING
2760 canvas.clipRect(SkRect::MakeXYWH(z, z, w, h), SkRegion::kIntersect_Op, true);
2761#endif
2762
edisonn@google.com59543d32013-06-18 22:00:40 +00002763 PdfMainLooper looper(NULL, tokenizer, &pdfContext, &canvas);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002764 looper.loop();
2765
2766 canvas.flush();
2767
2768 SkString out;
2769 out.appendf("%s-%i.png", inputFileName.c_str(), pn);
2770 SkImageEncoder::EncodeFile(out.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100);
2771 }
2772 return true;
2773 }
2774 }
2775 catch( PdfError & e )
2776 {
2777 std::cout << "ERROR: PDF can't be parsed!" << inputFileName.c_str() << std::endl;
2778 return false;
2779 }
2780
2781 return true;
2782 }
2783 bool write(void*) const { return false; }
2784};
2785
2786
2787
2788/**
2789 * Given list of directories and files to use as input, expects to find .pdf
2790 * files and it will convert them to .png files writing them in the same directory
2791 * one file for each page.
2792 *
2793 * Returns zero exit code if all .pdf files were converted successfully,
2794 * otherwise returns error code 1.
2795 */
2796
2797static const char PDF_FILE_EXTENSION[] = "pdf";
2798static const char PNG_FILE_EXTENSION[] = "png";
2799
2800// TODO(edisonn): add ability to write to a new directory.
2801static void usage(const char* argv0) {
2802 SkDebugf("PDF to PNG rendering tool\n");
2803 SkDebugf("\n"
2804"Usage: \n"
2805" %s <input>... -w <outputDir> \n"
2806, argv0);
2807 SkDebugf("\n\n");
2808 SkDebugf(
2809" input: A list of directories and files to use as input. Files are\n"
2810" expected to have the .skp extension.\n\n");
2811 SkDebugf(
2812" outputDir: directory to write the rendered pdfs.\n\n");
2813 SkDebugf("\n");
2814}
2815
2816/** Replaces the extension of a file.
2817 * @param path File name whose extension will be changed.
2818 * @param old_extension The old extension.
2819 * @param new_extension The new extension.
2820 * @returns false if the file did not has the expected extension.
2821 * if false is returned, contents of path are undefined.
2822 */
2823static bool replace_filename_extension(SkString* path,
2824 const char old_extension[],
2825 const char new_extension[]) {
2826 if (path->endsWith(old_extension)) {
2827 path->remove(path->size() - strlen(old_extension),
2828 strlen(old_extension));
2829 if (!path->endsWith(".")) {
2830 return false;
2831 }
2832 path->append(new_extension);
2833 return true;
2834 }
2835 return false;
2836}
2837
2838/** Builds the output filename. path = dir/name, and it replaces expected
2839 * .skp extension with .pdf extention.
2840 * @param path Output filename.
2841 * @param name The name of the file.
2842 * @returns false if the file did not has the expected extension.
2843 * if false is returned, contents of path are undefined.
2844 */
2845static bool make_output_filepath(SkString* path, const SkString& dir,
2846 const SkString& name) {
2847 sk_tools::make_filepath(path, dir, name);
2848 return replace_filename_extension(path,
2849 PDF_FILE_EXTENSION,
2850 PNG_FILE_EXTENSION);
2851}
2852
2853/** Write the output of pdf renderer to a file.
2854 * @param outputDir Output dir.
2855 * @param inputFilename The skp file that was read.
2856 * @param renderer The object responsible to write the pdf file.
2857 */
2858static bool write_output(const SkString& outputDir,
2859 const SkString& inputFilename,
2860 const SkPdfViewer& renderer) {
2861 if (outputDir.isEmpty()) {
2862 SkDynamicMemoryWStream stream;
2863 renderer.write(&stream);
2864 return true;
2865 }
2866
2867 SkString outputPath;
2868 if (!make_output_filepath(&outputPath, outputDir, inputFilename)) {
2869 return false;
2870 }
2871
2872 SkFILEWStream stream(outputPath.c_str());
2873 if (!stream.isValid()) {
2874 SkDebugf("Could not write to file %s\n", outputPath.c_str());
2875 return false;
2876 }
2877 renderer.write(&stream);
2878
2879 return true;
2880}
2881
2882/** Reads an skp file, renders it to pdf and writes the output to a pdf file
2883 * @param inputPath The skp file to be read.
2884 * @param outputDir Output dir.
2885 * @param renderer The object responsible to render the skp object into pdf.
2886 */
2887static bool parse_pdf(const SkString& inputPath, const SkString& outputDir,
2888 SkPdfViewer& renderer) {
2889 SkString inputFilename;
2890 sk_tools::get_basename(&inputFilename, inputPath);
2891
2892 SkFILEStream inputStream;
2893 inputStream.setPath(inputPath.c_str());
2894 if (!inputStream.isValid()) {
2895 SkDebugf("Could not open file %s\n", inputPath.c_str());
2896 return false;
2897 }
2898
2899 bool success = false;
2900
2901 success = renderer.load(inputPath, NULL);
2902
2903
2904// success = write_output(outputDir, inputFilename, renderer);
2905
2906 //renderer.end();
2907 return success;
2908}
2909
2910/** For each file in the directory or for the file passed in input, call
2911 * parse_pdf.
2912 * @param input A directory or an pdf file.
2913 * @param outputDir Output dir.
2914 * @param renderer The object responsible to render the skp object into pdf.
2915 */
2916static int process_input(const SkString& input, const SkString& outputDir,
2917 SkPdfViewer& renderer) {
2918 int failures = 0;
2919 if (sk_isdir(input.c_str())) {
2920 SkOSFile::Iter iter(input.c_str(), PDF_FILE_EXTENSION);
2921 SkString inputFilename;
2922 while (iter.next(&inputFilename)) {
2923 SkString inputPath;
2924 sk_tools::make_filepath(&inputPath, input, inputFilename);
2925 if (!parse_pdf(inputPath, outputDir, renderer)) {
2926 ++failures;
2927 }
2928 }
2929 } else {
2930 SkString inputPath(input);
2931 if (!parse_pdf(inputPath, outputDir, renderer)) {
2932 ++failures;
2933 }
2934 }
2935 return failures;
2936}
2937
2938static void parse_commandline(int argc, char* const argv[],
2939 SkTArray<SkString>* inputs,
2940 SkString* outputDir) {
2941 const char* argv0 = argv[0];
2942 char* const* stop = argv + argc;
2943
2944 for (++argv; argv < stop; ++argv) {
2945 if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
2946 usage(argv0);
2947 exit(-1);
2948 } else if (0 == strcmp(*argv, "-w")) {
2949 ++argv;
2950 if (argv >= stop) {
2951 SkDebugf("Missing outputDir for -w\n");
2952 usage(argv0);
2953 exit(-1);
2954 }
2955 *outputDir = SkString(*argv);
2956 } else {
2957 inputs->push_back(SkString(*argv));
2958 }
2959 }
2960
2961 if (inputs->count() < 1) {
2962 usage(argv0);
2963 exit(-1);
2964 }
2965}
2966
2967int tool_main(int argc, char** argv);
2968int tool_main(int argc, char** argv) {
2969 SkAutoGraphics ag;
2970 SkTArray<SkString> inputs;
2971
2972 SkAutoTUnref<SkPdfViewer>
2973 renderer(SkNEW(SkPdfViewer));
2974 SkASSERT(renderer.get());
2975
2976 SkString outputDir;
2977 parse_commandline(argc, argv, &inputs, &outputDir);
2978
2979 int failures = 0;
2980 for (int i = 0; i < inputs.count(); i ++) {
2981 failures += process_input(inputs[i], outputDir, *renderer);
2982 }
2983
2984 reportPdfRenderStats();
2985
2986 if (failures != 0) {
2987 SkDebugf("Failed to render %i PDFs.\n", failures);
2988 return 1;
2989 }
2990
2991 return 0;
2992}
2993
2994#if !defined SK_BUILD_FOR_IOS
2995int main(int argc, char * const argv[]) {
2996 return tool_main(argc, (char**) argv);
2997}
2998#endif