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