blob: a8d4cf94bf3837c0fffebff0fc137e4f5b4a7838 [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
27bool LongFromDictionary(const PdfMemDocument* pdfDoc,
28 const PdfDictionary& dict,
29 const char* key,
30 const char* abr,
31 long* data);
32
33bool BoolFromDictionary(const PdfMemDocument* pdfDoc,
34 const PdfDictionary& dict,
35 const char* key,
36 const char* abr,
37 bool* data);
38
39bool NameFromDictionary(const PdfMemDocument* pdfDoc,
40 const PdfDictionary& dict,
41 const char* key,
42 const char* abr,
43 std::string* data);
44
45
46
47#include "pdf_auto_gen.h"
edisonn@google.com01cd4d52013-06-10 20:44:45 +000048
49/*
50 * TODO(edisonn): ASAP so skp -> pdf -> png looks greap
51 * - load gs/ especially smask and already known prop
52 * - use transparency (I think ca and CA ops)
53 * - load font for baidu.pdf
54 * - load font for youtube.pdf
55*/
56
edisonn@google.come4d11be2013-06-12 19:53:42 +000057//#define PDF_TRACE
edisonn@google.com01cd4d52013-06-10 20:44:45 +000058//#define PDF_TRACE_DIFF_IN_PNG
59//#define PDF_DEBUG_NO_CLIPING
60//#define PDF_DEBUG_NO_PAGE_CLIPING
61//#define PDF_DEBUG_3X
62
63// TODO(edisonn): move in trace util.
64#ifdef PDF_TRACE
65static void SkTraceMatrix(const SkMatrix& matrix, const char* sz = "") {
66 printf("SkMatrix %s ", sz);
67 for (int i = 0 ; i < 9 ; i++) {
68 printf("%f ", SkScalarToDouble(matrix.get(i)));
69 }
70 printf("\n");
71}
72#else
73#define SkTraceMatrix(a,b)
74#endif
75
76using namespace std;
77using namespace PoDoFo;
78
79// Utilities
80static void setup_bitmap(SkBitmap* bitmap, int width, int height, SkColor color = SK_ColorWHITE) {
81 bitmap->setConfig(SkBitmap::kARGB_8888_Config, width, height);
82
83 bitmap->allocPixels();
84 bitmap->eraseColor(color);
85}
86
87// TODO(edisonn): synonyms? DeviceRGB and RGB ...
88int GetColorSpaceComponents(const std::string& colorSpace) {
89 if (colorSpace == "DeviceCMYK") {
90 return 4;
91 } else if (colorSpace == "DeviceGray" ||
92 colorSpace == "CalGray" ||
93 colorSpace == "Indexed") {
94 return 1;
95 } else if (colorSpace == "DeviceRGB" ||
96 colorSpace == "CalRGB" ||
97 colorSpace == "Lab") {
98 return 3;
99 } else {
100 return 0;
101 }
102}
103
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000104const PdfObject* resolveReferenceObject(const PdfMemDocument* pdfDoc,
105 const PdfObject* obj,
106 bool resolveOneElementArrays = false) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000107 while (obj && (obj->IsReference() || (resolveOneElementArrays &&
108 obj->IsArray() &&
109 obj->GetArray().GetSize() == 1))) {
110 if (obj->IsReference()) {
111 // We need to force the non const, the only update we will do is for recurssion checks.
112 PdfReference& ref = (PdfReference&)obj->GetReference();
113 obj = pdfDoc->GetObjects().GetObject(ref);
114 } else {
115 obj = &obj->GetArray()[0];
116 }
117 }
118
119 return obj;
120}
121
122static SkMatrix SkMatrixFromPdfMatrix(double array[6]) {
123 SkMatrix matrix;
124 matrix.setAll(SkDoubleToScalar(array[0]),
125 SkDoubleToScalar(array[2]),
126 SkDoubleToScalar(array[4]),
127 SkDoubleToScalar(array[1]),
128 SkDoubleToScalar(array[3]),
129 SkDoubleToScalar(array[5]),
130 SkDoubleToScalar(0),
131 SkDoubleToScalar(0),
132 SkDoubleToScalar(1));
133
134 return matrix;
135}
136
137// TODO(edisonn): better class design.
138struct PdfColorOperator {
139 std::string fColorSpace; // TODO(edisonn): use SkString
140 SkColor fColor;
141 // TODO(edisonn): add here other color space options.
142
143 void setRGBColor(SkColor color) {
144 // TODO(edisonn): ASSERT DeviceRGB is the color space.
145 fColor = color;
146 }
147 // TODO(edisonn): double check the default values for all fields.
148 PdfColorOperator() : fColor(SK_ColorBLACK) {}
149};
150
151// TODO(edisonn): better class design.
152struct PdfGraphicsState {
153 SkMatrix fMatrix;
154 SkMatrix fMatrixTm;
155 SkMatrix fMatrixTlm;
156
157 double fCurPosX;
158 double fCurPosY;
159
160 double fCurFontSize;
161 bool fTextBlock;
162 PdfFont* fCurFont;
163 SkPath fPath;
164 bool fPathClosed;
165
166 // Clip that is applied after the drawing is done!!!
167 bool fHasClipPathToApply;
168 SkPath fClipPath;
169
170 PdfColorOperator fStroking;
171 PdfColorOperator fNonStroking;
172
173 double fLineWidth;
174 double fTextLeading;
175 double fWordSpace;
176 double fCharSpace;
177
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000178 const PdfObject* fObjectWithResources;
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000179
180 SkBitmap fSMask;
181
182 PdfGraphicsState() {
183 fCurPosX = 0.0;
184 fCurPosY = 0.0;
185 fCurFontSize = 0.0;
186 fTextBlock = false;
187 fCurFont = NULL;
188 fMatrix = SkMatrix::I();
189 fMatrixTm = SkMatrix::I();
190 fMatrixTlm = SkMatrix::I();
191 fPathClosed = true;
192 fLineWidth = 0;
193 fTextLeading = 0;
194 fWordSpace = 0;
195 fCharSpace = 0;
196 fObjectWithResources = NULL;
197 fHasClipPathToApply = false;
198 }
199};
200
201// TODO(edisonn): better class design.
202struct PdfInlineImage {
203 std::map<std::string, std::string> fKeyValuePairs;
204 std::string fImageData;
205
206};
207
208// TODO(edisonn): better class design.
209struct PdfContext {
210 std::stack<PdfVariant> fVarStack;
211 std::stack<PdfGraphicsState> fStateStack;
212 PdfGraphicsState fGraphicsState;
213 PoDoFo::PdfPage* fPdfPage;
214 PdfMemDocument* fPdfDoc;
215 SkMatrix fOriginalMatrix;
216
217 PdfInlineImage fInlineImage;
218
219 PdfContext() : fPdfPage(NULL),
220 fPdfDoc(NULL) {}
221
222};
223
224// TODO(edisonn): temporary code, to report how much of the PDF we actually think we rendered.
225enum PdfResult {
226 kOK_PdfResult,
227 kPartial_PdfResult,
228 kNYI_PdfResult,
229 kIgnoreError_PdfResult,
230 kError_PdfResult,
231 kUnsupported_PdfResult,
232
233 kCount_PdfResult
234};
235
236struct PdfToken {
237 const char* pszToken;
238 PdfVariant var;
239 EPdfContentsType eType;
240
241 PdfToken() : pszToken(NULL) {}
242};
243
244PdfContext* gPdfContext = NULL;
245SkBitmap* gDumpBitmap = NULL;
246SkCanvas* gDumpCanvas = NULL;
247char gLastKeyword[100] = "";
248int gLastOpKeyword = -1;
249char allOpWithVisualEffects[100] = ",S,s,f,F,f*,B,B*,b,b*,n,Tj,TJ,\',\",d0,d1,sh,EI,Do,EX";
250int gReadOp = 0;
251
252
253
254bool hasVisualEffect(const char* pdfOp) {
255 return true;
256 if (*pdfOp == '\0') return false;
257
258 char markedPdfOp[100] = ",";
259 strcat(markedPdfOp, pdfOp);
260 strcat(markedPdfOp, ",");
261
262 return (strstr(allOpWithVisualEffects, markedPdfOp) != NULL);
263}
264
265// TODO(edisonn): Pass PdfContext and SkCanvasd only with the define for instrumentation.
266static bool readToken(PdfContentsTokenizer* fTokenizer, PdfToken* token) {
267 bool ret = fTokenizer->ReadNext(token->eType, token->pszToken, token->var);
268
269 gReadOp++;
270
271#ifdef PDF_TRACE_DIFF_IN_PNG
272 // TODO(edisonn): compare with old bitmap, and save only new bits are available, and save
273 // the numbar and name of last operation, so the file name will reflect op that changed.
274 if (hasVisualEffect(gLastKeyword)) { // TODO(edisonn): and has dirty bits.
275 gDumpCanvas->flush();
276
277 SkBitmap bitmap;
278 setup_bitmap(&bitmap, gDumpBitmap->width(), gDumpBitmap->height());
279
280 memcpy(bitmap.getPixels(), gDumpBitmap->getPixels(), gDumpBitmap->getSize());
281
282 SkAutoTUnref<SkDevice> device(SkNEW_ARGS(SkDevice, (bitmap)));
283 SkCanvas canvas(device);
284
285 // draw context stuff here
286 SkPaint blueBorder;
287 blueBorder.setColor(SK_ColorBLUE);
288 blueBorder.setStyle(SkPaint::kStroke_Style);
289 blueBorder.setTextSize(SkDoubleToScalar(20));
290
291 SkString str;
292
293 const SkClipStack* clipStack = gDumpCanvas->getClipStack();
294 if (clipStack) {
295 SkClipStack::Iter iter(*clipStack, SkClipStack::Iter::kBottom_IterStart);
296 const SkClipStack::Element* elem;
297 double y = 0;
298 int total = 0;
299 while (elem = iter.next()) {
300 total++;
301 y += 30;
302
303 switch (elem->getType()) {
304 case SkClipStack::Element::kRect_Type:
305 canvas.drawRect(elem->getRect(), blueBorder);
306 canvas.drawText("Rect Clip", strlen("Rect Clip"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
307 break;
308 case SkClipStack::Element::kPath_Type:
309 canvas.drawPath(elem->getPath(), blueBorder);
310 canvas.drawText("Path Clip", strlen("Path Clip"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
311 break;
312 case SkClipStack::Element::kEmpty_Type:
313 canvas.drawText("Empty Clip!!!", strlen("Empty Clip!!!"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
314 break;
315 default:
316 canvas.drawText("Unkown Clip!!!", strlen("Unkown Clip!!!"), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
317 break;
318 }
319 }
320
321 y += 30;
322 str.printf("Number of clips in stack: %i", total);
323 canvas.drawText(str.c_str(), str.size(), SkDoubleToScalar(10), SkDoubleToScalar(y), blueBorder);
324 }
325
326 const SkRegion& clipRegion = gDumpCanvas->getTotalClip();
327 SkPath clipPath;
328 if (clipRegion.getBoundaryPath(&clipPath)) {
329 SkPaint redBorder;
330 redBorder.setColor(SK_ColorRED);
331 redBorder.setStyle(SkPaint::kStroke_Style);
332 canvas.drawPath(clipPath, redBorder);
333 }
334
335 canvas.flush();
336
337 SkString out;
338
339 // TODO(edisonn): get the image, and overlay on top of it, the clip , grafic state, teh stack,
340 // ... and other properties, to be able to debug th code easily
341
342 out.appendf("/usr/local/google/home/edisonn/log_view2/step-%i-%s.png", gLastOpKeyword, gLastKeyword);
343 SkImageEncoder::EncodeFile(out.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100);
344 }
345
346 if (token->eType == ePdfContentsType_Keyword) {
347 strcpy(gLastKeyword, token->pszToken);
348 gLastOpKeyword = gReadOp;
349 } else {
350 strcpy(gLastKeyword, "");
351 }
352#endif
353
354 return ret;
355}
356
357// TODO(edisonn): Document PdfTokenLooper and subclasses.
358class PdfTokenLooper {
359protected:
360 PdfTokenLooper* fParent;
361 PdfContentsTokenizer* fTokenizer;
362 PdfContext* fPdfContext;
363 SkCanvas* fCanvas;
364
365public:
366 PdfTokenLooper(PdfTokenLooper* parent,
367 PdfContentsTokenizer* tokenizer,
368 PdfContext* pdfContext,
369 SkCanvas* canvas)
370 : fParent(parent), fTokenizer(tokenizer), fPdfContext(pdfContext), fCanvas(canvas) {}
371
372 virtual PdfResult consumeToken(PdfToken& token) = 0;
373 virtual void loop() = 0;
374
375 void setUp(PdfTokenLooper* parent) {
376 fParent = parent;
377 fTokenizer = parent->fTokenizer;
378 fPdfContext = parent->fPdfContext;
379 fCanvas = parent->fCanvas;
380 }
381};
382
383class PdfMainLooper : public PdfTokenLooper {
384public:
385 PdfMainLooper(PdfTokenLooper* parent,
386 PdfContentsTokenizer* tokenizer,
387 PdfContext* pdfContext,
388 SkCanvas* canvas)
389 : PdfTokenLooper(parent, tokenizer, pdfContext, canvas) {}
390
391 virtual PdfResult consumeToken(PdfToken& token);
392 virtual void loop();
393};
394
395class PdfInlineImageLooper : public PdfTokenLooper {
396public:
397 PdfInlineImageLooper()
398 : PdfTokenLooper(NULL, NULL, NULL, NULL) {}
399
400 virtual PdfResult consumeToken(PdfToken& token);
401 virtual void loop();
402 PdfResult done();
403};
404
405class PdfCompatibilitySectionLooper : public PdfTokenLooper {
406public:
407 PdfCompatibilitySectionLooper()
408 : PdfTokenLooper(NULL, NULL, NULL, NULL) {}
409
410 virtual PdfResult consumeToken(PdfToken& token);
411 virtual void loop();
412};
413
414typedef PdfResult (*PdfOperatorRenderer)(PdfContext*, SkCanvas*, PdfTokenLooper**);
415
416map<std::string, PdfOperatorRenderer> gPdfOps;
417
418map<std::string, int> gRenderStats[kCount_PdfResult];
419
420char* gRenderStatsNames[kCount_PdfResult] = {
421 "Success",
422 "Partially implemented",
423 "Not yet implemented",
424 "Ignore Error",
425 "Error",
426 "Unsupported/Unknown"
427};
428
429struct SkPdfStandardFont {
430 const char* fName;
431 bool fIsBold;
432 bool fIsItalic;
433};
434
435static map<std::string, SkPdfStandardFont>& getStandardFonts() {
436 static std::map<std::string, SkPdfStandardFont> gPdfStandardFonts;
437
438 // TODO (edisonn): , vs - ? what does it mean?
439 // TODO (edisonn): MT, PS, Oblique=italic?, ... what does it mean?
440 if (gPdfStandardFonts.empty()) {
441 gPdfStandardFonts["Arial"] = {"Arial", false, false};
442 gPdfStandardFonts["Arial,Bold"] = {"Arial", true, false};
443 gPdfStandardFonts["Arial,BoldItalic"] = {"Arial", true, true};
444 gPdfStandardFonts["Arial,Italic"] = {"Arial", false, true};
445 gPdfStandardFonts["Arial-Bold"] = {"Arial", true, false};
446 gPdfStandardFonts["Arial-BoldItalic"] = {"Arial", true, true};
447 gPdfStandardFonts["Arial-BoldItalicMT"] = {"Arial", true, true};
448 gPdfStandardFonts["Arial-BoldMT"] = {"Arial", true, false};
449 gPdfStandardFonts["Arial-Italic"] = {"Arial", false, true};
450 gPdfStandardFonts["Arial-ItalicMT"] = {"Arial", false, true};
451 gPdfStandardFonts["ArialMT"] = {"Arial", false, false};
452 gPdfStandardFonts["Courier"] = {"Courier New", false, false};
453 gPdfStandardFonts["Courier,Bold"] = {"Courier New", true, false};
454 gPdfStandardFonts["Courier,BoldItalic"] = {"Courier New", true, true};
455 gPdfStandardFonts["Courier,Italic"] = {"Courier New", false, true};
456 gPdfStandardFonts["Courier-Bold"] = {"Courier New", true, false};
457 gPdfStandardFonts["Courier-BoldOblique"] = {"Courier New", true, true};
458 gPdfStandardFonts["Courier-Oblique"] = {"Courier New", false, true};
459 gPdfStandardFonts["CourierNew"] = {"Courier New", false, false};
460 gPdfStandardFonts["CourierNew,Bold"] = {"Courier New", true, false};
461 gPdfStandardFonts["CourierNew,BoldItalic"] = {"Courier New", true, true};
462 gPdfStandardFonts["CourierNew,Italic"] = {"Courier New", false, true};
463 gPdfStandardFonts["CourierNew-Bold"] = {"Courier New", true, false};
464 gPdfStandardFonts["CourierNew-BoldItalic"] = {"Courier New", true, true};
465 gPdfStandardFonts["CourierNew-Italic"] = {"Courier New", false, true};
466 gPdfStandardFonts["CourierNewPS-BoldItalicMT"] = {"Courier New", true, true};
467 gPdfStandardFonts["CourierNewPS-BoldMT"] = {"Courier New", true, false};
468 gPdfStandardFonts["CourierNewPS-ItalicMT"] = {"Courier New", false, true};
469 gPdfStandardFonts["CourierNewPSMT"] = {"Courier New", false, false};
470 gPdfStandardFonts["Helvetica"] = {"Helvetica", false, false};
471 gPdfStandardFonts["Helvetica,Bold"] = {"Helvetica", true, false};
472 gPdfStandardFonts["Helvetica,BoldItalic"] = {"Helvetica", true, true};
473 gPdfStandardFonts["Helvetica,Italic"] = {"Helvetica", false, true};
474 gPdfStandardFonts["Helvetica-Bold"] = {"Helvetica", true, false};
475 gPdfStandardFonts["Helvetica-BoldItalic"] = {"Helvetica", true, true};
476 gPdfStandardFonts["Helvetica-BoldOblique"] = {"Helvetica", true, true};
477 gPdfStandardFonts["Helvetica-Italic"] = {"Helvetica", false, true};
478 gPdfStandardFonts["Helvetica-Oblique"] = {"Helvetica", false, true};
479 gPdfStandardFonts["Times-Bold"] = {"Times", true, false};
480 gPdfStandardFonts["Times-BoldItalic"] = {"Times", true, true};
481 gPdfStandardFonts["Times-Italic"] = {"Times", false, true};
482 gPdfStandardFonts["Times-Roman"] = {"Times New Roman", false, false};
483 gPdfStandardFonts["TimesNewRoman"] = {"Times New Roman", false, false};
484 gPdfStandardFonts["TimesNewRoman,Bold"] = {"Times New Roman", true, false};
485 gPdfStandardFonts["TimesNewRoman,BoldItalic"] = {"Times New Roman", true, true};
486 gPdfStandardFonts["TimesNewRoman,Italic"] = {"Times New Roman", false, true};
487 gPdfStandardFonts["TimesNewRoman-Bold"] = {"Times New Roman", true, false};
488 gPdfStandardFonts["TimesNewRoman-BoldItalic"] = {"Times New Roman", true, true};
489 gPdfStandardFonts["TimesNewRoman-Italic"] = {"Times New Roman", false, true};
490 gPdfStandardFonts["TimesNewRomanPS"] = {"Times New Roman", false, false};
491 gPdfStandardFonts["TimesNewRomanPS-Bold"] = {"Times New Roman", true, false};
492 gPdfStandardFonts["TimesNewRomanPS-BoldItalic"] = {"Times New Roman", true, true};
493 gPdfStandardFonts["TimesNewRomanPS-BoldItalicMT"] = {"Times New Roman", true, true};
494 gPdfStandardFonts["TimesNewRomanPS-BoldMT"] = {"Times New Roman", true, false};
495 gPdfStandardFonts["TimesNewRomanPS-Italic"] = {"Times New Roman", false, true};
496 gPdfStandardFonts["TimesNewRomanPS-ItalicMT"] = {"Times New Roman", false, true};
497 gPdfStandardFonts["TimesNewRomanPSMT"] = {"Times New Roman", false, false};
498 }
499
500 return gPdfStandardFonts;
501}
502
503static SkTypeface* SkTypefaceFromPdfStandardFont(const char* fontName, bool bold, bool italic) {
504 map<std::string, SkPdfStandardFont>& standardFontMap = getStandardFonts();
505
506 if (standardFontMap.find(fontName) != standardFontMap.end()) {
507 SkPdfStandardFont fontData = standardFontMap[fontName];
508
509 // TODO(edisonn): How does the bold/italic specified in standard definition combines with
510 // the one in /font key? use OR for now.
511 bold = bold || fontData.fIsBold;
512 italic = italic || fontData.fIsItalic;
513
514 SkTypeface* typeface = SkTypeface::CreateFromName(
515 fontData.fName,
516 SkTypeface::Style((bold ? SkTypeface::kBold : 0) |
517 (italic ? SkTypeface::kItalic : 0)));
518 if (typeface) {
519 typeface->ref();
520 }
521 return typeface;
522 }
523 return NULL;
524}
525
526static SkTypeface* SkTypefaceFromPdfFont(PdfFont* font) {
527 PdfObject* fontObject = font->GetObject();
528
529 PdfObject* pBaseFont = NULL;
530 // TODO(edisonn): warning, PoDoFo has a bug in PdfFont constructor, does not call InitVars()
531 // for now fixed locally.
532 pBaseFont = fontObject->GetIndirectKey( "BaseFont" );
533 const char* pszBaseFontName = pBaseFont->GetName().GetName().c_str();
534
535#ifdef PDF_TRACE
536 std::string str;
537 fontObject->ToString(str);
538 printf("Base Font Name: %s\n", pszBaseFontName);
539 printf("Font Object Data: %s\n", str.c_str());
540#endif
541
542 SkTypeface* typeface = SkTypefaceFromPdfStandardFont(pszBaseFontName, font->IsBold(), font->IsItalic());
543
544 if (typeface != NULL) {
545 return typeface;
546 }
547
548 char name[1000];
549 // HACK
550 strncpy(name, pszBaseFontName, 1000);
551 char* comma = strstr(name, ",");
552 char* dash = strstr(name, "-");
553 if (comma) *comma = '\0';
554 if (dash) *dash = '\0';
555
556 typeface = SkTypeface::CreateFromName(
557 name,
558 SkTypeface::Style((font->IsBold() ? SkTypeface::kBold : 0) |
559 (font->IsItalic() ? SkTypeface::kItalic : 0)));
560
561 if (typeface != NULL) {
562#ifdef PDF_TRACE
563 printf("HACKED FONT found %s\n", name);
564#endif
565 return typeface;
566 }
567
568#ifdef PDF_TRACE
569 printf("FONT_NOT_FOUND %s\n", pszBaseFontName);
570#endif
571
572 // TODO(edisonn): Report Warning, NYI
573 return SkTypeface::CreateFromName(
574 "Times New Roman",
575 SkTypeface::Style((font->IsBold() ? SkTypeface::kBold : 0) |
576 (font->IsItalic() ? SkTypeface::kItalic : 0)));
577}
578
579// TODO(edisonn): move this code in podofo, so we don't have to fix the font.
580// This logic needs to be moved in PdfEncodingObjectFactory::CreateEncoding
581std::map<PdfFont*, PdfCMapEncoding*> gFontsFixed;
582PdfEncoding* FixPdfFont(PdfContext* pdfContext, PdfFont* fCurFont) {
583 // TODO(edisonn): and is Identity-H
584 if (gFontsFixed.find(fCurFont) == gFontsFixed.end()) {
585 if (fCurFont->GetObject()->IsDictionary() && fCurFont->GetObject()->GetDictionary().HasKey(PdfName("ToUnicode"))) {
586 PdfCMapEncoding* enc = new PdfCMapEncoding(
587 fCurFont->GetObject(),
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000588 (PdfObject*)resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000589 fCurFont->GetObject()->GetDictionary().GetKey(PdfName("ToUnicode"))),
590 PdfCMapEncoding::eBaseEncoding_Identity); // todo, read the base encoding
591 gFontsFixed[fCurFont] = enc;
592 return enc;
593 }
594
595 return NULL;
596 }
597
598 return gFontsFixed[fCurFont];
599}
600
601PdfResult DrawText(PdfContext* pdfContext,
602 PdfFont* fCurFont,
603 const PdfString& rString,
604 SkCanvas* canvas)
605{
606 if (!fCurFont)
607 {
608 // TODO(edisonn): ignore the error, use the default font?
609 return kError_PdfResult;
610 }
611
612 const PdfEncoding* enc = FixPdfFont(pdfContext, fCurFont);
613 bool cMapUnicodeFont = enc != NULL;
614 if (!enc) enc = fCurFont->GetEncoding();
615 if (!enc)
616 {
617 // TODO(edisonn): Can we recover from this error?
618 return kError_PdfResult;
619 }
620
621 PdfString r2 = rString;
622 PdfString unicode;
623
624 if (cMapUnicodeFont) {
625 r2 = PdfString((pdf_utf16be*)rString.GetString(), rString.GetLength() / 2);
626 }
627
628 unicode = enc->ConvertToUnicode( r2, fCurFont );
629
630#ifdef PDF_TRACE
631 printf("%i %i ? %c rString.len = %i\n", (int)rString.GetString()[0], (int)rString.GetString()[1], (int)rString.GetString()[1], rString.GetLength());
632 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());
633#endif
634
635 SkPaint paint;
636 // TODO(edisonn): when should fCurFont->GetFontSize() used? When cur is fCurFontSize == 0?
637 // Or maybe just not call setTextSize at all?
638 if (pdfContext->fGraphicsState.fCurFontSize != 0) {
639 paint.setTextSize(SkDoubleToScalar(pdfContext->fGraphicsState.fCurFontSize));
640 }
641 if (fCurFont->GetFontScale() != 0) {
642 paint.setTextScaleX(SkFloatToScalar(fCurFont->GetFontScale() / 100.0));
643 }
644 paint.setColor(pdfContext->fGraphicsState.fNonStroking.fColor);
645
646 paint.setTypeface(SkTypefaceFromPdfFont(fCurFont));
647
648 paint.setAntiAlias(true);
649 // TODO(edisonn): paint.setStyle(...);
650
651 canvas->save();
652 SkMatrix matrix = pdfContext->fGraphicsState.fMatrixTm;
653
654#if 0
655 // Reverse now the space, otherwise the text is upside down.
656 SkScalar z = SkIntToScalar(0);
657 SkScalar one = SkIntToScalar(1);
658
659 SkPoint normalSpace1[4] = {SkPoint::Make(z, z), SkPoint::Make(one, z), SkPoint::Make(one, one), SkPoint::Make(z, one)};
660 SkPoint mirrorSpace1[4];
661 pdfContext->fGraphicsState.fMatrixTm.mapPoints(mirrorSpace1, normalSpace1, 4);
662
663 SkPoint normalSpace2[4] = {SkPoint::Make(z, z), SkPoint::Make(one, z), SkPoint::Make(one, -one), SkPoint::Make(z, -one)};
664 SkPoint mirrorSpace2[4];
665 pdfContext->fGraphicsState.fMatrixTm.mapPoints(mirrorSpace2, normalSpace2, 4);
666
667#ifdef PDF_TRACE
668 printf("mirror1[0], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[0].x()), SkScalarToDouble(mirrorSpace1[0].y()));
669 printf("mirror1[1], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[1].x()), SkScalarToDouble(mirrorSpace1[1].y()));
670 printf("mirror1[2], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[2].x()), SkScalarToDouble(mirrorSpace1[2].y()));
671 printf("mirror1[3], x = %f y = %f\n", SkScalarToDouble(mirrorSpace1[3].x()), SkScalarToDouble(mirrorSpace1[3].y()));
672 printf("mirror2[0], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[0].x()), SkScalarToDouble(mirrorSpace2[0].y()));
673 printf("mirror2[1], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[1].x()), SkScalarToDouble(mirrorSpace2[1].y()));
674 printf("mirror2[2], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[2].x()), SkScalarToDouble(mirrorSpace2[2].y()));
675 printf("mirror2[3], x = %f y = %f\n", SkScalarToDouble(mirrorSpace2[3].x()), SkScalarToDouble(mirrorSpace2[3].y()));
676#endif
677
678 SkMatrix mirror;
679 SkASSERT(mirror.setPolyToPoly(mirrorSpace1, mirrorSpace2, 4));
680
681 // TODO(edisonn): text positioning wrong right now. Need to get matrix operations right.
682 matrix.preConcat(mirror);
683 canvas->setMatrix(matrix);
684#endif
685
686 SkPoint point1;
687 pdfContext->fGraphicsState.fMatrixTm.mapXY(SkIntToScalar(0), SkIntToScalar(0), &point1);
688
689 SkMatrix mirror;
690 mirror.setTranslate(0, -point1.y());
691 // TODO(edisonn): fix rotated text, and skewed too
692 mirror.postScale(SK_Scalar1, -SK_Scalar1);
693 // TODO(edisonn): post rotate, skew
694 mirror.postTranslate(0, point1.y());
695
696 matrix.postConcat(mirror);
697
698 canvas->setMatrix(matrix);
699
700 SkTraceMatrix(matrix, "mirrored");
701
702#ifdef PDF_TRACE
703 SkPoint point;
704 pdfContext->fGraphicsState.fMatrixTm.mapXY(SkDoubleToScalar(0), SkDoubleToScalar(0), &point);
705 printf("Original SkCanvas resolved coordinates, x = %f y = %f\n", SkScalarToDouble(point.x()), SkScalarToDouble(point.y()));
706 matrix.mapXY(SkDoubleToScalar(0), SkDoubleToScalar(0), &point);
707 printf("Mirored SkCanvas resolved coordinates, x = %f y = %f\n", SkScalarToDouble(point.x()), SkScalarToDouble(point.y()));
708#endif
709
710 // TODO(edisonn): remove this call once we load the font properly
711 // The extra * will show that we got at least the text positioning right
712 // even if font failed to be loaded
713// canvas->drawText(".", 1, SkDoubleToScalar(-5.0), SkDoubleToScalar(0.0), paint);
714
715
716
717 // TODO(edisonn): use character and word spacing .. add utility function
718 if (cMapUnicodeFont) {
719 paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
720 SkScalar textWidth = paint.measureText(unicode.GetString(), unicode.GetLength());
721 pdfContext->fGraphicsState.fMatrixTm.preTranslate(textWidth, SkDoubleToScalar(0.0));
722 canvas->drawText(unicode.GetString(), unicode.GetLength(), SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), paint);
723 }
724 else {
725 paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
726 SkScalar textWidth = paint.measureText(unicode.GetStringUtf8().c_str(), strlen(unicode.GetStringUtf8().c_str()));
727 pdfContext->fGraphicsState.fMatrixTm.preTranslate(textWidth, SkDoubleToScalar(0.0));
728 canvas->drawText(unicode.GetStringUtf8().c_str(), strlen(unicode.GetStringUtf8().c_str()), SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), paint);
729 }
730
731// paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
732// unsigned char ch = *(unicode.GetString() + 3);
733// if ((ch & 0xC0) != 0x80 && ch < 0x80) {
734// printf("x%i", ch);
735// SkScalar textWidth = paint.measureText(&ch, 1);
736// pdfContext->fGraphicsState.fMatrixTm.preTranslate(textWidth, SkDoubleToScalar(0.0));
737// canvas->drawText(&ch, 1, SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), paint);
738// }
739
740 canvas->restore();
741
742
743 return kPartial_PdfResult;
744}
745
746// TODO(edisonn): create header files with declarations!
747PdfResult PdfOp_q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
748PdfResult PdfOp_Q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
749PdfResult PdfOp_Tw(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
750PdfResult PdfOp_Tc(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper);
751
752// TODO(edisonn): deal with synonyms (/BPC == /BitsPerComponent), here or in GetKey?
753// Always pass long form in key, and have a map of long -> short key
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000754bool LongFromDictionary(const PdfMemDocument* pdfDoc,
755 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000756 const char* key,
757 long* data) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000758 const PdfObject* value = resolveReferenceObject(pdfDoc,
759 dict.GetKey(PdfName(key)));
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000760
761 if (value == NULL || !value->IsNumber()) {
762 return false;
763 }
764
765 *data = value->GetNumber();
766 return true;
767}
768
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000769bool LongFromDictionary(const PdfMemDocument* pdfDoc,
770 const PdfDictionary& dict,
771 const char* key,
772 const char* abr,
773 long* data) {
774 if (LongFromDictionary(pdfDoc, dict, key, data)) return true;
775 if (abr == NULL || *abr == '\0') return false;
776 return LongFromDictionary(pdfDoc, dict, abr, data);
777}
778
779bool BoolFromDictionary(const PdfMemDocument* pdfDoc,
780 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000781 const char* key,
782 bool* data) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000783 const PdfObject* value = resolveReferenceObject(pdfDoc,
784 dict.GetKey(PdfName(key)));
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000785
786 if (value == NULL || !value->IsBool()) {
787 return false;
788 }
789
790 *data = value->GetBool();
791 return true;
792}
793
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000794bool BoolFromDictionary(const PdfMemDocument* pdfDoc,
795 const PdfDictionary& dict,
796 const char* key,
797 const char* abr,
798 bool* data) {
799 if (BoolFromDictionary(pdfDoc, dict, key, data)) return true;
800 if (abr == NULL || *abr == '\0') return false;
801 return BoolFromDictionary(pdfDoc, dict, abr, data);
802}
803
804bool NameFromDictionary(const PdfMemDocument* pdfDoc,
805 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000806 const char* key,
807 std::string* data) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000808 const PdfObject* value = resolveReferenceObject(pdfDoc,
809 dict.GetKey(PdfName(key)),
810 true);
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000811 if (value == NULL || !value->IsName()) {
812 return false;
813 }
814
815 *data = value->GetName().GetName();
816 return true;
817}
818
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000819bool NameFromDictionary(const PdfMemDocument* pdfDoc,
820 const PdfDictionary& dict,
821 const char* key,
822 const char* abr,
823 std::string* data) {
824 if (NameFromDictionary(pdfDoc, dict, key, data)) return true;
825 if (abr == NULL || *abr == '\0') return false;
826 return NameFromDictionary(pdfDoc, dict, abr, data);
827}
828
edisonn@google.com01cd4d52013-06-10 20:44:45 +0000829// TODO(edisonn): perf!!!
830
831static SkColorTable* getGrayColortable() {
832 static SkColorTable* grayColortable = NULL;
833 if (grayColortable == NULL) {
834 SkPMColor* colors = new SkPMColor[256];
835 for (int i = 0 ; i < 256; i++) {
836 colors[i] = SkPreMultiplyARGB(255, i, i, i);
837 }
838 grayColortable = new SkColorTable(colors, 256);
839 }
840 return grayColortable;
841}
842
843SkBitmap transferImageStreamToBitmap(unsigned char* uncompressedStream, pdf_long uncompressedStreamLength,
844 int width, int height, int bytesPerLine,
845 int bpc, const std::string& colorSpace,
846 bool transparencyMask) {
847 SkBitmap bitmap;
848
849 int components = GetColorSpaceComponents(colorSpace);
850//#define MAX_COMPONENTS 10
851
852 int bitsPerLine = width * components * bpc;
853 // TODO(edisonn): assume start of lines are aligned at 32 bits?
854 // Is there a faster way to load the uncompressed stream into a bitmap?
855
856 // minimal support for now
857 if ((colorSpace == "DeviceRGB" || colorSpace == "RGB") && bpc == 8) {
858 SkColor* uncompressedStreamArgb = (SkColor*)malloc(width * height * sizeof(SkColor));
859
860 for (int h = 0 ; h < height; h++) {
861 long i = width * (height - 1 - h);
862 for (int w = 0 ; w < width; w++) {
863 uncompressedStreamArgb[i] = SkColorSetRGB(uncompressedStream[3 * w],
864 uncompressedStream[3 * w + 1],
865 uncompressedStream[3 * w + 2]);
866 i++;
867 }
868 uncompressedStream += bytesPerLine;
869 }
870
871 bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
872 bitmap.setPixels(uncompressedStreamArgb);
873 }
874 else if ((colorSpace == "DeviceGray" || colorSpace == "Gray") && bpc == 8) {
875 unsigned char* uncompressedStreamA8 = (unsigned char*)malloc(width * height);
876
877 for (int h = 0 ; h < height; h++) {
878 long i = width * (height - 1 - h);
879 for (int w = 0 ; w < width; w++) {
880 uncompressedStreamA8[i] = transparencyMask ? 255 - uncompressedStream[w] :
881 uncompressedStream[w];
882 i++;
883 }
884 uncompressedStream += bytesPerLine;
885 }
886
887 bitmap.setConfig(transparencyMask ? SkBitmap::kA8_Config : SkBitmap::kIndex8_Config,
888 width, height);
889 bitmap.setPixels(uncompressedStreamA8, transparencyMask ? NULL : getGrayColortable());
890 }
891
892 // TODO(edisonn): Report Warning, NYI, or error
893 return bitmap;
894}
895
896bool transferImageStreamToARGB(unsigned char* uncompressedStream, pdf_long uncompressedStreamLength,
897 int width, int bytesPerLine,
898 int bpc, const std::string& colorSpace,
899 SkColor** uncompressedStreamArgb,
900 pdf_long* uncompressedStreamLengthInBytesArgb) {
901 int components = GetColorSpaceComponents(colorSpace);
902//#define MAX_COMPONENTS 10
903
904 int bitsPerLine = width * components * bpc;
905 // TODO(edisonn): assume start of lines are aligned at 32 bits?
906 int height = uncompressedStreamLength / bytesPerLine;
907
908 // minimal support for now
909 if ((colorSpace == "DeviceRGB" || colorSpace == "RGB") && bpc == 8) {
910 *uncompressedStreamLengthInBytesArgb = width * height * 4;
911 *uncompressedStreamArgb = (SkColor*)malloc(*uncompressedStreamLengthInBytesArgb);
912
913 for (int h = 0 ; h < height; h++) {
914 long i = width * (height - 1 - h);
915 for (int w = 0 ; w < width; w++) {
916 (*uncompressedStreamArgb)[i] = SkColorSetRGB(uncompressedStream[3 * w],
917 uncompressedStream[3 * w + 1],
918 uncompressedStream[3 * w + 2]);
919 i++;
920 }
921 uncompressedStream += bytesPerLine;
922 }
923 return true;
924 }
925
926 if ((colorSpace == "DeviceGray" || colorSpace == "Gray") && bpc == 8) {
927 *uncompressedStreamLengthInBytesArgb = width * height * 4;
928 *uncompressedStreamArgb = (SkColor*)malloc(*uncompressedStreamLengthInBytesArgb);
929
930 for (int h = 0 ; h < height; h++) {
931 long i = width * (height - 1 - h);
932 for (int w = 0 ; w < width; w++) {
933 (*uncompressedStreamArgb)[i] = SkColorSetRGB(uncompressedStream[w],
934 uncompressedStream[w],
935 uncompressedStream[w]);
936 i++;
937 }
938 uncompressedStream += bytesPerLine;
939 }
940 return true;
941 }
942
943 return false;
944}
945
946// utils
947
948// TODO(edisonn): add cache, or put the bitmap property directly on the PdfObject
949// TODO(edisonn): deal with colorSpaces, we could add them to SkBitmap::Config
950// TODO(edisonn): preserve A1 format that skia knows, + fast convert from 111, 222, 444 to closest
951// skia format, through a table
952
953// this functions returns the image, it does not look at the smask.
954
edisonn@google.comaf3daa02013-06-12 19:07:45 +0000955SkBitmap getImageFromObject(PdfContext* pdfContext, const SkPdfImage* image, bool transparencyMask) {
956 if (image == NULL || !image->valid()) {
957 // TODO(edisonn): report warning to be used in testing.
958 return SkBitmap();
959 }
960
961 // TODO (edisonn): Fast Jpeg(DCTDecode) draw, or fast PNG(FlateDecode) draw ...
962// PdfObject* value = resolveReferenceObject(pdfContext->fPdfDoc,
963// obj.GetDictionary().GetKey(PdfName("Filter")));
964// if (value && value->IsArray() && value->GetArray().GetSize() == 1) {
965// value = resolveReferenceObject(pdfContext->fPdfDoc,
966// &value->GetArray()[0]);
967// }
968// if (value && value->IsName() && value->GetName().GetName() == "DCTDecode") {
969// SkStream stream = SkStream::
970// SkImageDecoder::Factory()
971// }
972
973 long bpc = image->bpc();
974 long width = image->w();
975 long height = image->h();
976 std::string colorSpace = image->cs();
977
978/*
979 bool imageMask = image->imageMask();
980
981 if (imageMask) {
982 if (bpc != 0 && bpc != 1) {
983 // TODO(edisonn): report warning to be used in testing.
984 return SkBitmap();
985 }
986 bpc = 1;
987 }
988*/
989
990 const PdfObject* obj = image->podofo();
991
992 char* uncompressedStream = NULL;
993 pdf_long uncompressedStreamLength = 0;
994
995 PdfResult ret = kPartial_PdfResult;
996 // TODO(edisonn): get rid of try/catch exceptions! We should not throw on user data!
997 try {
998 obj->GetStream()->GetFilteredCopy(&uncompressedStream, &uncompressedStreamLength);
999 } catch (PdfError& e) {
1000 // TODO(edisonn): report warning to be used in testing.
1001 return SkBitmap();
1002 }
1003
1004 int bytesPerLine = uncompressedStreamLength / height;
1005#ifdef PDF_TRACE
1006 if (uncompressedStreamLength % height != 0) {
1007 printf("Warning uncompressedStreamLength % height != 0 !!!\n");
1008 }
1009#endif
1010
1011 SkBitmap bitmap = transferImageStreamToBitmap(
1012 (unsigned char*)uncompressedStream, uncompressedStreamLength,
1013 width, height, bytesPerLine,
1014 bpc, colorSpace,
1015 transparencyMask);
1016
1017 free(uncompressedStream);
1018
1019 return bitmap;
1020}
1021
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001022SkBitmap getSmaskFromObject(PdfContext* pdfContext, const SkPdfImage* obj) {
1023 const PdfObject* sMask = resolveReferenceObject(pdfContext->fPdfDoc,
1024 obj->podofo()->GetDictionary().GetKey(PdfName("SMask")));
1025
1026#ifdef PDF_TRACE
1027 std::string str;
1028 if (sMask) {
1029 sMask->ToString(str);
1030 printf("/SMask of /Subtype /Image: %s\n", str.c_str());
1031 }
1032#endif
1033
1034 if (sMask) {
1035 SkPdfImage skxobjmask(pdfContext->fPdfDoc, sMask);
1036 return getImageFromObject(pdfContext, &skxobjmask, true);
1037 }
1038
1039 // TODO(edisonn): implement GS SMask. Default to empty right now.
1040 return pdfContext->fGraphicsState.fSMask;
1041}
1042
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001043PdfResult doXObject_Image(PdfContext* pdfContext, SkCanvas* canvas, const SkPdfImage* skpdfimage) {
1044 if (skpdfimage == NULL || !skpdfimage->valid()) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001045 return kIgnoreError_PdfResult;
1046 }
1047
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001048 SkBitmap image = getImageFromObject(pdfContext, skpdfimage, false);
1049 SkBitmap sMask = getSmaskFromObject(pdfContext, skpdfimage);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001050
1051 canvas->save();
1052 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1053 SkRect dst = SkRect::MakeXYWH(SkDoubleToScalar(0.0), SkDoubleToScalar(0.0), SkDoubleToScalar(1.0), SkDoubleToScalar(1.0));
1054
1055 if (sMask.empty()) {
1056 canvas->drawBitmapRect(image, dst, NULL);
1057 } else {
1058 canvas->saveLayer(&dst, NULL);
1059 canvas->drawBitmapRect(image, dst, NULL);
1060 SkPaint xfer;
1061 xfer.setXfermodeMode(SkXfermode::kSrcOut_Mode); // SkXfermode::kSdtOut_Mode
1062 canvas->drawBitmapRect(sMask, dst, &xfer);
1063 canvas->restore();
1064 }
1065
1066 canvas->restore();
1067
1068 return kPartial_PdfResult;
1069}
1070
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001071bool SkMatrixFromDictionary(PdfContext* pdfContext,
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001072 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001073 const char* key,
1074 SkMatrix* matrix) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001075 const PdfObject* value = resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001076 dict.GetKey(PdfName(key)));
1077
1078 if (value == NULL || !value->IsArray()) {
1079 return false;
1080 }
1081
1082 if (value->GetArray().GetSize() != 6) {
1083 return false;
1084 }
1085
1086 double array[6];
1087 for (int i = 0; i < 6; i++) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001088 const PdfObject* elem = resolveReferenceObject(pdfContext->fPdfDoc, &value->GetArray()[i]);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001089 if (elem == NULL || (!elem->IsReal() && !elem->IsNumber())) {
1090 return false;
1091 }
1092 array[i] = elem->GetReal();
1093 }
1094
1095 *matrix = SkMatrixFromPdfMatrix(array);
1096 return true;
1097}
1098
1099bool SkRectFromDictionary(PdfContext* pdfContext,
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001100 const PdfDictionary& dict,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001101 const char* key,
1102 SkRect* rect) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001103 const PdfObject* value = resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001104 dict.GetKey(PdfName(key)));
1105
1106 if (value == NULL || !value->IsArray()) {
1107 return false;
1108 }
1109
1110 if (value->GetArray().GetSize() != 4) {
1111 return false;
1112 }
1113
1114 double array[4];
1115 for (int i = 0; i < 4; i++) {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001116 const PdfObject* elem = resolveReferenceObject(pdfContext->fPdfDoc, &value->GetArray()[i]);
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001117 if (elem == NULL || (!elem->IsReal() && !elem->IsNumber())) {
1118 return false;
1119 }
1120 array[i] = elem->GetReal();
1121 }
1122
1123 *rect = SkRect::MakeLTRB(SkDoubleToScalar(array[0]),
1124 SkDoubleToScalar(array[1]),
1125 SkDoubleToScalar(array[2]),
1126 SkDoubleToScalar(array[3]));
1127 return true;
1128}
1129
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001130PdfResult doXObject_Form(PdfContext* pdfContext, SkCanvas* canvas, const PdfObject& obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001131 if (!obj.HasStream() || obj.GetStream() == NULL || obj.GetStream()->GetLength() == 0) {
1132 return kOK_PdfResult;
1133 }
1134
1135 PdfOp_q(pdfContext, canvas, NULL);
1136 canvas->save();
1137
1138 pdfContext->fGraphicsState.fObjectWithResources = &obj;
1139
1140 SkTraceMatrix(pdfContext->fGraphicsState.fMatrix, "Current matrix");
1141
1142 SkMatrix matrix;
1143 if (SkMatrixFromDictionary(pdfContext, obj.GetDictionary(), "Matrix", &matrix)) {
1144 pdfContext->fGraphicsState.fMatrix.preConcat(matrix);
1145 pdfContext->fGraphicsState.fMatrixTm = pdfContext->fGraphicsState.fMatrix;
1146 pdfContext->fGraphicsState.fMatrixTlm = pdfContext->fGraphicsState.fMatrix;
1147 // TODO(edisonn) reset matrixTm and matricTlm also?
1148 }
1149
1150 SkTraceMatrix(pdfContext->fGraphicsState.fMatrix, "Total matrix");
1151
1152 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1153
1154 SkRect bbox;
1155 if (SkRectFromDictionary(pdfContext, obj.GetDictionary(), "BBox", &bbox)) {
1156 canvas->clipRect(bbox, SkRegion::kIntersect_Op, true); // TODO(edisonn): AA from settings.
1157 }
1158
1159 // TODO(edisonn): iterate smart on the stream even if it is compressed, tokenize it as we go.
1160 // For this PdfContentsTokenizer needs to be extended.
1161
1162 char* uncompressedStream = NULL;
1163 pdf_long uncompressedStreamLength = 0;
1164
1165 PdfResult ret = kPartial_PdfResult;
1166
1167 // TODO(edisonn): get rid of try/catch exceptions! We should not throw on user data!
1168 try {
1169 obj.GetStream()->GetFilteredCopy(&uncompressedStream, &uncompressedStreamLength);
1170 if (uncompressedStream != NULL && uncompressedStreamLength != 0) {
1171 PdfContentsTokenizer tokenizer(uncompressedStream, uncompressedStreamLength);
1172 PdfMainLooper looper(NULL, &tokenizer, pdfContext, canvas);
1173 looper.loop();
1174 }
1175 free(uncompressedStream);
1176 } catch (PdfError& e) {
1177 ret = kIgnoreError_PdfResult;
1178 }
1179
1180 // TODO(edisonn): should we restore the variable stack at the same state?
1181 // There could be operands left, that could be consumed by a parent tokenizer when we pop.
1182 canvas->restore();
1183 PdfOp_Q(pdfContext, canvas, NULL);
1184 return ret;
1185}
1186
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001187PdfResult doXObject_PS(PdfContext* pdfContext, SkCanvas* canvas, const PdfObject& obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001188 return kNYI_PdfResult;
1189}
1190
1191// TODO(edisonn): faster, have the property on the PdfObject itself.
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001192std::set<const PdfObject*> gInRendering;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001193
1194class CheckRecursiveRendering {
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001195 const PdfObject& fObj;
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001196public:
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001197 CheckRecursiveRendering(const PdfObject& obj) : fObj(obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001198 gInRendering.insert(&obj);
1199 }
1200
1201 ~CheckRecursiveRendering() {
1202 //SkASSERT(fObj.fInRendering);
1203 gInRendering.erase(&fObj);
1204 }
1205
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001206 static bool IsInRendering(const PdfObject& obj) {
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001207 return gInRendering.find(&obj) != gInRendering.end();
1208 }
1209};
1210
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001211PdfResult doXObject(PdfContext* pdfContext, SkCanvas* canvas, const PdfObject& obj) {
1212 if (CheckRecursiveRendering::IsInRendering(obj)) {
1213 // Oops, corrupt PDF!
1214 return kIgnoreError_PdfResult;
1215 }
1216
1217 CheckRecursiveRendering checkRecursion(obj);
1218
1219 // TODO(edisonn): check type
1220 SkPdfObject* skobj = NULL;
1221 if (!PodofoMapper::mapObject(*pdfContext->fPdfDoc, obj, &skobj)) return kIgnoreError_PdfResult;
1222
1223 if (!skobj || !skobj->valid()) return kIgnoreError_PdfResult;
1224
1225 PdfResult ret = kIgnoreError_PdfResult;
1226 switch (skobj->getType())
1227 {
1228 case kObjectDictionaryXObjectImage_SkPdfObjectType:
1229 ret = doXObject_Image(pdfContext, canvas, skobj->asImage());
edisonn@google.come4d11be2013-06-12 19:53:42 +00001230 break;
1231 case kObjectDictionaryXObjectForm_SkPdfObjectType:
1232 ret = doXObject_Form(pdfContext, canvas, obj);
1233 break;
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001234 //case kObjectDictionaryXObjectPS_SkPdfObjectType:
1235 //return doXObject_PS(skxobj.asPS());
1236 }
1237
1238 delete skobj;
1239 return ret;
1240}
1241
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001242PdfResult PdfOp_q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1243 pdfContext->fStateStack.push(pdfContext->fGraphicsState);
1244 canvas->save();
1245 return kOK_PdfResult;
1246}
1247
1248PdfResult PdfOp_Q(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1249 pdfContext->fGraphicsState = pdfContext->fStateStack.top();
1250 pdfContext->fStateStack.pop();
1251 canvas->restore();
1252 return kOK_PdfResult;
1253}
1254
1255PdfResult PdfOp_cm(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1256 double array[6];
1257 for (int i = 0 ; i < 6 ; i++) {
1258 array[5 - i] = pdfContext->fVarStack.top().GetReal();
1259 pdfContext->fVarStack.pop();
1260 }
1261
1262 // a b
1263 // c d
1264 // e f
1265
1266 // 0 1
1267 // 2 3
1268 // 4 5
1269
1270 // sx ky
1271 // kx sy
1272 // tx ty
1273 SkMatrix matrix = SkMatrixFromPdfMatrix(array);
1274
1275 pdfContext->fGraphicsState.fMatrix.preConcat(matrix);
1276
1277#ifdef PDF_TRACE
1278 printf("cm ");
1279 for (int i = 0 ; i < 6 ; i++) {
1280 printf("%f ", array[i]);
1281 }
1282 printf("\n");
1283 SkTraceMatrix(pdfContext->fGraphicsState.fMatrix);
1284#endif
1285
1286 return kOK_PdfResult;
1287}
1288
1289//leading TL Set the text leading, Tl
1290//, to leading, which is a number expressed in unscaled text
1291//space units. Text leading is used only by the T*, ', and " operators. Initial value: 0.
1292PdfResult PdfOp_TL(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1293 double ty = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1294
1295 pdfContext->fGraphicsState.fTextLeading = ty;
1296
1297 return kOK_PdfResult;
1298}
1299
1300PdfResult PdfOp_Td(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1301 double ty = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1302 double tx = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1303
1304 double array[6] = {1, 0, 0, 1, tx, ty};
1305 SkMatrix matrix = SkMatrixFromPdfMatrix(array);
1306
1307 pdfContext->fGraphicsState.fMatrixTm.preConcat(matrix);
1308 pdfContext->fGraphicsState.fMatrixTlm.preConcat(matrix);
1309
1310 return kPartial_PdfResult;
1311}
1312
1313PdfResult PdfOp_TD(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1314 double ty = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1315 double tx = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1316
1317 PdfVariant _ty(-ty);
1318 pdfContext->fVarStack.push(_ty);
1319 PdfOp_TL(pdfContext, canvas, looper);
1320
1321 PdfVariant vtx(tx);
1322 PdfVariant vty(ty);
1323 pdfContext->fVarStack.push(vtx);
1324 pdfContext->fVarStack.push(vty);
1325 return PdfOp_Td(pdfContext, canvas, looper);
1326}
1327
1328PdfResult PdfOp_Tm(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1329 double f = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1330 double e = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1331 double d = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1332 double c = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1333 double b = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1334 double a = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1335
1336 double array[6];
1337 array[0] = a;
1338 array[1] = b;
1339 array[2] = c;
1340 array[3] = d;
1341 array[4] = e;
1342 array[5] = f;
1343
1344 SkMatrix matrix = SkMatrixFromPdfMatrix(array);
1345 matrix.postConcat(pdfContext->fGraphicsState.fMatrix);
1346
1347 // TODO(edisonn): Text positioning.
1348 pdfContext->fGraphicsState.fMatrixTm = matrix;
1349 pdfContext->fGraphicsState.fMatrixTlm = matrix;;
1350
1351 return kPartial_PdfResult;
1352}
1353
1354//— T* Move to the start of the next line. This operator has the same effect as the code
1355//0 Tl Td
1356//where Tl is the current leading parameter in the text state
1357PdfResult PdfOp_T_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1358 PdfVariant zero(0.0);
1359 PdfVariant tl(pdfContext->fGraphicsState.fTextLeading);
1360
1361 pdfContext->fVarStack.push(zero);
1362 pdfContext->fVarStack.push(tl);
1363 return PdfOp_Td(pdfContext, canvas, looper);
1364}
1365
1366PdfResult PdfOp_m(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1367 if (pdfContext->fGraphicsState.fPathClosed) {
1368 pdfContext->fGraphicsState.fPath.reset();
1369 pdfContext->fGraphicsState.fPathClosed = false;
1370 }
1371
1372 pdfContext->fGraphicsState.fCurPosY = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1373 pdfContext->fGraphicsState.fCurPosX = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1374
1375 pdfContext->fGraphicsState.fPath.moveTo(SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosX),
1376 SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosY));
1377
1378 return kOK_PdfResult;
1379}
1380
1381PdfResult PdfOp_l(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1382 if (pdfContext->fGraphicsState.fPathClosed) {
1383 pdfContext->fGraphicsState.fPath.reset();
1384 pdfContext->fGraphicsState.fPathClosed = false;
1385 }
1386
1387 pdfContext->fGraphicsState.fCurPosY = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1388 pdfContext->fGraphicsState.fCurPosX = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1389
1390 pdfContext->fGraphicsState.fPath.lineTo(SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosX),
1391 SkDoubleToScalar(pdfContext->fGraphicsState.fCurPosY));
1392
1393 return kOK_PdfResult;
1394}
1395
1396PdfResult PdfOp_c(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1397 if (pdfContext->fGraphicsState.fPathClosed) {
1398 pdfContext->fGraphicsState.fPath.reset();
1399 pdfContext->fGraphicsState.fPathClosed = false;
1400 }
1401
1402 double y3 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1403 double x3 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1404 double y2 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1405 double x2 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1406 double y1 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1407 double x1 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1408
1409 pdfContext->fGraphicsState.fPath.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
1410 SkDoubleToScalar(x2), SkDoubleToScalar(y2),
1411 SkDoubleToScalar(x3), SkDoubleToScalar(y3));
1412
1413 pdfContext->fGraphicsState.fCurPosX = x3;
1414 pdfContext->fGraphicsState.fCurPosY = y3;
1415
1416 return kOK_PdfResult;
1417}
1418
1419PdfResult PdfOp_v(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1420 if (pdfContext->fGraphicsState.fPathClosed) {
1421 pdfContext->fGraphicsState.fPath.reset();
1422 pdfContext->fGraphicsState.fPathClosed = false;
1423 }
1424
1425 double y3 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1426 double x3 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1427 double y2 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1428 double x2 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1429 double y1 = pdfContext->fGraphicsState.fCurPosY;
1430 double x1 = pdfContext->fGraphicsState.fCurPosX;
1431
1432 pdfContext->fGraphicsState.fPath.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
1433 SkDoubleToScalar(x2), SkDoubleToScalar(y2),
1434 SkDoubleToScalar(x3), SkDoubleToScalar(y3));
1435
1436 pdfContext->fGraphicsState.fCurPosX = x3;
1437 pdfContext->fGraphicsState.fCurPosY = y3;
1438
1439 return kOK_PdfResult;
1440}
1441
1442PdfResult PdfOp_y(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1443 if (pdfContext->fGraphicsState.fPathClosed) {
1444 pdfContext->fGraphicsState.fPath.reset();
1445 pdfContext->fGraphicsState.fPathClosed = false;
1446 }
1447
1448 double y3 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1449 double x3 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1450 double y2 = pdfContext->fGraphicsState.fCurPosY;
1451 double x2 = pdfContext->fGraphicsState.fCurPosX;
1452 double y1 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1453 double x1 = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1454
1455 pdfContext->fGraphicsState.fPath.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
1456 SkDoubleToScalar(x2), SkDoubleToScalar(y2),
1457 SkDoubleToScalar(x3), SkDoubleToScalar(y3));
1458
1459 pdfContext->fGraphicsState.fCurPosX = x3;
1460 pdfContext->fGraphicsState.fCurPosY = y3;
1461
1462 return kOK_PdfResult;
1463}
1464
1465PdfResult PdfOp_re(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1466 if (pdfContext->fGraphicsState.fPathClosed) {
1467 pdfContext->fGraphicsState.fPath.reset();
1468 pdfContext->fGraphicsState.fPathClosed = false;
1469 }
1470
1471 double height = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1472 double width = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1473 double y = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1474 double x = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1475
1476 pdfContext->fGraphicsState.fPath.addRect(SkDoubleToScalar(x), SkDoubleToScalar(y),
1477 SkDoubleToScalar(x + width), SkDoubleToScalar(y + height));
1478
1479 pdfContext->fGraphicsState.fCurPosX = x;
1480 pdfContext->fGraphicsState.fCurPosY = y + height;
1481
1482 return kOK_PdfResult;
1483}
1484
1485PdfResult PdfOp_h(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1486 pdfContext->fGraphicsState.fPath.close();
1487 pdfContext->fGraphicsState.fPathClosed = true;
1488 return kOK_PdfResult;
1489}
1490
1491PdfResult PdfOp_fillAndStroke(PdfContext* pdfContext, SkCanvas* canvas, bool fill, bool stroke, bool close, bool evenOdd) {
1492 SkPath path = pdfContext->fGraphicsState.fPath;
1493
1494 if (close) {
1495 path.close();
1496 }
1497
1498 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1499
1500 SkPaint paint;
1501
1502 // TODO(edisonn): get this from pdfContext->options,
1503 // or pdfContext->addPaintOptions(&paint);
1504 paint.setAntiAlias(true);
1505
1506 // TODO(edisonn): dashing, miter, ...
1507
1508// path.transform(pdfContext->fGraphicsState.fMatrix);
1509// path.transform(pdfContext->fOriginalMatrix);
1510
1511 SkPoint line[2];
1512 if (fill && !stroke && path.isLine(line)) {
1513 paint.setStyle(SkPaint::kStroke_Style);
1514 paint.setColor(pdfContext->fGraphicsState.fNonStroking.fColor);
1515 paint.setStrokeWidth(SkDoubleToScalar(0));
1516 canvas->drawPath(path, paint);
1517 } else {
1518 if (fill) {
1519 paint.setStyle(SkPaint::kFill_Style);
1520 if (evenOdd) {
1521 path.setFillType(SkPath::kEvenOdd_FillType);
1522 }
1523 paint.setColor(pdfContext->fGraphicsState.fNonStroking.fColor);
1524 canvas->drawPath(path, paint);
1525 }
1526
1527 if (stroke) {
1528 paint.setStyle(SkPaint::kStroke_Style);
1529 paint.setColor(pdfContext->fGraphicsState.fStroking.fColor);
1530 paint.setStrokeWidth(SkDoubleToScalar(pdfContext->fGraphicsState.fLineWidth));
1531 path.setFillType(SkPath::kWinding_FillType); // reset it, just in case it messes up the stroke
1532 canvas->drawPath(path, paint);
1533 }
1534 }
1535
1536 pdfContext->fGraphicsState.fPath.reset();
1537 // todo zoom ... other stuff ?
1538
1539 if (pdfContext->fGraphicsState.fHasClipPathToApply) {
1540#ifndef PDF_DEBUG_NO_CLIPING
1541 canvas->clipPath(pdfContext->fGraphicsState.fClipPath, SkRegion::kIntersect_Op, true);
1542#endif
1543 }
1544
1545 //pdfContext->fGraphicsState.fClipPath.reset();
1546 pdfContext->fGraphicsState.fHasClipPathToApply = false;
1547
1548 return kPartial_PdfResult;
1549
1550}
1551
1552PdfResult PdfOp_S(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1553 return PdfOp_fillAndStroke(pdfContext, canvas, false, true, false, false);
1554}
1555
1556PdfResult PdfOp_s(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1557 return PdfOp_fillAndStroke(pdfContext, canvas, false, true, true, false);
1558}
1559
1560PdfResult PdfOp_F(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1561 return PdfOp_fillAndStroke(pdfContext, canvas, true, false, false, false);
1562}
1563
1564PdfResult PdfOp_f(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1565 return PdfOp_fillAndStroke(pdfContext, canvas, true, false, false, false);
1566}
1567
1568PdfResult PdfOp_f_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1569 return PdfOp_fillAndStroke(pdfContext, canvas, true, false, false, true);
1570}
1571
1572PdfResult PdfOp_B(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1573 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, false, false);
1574}
1575
1576PdfResult PdfOp_B_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1577 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, false, true);
1578}
1579
1580PdfResult PdfOp_b(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1581 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, true, false);
1582}
1583
1584PdfResult PdfOp_b_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1585 return PdfOp_fillAndStroke(pdfContext, canvas, true, true, true, true);
1586}
1587
1588PdfResult PdfOp_n(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1589 canvas->setMatrix(pdfContext->fGraphicsState.fMatrix);
1590 if (pdfContext->fGraphicsState.fHasClipPathToApply) {
1591#ifndef PDF_DEBUG_NO_CLIPING
1592 canvas->clipPath(pdfContext->fGraphicsState.fClipPath, SkRegion::kIntersect_Op, true);
1593#endif
1594 }
1595
1596 //pdfContext->fGraphicsState.fClipPath.reset();
1597 pdfContext->fGraphicsState.fHasClipPathToApply = false;
1598
1599 pdfContext->fGraphicsState.fPathClosed = true;
1600
1601 return kOK_PdfResult;
1602}
1603
1604PdfResult PdfOp_BT(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1605 pdfContext->fGraphicsState.fTextBlock = true;
1606 pdfContext->fGraphicsState.fMatrixTm = pdfContext->fGraphicsState.fMatrix;
1607 pdfContext->fGraphicsState.fMatrixTlm = pdfContext->fGraphicsState.fMatrix;
1608
1609 return kPartial_PdfResult;
1610}
1611
1612PdfResult PdfOp_ET(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1613 if (!pdfContext->fGraphicsState.fTextBlock) {
1614 return kIgnoreError_PdfResult;
1615 }
1616 // TODO(edisonn): anything else to be done once we are done with draw text? Like restore stack?
1617 return kPartial_PdfResult;
1618}
1619
1620//font size Tf Set the text font, Tf
1621//, to font and the text font size, Tfs, to size. font is the name of a
1622//font resource in the Fontsubdictionary of the current resource dictionary; size is
1623//a number representing a scale factor. There is no initial value for either font or
1624//size; they must be specified explicitly using Tf before any text is shown.
1625PdfResult PdfOp_Tf(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1626 pdfContext->fGraphicsState.fCurFontSize = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1627 PdfName fontName = pdfContext->fVarStack.top().GetName(); pdfContext->fVarStack.pop();
1628
1629 // TODO(edisonn): Load font from pdfContext->fGraphicsState.fObjectWithResources ?
1630 PdfObject* pFont = pdfContext->fPdfPage->GetFromResources( PdfName("Font"), fontName );
1631 if( !pFont )
1632 {
1633 // TODO(edisonn): try to ignore the error, make sure we do not crash.
1634 return kIgnoreError_PdfResult;
1635 }
1636
1637 pdfContext->fGraphicsState.fCurFont = pdfContext->fPdfDoc->GetFont( pFont );
1638 if( !pdfContext->fGraphicsState.fCurFont )
1639 {
1640 // TODO(edisonn): check ~/crasing, for one of the files PoDoFo throws exception
1641 // when calling pFont->Reference(), with Linked list corruption.
1642 return kIgnoreError_PdfResult;
1643 }
1644
1645 return kPartial_PdfResult;
1646}
1647
1648PdfResult PdfOp_Tj(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1649 if (!pdfContext->fGraphicsState.fTextBlock) {
1650 // TODO(edisonn): try to recover and draw it any way?
1651 return kIgnoreError_PdfResult;
1652 }
1653
1654 PdfResult ret = DrawText(pdfContext,
1655 pdfContext->fGraphicsState.fCurFont,
1656 pdfContext->fVarStack.top().GetString(),
1657 canvas);
1658 pdfContext->fVarStack.pop();
1659
1660 return ret;
1661}
1662
1663PdfResult PdfOp_quote(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1664 if (!pdfContext->fGraphicsState.fTextBlock) {
1665 // TODO(edisonn): try to recover and draw it any way?
1666 return kIgnoreError_PdfResult;
1667 }
1668
1669 PdfOp_T_star(pdfContext, canvas, looper);
1670 // Do not pop, and push, just transfer the param to Tj
1671 return PdfOp_Tj(pdfContext, canvas, looper);
1672}
1673
1674PdfResult PdfOp_doublequote(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1675 if (!pdfContext->fGraphicsState.fTextBlock) {
1676 // TODO(edisonn): try to recover and draw it any way?
1677 return kIgnoreError_PdfResult;
1678 }
1679
1680 PdfVariant str = pdfContext->fVarStack.top(); pdfContext->fVarStack.pop();
1681 PdfVariant ac = pdfContext->fVarStack.top(); pdfContext->fVarStack.pop();
1682 PdfVariant aw = pdfContext->fVarStack.top(); pdfContext->fVarStack.pop();
1683
1684 pdfContext->fVarStack.push(aw);
1685 PdfOp_Tw(pdfContext, canvas, looper);
1686
1687 pdfContext->fVarStack.push(ac);
1688 PdfOp_Tc(pdfContext, canvas, looper);
1689
1690 pdfContext->fVarStack.push(str);
1691 PdfOp_quote(pdfContext, canvas, looper);
1692
1693 return kPartial_PdfResult;
1694}
1695
1696PdfResult PdfOp_TJ(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1697 if (!pdfContext->fGraphicsState.fTextBlock) {
1698 // TODO(edisonn): try to recover and draw it any way?
1699 return kIgnoreError_PdfResult;
1700 }
1701
1702 PdfArray array = pdfContext->fVarStack.top().GetArray();
1703 pdfContext->fVarStack.pop();
1704
1705 for( int i=0; i<static_cast<int>(array.GetSize()); i++ )
1706 {
1707 if( array[i].IsString() || array[i].IsHexString() ) {
1708 DrawText(pdfContext,
1709 pdfContext->fGraphicsState.fCurFont,
1710 array[i].GetString(),
1711 canvas);
1712 } else if (array[i].IsReal() || array[i].IsNumber()) {
1713 double dx = array[i].GetReal();
1714 SkMatrix matrix;
1715 matrix.setAll(SkDoubleToScalar(1),
1716 SkDoubleToScalar(0),
1717 // TODO(edisonn): use writing mode, vertical/horizontal.
1718 SkDoubleToScalar(-dx), // amount is substracted!!!
1719 SkDoubleToScalar(0),
1720 SkDoubleToScalar(1),
1721 SkDoubleToScalar(0),
1722 SkDoubleToScalar(0),
1723 SkDoubleToScalar(0),
1724 SkDoubleToScalar(1));
1725
1726 pdfContext->fGraphicsState.fMatrixTm.preConcat(matrix);
1727 }
1728 }
1729 return kPartial_PdfResult; // TODO(edisonn): Implement fully DrawText before returing OK.
1730}
1731
1732PdfResult PdfOp_CS_cs(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
1733 colorOperator->fColorSpace = pdfContext->fVarStack.top().GetName().GetName(); pdfContext->fVarStack.pop();
1734 return kOK_PdfResult;
1735}
1736
1737PdfResult PdfOp_CS(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1738 return PdfOp_CS_cs(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
1739}
1740
1741PdfResult PdfOp_cs(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1742 return PdfOp_CS_cs(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
1743}
1744
1745PdfResult PdfOp_SC_sc(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
1746 double c[4];
1747 pdf_int64 v[4];
1748
1749 int n = GetColorSpaceComponents(colorOperator->fColorSpace);
1750
1751 bool doubles = true;
1752 if (colorOperator->fColorSpace == "Indexed") {
1753 doubles = false;
1754 }
1755
1756#ifdef PDF_TRACE
1757 printf("color space = %s, N = %i\n", colorOperator->fColorSpace.c_str(), n);
1758#endif
1759
1760 for (int i = n - 1; i >= 0 ; i--) {
1761 if (doubles) {
1762 c[i] = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1763 } else {
1764 v[i] = pdfContext->fVarStack.top().GetNumber(); pdfContext->fVarStack.pop();
1765 }
1766 }
1767
1768 // TODO(edisonn): Now, set that color. Only DeviceRGB supported.
1769 if (colorOperator->fColorSpace == "DeviceRGB") {
1770 colorOperator->setRGBColor(SkColorSetRGB(255*c[0], 255*c[1], 255*c[2]));
1771 }
1772 return kPartial_PdfResult;
1773}
1774
1775PdfResult PdfOp_SC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1776 return PdfOp_SC_sc(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
1777}
1778
1779PdfResult PdfOp_sc(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1780 return PdfOp_SC_sc(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
1781}
1782
1783PdfResult PdfOp_SCN_scn(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
1784 PdfString name;
1785
1786 if (pdfContext->fVarStack.top().IsName()) {
1787 pdfContext->fVarStack.pop();
1788 }
1789
1790 // TODO(edisonn): SCN supports more color spaces than SCN. Read and implement spec.
1791 PdfOp_SC_sc(pdfContext, canvas, colorOperator);
1792
1793 return kPartial_PdfResult;
1794}
1795
1796PdfResult PdfOp_SCN(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1797 return PdfOp_SCN_scn(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
1798}
1799
1800PdfResult PdfOp_scn(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1801 return PdfOp_SCN_scn(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
1802}
1803
1804PdfResult PdfOp_G_g(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
1805 double gray = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1806 return kNYI_PdfResult;
1807}
1808
1809PdfResult PdfOp_G(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1810 return PdfOp_G_g(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
1811}
1812
1813PdfResult PdfOp_g(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1814 return PdfOp_G_g(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
1815}
1816
1817PdfResult PdfOp_RG_rg(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
1818 double b = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1819 double g = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1820 double r = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1821
1822 colorOperator->fColorSpace = "DeviceRGB";
1823 colorOperator->setRGBColor(SkColorSetRGB(255*r, 255*g, 255*b));
1824 return kOK_PdfResult;
1825}
1826
1827PdfResult PdfOp_RG(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1828 return PdfOp_RG_rg(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
1829}
1830
1831PdfResult PdfOp_rg(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1832 return PdfOp_RG_rg(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
1833}
1834
1835PdfResult PdfOp_K_k(PdfContext* pdfContext, SkCanvas* canvas, PdfColorOperator* colorOperator) {
1836 // TODO(edisonn): spec has some rules about overprint, implement them.
1837 double k = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1838 double y = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1839 double m = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1840 double c = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1841
1842 colorOperator->fColorSpace = "DeviceCMYK";
1843 // TODO(edisonn): Set color.
1844 return kNYI_PdfResult;
1845}
1846
1847PdfResult PdfOp_K(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1848 return PdfOp_K_k(pdfContext, canvas, &pdfContext->fGraphicsState.fStroking);
1849}
1850
1851PdfResult PdfOp_k(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1852 return PdfOp_K_k(pdfContext, canvas, &pdfContext->fGraphicsState.fNonStroking);
1853}
1854
1855PdfResult PdfOp_W(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1856 pdfContext->fGraphicsState.fClipPath = pdfContext->fGraphicsState.fPath;
1857 pdfContext->fGraphicsState.fHasClipPathToApply = true;
1858
1859 return kOK_PdfResult;
1860}
1861
1862PdfResult PdfOp_W_star(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1863 pdfContext->fGraphicsState.fClipPath = pdfContext->fGraphicsState.fPath;
1864
1865#ifdef PDF_TRACE
1866 if (pdfContext->fGraphicsState.fClipPath.isRect(NULL)) {
1867 printf("CLIP IS RECT\n");
1868 }
1869#endif
1870
1871 // TODO(edisonn): there seem to be a bug with clipPath of a rect with even odd.
1872 pdfContext->fGraphicsState.fClipPath.setFillType(SkPath::kEvenOdd_FillType);
1873 pdfContext->fGraphicsState.fHasClipPathToApply = true;
1874
1875 return kPartial_PdfResult;
1876}
1877
1878PdfResult PdfOp_BX(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1879 *looper = new PdfCompatibilitySectionLooper();
1880 return kOK_PdfResult;
1881}
1882
1883PdfResult PdfOp_EX(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1884#ifdef ASSERT_BAD_PDF_OPS
1885 SkASSERT(false); // EX must be consumed by PdfCompatibilitySectionLooper, but let's
1886 // have the assert when testing good pdfs.
1887#endif
1888 return kIgnoreError_PdfResult;
1889}
1890
1891PdfResult PdfOp_BI(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1892 *looper = new PdfInlineImageLooper();
1893 return kOK_PdfResult;
1894}
1895
1896PdfResult PdfOp_ID(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1897#ifdef ASSERT_BAD_PDF_OPS
1898 SkASSERT(false); // must be processed in inline image looper, but let's
1899 // have the assert when testing good pdfs.
1900#endif
1901 return kIgnoreError_PdfResult;
1902}
1903
1904PdfResult PdfOp_EI(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1905#ifdef ASSERT_BAD_PDF_OPS
1906 SkASSERT(false); // must be processed in inline image looper, but let's
1907 // have the assert when testing good pdfs.
1908#endif
1909 return kIgnoreError_PdfResult;
1910}
1911
1912//lineWidth w Set the line width in the graphics state (see “Line Width” on page 152).
1913PdfResult PdfOp_w(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1914 double lineWidth = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1915 pdfContext->fGraphicsState.fLineWidth = lineWidth;
1916
1917 return kOK_PdfResult;
1918}
1919
1920//lineCap J Set the line cap style in the graphics state (see “Line Cap Style” on page 153).
1921PdfResult PdfOp_J(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1922 pdfContext->fVarStack.pop();
1923 //double lineCap = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1924
1925 return kNYI_PdfResult;
1926}
1927
1928//lineJoin j Set the line join style in the graphics state (see “Line Join Style” on page 153).
1929PdfResult PdfOp_j(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1930 pdfContext->fVarStack.pop();
1931 //double lineJoin = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1932
1933 return kNYI_PdfResult;
1934}
1935
1936//miterLimit M Set the miter limit in the graphics state (see “Miter Limit” on page 153).
1937PdfResult PdfOp_M(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1938 pdfContext->fVarStack.pop();
1939 //double miterLimit = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
1940
1941 return kNYI_PdfResult;
1942}
1943
1944//dashArray dashPhase d Set the line dash pattern in the graphics state (see “Line Dash Pattern” on
1945//page 155).
1946PdfResult PdfOp_d(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1947 pdfContext->fVarStack.pop();
1948 pdfContext->fVarStack.pop();
1949
1950 return kNYI_PdfResult;
1951}
1952
1953//intent ri (PDF 1.1) Set the color rendering intent in the graphics state (see “Rendering Intents” on page 197).
1954PdfResult PdfOp_ri(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1955 pdfContext->fVarStack.pop();
1956
1957 return kNYI_PdfResult;
1958}
1959
1960//flatness i Set the flatness tolerance in the graphics state (see Section 6.5.1, “Flatness
1961//Tolerance”). flatness is a number in the range 0 to 100; a value of 0 speci-
1962//fies the output device’s default flatness tolerance.
1963PdfResult PdfOp_i(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1964 pdfContext->fVarStack.pop();
1965
1966 return kNYI_PdfResult;
1967}
1968
1969//dictName gs (PDF 1.2) Set the specified parameters in the graphics state. dictName is
1970//the name of a graphics state parameter dictionary in the ExtGState subdictionary of the current resource dictionary (see the next section).
1971PdfResult PdfOp_gs(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
1972 PdfName name = pdfContext->fVarStack.top().GetName(); pdfContext->fVarStack.pop();
1973
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001974 const PdfDictionary& pageDict = pdfContext->fGraphicsState.fObjectWithResources->GetDictionary();
1975 const PdfObject* resources = resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001976 pageDict.GetKey("Resources"));
1977
1978 if (resources == NULL) {
1979#ifdef PDF_TRACE
1980 printf("WARNING: No Resources for a page with 'gs' operator!\n");
1981#endif
1982 return kIgnoreError_PdfResult;
1983 }
1984
1985#ifdef PDF_TRACE
1986 std::string str;
1987 resources->ToString(str);
1988 printf("Print gs Page Resources: %s\n", str.c_str());
1989#endif
1990
1991 if (!resources->IsDictionary()) {
1992#ifdef PDF_TRACE
1993 printf("Resources is not a dictionary!\n");
1994#endif
1995 return kIgnoreError_PdfResult;
1996 }
1997
edisonn@google.comaf3daa02013-06-12 19:07:45 +00001998 const PdfDictionary& resourceDict = resources->GetDictionary();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00001999 //Next, get the ExtGState Dictionary from the Resource Dictionary:
edisonn@google.comaf3daa02013-06-12 19:07:45 +00002000 const PdfObject* extGStateDictionary = resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002001 resourceDict.GetKey("ExtGState"));
2002
2003 if (extGStateDictionary == NULL) {
2004#ifdef PDF_TRACE
2005 printf("ExtGState is NULL!\n");
2006#endif
2007 return kIgnoreError_PdfResult;
2008 }
2009
2010 if (!extGStateDictionary->IsDictionary()) {
2011#ifdef PDF_TRACE
2012 printf("extGStateDictionary is not a dictionary!\n");
2013#endif
2014 return kIgnoreError_PdfResult;
2015 }
2016
edisonn@google.comaf3daa02013-06-12 19:07:45 +00002017 const PdfObject* value =
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002018 resolveReferenceObject(pdfContext->fPdfDoc,
2019 extGStateDictionary->GetDictionary().GetKey(name));
2020
2021 if (value == NULL) {
2022#ifdef PDF_TRACE
2023 printf("Named object not found!\n");
2024#endif
2025 return kIgnoreError_PdfResult;
2026 }
2027
2028#ifdef PDF_TRACE
2029 value->ToString(str);
2030 printf("gs object value: %s\n", str.c_str());
2031#endif
2032
2033 // TODO(edisonn): now load all those properties in graphic state.
2034
2035 return kNYI_PdfResult;
2036}
2037
2038//charSpace Tc Set the character spacing, Tc
2039//, to charSpace, which is a number expressed in unscaled text space units. Character spacing is used by the Tj, TJ, and ' operators.
2040//Initial value: 0.
2041PdfResult PdfOp_Tc(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2042 double charSpace = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
2043 pdfContext->fGraphicsState.fCharSpace = charSpace;
2044
2045 return kOK_PdfResult;
2046}
2047
2048//wordSpace Tw Set the word spacing, T
2049//w
2050//, to wordSpace, which is a number expressed in unscaled
2051//text space units. Word spacing is used by the Tj, TJ, and ' operators. Initial
2052//value: 0.
2053PdfResult PdfOp_Tw(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2054 double wordSpace = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
2055 pdfContext->fGraphicsState.fWordSpace = wordSpace;
2056
2057 return kOK_PdfResult;
2058}
2059
2060//scale Tz Set the horizontal scaling, Th
2061//, to (scale ˜ 100). scale is a number specifying the
2062//percentage of the normal width. Initial value: 100 (normal width).
2063PdfResult PdfOp_Tz(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2064 double scale = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
2065
2066 return kNYI_PdfResult;
2067}
2068
2069//render Tr Set the text rendering mode, T
2070//mode, to render, which is an integer. Initial value: 0.
2071PdfResult PdfOp_Tr(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2072 double render = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
2073
2074 return kNYI_PdfResult;
2075}
2076
2077//rise Ts Set the text rise, Trise, to rise, which is a number expressed in unscaled text space
2078//units. Initial value: 0.
2079PdfResult PdfOp_Ts(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2080 double rise = pdfContext->fVarStack.top().GetReal(); pdfContext->fVarStack.pop();
2081
2082 return kNYI_PdfResult;
2083}
2084
2085//wx wy d0
2086PdfResult PdfOp_d0(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2087 pdfContext->fVarStack.pop();
2088 pdfContext->fVarStack.pop();
2089
2090 return kNYI_PdfResult;
2091}
2092
2093//wx wy llx lly urx ury d1
2094PdfResult PdfOp_d1(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2095 pdfContext->fVarStack.pop();
2096 pdfContext->fVarStack.pop();
2097 pdfContext->fVarStack.pop();
2098 pdfContext->fVarStack.pop();
2099 pdfContext->fVarStack.pop();
2100 pdfContext->fVarStack.pop();
2101
2102 return kNYI_PdfResult;
2103}
2104
2105//name sh
2106PdfResult PdfOp_sh(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2107 pdfContext->fVarStack.pop();
2108
2109 return kNYI_PdfResult;
2110}
2111
2112//name Do
2113PdfResult PdfOp_Do(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2114 PdfName name = pdfContext->fVarStack.top().GetName(); pdfContext->fVarStack.pop();
2115
edisonn@google.comaf3daa02013-06-12 19:07:45 +00002116 const PdfDictionary& pageDict = pdfContext->fGraphicsState.fObjectWithResources->GetDictionary();
2117 const PdfObject* resources = resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002118 pageDict.GetKey("Resources"));
2119
2120 if (resources == NULL) {
2121#ifdef PDF_TRACE
2122 printf("WARNING: No Resources for a page with 'Do' operator!s\n");
2123#endif
2124 return kIgnoreError_PdfResult;
2125 }
2126
2127#ifdef PDF_TRACE
2128 std::string str;
2129 resources->ToString(str);
2130 printf("Print Do Page Resources: %s\n", str.c_str());
2131#endif
2132
2133 if (!resources->IsDictionary()) {
2134#ifdef PDF_TRACE
2135 printf("Resources is not a dictionary!\n");
2136#endif
2137 return kIgnoreError_PdfResult;
2138 }
2139
edisonn@google.comaf3daa02013-06-12 19:07:45 +00002140 const PdfDictionary& resourceDict = resources->GetDictionary();
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002141 //Next, get the XObject Dictionary from the Resource Dictionary:
edisonn@google.comaf3daa02013-06-12 19:07:45 +00002142 const PdfObject* xObjectDictionary = resolveReferenceObject(pdfContext->fPdfDoc,
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002143 resourceDict.GetKey("XObject"));
2144
2145 if (xObjectDictionary == NULL) {
2146#ifdef PDF_TRACE
2147 printf("XObject is NULL!\n");
2148#endif
2149 return kIgnoreError_PdfResult;
2150 }
2151
2152 if (!xObjectDictionary->IsDictionary()) {
2153#ifdef PDF_TRACE
2154 printf("xObjectDictionary is not a dictionary!\n");
2155#endif
2156 return kIgnoreError_PdfResult;
2157 }
2158
edisonn@google.comaf3daa02013-06-12 19:07:45 +00002159 const PdfObject* value =
edisonn@google.com01cd4d52013-06-10 20:44:45 +00002160 resolveReferenceObject(pdfContext->fPdfDoc,
2161 xObjectDictionary->GetDictionary().GetKey(name));
2162
2163 if (value == NULL) {
2164#ifdef PDF_TRACE
2165 printf("Named object not found!\n");
2166#endif
2167 return kIgnoreError_PdfResult;
2168 }
2169
2170#ifdef PDF_TRACE
2171 value->ToString(str);
2172 printf("Do object value: %s\n", str.c_str());
2173#endif
2174
2175 return doXObject(pdfContext, canvas, *value);
2176}
2177
2178
2179//tag MP Designate a marked-content point. tag is a name object indicating the role or
2180//significance of the point.
2181PdfResult PdfOp_MP(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2182 pdfContext->fVarStack.pop();
2183
2184 return kNYI_PdfResult;
2185}
2186
2187//tag properties DP Designate a marked-content point with an associated property list. tag is a
2188//name object indicating the role or significance of the point; properties is
2189//either an inline dictionary containing the property list or a name object
2190//associated with it in the Properties subdictionary of the current resource
2191//dictionary (see Section 9.5.1, “Property Lists”).
2192PdfResult PdfOp_DP(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2193 pdfContext->fVarStack.pop();
2194 pdfContext->fVarStack.pop();
2195
2196 return kNYI_PdfResult;
2197}
2198
2199//tag BMC Begin a marked-content sequence terminated by a balancing EMC operator.
2200//tag is a name object indicating the role or significance of the sequence.
2201PdfResult PdfOp_BMC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2202 pdfContext->fVarStack.pop();
2203
2204 return kNYI_PdfResult;
2205}
2206
2207//tag properties BDC Begin a marked-content sequence with an associated property list, terminated
2208//by a balancing EMCoperator. tag is a name object indicating the role or significance of the sequence; propertiesis either an inline dictionary containing the
2209//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”).
2210PdfResult PdfOp_BDC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2211 pdfContext->fVarStack.pop();
2212 pdfContext->fVarStack.pop();
2213
2214 return kNYI_PdfResult;
2215}
2216
2217//— EMC End a marked-content sequence begun by a BMC or BDC operator.
2218PdfResult PdfOp_EMC(PdfContext* pdfContext, SkCanvas* canvas, PdfTokenLooper** looper) {
2219 return kNYI_PdfResult;
2220}
2221
2222void initPdfOperatorRenderes() {
2223 static bool gInitialized = false;
2224 if (gInitialized) {
2225 return;
2226 }
2227
2228 gPdfOps["q"] = PdfOp_q;
2229 gPdfOps["Q"] = PdfOp_Q;
2230 gPdfOps["cm"] = PdfOp_cm;
2231
2232 gPdfOps["TD"] = PdfOp_TD;
2233 gPdfOps["Td"] = PdfOp_Td;
2234 gPdfOps["Tm"] = PdfOp_Tm;
2235 gPdfOps["T*"] = PdfOp_T_star;
2236
2237 gPdfOps["m"] = PdfOp_m;
2238 gPdfOps["l"] = PdfOp_l;
2239 gPdfOps["c"] = PdfOp_c;
2240 gPdfOps["v"] = PdfOp_v;
2241 gPdfOps["y"] = PdfOp_y;
2242 gPdfOps["h"] = PdfOp_h;
2243 gPdfOps["re"] = PdfOp_re;
2244
2245 gPdfOps["S"] = PdfOp_S;
2246 gPdfOps["s"] = PdfOp_s;
2247 gPdfOps["f"] = PdfOp_f;
2248 gPdfOps["F"] = PdfOp_F;
2249 gPdfOps["f*"] = PdfOp_f_star;
2250 gPdfOps["B"] = PdfOp_B;
2251 gPdfOps["B*"] = PdfOp_B_star;
2252 gPdfOps["b"] = PdfOp_b;
2253 gPdfOps["b*"] = PdfOp_b_star;
2254 gPdfOps["n"] = PdfOp_n;
2255
2256 gPdfOps["BT"] = PdfOp_BT;
2257 gPdfOps["ET"] = PdfOp_ET;
2258
2259 gPdfOps["Tj"] = PdfOp_Tj;
2260 gPdfOps["'"] = PdfOp_quote;
2261 gPdfOps["\""] = PdfOp_doublequote;
2262 gPdfOps["TJ"] = PdfOp_TJ;
2263
2264 gPdfOps["CS"] = PdfOp_CS;
2265 gPdfOps["cs"] = PdfOp_cs;
2266 gPdfOps["SC"] = PdfOp_SC;
2267 gPdfOps["SCN"] = PdfOp_SCN;
2268 gPdfOps["sc"] = PdfOp_sc;
2269 gPdfOps["scn"] = PdfOp_scn;
2270 gPdfOps["G"] = PdfOp_G;
2271 gPdfOps["g"] = PdfOp_g;
2272 gPdfOps["RG"] = PdfOp_RG;
2273 gPdfOps["rg"] = PdfOp_rg;
2274 gPdfOps["K"] = PdfOp_K;
2275 gPdfOps["k"] = PdfOp_k;
2276
2277 gPdfOps["W"] = PdfOp_W;
2278 gPdfOps["W*"] = PdfOp_W_star;
2279
2280 gPdfOps["BX"] = PdfOp_BX;
2281 gPdfOps["EX"] = PdfOp_EX;
2282
2283 gPdfOps["BI"] = PdfOp_BI;
2284 gPdfOps["ID"] = PdfOp_ID;
2285 gPdfOps["EI"] = PdfOp_EI;
2286
2287 gPdfOps["w"] = PdfOp_w;
2288 gPdfOps["J"] = PdfOp_J;
2289 gPdfOps["j"] = PdfOp_j;
2290 gPdfOps["M"] = PdfOp_M;
2291 gPdfOps["d"] = PdfOp_d;
2292 gPdfOps["ri"] = PdfOp_ri;
2293 gPdfOps["i"] = PdfOp_i;
2294 gPdfOps["gs"] = PdfOp_gs;
2295
2296 gPdfOps["Tc"] = PdfOp_Tc;
2297 gPdfOps["Tw"] = PdfOp_Tw;
2298 gPdfOps["Tz"] = PdfOp_Tz;
2299 gPdfOps["TL"] = PdfOp_TL;
2300 gPdfOps["Tf"] = PdfOp_Tf;
2301 gPdfOps["Tr"] = PdfOp_Tr;
2302 gPdfOps["Ts"] = PdfOp_Ts;
2303
2304 gPdfOps["d0"] = PdfOp_d0;
2305 gPdfOps["d1"] = PdfOp_d1;
2306
2307 gPdfOps["sh"] = PdfOp_sh;
2308
2309 gPdfOps["Do"] = PdfOp_Do;
2310
2311 gPdfOps["MP"] = PdfOp_MP;
2312 gPdfOps["DP"] = PdfOp_DP;
2313 gPdfOps["BMC"] = PdfOp_BMC;
2314 gPdfOps["BDC"] = PdfOp_BDC;
2315 gPdfOps["EMC"] = PdfOp_EMC;
2316
2317 gInitialized = true;
2318}
2319
2320void reportPdfRenderStats() {
2321 std::map<std::string, int>::iterator iter;
2322
2323 for (int i = 0 ; i < kCount_PdfResult; i++) {
2324 for (iter = gRenderStats[i].begin(); iter != gRenderStats[i].end(); ++iter) {
2325 printf("%s: %s -> count %i\n", gRenderStatsNames[i], iter->first.c_str(), iter->second);
2326 }
2327 }
2328}
2329
2330PdfResult PdfMainLooper::consumeToken(PdfToken& token) {
2331 if( token.eType == ePdfContentsType_Keyword )
2332 {
2333 // TODO(edisonn): log trace flag (verbose, error, info, warning, ...)
2334#ifdef PDF_TRACE
2335 printf("KEYWORD: %s\n", token.pszToken);
2336#endif
2337 PdfOperatorRenderer pdfOperatorRenderer = gPdfOps[token.pszToken];
2338 if (pdfOperatorRenderer) {
2339 // caller, main work is done by pdfOperatorRenderer(...)
2340 PdfTokenLooper* childLooper = NULL;
2341 gRenderStats[pdfOperatorRenderer(fPdfContext, fCanvas, &childLooper)][token.pszToken]++;
2342
2343 if (childLooper) {
2344 childLooper->setUp(this);
2345 childLooper->loop();
2346 delete childLooper;
2347 }
2348 } else {
2349 gRenderStats[kUnsupported_PdfResult][token.pszToken]++;
2350 }
2351 }
2352 else if ( token.eType == ePdfContentsType_Variant )
2353 {
2354#ifdef PDF_TRACE
2355 std::string _var;
2356 token.var.ToString(_var);
2357 printf("var: %s\n", _var.c_str());
2358#endif
2359 fPdfContext->fVarStack.push( token.var );
2360 }
2361 else if ( token.eType == ePdfContentsType_ImageData) {
2362 // TODO(edisonn): implement inline image.
2363 }
2364 else {
2365 return kIgnoreError_PdfResult;
2366 }
2367 return kOK_PdfResult;
2368}
2369
2370void PdfMainLooper::loop() {
2371 PdfToken token;
2372 while (readToken(fTokenizer, &token)) {
2373 consumeToken(token);
2374 }
2375}
2376
2377PdfResult PdfInlineImageLooper::consumeToken(PdfToken& token) {
2378 //pdfContext.fInlineImage.fKeyValuePairs[key] = value;
2379 return kNYI_PdfResult;
2380}
2381
2382void PdfInlineImageLooper::loop() {
2383 PdfToken token;
2384 while (readToken(fTokenizer, &token)) {
2385 if (token.eType == ePdfContentsType_Keyword && strcmp(token.pszToken, "BX") == 0) {
2386 PdfTokenLooper* looper = new PdfCompatibilitySectionLooper();
2387 looper->setUp(this);
2388 looper->loop();
2389 } else {
2390 if (token.eType == ePdfContentsType_Keyword && strcmp(token.pszToken, "EI") == 0) {
2391 done();
2392 return;
2393 }
2394
2395 consumeToken(token);
2396 }
2397 }
2398 // TODO(edisonn): report error/warning, EOF without EI.
2399}
2400
2401PdfResult PdfInlineImageLooper::done() {
2402
2403 // TODO(edisonn): long to short names
2404 // TODO(edisonn): set properties in a map
2405 // TODO(edisonn): extract bitmap stream, check if PoDoFo has public utilities to uncompress
2406 // the stream.
2407
2408 SkBitmap bitmap;
2409 setup_bitmap(&bitmap, 50, 50, SK_ColorRED);
2410
2411 // TODO(edisonn): matrix use.
2412 // Draw dummy red square, to show the prezence of the inline image.
2413 fCanvas->drawBitmap(bitmap,
2414 SkDoubleToScalar(0),
2415 SkDoubleToScalar(0),
2416 NULL);
2417 return kNYI_PdfResult;
2418}
2419
2420PdfResult PdfCompatibilitySectionLooper::consumeToken(PdfToken& token) {
2421 return fParent->consumeToken(token);
2422}
2423
2424void PdfCompatibilitySectionLooper::loop() {
2425 // TODO(edisonn): save stacks position, or create a new stack?
2426 // TODO(edisonn): what happens if we pop out more variables then when we started?
2427 // restore them? fail? We could create a new operands stack for every new BX/EX section,
2428 // pop-ing too much will not affect outside the section.
2429 PdfToken token;
2430 while (readToken(fTokenizer, &token)) {
2431 if (token.eType == ePdfContentsType_Keyword && strcmp(token.pszToken, "BX") == 0) {
2432 PdfTokenLooper* looper = new PdfCompatibilitySectionLooper();
2433 looper->setUp(this);
2434 looper->loop();
2435 delete looper;
2436 } else {
2437 if (token.eType == ePdfContentsType_Keyword && strcmp(token.pszToken, "EX") == 0) break;
2438 fParent->consumeToken(token);
2439 }
2440 }
2441 // TODO(edisonn): restore stack.
2442}
2443
2444// TODO(edisonn): fix PoDoFo load ~/crashing/Shading.pdf
2445// TODO(edisonn): Add API for Forms viewing and editing
2446// e.g. SkBitmap getPage(int page);
2447// int formsCount();
2448// SkForm getForm(int formID); // SkForm(SkRect, .. other data)
2449// TODO (edisonn): Add intend when loading pdf, for example: for viewing, parsing all content, ...
2450// if we load the first page, and we zoom to fit to screen horizontally, then load only those
2451// resources needed, so the preview is fast.
2452// TODO (edisonn): hide parser/tokenizer behind and interface and a query language, and resolve
2453// references automatically.
2454class SkPdfViewer : public SkRefCnt {
2455public:
2456
2457 bool load(const SkString inputFileName, SkPicture* out) {
2458
2459 initPdfOperatorRenderes();
2460
2461 try
2462 {
2463 std::cout << "Init: " << inputFileName.c_str() << std::endl;
2464
2465 PdfMemDocument doc(inputFileName.c_str());
2466 if( !doc.GetPageCount() )
2467 {
2468 std::cout << "ERROR: Empty Document" << inputFileName.c_str() << std::endl;
2469 return false;
2470 } else {
2471
2472 for (int pn = 0; pn < doc.GetPageCount(); ++pn) {
2473 PoDoFo::PdfPage* page = doc.GetPage(pn);
2474 PdfRect rect = page->GetMediaBox();
2475#ifdef PDF_TRACE
2476 printf("Page Width: %f, Page Height: %f\n", rect.GetWidth(), rect.GetHeight());
2477#endif
2478
2479 // TODO(edisonn): page->GetCropBox(), page->GetTrimBox() ... how to use?
2480
2481 SkBitmap bitmap;
2482#ifdef PDF_DEBUG_3X
2483 setup_bitmap(&bitmap, 3*rect.GetWidth(), 3*rect.GetHeight());
2484#else
2485 setup_bitmap(&bitmap, rect.GetWidth(), rect.GetHeight());
2486#endif
2487 SkAutoTUnref<SkDevice> device(SkNEW_ARGS(SkDevice, (bitmap)));
2488 SkCanvas canvas(device);
2489
2490
2491 const char* pszToken = NULL;
2492 PdfVariant var;
2493 EPdfContentsType eType;
2494
2495 PdfContentsTokenizer tokenizer( page );
2496
2497 PdfContext pdfContext;
2498 pdfContext.fPdfPage = page;
2499 pdfContext.fPdfDoc = &doc;
2500 pdfContext.fOriginalMatrix = SkMatrix::I();
2501 pdfContext.fGraphicsState.fObjectWithResources = pdfContext.fPdfPage->GetObject();
2502
2503 gPdfContext = &pdfContext;
2504 gDumpBitmap = &bitmap;
2505 gDumpCanvas = &canvas;
2506
2507
2508 // TODO(edisonn): get matrix stuff right.
2509 // TODO(edisonn): add DPI/scale/zoom.
2510 SkScalar z = SkIntToScalar(0);
2511 SkScalar w = SkDoubleToScalar(rect.GetWidth());
2512 SkScalar h = SkDoubleToScalar(rect.GetHeight());
2513
2514 SkPoint pdfSpace[4] = {SkPoint::Make(z, z), SkPoint::Make(w, z), SkPoint::Make(w, h), SkPoint::Make(z, h)};
2515// SkPoint skiaSpace[4] = {SkPoint::Make(z, h), SkPoint::Make(w, h), SkPoint::Make(w, z), SkPoint::Make(z, z)};
2516
2517 // TODO(edisonn): add flag for this app to create sourunding buffer zone
2518 // TODO(edisonn): add flagg for no clipping.
2519 // Use larger image to make sure we do not draw anything outside of page
2520 // could be used in tests.
2521
2522#ifdef PDF_DEBUG_3X
2523 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)};
2524#else
2525 SkPoint skiaSpace[4] = {SkPoint::Make(z, h), SkPoint::Make(w, h), SkPoint::Make(w, z), SkPoint::Make(z, z)};
2526#endif
2527 //SkPoint pdfSpace[2] = {SkPoint::Make(z, z), SkPoint::Make(w, h)};
2528 //SkPoint skiaSpace[2] = {SkPoint::Make(w, z), SkPoint::Make(z, h)};
2529
2530 //SkPoint pdfSpace[2] = {SkPoint::Make(z, z), SkPoint::Make(z, h)};
2531 //SkPoint skiaSpace[2] = {SkPoint::Make(z, h), SkPoint::Make(z, z)};
2532
2533 //SkPoint pdfSpace[3] = {SkPoint::Make(z, z), SkPoint::Make(z, h), SkPoint::Make(w, h)};
2534 //SkPoint skiaSpace[3] = {SkPoint::Make(z, h), SkPoint::Make(z, z), SkPoint::Make(w, 0)};
2535
2536 SkAssertResult(pdfContext.fOriginalMatrix.setPolyToPoly(pdfSpace, skiaSpace, 4));
2537 SkTraceMatrix(pdfContext.fOriginalMatrix, "Original matrix");
2538
2539
2540 pdfContext.fGraphicsState.fMatrix = pdfContext.fOriginalMatrix;
2541 pdfContext.fGraphicsState.fMatrixTm = pdfContext.fGraphicsState.fMatrix;
2542 pdfContext.fGraphicsState.fMatrixTlm = pdfContext.fGraphicsState.fMatrix;
2543
2544 canvas.setMatrix(pdfContext.fOriginalMatrix);
2545
2546#ifndef PDF_DEBUG_NO_PAGE_CLIPING
2547 canvas.clipRect(SkRect::MakeXYWH(z, z, w, h), SkRegion::kIntersect_Op, true);
2548#endif
2549
2550 PdfMainLooper looper(NULL, &tokenizer, &pdfContext, &canvas);
2551 looper.loop();
2552
2553 canvas.flush();
2554
2555 SkString out;
2556 out.appendf("%s-%i.png", inputFileName.c_str(), pn);
2557 SkImageEncoder::EncodeFile(out.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100);
2558 }
2559 return true;
2560 }
2561 }
2562 catch( PdfError & e )
2563 {
2564 std::cout << "ERROR: PDF can't be parsed!" << inputFileName.c_str() << std::endl;
2565 return false;
2566 }
2567
2568 return true;
2569 }
2570 bool write(void*) const { return false; }
2571};
2572
2573
2574
2575/**
2576 * Given list of directories and files to use as input, expects to find .pdf
2577 * files and it will convert them to .png files writing them in the same directory
2578 * one file for each page.
2579 *
2580 * Returns zero exit code if all .pdf files were converted successfully,
2581 * otherwise returns error code 1.
2582 */
2583
2584static const char PDF_FILE_EXTENSION[] = "pdf";
2585static const char PNG_FILE_EXTENSION[] = "png";
2586
2587// TODO(edisonn): add ability to write to a new directory.
2588static void usage(const char* argv0) {
2589 SkDebugf("PDF to PNG rendering tool\n");
2590 SkDebugf("\n"
2591"Usage: \n"
2592" %s <input>... -w <outputDir> \n"
2593, argv0);
2594 SkDebugf("\n\n");
2595 SkDebugf(
2596" input: A list of directories and files to use as input. Files are\n"
2597" expected to have the .skp extension.\n\n");
2598 SkDebugf(
2599" outputDir: directory to write the rendered pdfs.\n\n");
2600 SkDebugf("\n");
2601}
2602
2603/** Replaces the extension of a file.
2604 * @param path File name whose extension will be changed.
2605 * @param old_extension The old extension.
2606 * @param new_extension The new extension.
2607 * @returns false if the file did not has the expected extension.
2608 * if false is returned, contents of path are undefined.
2609 */
2610static bool replace_filename_extension(SkString* path,
2611 const char old_extension[],
2612 const char new_extension[]) {
2613 if (path->endsWith(old_extension)) {
2614 path->remove(path->size() - strlen(old_extension),
2615 strlen(old_extension));
2616 if (!path->endsWith(".")) {
2617 return false;
2618 }
2619 path->append(new_extension);
2620 return true;
2621 }
2622 return false;
2623}
2624
2625/** Builds the output filename. path = dir/name, and it replaces expected
2626 * .skp extension with .pdf extention.
2627 * @param path Output filename.
2628 * @param name The name of the file.
2629 * @returns false if the file did not has the expected extension.
2630 * if false is returned, contents of path are undefined.
2631 */
2632static bool make_output_filepath(SkString* path, const SkString& dir,
2633 const SkString& name) {
2634 sk_tools::make_filepath(path, dir, name);
2635 return replace_filename_extension(path,
2636 PDF_FILE_EXTENSION,
2637 PNG_FILE_EXTENSION);
2638}
2639
2640/** Write the output of pdf renderer to a file.
2641 * @param outputDir Output dir.
2642 * @param inputFilename The skp file that was read.
2643 * @param renderer The object responsible to write the pdf file.
2644 */
2645static bool write_output(const SkString& outputDir,
2646 const SkString& inputFilename,
2647 const SkPdfViewer& renderer) {
2648 if (outputDir.isEmpty()) {
2649 SkDynamicMemoryWStream stream;
2650 renderer.write(&stream);
2651 return true;
2652 }
2653
2654 SkString outputPath;
2655 if (!make_output_filepath(&outputPath, outputDir, inputFilename)) {
2656 return false;
2657 }
2658
2659 SkFILEWStream stream(outputPath.c_str());
2660 if (!stream.isValid()) {
2661 SkDebugf("Could not write to file %s\n", outputPath.c_str());
2662 return false;
2663 }
2664 renderer.write(&stream);
2665
2666 return true;
2667}
2668
2669/** Reads an skp file, renders it to pdf and writes the output to a pdf file
2670 * @param inputPath The skp file to be read.
2671 * @param outputDir Output dir.
2672 * @param renderer The object responsible to render the skp object into pdf.
2673 */
2674static bool parse_pdf(const SkString& inputPath, const SkString& outputDir,
2675 SkPdfViewer& renderer) {
2676 SkString inputFilename;
2677 sk_tools::get_basename(&inputFilename, inputPath);
2678
2679 SkFILEStream inputStream;
2680 inputStream.setPath(inputPath.c_str());
2681 if (!inputStream.isValid()) {
2682 SkDebugf("Could not open file %s\n", inputPath.c_str());
2683 return false;
2684 }
2685
2686 bool success = false;
2687
2688 success = renderer.load(inputPath, NULL);
2689
2690
2691// success = write_output(outputDir, inputFilename, renderer);
2692
2693 //renderer.end();
2694 return success;
2695}
2696
2697/** For each file in the directory or for the file passed in input, call
2698 * parse_pdf.
2699 * @param input A directory or an pdf file.
2700 * @param outputDir Output dir.
2701 * @param renderer The object responsible to render the skp object into pdf.
2702 */
2703static int process_input(const SkString& input, const SkString& outputDir,
2704 SkPdfViewer& renderer) {
2705 int failures = 0;
2706 if (sk_isdir(input.c_str())) {
2707 SkOSFile::Iter iter(input.c_str(), PDF_FILE_EXTENSION);
2708 SkString inputFilename;
2709 while (iter.next(&inputFilename)) {
2710 SkString inputPath;
2711 sk_tools::make_filepath(&inputPath, input, inputFilename);
2712 if (!parse_pdf(inputPath, outputDir, renderer)) {
2713 ++failures;
2714 }
2715 }
2716 } else {
2717 SkString inputPath(input);
2718 if (!parse_pdf(inputPath, outputDir, renderer)) {
2719 ++failures;
2720 }
2721 }
2722 return failures;
2723}
2724
2725static void parse_commandline(int argc, char* const argv[],
2726 SkTArray<SkString>* inputs,
2727 SkString* outputDir) {
2728 const char* argv0 = argv[0];
2729 char* const* stop = argv + argc;
2730
2731 for (++argv; argv < stop; ++argv) {
2732 if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
2733 usage(argv0);
2734 exit(-1);
2735 } else if (0 == strcmp(*argv, "-w")) {
2736 ++argv;
2737 if (argv >= stop) {
2738 SkDebugf("Missing outputDir for -w\n");
2739 usage(argv0);
2740 exit(-1);
2741 }
2742 *outputDir = SkString(*argv);
2743 } else {
2744 inputs->push_back(SkString(*argv));
2745 }
2746 }
2747
2748 if (inputs->count() < 1) {
2749 usage(argv0);
2750 exit(-1);
2751 }
2752}
2753
2754int tool_main(int argc, char** argv);
2755int tool_main(int argc, char** argv) {
2756 SkAutoGraphics ag;
2757 SkTArray<SkString> inputs;
2758
2759 SkAutoTUnref<SkPdfViewer>
2760 renderer(SkNEW(SkPdfViewer));
2761 SkASSERT(renderer.get());
2762
2763 SkString outputDir;
2764 parse_commandline(argc, argv, &inputs, &outputDir);
2765
2766 int failures = 0;
2767 for (int i = 0; i < inputs.count(); i ++) {
2768 failures += process_input(inputs[i], outputDir, *renderer);
2769 }
2770
2771 reportPdfRenderStats();
2772
2773 if (failures != 0) {
2774 SkDebugf("Failed to render %i PDFs.\n", failures);
2775 return 1;
2776 }
2777
2778 return 0;
2779}
2780
2781#if !defined SK_BUILD_FOR_IOS
2782int main(int argc, char * const argv[]) {
2783 return tool_main(argc, (char**) argv);
2784}
2785#endif