Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / pdf / SkPDFDevice.cpp
1 /*
2  * Copyright 2011 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 "SkPDFDevice.h"
9
10 #include "SkAnnotation.h"
11 #include "SkColor.h"
12 #include "SkClipStack.h"
13 #include "SkData.h"
14 #include "SkDraw.h"
15 #include "SkFontHost.h"
16 #include "SkGlyphCache.h"
17 #include "SkPaint.h"
18 #include "SkPath.h"
19 #include "SkPathOps.h"
20 #include "SkPDFFont.h"
21 #include "SkPDFFormXObject.h"
22 #include "SkPDFGraphicState.h"
23 #include "SkPDFImage.h"
24 #include "SkPDFResourceDict.h"
25 #include "SkPDFShader.h"
26 #include "SkPDFStream.h"
27 #include "SkPDFTypes.h"
28 #include "SkPDFUtils.h"
29 #include "SkRect.h"
30 #include "SkRRect.h"
31 #include "SkString.h"
32 #include "SkSurface.h"
33 #include "SkTextFormatParams.h"
34 #include "SkTemplates.h"
35 #include "SkTypefacePriv.h"
36 #include "SkTSet.h"
37
38 #define DPI_FOR_RASTER_SCALE_ONE 72
39
40 // Utility functions
41
42 static void emit_pdf_color(SkColor color, SkWStream* result) {
43     SkASSERT(SkColorGetA(color) == 0xFF);  // We handle alpha elsewhere.
44     SkScalar colorMax = SkIntToScalar(0xFF);
45     SkPDFScalar::Append(
46             SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
47     result->writeText(" ");
48     SkPDFScalar::Append(
49             SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
50     result->writeText(" ");
51     SkPDFScalar::Append(
52             SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
53     result->writeText(" ");
54 }
55
56 static SkPaint calculate_text_paint(const SkPaint& paint) {
57     SkPaint result = paint;
58     if (result.isFakeBoldText()) {
59         SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
60                                                     kStdFakeBoldInterpKeys,
61                                                     kStdFakeBoldInterpValues,
62                                                     kStdFakeBoldInterpLength);
63         SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
64         if (result.getStyle() == SkPaint::kFill_Style) {
65             result.setStyle(SkPaint::kStrokeAndFill_Style);
66         } else {
67             width += result.getStrokeWidth();
68         }
69         result.setStrokeWidth(width);
70     }
71     return result;
72 }
73
74 // Stolen from measure_text in SkDraw.cpp and then tweaked.
75 static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
76                        const uint16_t* glyphs, size_t len,
77                        SkScalar* x, SkScalar* y) {
78     if (paint.getTextAlign() == SkPaint::kLeft_Align) {
79         return;
80     }
81
82     SkMatrix ident;
83     ident.reset();
84     SkAutoGlyphCache autoCache(paint, NULL, &ident);
85     SkGlyphCache* cache = autoCache.getCache();
86
87     const char* start = reinterpret_cast<const char*>(glyphs);
88     const char* stop = reinterpret_cast<const char*>(glyphs + len);
89     SkFixed xAdv = 0, yAdv = 0;
90
91     // TODO(vandebo): This probably needs to take kerning into account.
92     while (start < stop) {
93         const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
94         xAdv += glyph.fAdvanceX;
95         yAdv += glyph.fAdvanceY;
96     };
97     if (paint.getTextAlign() == SkPaint::kLeft_Align) {
98         return;
99     }
100
101     SkScalar xAdj = SkFixedToScalar(xAdv);
102     SkScalar yAdj = SkFixedToScalar(yAdv);
103     if (paint.getTextAlign() == SkPaint::kCenter_Align) {
104         xAdj = SkScalarHalf(xAdj);
105         yAdj = SkScalarHalf(yAdj);
106     }
107     *x = *x - xAdj;
108     *y = *y - yAdj;
109 }
110
111 static int max_glyphid_for_typeface(SkTypeface* typeface) {
112     SkAutoResolveDefaultTypeface autoResolve(typeface);
113     typeface = autoResolve.get();
114     return typeface->countGlyphs() - 1;
115 }
116
117 typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
118
119 static int force_glyph_encoding(const SkPaint& paint, const void* text,
120                                 size_t len, SkGlyphStorage* storage,
121                                 const uint16_t** glyphIDs) {
122     // Make sure we have a glyph id encoding.
123     if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
124         int numGlyphs = paint.textToGlyphs(text, len, NULL);
125         storage->reset(numGlyphs);
126         paint.textToGlyphs(text, len, storage->get());
127         *glyphIDs = storage->get();
128         return numGlyphs;
129     }
130
131     // For user supplied glyph ids we need to validate them.
132     SkASSERT((len & 1) == 0);
133     int numGlyphs = SkToInt(len / 2);
134     const uint16_t* input = static_cast<const uint16_t*>(text);
135
136     int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
137     int validated;
138     for (validated = 0; validated < numGlyphs; ++validated) {
139         if (input[validated] > maxGlyphID) {
140             break;
141         }
142     }
143     if (validated >= numGlyphs) {
144         *glyphIDs = static_cast<const uint16_t*>(text);
145         return numGlyphs;
146     }
147
148     // Silently drop anything out of range.
149     storage->reset(numGlyphs);
150     if (validated > 0) {
151         memcpy(storage->get(), input, validated * sizeof(uint16_t));
152     }
153
154     for (int i = validated; i < numGlyphs; ++i) {
155         storage->get()[i] = input[i];
156         if (input[i] > maxGlyphID) {
157             storage->get()[i] = 0;
158         }
159     }
160     *glyphIDs = storage->get();
161     return numGlyphs;
162 }
163
164 static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
165                                SkWStream* content) {
166     // Flip the text about the x-axis to account for origin swap and include
167     // the passed parameters.
168     content->writeText("1 0 ");
169     SkPDFScalar::Append(0 - textSkewX, content);
170     content->writeText(" -1 ");
171     SkPDFScalar::Append(x, content);
172     content->writeText(" ");
173     SkPDFScalar::Append(y, content);
174     content->writeText(" Tm\n");
175 }
176
177 // It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
178 // later being our representation of an object in the PDF file.
179 struct GraphicStateEntry {
180     GraphicStateEntry();
181
182     // Compare the fields we care about when setting up a new content entry.
183     bool compareInitialState(const GraphicStateEntry& b);
184
185     SkMatrix fMatrix;
186     // We can't do set operations on Paths, though PDF natively supports
187     // intersect.  If the clip stack does anything other than intersect,
188     // we have to fall back to the region.  Treat fClipStack as authoritative.
189     // See http://code.google.com/p/skia/issues/detail?id=221
190     SkClipStack fClipStack;
191     SkRegion fClipRegion;
192
193     // When emitting the content entry, we will ensure the graphic state
194     // is set to these values first.
195     SkColor fColor;
196     SkScalar fTextScaleX;  // Zero means we don't care what the value is.
197     SkPaint::Style fTextFill;  // Only if TextScaleX is non-zero.
198     int fShaderIndex;
199     int fGraphicStateIndex;
200
201     // We may change the font (i.e. for Type1 support) within a
202     // ContentEntry.  This is the one currently in effect, or NULL if none.
203     SkPDFFont* fFont;
204     // In PDF, text size has no default value. It is only valid if fFont is
205     // not NULL.
206     SkScalar fTextSize;
207 };
208
209 GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
210                                          fTextScaleX(SK_Scalar1),
211                                          fTextFill(SkPaint::kFill_Style),
212                                          fShaderIndex(-1),
213                                          fGraphicStateIndex(-1),
214                                          fFont(NULL),
215                                          fTextSize(SK_ScalarNaN) {
216     fMatrix.reset();
217 }
218
219 bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
220     return fColor == cur.fColor &&
221            fShaderIndex == cur.fShaderIndex &&
222            fGraphicStateIndex == cur.fGraphicStateIndex &&
223            fMatrix == cur.fMatrix &&
224            fClipStack == cur.fClipStack &&
225            (fTextScaleX == 0 ||
226                (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
227 }
228
229 class GraphicStackState {
230 public:
231     GraphicStackState(const SkClipStack& existingClipStack,
232                       const SkRegion& existingClipRegion,
233                       SkWStream* contentStream)
234             : fStackDepth(0),
235               fContentStream(contentStream) {
236         fEntries[0].fClipStack = existingClipStack;
237         fEntries[0].fClipRegion = existingClipRegion;
238     }
239
240     void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
241                     const SkPoint& translation);
242     void updateMatrix(const SkMatrix& matrix);
243     void updateDrawingState(const GraphicStateEntry& state);
244
245     void drainStack();
246
247 private:
248     void push();
249     void pop();
250     GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
251
252     // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
253     static const int kMaxStackDepth = 12;
254     GraphicStateEntry fEntries[kMaxStackDepth + 1];
255     int fStackDepth;
256     SkWStream* fContentStream;
257 };
258
259 void GraphicStackState::drainStack() {
260     while (fStackDepth) {
261         pop();
262     }
263 }
264
265 void GraphicStackState::push() {
266     SkASSERT(fStackDepth < kMaxStackDepth);
267     fContentStream->writeText("q\n");
268     fStackDepth++;
269     fEntries[fStackDepth] = fEntries[fStackDepth - 1];
270 }
271
272 void GraphicStackState::pop() {
273     SkASSERT(fStackDepth > 0);
274     fContentStream->writeText("Q\n");
275     fStackDepth--;
276 }
277
278 // This function initializes iter to be an iterator on the "stack" argument
279 // and then skips over the leading entries as specified in prefix.  It requires
280 // and asserts that "prefix" will be a prefix to "stack."
281 static void skip_clip_stack_prefix(const SkClipStack& prefix,
282                                    const SkClipStack& stack,
283                                    SkClipStack::Iter* iter) {
284     SkClipStack::B2TIter prefixIter(prefix);
285     iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
286
287     const SkClipStack::Element* prefixEntry;
288     const SkClipStack::Element* iterEntry;
289
290     for (prefixEntry = prefixIter.next(); prefixEntry;
291             prefixEntry = prefixIter.next()) {
292         iterEntry = iter->next();
293         SkASSERT(iterEntry);
294         // Because of SkClipStack does internal intersection, the last clip
295         // entry may differ.
296         if (*prefixEntry != *iterEntry) {
297             SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
298             SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
299             SkASSERT(iterEntry->getType() == prefixEntry->getType());
300             // back up the iterator by one
301             iter->prev();
302             prefixEntry = prefixIter.next();
303             break;
304         }
305     }
306
307     SkASSERT(prefixEntry == NULL);
308 }
309
310 static void emit_clip(SkPath* clipPath, SkRect* clipRect,
311                       SkWStream* contentStream) {
312     SkASSERT(clipPath || clipRect);
313
314     SkPath::FillType clipFill;
315     if (clipPath) {
316         SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
317         clipFill = clipPath->getFillType();
318     } else {
319         SkPDFUtils::AppendRectangle(*clipRect, contentStream);
320         clipFill = SkPath::kWinding_FillType;
321     }
322
323     NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
324     NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
325     if (clipFill == SkPath::kEvenOdd_FillType) {
326         contentStream->writeText("W* n\n");
327     } else {
328         contentStream->writeText("W n\n");
329     }
330 }
331
332 #ifdef SK_PDF_USE_PATHOPS
333 /* Calculate an inverted path's equivalent non-inverted path, given the
334  * canvas bounds.
335  * outPath may alias with invPath (since this is supported by PathOps).
336  */
337 static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
338                                    SkPath* outPath) {
339     SkASSERT(invPath.isInverseFillType());
340
341     SkPath clipPath;
342     clipPath.addRect(bounds);
343
344     return Op(clipPath, invPath, kIntersect_PathOp, outPath);
345 }
346
347 // Sanity check the numerical values of the SkRegion ops and PathOps ops
348 // enums so region_op_to_pathops_op can do a straight passthrough cast.
349 // If these are failing, it may be necessary to make region_op_to_pathops_op
350 // do more.
351 SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
352                   region_pathop_mismatch);
353 SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
354                   region_pathop_mismatch);
355 SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
356                   region_pathop_mismatch);
357 SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
358                   region_pathop_mismatch);
359 SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
360                   (int)kReverseDifference_PathOp,
361                   region_pathop_mismatch);
362
363 static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
364     SkASSERT(op >= 0);
365     SkASSERT(op <= SkRegion::kReverseDifference_Op);
366     return (SkPathOp)op;
367 }
368
369 /* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
370  * Returns true if successful, or false if not successful.
371  * If successful, the resulting clip is stored in outClipPath.
372  * If not successful, outClipPath is undefined, and a fallback method
373  * should be used.
374  */
375 static bool get_clip_stack_path(const SkMatrix& transform,
376                                 const SkClipStack& clipStack,
377                                 const SkRegion& clipRegion,
378                                 SkPath* outClipPath) {
379     outClipPath->reset();
380     outClipPath->setFillType(SkPath::kInverseWinding_FillType);
381
382     const SkClipStack::Element* clipEntry;
383     SkClipStack::Iter iter;
384     iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
385     for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
386         SkPath entryPath;
387         if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
388             outClipPath->reset();
389             outClipPath->setFillType(SkPath::kInverseWinding_FillType);
390             continue;
391         } else {
392             clipEntry->asPath(&entryPath);
393         }
394         entryPath.transform(transform);
395
396         if (SkRegion::kReplace_Op == clipEntry->getOp()) {
397             *outClipPath = entryPath;
398         } else {
399             SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
400             if (!Op(*outClipPath, entryPath, op, outClipPath)) {
401                 return false;
402             }
403         }
404     }
405
406     if (outClipPath->isInverseFillType()) {
407         // The bounds are slightly outset to ensure this is correct in the
408         // face of floating-point accuracy and possible SkRegion bitmap
409         // approximations.
410         SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
411         clipBounds.outset(SK_Scalar1, SK_Scalar1);
412         if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
413             return false;
414         }
415     }
416     return true;
417 }
418 #endif
419
420 // TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
421 // graphic state stack, and the fact that we can know all the clips used
422 // on the page to optimize this.
423 void GraphicStackState::updateClip(const SkClipStack& clipStack,
424                                    const SkRegion& clipRegion,
425                                    const SkPoint& translation) {
426     if (clipStack == currentEntry()->fClipStack) {
427         return;
428     }
429
430     while (fStackDepth > 0) {
431         pop();
432         if (clipStack == currentEntry()->fClipStack) {
433             return;
434         }
435     }
436     push();
437
438     currentEntry()->fClipStack = clipStack;
439     currentEntry()->fClipRegion = clipRegion;
440
441     SkMatrix transform;
442     transform.setTranslate(translation.fX, translation.fY);
443
444 #ifdef SK_PDF_USE_PATHOPS
445     SkPath clipPath;
446     if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
447         emit_clip(&clipPath, NULL, fContentStream);
448         return;
449     }
450 #endif
451     // gsState->initialEntry()->fClipStack/Region specifies the clip that has
452     // already been applied.  (If this is a top level device, then it specifies
453     // a clip to the content area.  If this is a layer, then it specifies
454     // the clip in effect when the layer was created.)  There's no need to
455     // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
456     // initial clip on the parent layer.  (This means there's a bug if the user
457     // expands the clip and then uses any xfer mode that uses dst:
458     // http://code.google.com/p/skia/issues/detail?id=228 )
459     SkClipStack::Iter iter;
460     skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
461
462     // If the clip stack does anything other than intersect or if it uses
463     // an inverse fill type, we have to fall back to the clip region.
464     bool needRegion = false;
465     const SkClipStack::Element* clipEntry;
466     for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
467         if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
468                 clipEntry->isInverseFilled()) {
469             needRegion = true;
470             break;
471         }
472     }
473
474     if (needRegion) {
475         SkPath clipPath;
476         SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
477         emit_clip(&clipPath, NULL, fContentStream);
478     } else {
479         skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
480         const SkClipStack::Element* clipEntry;
481         for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
482             SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
483             switch (clipEntry->getType()) {
484                 case SkClipStack::Element::kRect_Type: {
485                     SkRect translatedClip;
486                     transform.mapRect(&translatedClip, clipEntry->getRect());
487                     emit_clip(NULL, &translatedClip, fContentStream);
488                     break;
489                 }
490                 default: {
491                     SkPath translatedPath;
492                     clipEntry->asPath(&translatedPath);
493                     translatedPath.transform(transform, &translatedPath);
494                     emit_clip(&translatedPath, NULL, fContentStream);
495                     break;
496                 }
497             }
498         }
499     }
500 }
501
502 void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
503     if (matrix == currentEntry()->fMatrix) {
504         return;
505     }
506
507     if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
508         SkASSERT(fStackDepth > 0);
509         SkASSERT(fEntries[fStackDepth].fClipStack ==
510                  fEntries[fStackDepth -1].fClipStack);
511         pop();
512
513         SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
514     }
515     if (matrix.getType() == SkMatrix::kIdentity_Mask) {
516         return;
517     }
518
519     push();
520     SkPDFUtils::AppendTransform(matrix, fContentStream);
521     currentEntry()->fMatrix = matrix;
522 }
523
524 void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
525     // PDF treats a shader as a color, so we only set one or the other.
526     if (state.fShaderIndex >= 0) {
527         if (state.fShaderIndex != currentEntry()->fShaderIndex) {
528             SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
529             currentEntry()->fShaderIndex = state.fShaderIndex;
530         }
531     } else {
532         if (state.fColor != currentEntry()->fColor ||
533                 currentEntry()->fShaderIndex >= 0) {
534             emit_pdf_color(state.fColor, fContentStream);
535             fContentStream->writeText("RG ");
536             emit_pdf_color(state.fColor, fContentStream);
537             fContentStream->writeText("rg\n");
538             currentEntry()->fColor = state.fColor;
539             currentEntry()->fShaderIndex = -1;
540         }
541     }
542
543     if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
544         SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
545         currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
546     }
547
548     if (state.fTextScaleX) {
549         if (state.fTextScaleX != currentEntry()->fTextScaleX) {
550             SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
551                                             SkIntToScalar(100));
552             SkPDFScalar::Append(pdfScale, fContentStream);
553             fContentStream->writeText(" Tz\n");
554             currentEntry()->fTextScaleX = state.fTextScaleX;
555         }
556         if (state.fTextFill != currentEntry()->fTextFill) {
557             SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
558             SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
559                               enum_must_match_value);
560             SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
561                               enum_must_match_value);
562             fContentStream->writeDecAsText(state.fTextFill);
563             fContentStream->writeText(" Tr\n");
564             currentEntry()->fTextFill = state.fTextFill;
565         }
566     }
567 }
568
569 SkBaseDevice* SkPDFDevice::onCreateDevice(const SkImageInfo& info, Usage usage) {
570     SkMatrix initialTransform;
571     initialTransform.reset();
572     SkISize size = SkISize::Make(info.width(), info.height());
573     return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
574 }
575
576
577 struct ContentEntry {
578     GraphicStateEntry fState;
579     SkDynamicMemoryWStream fContent;
580     SkAutoTDelete<ContentEntry> fNext;
581
582     // If the stack is too deep we could get Stack Overflow.
583     // So we manually destruct the object.
584     ~ContentEntry() {
585         ContentEntry* val = fNext.detach();
586         while (val != NULL) {
587             ContentEntry* valNext = val->fNext.detach();
588             // When the destructor is called, fNext is NULL and exits.
589             delete val;
590             val = valNext;
591         }
592     }
593 };
594
595 // A helper class to automatically finish a ContentEntry at the end of a
596 // drawing method and maintain the state needed between set up and finish.
597 class ScopedContentEntry {
598 public:
599     ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
600                        const SkPaint& paint, bool hasText = false)
601         : fDevice(device),
602           fContentEntry(NULL),
603           fXfermode(SkXfermode::kSrcOver_Mode),
604           fDstFormXObject(NULL) {
605         init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
606     }
607     ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
608                        const SkRegion& clipRegion, const SkMatrix& matrix,
609                        const SkPaint& paint, bool hasText = false)
610         : fDevice(device),
611           fContentEntry(NULL),
612           fXfermode(SkXfermode::kSrcOver_Mode),
613           fDstFormXObject(NULL) {
614         init(clipStack, clipRegion, matrix, paint, hasText);
615     }
616
617     ~ScopedContentEntry() {
618         if (fContentEntry) {
619             SkPath* shape = &fShape;
620             if (shape->isEmpty()) {
621                 shape = NULL;
622             }
623             fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
624         }
625         SkSafeUnref(fDstFormXObject);
626     }
627
628     ContentEntry* entry() { return fContentEntry; }
629
630     /* Returns true when we explicitly need the shape of the drawing. */
631     bool needShape() {
632         switch (fXfermode) {
633             case SkXfermode::kClear_Mode:
634             case SkXfermode::kSrc_Mode:
635             case SkXfermode::kSrcIn_Mode:
636             case SkXfermode::kSrcOut_Mode:
637             case SkXfermode::kDstIn_Mode:
638             case SkXfermode::kDstOut_Mode:
639             case SkXfermode::kSrcATop_Mode:
640             case SkXfermode::kDstATop_Mode:
641             case SkXfermode::kModulate_Mode:
642                 return true;
643             default:
644                 return false;
645         }
646     }
647
648     /* Returns true unless we only need the shape of the drawing. */
649     bool needSource() {
650         if (fXfermode == SkXfermode::kClear_Mode) {
651             return false;
652         }
653         return true;
654     }
655
656     /* If the shape is different than the alpha component of the content, then
657      * setShape should be called with the shape.  In particular, images and
658      * devices have rectangular shape.
659      */
660     void setShape(const SkPath& shape) {
661         fShape = shape;
662     }
663
664 private:
665     SkPDFDevice* fDevice;
666     ContentEntry* fContentEntry;
667     SkXfermode::Mode fXfermode;
668     SkPDFFormXObject* fDstFormXObject;
669     SkPath fShape;
670
671     void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
672               const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
673         // Shape has to be flatten before we get here.
674         if (matrix.hasPerspective()) {
675             NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
676             return;
677         }
678         if (paint.getXfermode()) {
679             paint.getXfermode()->asMode(&fXfermode);
680         }
681         fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
682                                                    matrix, paint, hasText,
683                                                    &fDstFormXObject);
684     }
685 };
686
687 ////////////////////////////////////////////////////////////////////////////////
688
689 static inline SkImageInfo make_content_info(const SkISize& contentSize,
690                                             const SkMatrix* initialTransform) {
691     SkImageInfo info;
692     if (initialTransform) {
693         // Compute the size of the drawing area.
694         SkVector drawingSize;
695         SkMatrix inverse;
696         drawingSize.set(SkIntToScalar(contentSize.fWidth),
697                         SkIntToScalar(contentSize.fHeight));
698         if (!initialTransform->invert(&inverse)) {
699             // This shouldn't happen, initial transform should be invertible.
700             SkASSERT(false);
701             inverse.reset();
702         }
703         inverse.mapVectors(&drawingSize, 1);
704         SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
705         info = SkImageInfo::MakeUnknown(abs(size.fWidth), abs(size.fHeight));
706     } else {
707         info = SkImageInfo::MakeUnknown(abs(contentSize.fWidth),
708                                         abs(contentSize.fHeight));
709     }
710     return info;
711 }
712
713 // TODO(vandebo) change pageSize to SkSize.
714 SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
715                          const SkMatrix& initialTransform)
716     : fPageSize(pageSize)
717     , fContentSize(contentSize)
718     , fLastContentEntry(NULL)
719     , fLastMarginContentEntry(NULL)
720     , fClipStack(NULL)
721     , fEncoder(NULL)
722     , fRasterDpi(72.0f)
723 {
724     const SkImageInfo info = make_content_info(contentSize, &initialTransform);
725
726     // Just report that PDF does not supports perspective in the
727     // initial transform.
728     NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
729
730     // Skia generally uses the top left as the origin but PDF natively has the
731     // origin at the bottom left. This matrix corrects for that.  But that only
732     // needs to be done once, we don't do it when layering.
733     fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
734     fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
735     fInitialTransform.preConcat(initialTransform);
736     fLegacyBitmap.setInfo(info);
737
738     SkIRect existingClip = SkIRect::MakeWH(info.width(), info.height());
739     fExistingClipRegion.setRect(existingClip);
740     this->init();
741 }
742
743 // TODO(vandebo) change layerSize to SkSize.
744 SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
745                          const SkClipStack& existingClipStack,
746                          const SkRegion& existingClipRegion)
747     : fPageSize(layerSize)
748     , fContentSize(layerSize)
749     , fExistingClipStack(existingClipStack)
750     , fExistingClipRegion(existingClipRegion)
751     , fLastContentEntry(NULL)
752     , fLastMarginContentEntry(NULL)
753     , fClipStack(NULL)
754     , fEncoder(NULL)
755     , fRasterDpi(72.0f)
756 {
757     fInitialTransform.reset();
758     fLegacyBitmap.setInfo(make_content_info(layerSize, NULL));
759
760     this->init();
761 }
762
763 SkPDFDevice::~SkPDFDevice() {
764     this->cleanUp(true);
765 }
766
767 void SkPDFDevice::init() {
768     fAnnotations = NULL;
769     fResourceDict = NULL;
770     fContentEntries.free();
771     fLastContentEntry = NULL;
772     fMarginContentEntries.free();
773     fLastMarginContentEntry = NULL;
774     fDrawingArea = kContent_DrawingArea;
775     if (fFontGlyphUsage.get() == NULL) {
776         fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
777     }
778 }
779
780 void SkPDFDevice::cleanUp(bool clearFontUsage) {
781     fGraphicStateResources.unrefAll();
782     fXObjectResources.unrefAll();
783     fFontResources.unrefAll();
784     fShaderResources.unrefAll();
785     SkSafeUnref(fAnnotations);
786     SkSafeUnref(fResourceDict);
787     fNamedDestinations.deleteAll();
788
789     if (clearFontUsage) {
790         fFontGlyphUsage->reset();
791     }
792 }
793
794 void SkPDFDevice::clear(SkColor color) {
795     this->cleanUp(true);
796     this->init();
797
798     SkPaint paint;
799     paint.setColor(color);
800     paint.setStyle(SkPaint::kFill_Style);
801     SkMatrix identity;
802     identity.reset();
803     ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
804                                identity, paint);
805     internalDrawPaint(paint, content.entry());
806 }
807
808 void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
809     SkPaint newPaint = paint;
810     newPaint.setStyle(SkPaint::kFill_Style);
811     ScopedContentEntry content(this, d, newPaint);
812     internalDrawPaint(newPaint, content.entry());
813 }
814
815 void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
816                                     ContentEntry* contentEntry) {
817     if (!contentEntry) {
818         return;
819     }
820     SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
821                                  SkIntToScalar(this->height()));
822     SkMatrix inverse;
823     if (!contentEntry->fState.fMatrix.invert(&inverse)) {
824         return;
825     }
826     inverse.mapRect(&bbox);
827
828     SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
829     SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
830                           &contentEntry->fContent);
831 }
832
833 void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
834                              size_t count, const SkPoint* points,
835                              const SkPaint& passedPaint) {
836     if (count == 0) {
837         return;
838     }
839
840     if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
841         return;
842     }
843
844     // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
845     // We only use this when there's a path effect because of the overhead
846     // of multiple calls to setUpContentEntry it causes.
847     if (passedPaint.getPathEffect()) {
848         if (d.fClip->isEmpty()) {
849             return;
850         }
851         SkDraw pointDraw(d);
852         pointDraw.fDevice = this;
853         pointDraw.drawPoints(mode, count, points, passedPaint, true);
854         return;
855     }
856
857     const SkPaint* paint = &passedPaint;
858     SkPaint modifiedPaint;
859
860     if (mode == SkCanvas::kPoints_PointMode &&
861             paint->getStrokeCap() != SkPaint::kRound_Cap) {
862         modifiedPaint = *paint;
863         paint = &modifiedPaint;
864         if (paint->getStrokeWidth()) {
865             // PDF won't draw a single point with square/butt caps because the
866             // orientation is ambiguous.  Draw a rectangle instead.
867             modifiedPaint.setStyle(SkPaint::kFill_Style);
868             SkScalar strokeWidth = paint->getStrokeWidth();
869             SkScalar halfStroke = SkScalarHalf(strokeWidth);
870             for (size_t i = 0; i < count; i++) {
871                 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
872                 r.inset(-halfStroke, -halfStroke);
873                 drawRect(d, r, modifiedPaint);
874             }
875             return;
876         } else {
877             modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
878         }
879     }
880
881     ScopedContentEntry content(this, d, *paint);
882     if (!content.entry()) {
883         return;
884     }
885
886     switch (mode) {
887         case SkCanvas::kPolygon_PointMode:
888             SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
889                                &content.entry()->fContent);
890             for (size_t i = 1; i < count; i++) {
891                 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
892                                        &content.entry()->fContent);
893             }
894             SkPDFUtils::StrokePath(&content.entry()->fContent);
895             break;
896         case SkCanvas::kLines_PointMode:
897             for (size_t i = 0; i < count/2; i++) {
898                 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
899                                    &content.entry()->fContent);
900                 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
901                                        points[i * 2 + 1].fY,
902                                        &content.entry()->fContent);
903                 SkPDFUtils::StrokePath(&content.entry()->fContent);
904             }
905             break;
906         case SkCanvas::kPoints_PointMode:
907             SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
908             for (size_t i = 0; i < count; i++) {
909                 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
910                                    &content.entry()->fContent);
911                 SkPDFUtils::ClosePath(&content.entry()->fContent);
912                 SkPDFUtils::StrokePath(&content.entry()->fContent);
913             }
914             break;
915         default:
916             SkASSERT(false);
917     }
918 }
919
920 void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
921                            const SkPaint& paint) {
922     SkRect r = rect;
923     r.sort();
924
925     if (paint.getPathEffect()) {
926         if (d.fClip->isEmpty()) {
927             return;
928         }
929         SkPath path;
930         path.addRect(r);
931         drawPath(d, path, paint, NULL, true);
932         return;
933     }
934
935     if (handleRectAnnotation(r, *d.fMatrix, paint)) {
936         return;
937     }
938
939     ScopedContentEntry content(this, d, paint);
940     if (!content.entry()) {
941         return;
942     }
943     SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
944     SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
945                           &content.entry()->fContent);
946 }
947
948 void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
949     SkPath  path;
950     path.addRRect(rrect);
951     this->drawPath(draw, path, paint, NULL, true);
952 }
953
954 void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
955     SkPath  path;
956     path.addOval(oval);
957     this->drawPath(draw, path, paint, NULL, true);
958 }
959
960 void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
961                            const SkPaint& paint, const SkMatrix* prePathMatrix,
962                            bool pathIsMutable) {
963     SkPath modifiedPath;
964     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
965
966     SkMatrix matrix = *d.fMatrix;
967     if (prePathMatrix) {
968         if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
969             if (!pathIsMutable) {
970                 pathPtr = &modifiedPath;
971                 pathIsMutable = true;
972             }
973             origPath.transform(*prePathMatrix, pathPtr);
974         } else {
975             matrix.preConcat(*prePathMatrix);
976         }
977     }
978
979     if (paint.getPathEffect()) {
980         if (d.fClip->isEmpty()) {
981             return;
982         }
983         if (!pathIsMutable) {
984             pathPtr = &modifiedPath;
985             pathIsMutable = true;
986         }
987         bool fill = paint.getFillPath(origPath, pathPtr);
988
989         SkPaint noEffectPaint(paint);
990         noEffectPaint.setPathEffect(NULL);
991         if (fill) {
992             noEffectPaint.setStyle(SkPaint::kFill_Style);
993         } else {
994             noEffectPaint.setStyle(SkPaint::kStroke_Style);
995             noEffectPaint.setStrokeWidth(0);
996         }
997         drawPath(d, *pathPtr, noEffectPaint, NULL, true);
998         return;
999     }
1000
1001 #ifdef SK_PDF_USE_PATHOPS
1002     if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
1003         return;
1004     }
1005 #endif
1006
1007     if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
1008         return;
1009     }
1010
1011     ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
1012     if (!content.entry()) {
1013         return;
1014     }
1015     SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1016                          &content.entry()->fContent);
1017     SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
1018                           &content.entry()->fContent);
1019 }
1020
1021 void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1022                                  const SkRect* src, const SkRect& dst,
1023                                  const SkPaint& paint,
1024                                  SkCanvas::DrawBitmapRectFlags flags) {
1025     // TODO: this code path must be updated to respect the flags parameter
1026     SkMatrix    matrix;
1027     SkRect      bitmapBounds, tmpSrc, tmpDst;
1028     SkBitmap    tmpBitmap;
1029
1030     bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1031
1032     // Compute matrix from the two rectangles
1033     if (src) {
1034         tmpSrc = *src;
1035     } else {
1036         tmpSrc = bitmapBounds;
1037     }
1038     matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1039
1040     const SkBitmap* bitmapPtr = &bitmap;
1041
1042     // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1043     // needed (if the src was clipped). No check needed if src==null.
1044     if (src) {
1045         if (!bitmapBounds.contains(*src)) {
1046             if (!tmpSrc.intersect(bitmapBounds)) {
1047                 return; // nothing to draw
1048             }
1049             // recompute dst, based on the smaller tmpSrc
1050             matrix.mapRect(&tmpDst, tmpSrc);
1051         }
1052
1053         // since we may need to clamp to the borders of the src rect within
1054         // the bitmap, we extract a subset.
1055         // TODO: make sure this is handled in drawBitmap and remove from here.
1056         SkIRect srcIR;
1057         tmpSrc.roundOut(&srcIR);
1058         if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1059             return;
1060         }
1061         bitmapPtr = &tmpBitmap;
1062
1063         // Since we did an extract, we need to adjust the matrix accordingly
1064         SkScalar dx = 0, dy = 0;
1065         if (srcIR.fLeft > 0) {
1066             dx = SkIntToScalar(srcIR.fLeft);
1067         }
1068         if (srcIR.fTop > 0) {
1069             dy = SkIntToScalar(srcIR.fTop);
1070         }
1071         if (dx || dy) {
1072             matrix.preTranslate(dx, dy);
1073         }
1074     }
1075     this->drawBitmap(draw, *bitmapPtr, matrix, paint);
1076 }
1077
1078 void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
1079                              const SkMatrix& matrix, const SkPaint& paint) {
1080     if (d.fClip->isEmpty()) {
1081         return;
1082     }
1083
1084     SkMatrix transform = matrix;
1085     transform.postConcat(*d.fMatrix);
1086     this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1087                              paint);
1088 }
1089
1090 void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
1091                              int x, int y, const SkPaint& paint) {
1092     if (d.fClip->isEmpty()) {
1093         return;
1094     }
1095
1096     SkMatrix matrix;
1097     matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1098     this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1099                              paint);
1100 }
1101
1102 void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1103                            SkScalar x, SkScalar y, const SkPaint& paint) {
1104     NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1105     if (paint.getMaskFilter() != NULL) {
1106         // Don't pretend we support drawing MaskFilters, it makes for artifacts
1107         // making text unreadable (e.g. same text twice when using CSS shadows).
1108         return;
1109     }
1110     SkPaint textPaint = calculate_text_paint(paint);
1111     ScopedContentEntry content(this, d, textPaint, true);
1112     if (!content.entry()) {
1113         return;
1114     }
1115
1116     SkGlyphStorage storage(0);
1117     const uint16_t* glyphIDs = NULL;
1118     int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
1119     textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1120
1121     SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
1122     align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
1123     content.entry()->fContent.writeText("BT\n");
1124     set_text_transform(x, y, textPaint.getTextSkewX(),
1125                        &content.entry()->fContent);
1126     int consumedGlyphCount = 0;
1127     while (numGlyphs > consumedGlyphCount) {
1128         updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1129         SkPDFFont* font = content.entry()->fState.fFont;
1130         //TODO: the const_cast here is a bug if the encoding started out as glyph encoding.
1131         int availableGlyphs =
1132             font->glyphsToPDFFontEncoding(const_cast<uint16_t*>(glyphIDs) + consumedGlyphCount,
1133                                           numGlyphs - consumedGlyphCount);
1134         fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1135                                         availableGlyphs);
1136         SkString encodedString =
1137             SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
1138                                       availableGlyphs, font->multiByteGlyphs());
1139         content.entry()->fContent.writeText(encodedString.c_str());
1140         consumedGlyphCount += availableGlyphs;
1141         content.entry()->fContent.writeText(" Tj\n");
1142     }
1143     content.entry()->fContent.writeText("ET\n");
1144 }
1145
1146 void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1147                               const SkScalar pos[], SkScalar constY,
1148                               int scalarsPerPos, const SkPaint& paint) {
1149     NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1150     if (paint.getMaskFilter() != NULL) {
1151         // Don't pretend we support drawing MaskFilters, it makes for artifacts
1152         // making text unreadable (e.g. same text twice when using CSS shadows).
1153         return;
1154     }
1155     SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
1156     SkPaint textPaint = calculate_text_paint(paint);
1157     ScopedContentEntry content(this, d, textPaint, true);
1158     if (!content.entry()) {
1159         return;
1160     }
1161
1162     SkGlyphStorage storage(0);
1163     const uint16_t* glyphIDs = NULL;
1164     size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
1165     textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1166
1167     SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
1168     content.entry()->fContent.writeText("BT\n");
1169     updateFont(textPaint, glyphIDs[0], content.entry());
1170     for (size_t i = 0; i < numGlyphs; i++) {
1171         SkPDFFont* font = content.entry()->fState.fFont;
1172         uint16_t encodedValue = glyphIDs[i];
1173         if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1174             // The current pdf font cannot encode the current glyph.
1175             // Try to get a pdf font which can encode the current glyph.
1176             updateFont(textPaint, glyphIDs[i], content.entry());
1177             font = content.entry()->fState.fFont;
1178             if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1179                 SkDEBUGFAIL("PDF could not encode glyph.");
1180                 continue;
1181             }
1182         }
1183
1184         fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
1185         SkScalar x = pos[i * scalarsPerPos];
1186         SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
1187         align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
1188         set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
1189         SkString encodedString =
1190             SkPDFString::FormatString(&encodedValue, 1, font->multiByteGlyphs());
1191         content.entry()->fContent.writeText(encodedString.c_str());
1192         content.entry()->fContent.writeText(" Tj\n");
1193     }
1194     content.entry()->fContent.writeText("ET\n");
1195 }
1196
1197 void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
1198                                  const SkPath& path, const SkMatrix* matrix,
1199                                  const SkPaint& paint) {
1200     if (d.fClip->isEmpty()) {
1201         return;
1202     }
1203     d.drawTextOnPath((const char*)text, len, path, matrix, paint);
1204 }
1205
1206 void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
1207                                int vertexCount, const SkPoint verts[],
1208                                const SkPoint texs[], const SkColor colors[],
1209                                SkXfermode* xmode, const uint16_t indices[],
1210                                int indexCount, const SkPaint& paint) {
1211     if (d.fClip->isEmpty()) {
1212         return;
1213     }
1214     // TODO: implement drawVertices
1215 }
1216
1217 void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1218                              int x, int y, const SkPaint& paint) {
1219     // our onCreateDevice() always creates SkPDFDevice subclasses.
1220     SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
1221     if (pdfDevice->isContentEmpty()) {
1222         return;
1223     }
1224
1225     SkMatrix matrix;
1226     matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1227     ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
1228     if (!content.entry()) {
1229         return;
1230     }
1231     if (content.needShape()) {
1232         SkPath shape;
1233         shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
1234                                        SkIntToScalar(device->width()),
1235                                        SkIntToScalar(device->height())));
1236         content.setShape(shape);
1237     }
1238     if (!content.needSource()) {
1239         return;
1240     }
1241
1242     SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1243     SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
1244                                 &content.entry()->fContent);
1245
1246     // Merge glyph sets from the drawn device.
1247     fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
1248 }
1249
1250 SkImageInfo SkPDFDevice::imageInfo() const {
1251     return fLegacyBitmap.info();
1252 }
1253
1254 void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1255     INHERITED::onAttachToCanvas(canvas);
1256
1257     // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1258     fClipStack = canvas->getClipStack();
1259 }
1260
1261 void SkPDFDevice::onDetachFromCanvas() {
1262     INHERITED::onDetachFromCanvas();
1263
1264     fClipStack = NULL;
1265 }
1266
1267 SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1268     return SkSurface::NewRaster(info, &props);
1269 }
1270
1271 ContentEntry* SkPDFDevice::getLastContentEntry() {
1272     if (fDrawingArea == kContent_DrawingArea) {
1273         return fLastContentEntry;
1274     } else {
1275         return fLastMarginContentEntry;
1276     }
1277 }
1278
1279 SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
1280     if (fDrawingArea == kContent_DrawingArea) {
1281         return &fContentEntries;
1282     } else {
1283         return &fMarginContentEntries;
1284     }
1285 }
1286
1287 void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1288     if (fDrawingArea == kContent_DrawingArea) {
1289         fLastContentEntry = contentEntry;
1290     } else {
1291         fLastMarginContentEntry = contentEntry;
1292     }
1293 }
1294
1295 void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
1296     // A ScopedContentEntry only exists during the course of a draw call, so
1297     // this can't be called while a ScopedContentEntry exists.
1298     fDrawingArea = drawingArea;
1299 }
1300
1301 SkPDFResourceDict* SkPDFDevice::getResourceDict() {
1302     if (NULL == fResourceDict) {
1303         fResourceDict = SkNEW(SkPDFResourceDict);
1304
1305         if (fGraphicStateResources.count()) {
1306             for (int i = 0; i < fGraphicStateResources.count(); i++) {
1307                 fResourceDict->insertResourceAsReference(
1308                         SkPDFResourceDict::kExtGState_ResourceType,
1309                         i, fGraphicStateResources[i]);
1310             }
1311         }
1312
1313         if (fXObjectResources.count()) {
1314             for (int i = 0; i < fXObjectResources.count(); i++) {
1315                 fResourceDict->insertResourceAsReference(
1316                         SkPDFResourceDict::kXObject_ResourceType,
1317                         i, fXObjectResources[i]);
1318             }
1319         }
1320
1321         if (fFontResources.count()) {
1322             for (int i = 0; i < fFontResources.count(); i++) {
1323                 fResourceDict->insertResourceAsReference(
1324                         SkPDFResourceDict::kFont_ResourceType,
1325                         i, fFontResources[i]);
1326             }
1327         }
1328
1329         if (fShaderResources.count()) {
1330             SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
1331             for (int i = 0; i < fShaderResources.count(); i++) {
1332                 fResourceDict->insertResourceAsReference(
1333                         SkPDFResourceDict::kPattern_ResourceType,
1334                         i, fShaderResources[i]);
1335             }
1336         }
1337     }
1338     return fResourceDict;
1339 }
1340
1341 const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1342     return fFontResources;
1343 }
1344
1345 SkPDFArray* SkPDFDevice::copyMediaBox() const {
1346     // should this be a singleton?
1347     SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
1348
1349     SkPDFArray* mediaBox = SkNEW(SkPDFArray);
1350     mediaBox->reserve(4);
1351     mediaBox->append(zero.get());
1352     mediaBox->append(zero.get());
1353     mediaBox->appendInt(fPageSize.fWidth);
1354     mediaBox->appendInt(fPageSize.fHeight);
1355     return mediaBox;
1356 }
1357
1358 SkStream* SkPDFDevice::content() const {
1359     SkMemoryStream* result = new SkMemoryStream;
1360     result->setData(this->copyContentToData())->unref();
1361     return result;
1362 }
1363
1364 void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1365         SkWStream* data) const {
1366     // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1367     // right thing to pass here.
1368     GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
1369     while (entry != NULL) {
1370         SkPoint translation;
1371         translation.iset(this->getOrigin());
1372         translation.negate();
1373         gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1374                            translation);
1375         gsState.updateMatrix(entry->fState.fMatrix);
1376         gsState.updateDrawingState(entry->fState);
1377
1378         SkAutoDataUnref copy(entry->fContent.copyToData());
1379         data->write(copy->data(), copy->size());
1380         entry = entry->fNext.get();
1381     }
1382     gsState.drainStack();
1383 }
1384
1385 SkData* SkPDFDevice::copyContentToData() const {
1386     SkDynamicMemoryWStream data;
1387     if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1388         SkPDFUtils::AppendTransform(fInitialTransform, &data);
1389     }
1390
1391     // TODO(aayushkumar): Apply clip along the margins.  Currently, webkit
1392     // colors the contentArea white before it starts drawing into it and
1393     // that currently acts as our clip.
1394     // Also, think about adding a transform here (or assume that the values
1395     // sent across account for that)
1396     SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
1397
1398     // If the content area is the entire page, then we don't need to clip
1399     // the content area (PDF area clips to the page size).  Otherwise,
1400     // we have to clip to the content area; we've already applied the
1401     // initial transform, so just clip to the device size.
1402     if (fPageSize != fContentSize) {
1403         SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1404                                   SkIntToScalar(this->height()));
1405         emit_clip(NULL, &r, &data);
1406     }
1407
1408     SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
1409
1410     // potentially we could cache this SkData, and only rebuild it if we
1411     // see that our state has changed.
1412     return data.copyToData();
1413 }
1414
1415 #ifdef SK_PDF_USE_PATHOPS
1416 /* Draws an inverse filled path by using Path Ops to compute the positive
1417  * inverse using the current clip as the inverse bounds.
1418  * Return true if this was an inverse path and was properly handled,
1419  * otherwise returns false and the normal drawing routine should continue,
1420  * either as a (incorrect) fallback or because the path was not inverse
1421  * in the first place.
1422  */
1423 bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
1424                                     const SkPaint& paint, bool pathIsMutable,
1425                                     const SkMatrix* prePathMatrix) {
1426     if (!origPath.isInverseFillType()) {
1427         return false;
1428     }
1429
1430     if (d.fClip->isEmpty()) {
1431         return false;
1432     }
1433
1434     SkPath modifiedPath;
1435     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1436     SkPaint noInversePaint(paint);
1437
1438     // Merge stroking operations into final path.
1439     if (SkPaint::kStroke_Style == paint.getStyle() ||
1440         SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1441         bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1442         if (doFillPath) {
1443             noInversePaint.setStyle(SkPaint::kFill_Style);
1444             noInversePaint.setStrokeWidth(0);
1445             pathPtr = &modifiedPath;
1446         } else {
1447             // To be consistent with the raster output, hairline strokes
1448             // are rendered as non-inverted.
1449             modifiedPath.toggleInverseFillType();
1450             drawPath(d, modifiedPath, paint, NULL, true);
1451             return true;
1452         }
1453     }
1454
1455     // Get bounds of clip in current transform space
1456     // (clip bounds are given in device space).
1457     SkRect bounds;
1458     SkMatrix transformInverse;
1459     SkMatrix totalMatrix = *d.fMatrix;
1460     if (prePathMatrix) {
1461         totalMatrix.preConcat(*prePathMatrix);
1462     }
1463     if (!totalMatrix.invert(&transformInverse)) {
1464         return false;
1465     }
1466     bounds.set(d.fClip->getBounds());
1467     transformInverse.mapRect(&bounds);
1468
1469     // Extend the bounds by the line width (plus some padding)
1470     // so the edge doesn't cause a visible stroke.
1471     bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1472                   paint.getStrokeWidth() + SK_Scalar1);
1473
1474     if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1475         return false;
1476     }
1477
1478     drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
1479     return true;
1480 }
1481 #endif
1482
1483 bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1484                                        const SkPaint& p) {
1485     SkAnnotation* annotationInfo = p.getAnnotation();
1486     if (!annotationInfo) {
1487         return false;
1488     }
1489     SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
1490     if (urlData) {
1491         handleLinkToURL(urlData, r, matrix);
1492         return p.getAnnotation() != NULL;
1493     }
1494     SkData* linkToName = annotationInfo->find(
1495             SkAnnotationKeys::Link_Named_Dest_Key());
1496     if (linkToName) {
1497         handleLinkToNamedDest(linkToName, r, matrix);
1498         return p.getAnnotation() != NULL;
1499     }
1500     return false;
1501 }
1502
1503 bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1504                                         const SkMatrix& matrix,
1505                                         const SkPaint& paint) {
1506     SkAnnotation* annotationInfo = paint.getAnnotation();
1507     if (!annotationInfo) {
1508         return false;
1509     }
1510     SkData* nameData = annotationInfo->find(
1511             SkAnnotationKeys::Define_Named_Dest_Key());
1512     if (nameData) {
1513         for (size_t i = 0; i < count; i++) {
1514             defineNamedDestination(nameData, points[i], matrix);
1515         }
1516         return paint.getAnnotation() != NULL;
1517     }
1518     return false;
1519 }
1520
1521 SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1522                                              const SkMatrix& matrix) {
1523     SkMatrix transform = matrix;
1524     transform.postConcat(fInitialTransform);
1525     SkRect translatedRect;
1526     transform.mapRect(&translatedRect, r);
1527
1528     if (NULL == fAnnotations) {
1529         fAnnotations = SkNEW(SkPDFArray);
1530     }
1531     SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
1532     annotation->insertName("Subtype", "Link");
1533     fAnnotations->append(annotation);
1534
1535     SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
1536     border->reserve(3);
1537     border->appendInt(0);  // Horizontal corner radius.
1538     border->appendInt(0);  // Vertical corner radius.
1539     border->appendInt(0);  // Width, 0 = no border.
1540     annotation->insert("Border", border.get());
1541
1542     SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
1543     rect->reserve(4);
1544     rect->appendScalar(translatedRect.fLeft);
1545     rect->appendScalar(translatedRect.fTop);
1546     rect->appendScalar(translatedRect.fRight);
1547     rect->appendScalar(translatedRect.fBottom);
1548     annotation->insert("Rect", rect.get());
1549
1550     return annotation;
1551 }
1552
1553 void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1554                                   const SkMatrix& matrix) {
1555     SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1556
1557     SkString url(static_cast<const char *>(urlData->data()),
1558                  urlData->size() - 1);
1559     SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1560     action->insertName("S", "URI");
1561     action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1562     annotation->insert("A", action.get());
1563 }
1564
1565 void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1566                                         const SkMatrix& matrix) {
1567     SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1568     SkString name(static_cast<const char *>(nameData->data()),
1569                   nameData->size() - 1);
1570     annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1571 }
1572
1573 struct NamedDestination {
1574     const SkData* nameData;
1575     SkPoint point;
1576
1577     NamedDestination(const SkData* nameData, const SkPoint& point)
1578         : nameData(nameData), point(point) {
1579         nameData->ref();
1580     }
1581
1582     ~NamedDestination() {
1583         nameData->unref();
1584     }
1585 };
1586
1587 void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1588                                          const SkMatrix& matrix) {
1589     SkMatrix transform = matrix;
1590     transform.postConcat(fInitialTransform);
1591     SkPoint translatedPoint;
1592     transform.mapXY(point.x(), point.y(), &translatedPoint);
1593     fNamedDestinations.push(
1594         SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1595 }
1596
1597 void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1598     int nDest = fNamedDestinations.count();
1599     for (int i = 0; i < nDest; i++) {
1600         NamedDestination* dest = fNamedDestinations[i];
1601         SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1602         pdfDest->reserve(5);
1603         pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1604         pdfDest->appendName("XYZ");
1605         pdfDest->appendScalar(dest->point.x());
1606         pdfDest->appendScalar(dest->point.y());
1607         pdfDest->appendInt(0);  // Leave zoom unchanged
1608         dict->insert(static_cast<const char *>(dest->nameData->data()),
1609                      pdfDest);
1610     }
1611 }
1612
1613 SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1614     SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
1615     // We always draw the form xobjects that we create back into the device, so
1616     // we simply preserve the font usage instead of pulling it out and merging
1617     // it back in later.
1618     cleanUp(false);  // Reset this device to have no content.
1619     init();
1620     return xobject;
1621 }
1622
1623 void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1624                                           SkPDFFormXObject* mask,
1625                                           const SkClipStack* clipStack,
1626                                           const SkRegion& clipRegion,
1627                                           SkXfermode::Mode mode,
1628                                           bool invertClip) {
1629     if (clipRegion.isEmpty() && !invertClip) {
1630         return;
1631     }
1632
1633     SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1634         SkPDFGraphicState::GetSMaskGraphicState(
1635             mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1636
1637     SkMatrix identity;
1638     identity.reset();
1639     SkPaint paint;
1640     paint.setXfermodeMode(mode);
1641     ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
1642     if (!content.entry()) {
1643         return;
1644     }
1645     SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1646                                   &content.entry()->fContent);
1647     SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
1648
1649     sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
1650     SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1651                                   &content.entry()->fContent);
1652 }
1653
1654 ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1655                                              const SkRegion& clipRegion,
1656                                              const SkMatrix& matrix,
1657                                              const SkPaint& paint,
1658                                              bool hasText,
1659                                              SkPDFFormXObject** dst) {
1660     *dst = NULL;
1661     if (clipRegion.isEmpty()) {
1662         return NULL;
1663     }
1664
1665     // The clip stack can come from an SkDraw where it is technically optional.
1666     SkClipStack synthesizedClipStack;
1667     if (clipStack == NULL) {
1668         if (clipRegion == fExistingClipRegion) {
1669             clipStack = &fExistingClipStack;
1670         } else {
1671             // GraphicStackState::updateClip expects the clip stack to have
1672             // fExistingClip as a prefix, so start there, then set the clip
1673             // to the passed region.
1674             synthesizedClipStack = fExistingClipStack;
1675             SkPath clipPath;
1676             clipRegion.getBoundaryPath(&clipPath);
1677             synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1678                                              false);
1679             clipStack = &synthesizedClipStack;
1680         }
1681     }
1682
1683     SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1684     if (paint.getXfermode()) {
1685         paint.getXfermode()->asMode(&xfermode);
1686     }
1687
1688     // For the following modes, we want to handle source and destination
1689     // separately, so make an object of what's already there.
1690     if (xfermode == SkXfermode::kClear_Mode       ||
1691             xfermode == SkXfermode::kSrc_Mode     ||
1692             xfermode == SkXfermode::kSrcIn_Mode   ||
1693             xfermode == SkXfermode::kDstIn_Mode   ||
1694             xfermode == SkXfermode::kSrcOut_Mode  ||
1695             xfermode == SkXfermode::kDstOut_Mode  ||
1696             xfermode == SkXfermode::kSrcATop_Mode ||
1697             xfermode == SkXfermode::kDstATop_Mode ||
1698             xfermode == SkXfermode::kModulate_Mode) {
1699         if (!isContentEmpty()) {
1700             *dst = createFormXObjectFromDevice();
1701             SkASSERT(isContentEmpty());
1702         } else if (xfermode != SkXfermode::kSrc_Mode &&
1703                    xfermode != SkXfermode::kSrcOut_Mode) {
1704             // Except for Src and SrcOut, if there isn't anything already there,
1705             // then we're done.
1706             return NULL;
1707         }
1708     }
1709     // TODO(vandebo): Figure out how/if we can handle the following modes:
1710     // Xor, Plus.
1711
1712     // Dst xfer mode doesn't draw source at all.
1713     if (xfermode == SkXfermode::kDst_Mode) {
1714         return NULL;
1715     }
1716
1717     ContentEntry* entry;
1718     SkAutoTDelete<ContentEntry> newEntry;
1719
1720     ContentEntry* lastContentEntry = getLastContentEntry();
1721     if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1722         entry = lastContentEntry;
1723     } else {
1724         newEntry.reset(new ContentEntry);
1725         entry = newEntry.get();
1726     }
1727
1728     populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
1729                                        hasText, &entry->fState);
1730     if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1731             entry->fState.compareInitialState(lastContentEntry->fState)) {
1732         return lastContentEntry;
1733     }
1734
1735     SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1736     if (!lastContentEntry) {
1737         contentEntries->reset(entry);
1738         setLastContentEntry(entry);
1739     } else if (xfermode == SkXfermode::kDstOver_Mode) {
1740         entry->fNext.reset(contentEntries->detach());
1741         contentEntries->reset(entry);
1742     } else {
1743         lastContentEntry->fNext.reset(entry);
1744         setLastContentEntry(entry);
1745     }
1746     newEntry.detach();
1747     return entry;
1748 }
1749
1750 void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
1751                                      SkPDFFormXObject* dst,
1752                                      SkPath* shape) {
1753     if (xfermode != SkXfermode::kClear_Mode       &&
1754             xfermode != SkXfermode::kSrc_Mode     &&
1755             xfermode != SkXfermode::kDstOver_Mode &&
1756             xfermode != SkXfermode::kSrcIn_Mode   &&
1757             xfermode != SkXfermode::kDstIn_Mode   &&
1758             xfermode != SkXfermode::kSrcOut_Mode  &&
1759             xfermode != SkXfermode::kDstOut_Mode  &&
1760             xfermode != SkXfermode::kSrcATop_Mode &&
1761             xfermode != SkXfermode::kDstATop_Mode &&
1762             xfermode != SkXfermode::kModulate_Mode) {
1763         SkASSERT(!dst);
1764         return;
1765     }
1766     if (xfermode == SkXfermode::kDstOver_Mode) {
1767         SkASSERT(!dst);
1768         ContentEntry* firstContentEntry = getContentEntries()->get();
1769         if (firstContentEntry->fContent.getOffset() == 0) {
1770             // For DstOver, an empty content entry was inserted before the rest
1771             // of the content entries. If nothing was drawn, it needs to be
1772             // removed.
1773             SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1774             contentEntries->reset(firstContentEntry->fNext.detach());
1775         }
1776         return;
1777     }
1778     if (!dst) {
1779         SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1780                  xfermode == SkXfermode::kSrcOut_Mode);
1781         return;
1782     }
1783
1784     ContentEntry* contentEntries = getContentEntries()->get();
1785     SkASSERT(dst);
1786     SkASSERT(!contentEntries->fNext.get());
1787     // Changing the current content into a form-xobject will destroy the clip
1788     // objects which is fine since the xobject will already be clipped. However
1789     // if source has shape, we need to clip it too, so a copy of the clip is
1790     // saved.
1791     SkClipStack clipStack = contentEntries->fState.fClipStack;
1792     SkRegion clipRegion = contentEntries->fState.fClipRegion;
1793
1794     SkMatrix identity;
1795     identity.reset();
1796     SkPaint stockPaint;
1797
1798     SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
1799     if (isContentEmpty()) {
1800         // If nothing was drawn and there's no shape, then the draw was a
1801         // no-op, but dst needs to be restored for that to be true.
1802         // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1803         // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1804         // reduces to Dst.
1805         if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1806                 xfermode == SkXfermode::kSrcATop_Mode) {
1807             ScopedContentEntry content(this, &fExistingClipStack,
1808                                        fExistingClipRegion, identity,
1809                                        stockPaint);
1810             SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1811                                         &content.entry()->fContent);
1812             return;
1813         } else {
1814             xfermode = SkXfermode::kClear_Mode;
1815         }
1816     } else {
1817         SkASSERT(!fContentEntries->fNext.get());
1818         srcFormXObject.reset(createFormXObjectFromDevice());
1819     }
1820
1821     // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1822     // without alpha.
1823     if (xfermode == SkXfermode::kSrcATop_Mode) {
1824         // TODO(vandebo): In order to properly support SrcATop we have to track
1825         // the shape of what's been drawn at all times. It's the intersection of
1826         // the non-transparent parts of the device and the outlines (shape) of
1827         // all images and devices drawn.
1828         drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1829                                 &fExistingClipStack, fExistingClipRegion,
1830                                 SkXfermode::kSrcOver_Mode, true);
1831     } else {
1832         SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1833         SkPDFFormXObject* dstMask = srcFormXObject.get();
1834         if (shape != NULL) {
1835             // Draw shape into a form-xobject.
1836             SkDraw d;
1837             d.fMatrix = &identity;
1838             d.fClip = &clipRegion;
1839             d.fClipStack = &clipStack;
1840             SkPaint filledPaint;
1841             filledPaint.setColor(SK_ColorBLACK);
1842             filledPaint.setStyle(SkPaint::kFill_Style);
1843             this->drawPath(d, *shape, filledPaint, NULL, true);
1844
1845             dstMaskStorage.reset(createFormXObjectFromDevice());
1846             dstMask = dstMaskStorage.get();
1847         }
1848         drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1849                                 &fExistingClipStack, fExistingClipRegion,
1850                                 SkXfermode::kSrcOver_Mode, true);
1851     }
1852
1853     if (xfermode == SkXfermode::kClear_Mode) {
1854         return;
1855     } else if (xfermode == SkXfermode::kSrc_Mode ||
1856             xfermode == SkXfermode::kDstATop_Mode) {
1857         ScopedContentEntry content(this, &fExistingClipStack,
1858                                    fExistingClipRegion, identity, stockPaint);
1859         if (content.entry()) {
1860             SkPDFUtils::DrawFormXObject(
1861                     this->addXObjectResource(srcFormXObject.get()),
1862                     &content.entry()->fContent);
1863         }
1864         if (xfermode == SkXfermode::kSrc_Mode) {
1865             return;
1866         }
1867     } else if (xfermode == SkXfermode::kSrcATop_Mode) {
1868         ScopedContentEntry content(this, &fExistingClipStack,
1869                                    fExistingClipRegion, identity, stockPaint);
1870         if (content.entry()) {
1871             SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1872                                         &content.entry()->fContent);
1873         }
1874     }
1875
1876     SkASSERT(xfermode == SkXfermode::kSrcIn_Mode   ||
1877              xfermode == SkXfermode::kDstIn_Mode   ||
1878              xfermode == SkXfermode::kSrcOut_Mode  ||
1879              xfermode == SkXfermode::kDstOut_Mode  ||
1880              xfermode == SkXfermode::kSrcATop_Mode ||
1881              xfermode == SkXfermode::kDstATop_Mode ||
1882              xfermode == SkXfermode::kModulate_Mode);
1883
1884     if (xfermode == SkXfermode::kSrcIn_Mode ||
1885             xfermode == SkXfermode::kSrcOut_Mode ||
1886             xfermode == SkXfermode::kSrcATop_Mode) {
1887         drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1888                                 &fExistingClipStack, fExistingClipRegion,
1889                                 SkXfermode::kSrcOver_Mode,
1890                                 xfermode == SkXfermode::kSrcOut_Mode);
1891     } else {
1892         SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1893         if (xfermode == SkXfermode::kModulate_Mode) {
1894             drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1895                                     dst, &fExistingClipStack,
1896                                     fExistingClipRegion,
1897                                     SkXfermode::kSrcOver_Mode, false);
1898             mode = SkXfermode::kMultiply_Mode;
1899         }
1900         drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
1901                                 &fExistingClipStack, fExistingClipRegion, mode,
1902                                 xfermode == SkXfermode::kDstOut_Mode);
1903     }
1904 }
1905
1906 bool SkPDFDevice::isContentEmpty() {
1907     ContentEntry* contentEntries = getContentEntries()->get();
1908     if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1909         SkASSERT(!contentEntries || !contentEntries->fNext.get());
1910         return true;
1911     }
1912     return false;
1913 }
1914
1915 void SkPDFDevice::populateGraphicStateEntryFromPaint(
1916         const SkMatrix& matrix,
1917         const SkClipStack& clipStack,
1918         const SkRegion& clipRegion,
1919         const SkPaint& paint,
1920         bool hasText,
1921         GraphicStateEntry* entry) {
1922     NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
1923     NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1924     NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
1925
1926     entry->fMatrix = matrix;
1927     entry->fClipStack = clipStack;
1928     entry->fClipRegion = clipRegion;
1929     entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1930     entry->fShaderIndex = -1;
1931
1932     // PDF treats a shader as a color, so we only set one or the other.
1933     SkAutoTUnref<SkPDFObject> pdfShader;
1934     const SkShader* shader = paint.getShader();
1935     SkColor color = paint.getColor();
1936     if (shader) {
1937         // PDF positions patterns relative to the initial transform, so
1938         // we need to apply the current transform to the shader parameters.
1939         SkMatrix transform = matrix;
1940         transform.postConcat(fInitialTransform);
1941
1942         // PDF doesn't support kClamp_TileMode, so we simulate it by making
1943         // a pattern the size of the current clip.
1944         SkIRect bounds = clipRegion.getBounds();
1945
1946         // We need to apply the initial transform to bounds in order to get
1947         // bounds in a consistent coordinate system.
1948         SkRect boundsTemp;
1949         boundsTemp.set(bounds);
1950         fInitialTransform.mapRect(&boundsTemp);
1951         boundsTemp.roundOut(&bounds);
1952
1953         pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
1954
1955         if (pdfShader.get()) {
1956             // pdfShader has been canonicalized so we can directly compare
1957             // pointers.
1958             int resourceIndex = fShaderResources.find(pdfShader.get());
1959             if (resourceIndex < 0) {
1960                 resourceIndex = fShaderResources.count();
1961                 fShaderResources.push(pdfShader.get());
1962                 pdfShader.get()->ref();
1963             }
1964             entry->fShaderIndex = resourceIndex;
1965         } else {
1966             // A color shader is treated as an invalid shader so we don't have
1967             // to set a shader just for a color.
1968             SkShader::GradientInfo gradientInfo;
1969             SkColor gradientColor;
1970             gradientInfo.fColors = &gradientColor;
1971             gradientInfo.fColorOffsets = NULL;
1972             gradientInfo.fColorCount = 1;
1973             if (shader->asAGradient(&gradientInfo) ==
1974                     SkShader::kColor_GradientType) {
1975                 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1976                 color = gradientColor;
1977             }
1978         }
1979     }
1980
1981     SkAutoTUnref<SkPDFGraphicState> newGraphicState;
1982     if (color == paint.getColor()) {
1983         newGraphicState.reset(
1984                 SkPDFGraphicState::GetGraphicStateForPaint(paint));
1985     } else {
1986         SkPaint newPaint = paint;
1987         newPaint.setColor(color);
1988         newGraphicState.reset(
1989                 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
1990     }
1991     int resourceIndex = addGraphicStateResource(newGraphicState.get());
1992     entry->fGraphicStateIndex = resourceIndex;
1993
1994     if (hasText) {
1995         entry->fTextScaleX = paint.getTextScaleX();
1996         entry->fTextFill = paint.getStyle();
1997     } else {
1998         entry->fTextScaleX = 0;
1999     }
2000 }
2001
2002 int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2003     // Assumes that gs has been canonicalized (so we can directly compare
2004     // pointers).
2005     int result = fGraphicStateResources.find(gs);
2006     if (result < 0) {
2007         result = fGraphicStateResources.count();
2008         fGraphicStateResources.push(gs);
2009         gs->ref();
2010     }
2011     return result;
2012 }
2013
2014 int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2015     // Assumes that xobject has been canonicalized (so we can directly compare
2016     // pointers).
2017     int result = fXObjectResources.find(xObject);
2018     if (result < 0) {
2019         result = fXObjectResources.count();
2020         fXObjectResources.push(xObject);
2021         xObject->ref();
2022     }
2023     return result;
2024 }
2025
2026 void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2027                              ContentEntry* contentEntry) {
2028     SkTypeface* typeface = paint.getTypeface();
2029     if (contentEntry->fState.fFont == NULL ||
2030             contentEntry->fState.fTextSize != paint.getTextSize() ||
2031             !contentEntry->fState.fFont->hasGlyph(glyphID)) {
2032         int fontIndex = getFontResourceIndex(typeface, glyphID);
2033         contentEntry->fContent.writeText("/");
2034         contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2035                 SkPDFResourceDict::kFont_ResourceType,
2036                 fontIndex).c_str());
2037         contentEntry->fContent.writeText(" ");
2038         SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2039         contentEntry->fContent.writeText(" Tf\n");
2040         contentEntry->fState.fFont = fFontResources[fontIndex];
2041     }
2042 }
2043
2044 int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
2045     SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2046                                                                glyphID));
2047     int resourceIndex = fFontResources.find(newFont.get());
2048     if (resourceIndex < 0) {
2049         resourceIndex = fFontResources.count();
2050         fFontResources.push(newFont.get());
2051         newFont.get()->ref();
2052     }
2053     return resourceIndex;
2054 }
2055
2056 void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
2057                                      const SkClipStack* clipStack,
2058                                      const SkRegion& origClipRegion,
2059                                      const SkBitmap& origBitmap,
2060                                      const SkIRect* srcRect,
2061                                      const SkPaint& paint) {
2062     SkMatrix matrix = origMatrix;
2063     SkRegion perspectiveBounds;
2064     const SkRegion* clipRegion = &origClipRegion;
2065     SkBitmap perspectiveBitmap;
2066     const SkBitmap* bitmap = &origBitmap;
2067     SkBitmap tmpSubsetBitmap;
2068
2069     // Rasterize the bitmap using perspective in a new bitmap.
2070     if (origMatrix.hasPerspective()) {
2071         if (fRasterDpi == 0) {
2072             return;
2073         }
2074         SkBitmap* subsetBitmap;
2075         if (srcRect) {
2076             if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2077                return;
2078             }
2079             subsetBitmap = &tmpSubsetBitmap;
2080         } else {
2081             subsetBitmap = &tmpSubsetBitmap;
2082             *subsetBitmap = origBitmap;
2083         }
2084         srcRect = NULL;
2085
2086         // Transform the bitmap in the new space, without taking into
2087         // account the initial transform.
2088         SkPath perspectiveOutline;
2089         perspectiveOutline.addRect(
2090                 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2091                                SkIntToScalar(subsetBitmap->height())));
2092         perspectiveOutline.transform(origMatrix);
2093
2094         // TODO(edisonn): perf - use current clip too.
2095         // Retrieve the bounds of the new shape.
2096         SkRect bounds = perspectiveOutline.getBounds();
2097
2098         // Transform the bitmap in the new space, taking into
2099         // account the initial transform.
2100         SkMatrix total = origMatrix;
2101         total.postConcat(fInitialTransform);
2102         total.postScale(SkIntToScalar(fRasterDpi) /
2103                             SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2104                         SkIntToScalar(fRasterDpi) /
2105                             SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2106         SkPath physicalPerspectiveOutline;
2107         physicalPerspectiveOutline.addRect(
2108                 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2109                                SkIntToScalar(subsetBitmap->height())));
2110         physicalPerspectiveOutline.transform(total);
2111
2112         SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2113                               bounds.width();
2114         SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2115                               bounds.height();
2116
2117         // TODO(edisonn): A better approach would be to use a bitmap shader
2118         // (in clamp mode) and draw a rect over the entire bounding box. Then
2119         // intersect perspectiveOutline to the clip. That will avoid introducing
2120         // alpha to the image while still giving good behavior at the edge of
2121         // the image.  Avoiding alpha will reduce the pdf size and generation
2122         // CPU time some.
2123
2124         const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2125         const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
2126         if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
2127             return;
2128         }
2129         perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2130
2131         SkCanvas canvas(perspectiveBitmap);
2132
2133         SkScalar deltaX = bounds.left();
2134         SkScalar deltaY = bounds.top();
2135
2136         SkMatrix offsetMatrix = origMatrix;
2137         offsetMatrix.postTranslate(-deltaX, -deltaY);
2138         offsetMatrix.postScale(scaleX, scaleY);
2139
2140         // Translate the draw in the new canvas, so we perfectly fit the
2141         // shape in the bitmap.
2142         canvas.setMatrix(offsetMatrix);
2143
2144         canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2145
2146         // Make sure the final bits are in the bitmap.
2147         canvas.flush();
2148
2149         // In the new space, we use the identity matrix translated
2150         // and scaled to reflect DPI.
2151         matrix.setScale(1 / scaleX, 1 / scaleY);
2152         matrix.postTranslate(deltaX, deltaY);
2153
2154         perspectiveBounds.setRect(
2155                 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2156                                   SkScalarFloorToInt(bounds.y()),
2157                                   SkScalarCeilToInt(bounds.width()),
2158                                   SkScalarCeilToInt(bounds.height())));
2159         clipRegion = &perspectiveBounds;
2160         srcRect = NULL;
2161         bitmap = &perspectiveBitmap;
2162     }
2163
2164     SkMatrix scaled;
2165     // Adjust for origin flip.
2166     scaled.setScale(SK_Scalar1, -SK_Scalar1);
2167     scaled.postTranslate(0, SK_Scalar1);
2168     // Scale the image up from 1x1 to WxH.
2169     SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
2170     scaled.postScale(SkIntToScalar(subset.width()),
2171                      SkIntToScalar(subset.height()));
2172     scaled.postConcat(matrix);
2173     ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
2174     if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2175         return;
2176     }
2177     if (content.needShape()) {
2178         SkPath shape;
2179         shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2180                                      SkIntToScalar( subset.height())));
2181         shape.transform(matrix);
2182         content.setShape(shape);
2183     }
2184     if (!content.needSource()) {
2185         return;
2186     }
2187
2188     SkAutoTUnref<SkPDFObject> image(
2189             SkPDFCreateImageObject(*bitmap, subset, fEncoder));
2190     if (!image) {
2191         return;
2192     }
2193
2194     SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
2195                                 &content.entry()->fContent);
2196 }
2197