2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkPDFDevice.h"
10 #include "SkAnnotation.h"
12 #include "SkClipStack.h"
15 #include "SkFontHost.h"
16 #include "SkGlyphCache.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"
32 #include "SkSurface.h"
33 #include "SkTextFormatParams.h"
34 #include "SkTemplates.h"
35 #include "SkTypefacePriv.h"
38 #define DPI_FOR_RASTER_SCALE_ONE 72
42 static void emit_pdf_color(SkColor color, SkWStream* result) {
43 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
44 SkScalar colorMax = SkIntToScalar(0xFF);
46 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
47 result->writeText(" ");
49 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
50 result->writeText(" ");
52 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
53 result->writeText(" ");
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);
67 width += result.getStrokeWidth();
69 result.setStrokeWidth(width);
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) {
84 SkAutoGlyphCache autoCache(paint, NULL, &ident);
85 SkGlyphCache* cache = autoCache.getCache();
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;
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;
97 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
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);
111 static int max_glyphid_for_typeface(SkTypeface* typeface) {
112 SkAutoResolveDefaultTypeface autoResolve(typeface);
113 typeface = autoResolve.get();
114 return typeface->countGlyphs() - 1;
117 typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
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();
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);
136 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
138 for (validated = 0; validated < numGlyphs; ++validated) {
139 if (input[validated] > maxGlyphID) {
143 if (validated >= numGlyphs) {
144 *glyphIDs = static_cast<const uint16_t*>(text);
148 // Silently drop anything out of range.
149 storage->reset(numGlyphs);
151 memcpy(storage->get(), input, validated * sizeof(uint16_t));
154 for (int i = validated; i < numGlyphs; ++i) {
155 storage->get()[i] = input[i];
156 if (input[i] > maxGlyphID) {
157 storage->get()[i] = 0;
160 *glyphIDs = storage->get();
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");
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 {
182 // Compare the fields we care about when setting up a new content entry.
183 bool compareInitialState(const GraphicStateEntry& b);
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;
193 // When emitting the content entry, we will ensure the graphic state
194 // is set to these values first.
196 SkScalar fTextScaleX; // Zero means we don't care what the value is.
197 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
199 int fGraphicStateIndex;
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.
204 // In PDF, text size has no default value. It is only valid if fFont is
209 GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
210 fTextScaleX(SK_Scalar1),
211 fTextFill(SkPaint::kFill_Style),
213 fGraphicStateIndex(-1),
215 fTextSize(SK_ScalarNaN) {
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 &&
226 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
229 class GraphicStackState {
231 GraphicStackState(const SkClipStack& existingClipStack,
232 const SkRegion& existingClipRegion,
233 SkWStream* contentStream)
235 fContentStream(contentStream) {
236 fEntries[0].fClipStack = existingClipStack;
237 fEntries[0].fClipRegion = existingClipRegion;
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);
250 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
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];
256 SkWStream* fContentStream;
259 void GraphicStackState::drainStack() {
260 while (fStackDepth) {
265 void GraphicStackState::push() {
266 SkASSERT(fStackDepth < kMaxStackDepth);
267 fContentStream->writeText("q\n");
269 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
272 void GraphicStackState::pop() {
273 SkASSERT(fStackDepth > 0);
274 fContentStream->writeText("Q\n");
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);
287 const SkClipStack::Element* prefixEntry;
288 const SkClipStack::Element* iterEntry;
290 for (prefixEntry = prefixIter.next(); prefixEntry;
291 prefixEntry = prefixIter.next()) {
292 iterEntry = iter->next();
294 // Because of SkClipStack does internal intersection, the last clip
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
302 prefixEntry = prefixIter.next();
307 SkASSERT(prefixEntry == NULL);
310 static void emit_clip(SkPath* clipPath, SkRect* clipRect,
311 SkWStream* contentStream) {
312 SkASSERT(clipPath || clipRect);
314 SkPath::FillType clipFill;
316 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
317 clipFill = clipPath->getFillType();
319 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
320 clipFill = SkPath::kWinding_FillType;
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");
328 contentStream->writeText("W n\n");
332 #ifdef SK_PDF_USE_PATHOPS
333 /* Calculate an inverted path's equivalent non-inverted path, given the
335 * outPath may alias with invPath (since this is supported by PathOps).
337 static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
339 SkASSERT(invPath.isInverseFillType());
342 clipPath.addRect(bounds);
344 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
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
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);
363 static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
365 SkASSERT(op <= SkRegion::kReverseDifference_Op);
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
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);
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()) {
387 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
388 outClipPath->reset();
389 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
392 clipEntry->asPath(&entryPath);
394 entryPath.transform(transform);
396 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
397 *outClipPath = entryPath;
399 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
400 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
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
410 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
411 clipBounds.outset(SK_Scalar1, SK_Scalar1);
412 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
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) {
430 while (fStackDepth > 0) {
432 if (clipStack == currentEntry()->fClipStack) {
438 currentEntry()->fClipStack = clipStack;
439 currentEntry()->fClipRegion = clipRegion;
442 transform.setTranslate(translation.fX, translation.fY);
444 #ifdef SK_PDF_USE_PATHOPS
446 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
447 emit_clip(&clipPath, NULL, fContentStream);
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);
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()) {
476 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
477 emit_clip(&clipPath, NULL, fContentStream);
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);
491 SkPath translatedPath;
492 clipEntry->asPath(&translatedPath);
493 translatedPath.transform(transform, &translatedPath);
494 emit_clip(&translatedPath, NULL, fContentStream);
502 void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
503 if (matrix == currentEntry()->fMatrix) {
507 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
508 SkASSERT(fStackDepth > 0);
509 SkASSERT(fEntries[fStackDepth].fClipStack ==
510 fEntries[fStackDepth -1].fClipStack);
513 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
515 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
520 SkPDFUtils::AppendTransform(matrix, fContentStream);
521 currentEntry()->fMatrix = matrix;
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;
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;
543 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
544 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
545 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
548 if (state.fTextScaleX) {
549 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
550 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
552 SkPDFScalar::Append(pdfScale, fContentStream);
553 fContentStream->writeText(" Tz\n");
554 currentEntry()->fTextScaleX = state.fTextScaleX;
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;
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));
577 struct ContentEntry {
578 GraphicStateEntry fState;
579 SkDynamicMemoryWStream fContent;
580 SkAutoTDelete<ContentEntry> fNext;
582 // If the stack is too deep we could get Stack Overflow.
583 // So we manually destruct the object.
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.
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 {
599 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
600 const SkPaint& paint, bool hasText = false)
603 fXfermode(SkXfermode::kSrcOver_Mode),
604 fDstFormXObject(NULL) {
605 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
607 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
608 const SkRegion& clipRegion, const SkMatrix& matrix,
609 const SkPaint& paint, bool hasText = false)
612 fXfermode(SkXfermode::kSrcOver_Mode),
613 fDstFormXObject(NULL) {
614 init(clipStack, clipRegion, matrix, paint, hasText);
617 ~ScopedContentEntry() {
619 SkPath* shape = &fShape;
620 if (shape->isEmpty()) {
623 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
625 SkSafeUnref(fDstFormXObject);
628 ContentEntry* entry() { return fContentEntry; }
630 /* Returns true when we explicitly need the shape of the drawing. */
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:
648 /* Returns true unless we only need the shape of the drawing. */
650 if (fXfermode == SkXfermode::kClear_Mode) {
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.
660 void setShape(const SkPath& shape) {
665 SkPDFDevice* fDevice;
666 ContentEntry* fContentEntry;
667 SkXfermode::Mode fXfermode;
668 SkPDFFormXObject* fDstFormXObject;
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);
678 if (paint.getXfermode()) {
679 paint.getXfermode()->asMode(&fXfermode);
681 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
682 matrix, paint, hasText,
687 ////////////////////////////////////////////////////////////////////////////////
689 static inline SkImageInfo make_content_info(const SkISize& contentSize,
690 const SkMatrix* initialTransform) {
692 if (initialTransform) {
693 // Compute the size of the drawing area.
694 SkVector drawingSize;
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.
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));
707 info = SkImageInfo::MakeUnknown(abs(contentSize.fWidth),
708 abs(contentSize.fHeight));
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)
724 const SkImageInfo info = make_content_info(contentSize, &initialTransform);
726 // Just report that PDF does not supports perspective in the
727 // initial transform.
728 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
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);
738 SkIRect existingClip = SkIRect::MakeWH(info.width(), info.height());
739 fExistingClipRegion.setRect(existingClip);
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)
757 fInitialTransform.reset();
758 fLegacyBitmap.setInfo(make_content_info(layerSize, NULL));
763 SkPDFDevice::~SkPDFDevice() {
767 void SkPDFDevice::init() {
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());
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();
789 if (clearFontUsage) {
790 fFontGlyphUsage->reset();
794 void SkPDFDevice::clear(SkColor color) {
799 paint.setColor(color);
800 paint.setStyle(SkPaint::kFill_Style);
803 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
805 internalDrawPaint(paint, content.entry());
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());
815 void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
816 ContentEntry* contentEntry) {
820 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
821 SkIntToScalar(this->height()));
823 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
826 inverse.mapRect(&bbox);
828 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
829 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
830 &contentEntry->fContent);
833 void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
834 size_t count, const SkPoint* points,
835 const SkPaint& passedPaint) {
840 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
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()) {
852 pointDraw.fDevice = this;
853 pointDraw.drawPoints(mode, count, points, passedPaint, true);
857 const SkPaint* paint = &passedPaint;
858 SkPaint modifiedPaint;
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);
877 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
881 ScopedContentEntry content(this, d, *paint);
882 if (!content.entry()) {
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);
894 SkPDFUtils::StrokePath(&content.entry()->fContent);
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);
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);
920 void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
921 const SkPaint& paint) {
925 if (paint.getPathEffect()) {
926 if (d.fClip->isEmpty()) {
931 drawPath(d, path, paint, NULL, true);
935 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
939 ScopedContentEntry content(this, d, paint);
940 if (!content.entry()) {
943 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
944 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
945 &content.entry()->fContent);
948 void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
950 path.addRRect(rrect);
951 this->drawPath(draw, path, paint, NULL, true);
954 void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
957 this->drawPath(draw, path, paint, NULL, true);
960 void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
961 const SkPaint& paint, const SkMatrix* prePathMatrix,
962 bool pathIsMutable) {
964 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
966 SkMatrix matrix = *d.fMatrix;
968 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
969 if (!pathIsMutable) {
970 pathPtr = &modifiedPath;
971 pathIsMutable = true;
973 origPath.transform(*prePathMatrix, pathPtr);
975 matrix.preConcat(*prePathMatrix);
979 if (paint.getPathEffect()) {
980 if (d.fClip->isEmpty()) {
983 if (!pathIsMutable) {
984 pathPtr = &modifiedPath;
985 pathIsMutable = true;
987 bool fill = paint.getFillPath(origPath, pathPtr);
989 SkPaint noEffectPaint(paint);
990 noEffectPaint.setPathEffect(NULL);
992 noEffectPaint.setStyle(SkPaint::kFill_Style);
994 noEffectPaint.setStyle(SkPaint::kStroke_Style);
995 noEffectPaint.setStrokeWidth(0);
997 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
1001 #ifdef SK_PDF_USE_PATHOPS
1002 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
1007 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
1011 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
1012 if (!content.entry()) {
1015 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1016 &content.entry()->fContent);
1017 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
1018 &content.entry()->fContent);
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
1027 SkRect bitmapBounds, tmpSrc, tmpDst;
1030 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1032 // Compute matrix from the two rectangles
1036 tmpSrc = bitmapBounds;
1038 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1040 const SkBitmap* bitmapPtr = &bitmap;
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.
1045 if (!bitmapBounds.contains(*src)) {
1046 if (!tmpSrc.intersect(bitmapBounds)) {
1047 return; // nothing to draw
1049 // recompute dst, based on the smaller tmpSrc
1050 matrix.mapRect(&tmpDst, tmpSrc);
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.
1057 tmpSrc.roundOut(&srcIR);
1058 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1061 bitmapPtr = &tmpBitmap;
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);
1068 if (srcIR.fTop > 0) {
1069 dy = SkIntToScalar(srcIR.fTop);
1072 matrix.preTranslate(dx, dy);
1075 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
1078 void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
1079 const SkMatrix& matrix, const SkPaint& paint) {
1080 if (d.fClip->isEmpty()) {
1084 SkMatrix transform = matrix;
1085 transform.postConcat(*d.fMatrix);
1086 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1090 void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
1091 int x, int y, const SkPaint& paint) {
1092 if (d.fClip->isEmpty()) {
1097 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1098 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
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).
1110 SkPaint textPaint = calculate_text_paint(paint);
1111 ScopedContentEntry content(this, d, textPaint, true);
1112 if (!content.entry()) {
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);
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,
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");
1143 content.entry()->fContent.writeText("ET\n");
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).
1155 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
1156 SkPaint textPaint = calculate_text_paint(paint);
1157 ScopedContentEntry content(this, d, textPaint, true);
1158 if (!content.entry()) {
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);
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.");
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");
1194 content.entry()->fContent.writeText("ET\n");
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()) {
1203 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
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()) {
1214 // TODO: implement drawVertices
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()) {
1226 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1227 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
1228 if (!content.entry()) {
1231 if (content.needShape()) {
1233 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
1234 SkIntToScalar(device->width()),
1235 SkIntToScalar(device->height())));
1236 content.setShape(shape);
1238 if (!content.needSource()) {
1242 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1243 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
1244 &content.entry()->fContent);
1246 // Merge glyph sets from the drawn device.
1247 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
1250 SkImageInfo SkPDFDevice::imageInfo() const {
1251 return fLegacyBitmap.info();
1254 void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1255 INHERITED::onAttachToCanvas(canvas);
1257 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1258 fClipStack = canvas->getClipStack();
1261 void SkPDFDevice::onDetachFromCanvas() {
1262 INHERITED::onDetachFromCanvas();
1267 SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1268 return SkSurface::NewRaster(info, &props);
1271 ContentEntry* SkPDFDevice::getLastContentEntry() {
1272 if (fDrawingArea == kContent_DrawingArea) {
1273 return fLastContentEntry;
1275 return fLastMarginContentEntry;
1279 SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
1280 if (fDrawingArea == kContent_DrawingArea) {
1281 return &fContentEntries;
1283 return &fMarginContentEntries;
1287 void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1288 if (fDrawingArea == kContent_DrawingArea) {
1289 fLastContentEntry = contentEntry;
1291 fLastMarginContentEntry = contentEntry;
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;
1301 SkPDFResourceDict* SkPDFDevice::getResourceDict() {
1302 if (NULL == fResourceDict) {
1303 fResourceDict = SkNEW(SkPDFResourceDict);
1305 if (fGraphicStateResources.count()) {
1306 for (int i = 0; i < fGraphicStateResources.count(); i++) {
1307 fResourceDict->insertResourceAsReference(
1308 SkPDFResourceDict::kExtGState_ResourceType,
1309 i, fGraphicStateResources[i]);
1313 if (fXObjectResources.count()) {
1314 for (int i = 0; i < fXObjectResources.count(); i++) {
1315 fResourceDict->insertResourceAsReference(
1316 SkPDFResourceDict::kXObject_ResourceType,
1317 i, fXObjectResources[i]);
1321 if (fFontResources.count()) {
1322 for (int i = 0; i < fFontResources.count(); i++) {
1323 fResourceDict->insertResourceAsReference(
1324 SkPDFResourceDict::kFont_ResourceType,
1325 i, fFontResources[i]);
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]);
1338 return fResourceDict;
1341 const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1342 return fFontResources;
1345 SkPDFArray* SkPDFDevice::copyMediaBox() const {
1346 // should this be a singleton?
1347 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
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);
1358 SkStream* SkPDFDevice::content() const {
1359 SkMemoryStream* result = new SkMemoryStream;
1360 result->setData(this->copyContentToData())->unref();
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,
1375 gsState.updateMatrix(entry->fState.fMatrix);
1376 gsState.updateDrawingState(entry->fState);
1378 SkAutoDataUnref copy(entry->fContent.copyToData());
1379 data->write(copy->data(), copy->size());
1380 entry = entry->fNext.get();
1382 gsState.drainStack();
1385 SkData* SkPDFDevice::copyContentToData() const {
1386 SkDynamicMemoryWStream data;
1387 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1388 SkPDFUtils::AppendTransform(fInitialTransform, &data);
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);
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);
1408 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
1410 // potentially we could cache this SkData, and only rebuild it if we
1411 // see that our state has changed.
1412 return data.copyToData();
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.
1423 bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
1424 const SkPaint& paint, bool pathIsMutable,
1425 const SkMatrix* prePathMatrix) {
1426 if (!origPath.isInverseFillType()) {
1430 if (d.fClip->isEmpty()) {
1434 SkPath modifiedPath;
1435 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1436 SkPaint noInversePaint(paint);
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);
1443 noInversePaint.setStyle(SkPaint::kFill_Style);
1444 noInversePaint.setStrokeWidth(0);
1445 pathPtr = &modifiedPath;
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);
1455 // Get bounds of clip in current transform space
1456 // (clip bounds are given in device space).
1458 SkMatrix transformInverse;
1459 SkMatrix totalMatrix = *d.fMatrix;
1460 if (prePathMatrix) {
1461 totalMatrix.preConcat(*prePathMatrix);
1463 if (!totalMatrix.invert(&transformInverse)) {
1466 bounds.set(d.fClip->getBounds());
1467 transformInverse.mapRect(&bounds);
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);
1474 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1478 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
1483 bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1485 SkAnnotation* annotationInfo = p.getAnnotation();
1486 if (!annotationInfo) {
1489 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
1491 handleLinkToURL(urlData, r, matrix);
1492 return p.getAnnotation() != NULL;
1494 SkData* linkToName = annotationInfo->find(
1495 SkAnnotationKeys::Link_Named_Dest_Key());
1497 handleLinkToNamedDest(linkToName, r, matrix);
1498 return p.getAnnotation() != NULL;
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) {
1510 SkData* nameData = annotationInfo->find(
1511 SkAnnotationKeys::Define_Named_Dest_Key());
1513 for (size_t i = 0; i < count; i++) {
1514 defineNamedDestination(nameData, points[i], matrix);
1516 return paint.getAnnotation() != NULL;
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);
1528 if (NULL == fAnnotations) {
1529 fAnnotations = SkNEW(SkPDFArray);
1531 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
1532 annotation->insertName("Subtype", "Link");
1533 fAnnotations->append(annotation);
1535 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
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());
1542 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
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());
1553 void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1554 const SkMatrix& matrix) {
1555 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
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());
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();
1573 struct NamedDestination {
1574 const SkData* nameData;
1577 NamedDestination(const SkData* nameData, const SkPoint& point)
1578 : nameData(nameData), point(point) {
1582 ~NamedDestination() {
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)));
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()),
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.
1623 void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1624 SkPDFFormXObject* mask,
1625 const SkClipStack* clipStack,
1626 const SkRegion& clipRegion,
1627 SkXfermode::Mode mode,
1629 if (clipRegion.isEmpty() && !invertClip) {
1633 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1634 SkPDFGraphicState::GetSMaskGraphicState(
1635 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1640 paint.setXfermodeMode(mode);
1641 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
1642 if (!content.entry()) {
1645 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1646 &content.entry()->fContent);
1647 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
1649 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
1650 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1651 &content.entry()->fContent);
1654 ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1655 const SkRegion& clipRegion,
1656 const SkMatrix& matrix,
1657 const SkPaint& paint,
1659 SkPDFFormXObject** dst) {
1661 if (clipRegion.isEmpty()) {
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;
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;
1676 clipRegion.getBoundaryPath(&clipPath);
1677 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1679 clipStack = &synthesizedClipStack;
1683 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1684 if (paint.getXfermode()) {
1685 paint.getXfermode()->asMode(&xfermode);
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,
1709 // TODO(vandebo): Figure out how/if we can handle the following modes:
1712 // Dst xfer mode doesn't draw source at all.
1713 if (xfermode == SkXfermode::kDst_Mode) {
1717 ContentEntry* entry;
1718 SkAutoTDelete<ContentEntry> newEntry;
1720 ContentEntry* lastContentEntry = getLastContentEntry();
1721 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1722 entry = lastContentEntry;
1724 newEntry.reset(new ContentEntry);
1725 entry = newEntry.get();
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;
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);
1743 lastContentEntry->fNext.reset(entry);
1744 setLastContentEntry(entry);
1750 void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
1751 SkPDFFormXObject* dst,
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) {
1766 if (xfermode == SkXfermode::kDstOver_Mode) {
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
1773 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1774 contentEntries->reset(firstContentEntry->fNext.detach());
1779 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1780 xfermode == SkXfermode::kSrcOut_Mode);
1784 ContentEntry* contentEntries = getContentEntries()->get();
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
1791 SkClipStack clipStack = contentEntries->fState.fClipStack;
1792 SkRegion clipRegion = contentEntries->fState.fClipRegion;
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
1805 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1806 xfermode == SkXfermode::kSrcATop_Mode) {
1807 ScopedContentEntry content(this, &fExistingClipStack,
1808 fExistingClipRegion, identity,
1810 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1811 &content.entry()->fContent);
1814 xfermode = SkXfermode::kClear_Mode;
1817 SkASSERT(!fContentEntries->fNext.get());
1818 srcFormXObject.reset(createFormXObjectFromDevice());
1821 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
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);
1832 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1833 SkPDFFormXObject* dstMask = srcFormXObject.get();
1834 if (shape != NULL) {
1835 // Draw shape into a form-xobject.
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);
1845 dstMaskStorage.reset(createFormXObjectFromDevice());
1846 dstMask = dstMaskStorage.get();
1848 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1849 &fExistingClipStack, fExistingClipRegion,
1850 SkXfermode::kSrcOver_Mode, true);
1853 if (xfermode == SkXfermode::kClear_Mode) {
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);
1864 if (xfermode == SkXfermode::kSrc_Mode) {
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);
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);
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);
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;
1900 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
1901 &fExistingClipStack, fExistingClipRegion, mode,
1902 xfermode == SkXfermode::kDstOut_Mode);
1906 bool SkPDFDevice::isContentEmpty() {
1907 ContentEntry* contentEntries = getContentEntries()->get();
1908 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1909 SkASSERT(!contentEntries || !contentEntries->fNext.get());
1915 void SkPDFDevice::populateGraphicStateEntryFromPaint(
1916 const SkMatrix& matrix,
1917 const SkClipStack& clipStack,
1918 const SkRegion& clipRegion,
1919 const SkPaint& paint,
1921 GraphicStateEntry* entry) {
1922 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
1923 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1924 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
1926 entry->fMatrix = matrix;
1927 entry->fClipStack = clipStack;
1928 entry->fClipRegion = clipRegion;
1929 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1930 entry->fShaderIndex = -1;
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();
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);
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();
1946 // We need to apply the initial transform to bounds in order to get
1947 // bounds in a consistent coordinate system.
1949 boundsTemp.set(bounds);
1950 fInitialTransform.mapRect(&boundsTemp);
1951 boundsTemp.roundOut(&bounds);
1953 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
1955 if (pdfShader.get()) {
1956 // pdfShader has been canonicalized so we can directly compare
1958 int resourceIndex = fShaderResources.find(pdfShader.get());
1959 if (resourceIndex < 0) {
1960 resourceIndex = fShaderResources.count();
1961 fShaderResources.push(pdfShader.get());
1962 pdfShader.get()->ref();
1964 entry->fShaderIndex = resourceIndex;
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;
1981 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
1982 if (color == paint.getColor()) {
1983 newGraphicState.reset(
1984 SkPDFGraphicState::GetGraphicStateForPaint(paint));
1986 SkPaint newPaint = paint;
1987 newPaint.setColor(color);
1988 newGraphicState.reset(
1989 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
1991 int resourceIndex = addGraphicStateResource(newGraphicState.get());
1992 entry->fGraphicStateIndex = resourceIndex;
1995 entry->fTextScaleX = paint.getTextScaleX();
1996 entry->fTextFill = paint.getStyle();
1998 entry->fTextScaleX = 0;
2002 int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2003 // Assumes that gs has been canonicalized (so we can directly compare
2005 int result = fGraphicStateResources.find(gs);
2007 result = fGraphicStateResources.count();
2008 fGraphicStateResources.push(gs);
2014 int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2015 // Assumes that xobject has been canonicalized (so we can directly compare
2017 int result = fXObjectResources.find(xObject);
2019 result = fXObjectResources.count();
2020 fXObjectResources.push(xObject);
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];
2044 int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
2045 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2047 int resourceIndex = fFontResources.find(newFont.get());
2048 if (resourceIndex < 0) {
2049 resourceIndex = fFontResources.count();
2050 fFontResources.push(newFont.get());
2051 newFont.get()->ref();
2053 return resourceIndex;
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;
2069 // Rasterize the bitmap using perspective in a new bitmap.
2070 if (origMatrix.hasPerspective()) {
2071 if (fRasterDpi == 0) {
2074 SkBitmap* subsetBitmap;
2076 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2079 subsetBitmap = &tmpSubsetBitmap;
2081 subsetBitmap = &tmpSubsetBitmap;
2082 *subsetBitmap = origBitmap;
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);
2094 // TODO(edisonn): perf - use current clip too.
2095 // Retrieve the bounds of the new shape.
2096 SkRect bounds = perspectiveOutline.getBounds();
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);
2112 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2114 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
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
2124 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2125 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
2126 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
2129 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2131 SkCanvas canvas(perspectiveBitmap);
2133 SkScalar deltaX = bounds.left();
2134 SkScalar deltaY = bounds.top();
2136 SkMatrix offsetMatrix = origMatrix;
2137 offsetMatrix.postTranslate(-deltaX, -deltaY);
2138 offsetMatrix.postScale(scaleX, scaleY);
2140 // Translate the draw in the new canvas, so we perfectly fit the
2141 // shape in the bitmap.
2142 canvas.setMatrix(offsetMatrix);
2144 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2146 // Make sure the final bits are in the bitmap.
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);
2154 perspectiveBounds.setRect(
2155 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2156 SkScalarFloorToInt(bounds.y()),
2157 SkScalarCeilToInt(bounds.width()),
2158 SkScalarCeilToInt(bounds.height())));
2159 clipRegion = &perspectiveBounds;
2161 bitmap = &perspectiveBitmap;
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))) {
2177 if (content.needShape()) {
2179 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2180 SkIntToScalar( subset.height())));
2181 shape.transform(matrix);
2182 content.setShape(shape);
2184 if (!content.needSource()) {
2188 SkAutoTUnref<SkPDFObject> image(
2189 SkPDFCreateImageObject(*bitmap, subset, fEncoder));
2194 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
2195 &content.entry()->fContent);