gfx/skia/trunk/src/pdf/SkPDFDevice.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/gfx/skia/trunk/src/pdf/SkPDFDevice.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,2320 @@
     1.4 +/*
     1.5 + * Copyright 2011 Google Inc.
     1.6 + *
     1.7 + * Use of this source code is governed by a BSD-style license that can be
     1.8 + * found in the LICENSE file.
     1.9 + */
    1.10 +
    1.11 +#include "SkPDFDevice.h"
    1.12 +
    1.13 +#include "SkAnnotation.h"
    1.14 +#include "SkColor.h"
    1.15 +#include "SkClipStack.h"
    1.16 +#include "SkData.h"
    1.17 +#include "SkDraw.h"
    1.18 +#include "SkFontHost.h"
    1.19 +#include "SkGlyphCache.h"
    1.20 +#include "SkPaint.h"
    1.21 +#include "SkPath.h"
    1.22 +#include "SkPathOps.h"
    1.23 +#include "SkPDFFont.h"
    1.24 +#include "SkPDFFormXObject.h"
    1.25 +#include "SkPDFGraphicState.h"
    1.26 +#include "SkPDFImage.h"
    1.27 +#include "SkPDFResourceDict.h"
    1.28 +#include "SkPDFShader.h"
    1.29 +#include "SkPDFStream.h"
    1.30 +#include "SkPDFTypes.h"
    1.31 +#include "SkPDFUtils.h"
    1.32 +#include "SkRect.h"
    1.33 +#include "SkRRect.h"
    1.34 +#include "SkString.h"
    1.35 +#include "SkTextFormatParams.h"
    1.36 +#include "SkTemplates.h"
    1.37 +#include "SkTypefacePriv.h"
    1.38 +#include "SkTSet.h"
    1.39 +
    1.40 +#ifdef SK_BUILD_FOR_ANDROID
    1.41 +#include "SkTypeface_android.h"
    1.42 +
    1.43 +struct TypefaceFallbackData {
    1.44 +    SkTypeface* typeface;
    1.45 +    int lowerBounds;
    1.46 +    int upperBounds;
    1.47 +
    1.48 +    bool operator==(const TypefaceFallbackData& b) const {
    1.49 +        return typeface == b.typeface &&
    1.50 +               lowerBounds == b.lowerBounds &&
    1.51 +               upperBounds == b.upperBounds;
    1.52 +    }
    1.53 +};
    1.54 +#endif
    1.55 +
    1.56 +#define DPI_FOR_RASTER_SCALE_ONE 72
    1.57 +
    1.58 +// Utility functions
    1.59 +
    1.60 +static void emit_pdf_color(SkColor color, SkWStream* result) {
    1.61 +    SkASSERT(SkColorGetA(color) == 0xFF);  // We handle alpha elsewhere.
    1.62 +    SkScalar colorMax = SkIntToScalar(0xFF);
    1.63 +    SkPDFScalar::Append(
    1.64 +            SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
    1.65 +    result->writeText(" ");
    1.66 +    SkPDFScalar::Append(
    1.67 +            SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
    1.68 +    result->writeText(" ");
    1.69 +    SkPDFScalar::Append(
    1.70 +            SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
    1.71 +    result->writeText(" ");
    1.72 +}
    1.73 +
    1.74 +static SkPaint calculate_text_paint(const SkPaint& paint) {
    1.75 +    SkPaint result = paint;
    1.76 +    if (result.isFakeBoldText()) {
    1.77 +        SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
    1.78 +                                                    kStdFakeBoldInterpKeys,
    1.79 +                                                    kStdFakeBoldInterpValues,
    1.80 +                                                    kStdFakeBoldInterpLength);
    1.81 +        SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
    1.82 +        if (result.getStyle() == SkPaint::kFill_Style) {
    1.83 +            result.setStyle(SkPaint::kStrokeAndFill_Style);
    1.84 +        } else {
    1.85 +            width += result.getStrokeWidth();
    1.86 +        }
    1.87 +        result.setStrokeWidth(width);
    1.88 +    }
    1.89 +    return result;
    1.90 +}
    1.91 +
    1.92 +// Stolen from measure_text in SkDraw.cpp and then tweaked.
    1.93 +static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
    1.94 +                       const uint16_t* glyphs, size_t len,
    1.95 +                       SkScalar* x, SkScalar* y) {
    1.96 +    if (paint.getTextAlign() == SkPaint::kLeft_Align) {
    1.97 +        return;
    1.98 +    }
    1.99 +
   1.100 +    SkMatrix ident;
   1.101 +    ident.reset();
   1.102 +    SkAutoGlyphCache autoCache(paint, NULL, &ident);
   1.103 +    SkGlyphCache* cache = autoCache.getCache();
   1.104 +
   1.105 +    const char* start = reinterpret_cast<const char*>(glyphs);
   1.106 +    const char* stop = reinterpret_cast<const char*>(glyphs + len);
   1.107 +    SkFixed xAdv = 0, yAdv = 0;
   1.108 +
   1.109 +    // TODO(vandebo): This probably needs to take kerning into account.
   1.110 +    while (start < stop) {
   1.111 +        const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
   1.112 +        xAdv += glyph.fAdvanceX;
   1.113 +        yAdv += glyph.fAdvanceY;
   1.114 +    };
   1.115 +    if (paint.getTextAlign() == SkPaint::kLeft_Align) {
   1.116 +        return;
   1.117 +    }
   1.118 +
   1.119 +    SkScalar xAdj = SkFixedToScalar(xAdv);
   1.120 +    SkScalar yAdj = SkFixedToScalar(yAdv);
   1.121 +    if (paint.getTextAlign() == SkPaint::kCenter_Align) {
   1.122 +        xAdj = SkScalarHalf(xAdj);
   1.123 +        yAdj = SkScalarHalf(yAdj);
   1.124 +    }
   1.125 +    *x = *x - xAdj;
   1.126 +    *y = *y - yAdj;
   1.127 +}
   1.128 +
   1.129 +static int max_glyphid_for_typeface(SkTypeface* typeface) {
   1.130 +    SkAutoResolveDefaultTypeface autoResolve(typeface);
   1.131 +    typeface = autoResolve.get();
   1.132 +    return typeface->countGlyphs() - 1;
   1.133 +}
   1.134 +
   1.135 +typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
   1.136 +
   1.137 +static size_t force_glyph_encoding(const SkPaint& paint, const void* text,
   1.138 +                                   size_t len, SkGlyphStorage* storage,
   1.139 +                                   uint16_t** glyphIDs) {
   1.140 +    // Make sure we have a glyph id encoding.
   1.141 +    if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
   1.142 +        size_t numGlyphs = paint.textToGlyphs(text, len, NULL);
   1.143 +        storage->reset(numGlyphs);
   1.144 +        paint.textToGlyphs(text, len, storage->get());
   1.145 +        *glyphIDs = storage->get();
   1.146 +        return numGlyphs;
   1.147 +    }
   1.148 +
   1.149 +    // For user supplied glyph ids we need to validate them.
   1.150 +    SkASSERT((len & 1) == 0);
   1.151 +    size_t numGlyphs = len / 2;
   1.152 +    const uint16_t* input =
   1.153 +        reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
   1.154 +
   1.155 +    int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
   1.156 +    size_t validated;
   1.157 +    for (validated = 0; validated < numGlyphs; ++validated) {
   1.158 +        if (input[validated] > maxGlyphID) {
   1.159 +            break;
   1.160 +        }
   1.161 +    }
   1.162 +    if (validated >= numGlyphs) {
   1.163 +        *glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
   1.164 +        return numGlyphs;
   1.165 +    }
   1.166 +
   1.167 +    // Silently drop anything out of range.
   1.168 +    storage->reset(numGlyphs);
   1.169 +    if (validated > 0) {
   1.170 +        memcpy(storage->get(), input, validated * sizeof(uint16_t));
   1.171 +    }
   1.172 +
   1.173 +    for (size_t i = validated; i < numGlyphs; ++i) {
   1.174 +        storage->get()[i] = input[i];
   1.175 +        if (input[i] > maxGlyphID) {
   1.176 +            storage->get()[i] = 0;
   1.177 +        }
   1.178 +    }
   1.179 +    *glyphIDs = storage->get();
   1.180 +    return numGlyphs;
   1.181 +}
   1.182 +
   1.183 +static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
   1.184 +                               SkWStream* content) {
   1.185 +    // Flip the text about the x-axis to account for origin swap and include
   1.186 +    // the passed parameters.
   1.187 +    content->writeText("1 0 ");
   1.188 +    SkPDFScalar::Append(0 - textSkewX, content);
   1.189 +    content->writeText(" -1 ");
   1.190 +    SkPDFScalar::Append(x, content);
   1.191 +    content->writeText(" ");
   1.192 +    SkPDFScalar::Append(y, content);
   1.193 +    content->writeText(" Tm\n");
   1.194 +}
   1.195 +
   1.196 +// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
   1.197 +// later being our representation of an object in the PDF file.
   1.198 +struct GraphicStateEntry {
   1.199 +    GraphicStateEntry();
   1.200 +
   1.201 +    // Compare the fields we care about when setting up a new content entry.
   1.202 +    bool compareInitialState(const GraphicStateEntry& b);
   1.203 +
   1.204 +    SkMatrix fMatrix;
   1.205 +    // We can't do set operations on Paths, though PDF natively supports
   1.206 +    // intersect.  If the clip stack does anything other than intersect,
   1.207 +    // we have to fall back to the region.  Treat fClipStack as authoritative.
   1.208 +    // See http://code.google.com/p/skia/issues/detail?id=221
   1.209 +    SkClipStack fClipStack;
   1.210 +    SkRegion fClipRegion;
   1.211 +
   1.212 +    // When emitting the content entry, we will ensure the graphic state
   1.213 +    // is set to these values first.
   1.214 +    SkColor fColor;
   1.215 +    SkScalar fTextScaleX;  // Zero means we don't care what the value is.
   1.216 +    SkPaint::Style fTextFill;  // Only if TextScaleX is non-zero.
   1.217 +    int fShaderIndex;
   1.218 +    int fGraphicStateIndex;
   1.219 +
   1.220 +    // We may change the font (i.e. for Type1 support) within a
   1.221 +    // ContentEntry.  This is the one currently in effect, or NULL if none.
   1.222 +    SkPDFFont* fFont;
   1.223 +    // In PDF, text size has no default value. It is only valid if fFont is
   1.224 +    // not NULL.
   1.225 +    SkScalar fTextSize;
   1.226 +};
   1.227 +
   1.228 +GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
   1.229 +                                         fTextScaleX(SK_Scalar1),
   1.230 +                                         fTextFill(SkPaint::kFill_Style),
   1.231 +                                         fShaderIndex(-1),
   1.232 +                                         fGraphicStateIndex(-1),
   1.233 +                                         fFont(NULL),
   1.234 +                                         fTextSize(SK_ScalarNaN) {
   1.235 +    fMatrix.reset();
   1.236 +}
   1.237 +
   1.238 +bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
   1.239 +    return fColor == cur.fColor &&
   1.240 +           fShaderIndex == cur.fShaderIndex &&
   1.241 +           fGraphicStateIndex == cur.fGraphicStateIndex &&
   1.242 +           fMatrix == cur.fMatrix &&
   1.243 +           fClipStack == cur.fClipStack &&
   1.244 +           (fTextScaleX == 0 ||
   1.245 +               (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
   1.246 +}
   1.247 +
   1.248 +class GraphicStackState {
   1.249 +public:
   1.250 +    GraphicStackState(const SkClipStack& existingClipStack,
   1.251 +                      const SkRegion& existingClipRegion,
   1.252 +                      SkWStream* contentStream)
   1.253 +            : fStackDepth(0),
   1.254 +              fContentStream(contentStream) {
   1.255 +        fEntries[0].fClipStack = existingClipStack;
   1.256 +        fEntries[0].fClipRegion = existingClipRegion;
   1.257 +    }
   1.258 +
   1.259 +    void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
   1.260 +                    const SkPoint& translation);
   1.261 +    void updateMatrix(const SkMatrix& matrix);
   1.262 +    void updateDrawingState(const GraphicStateEntry& state);
   1.263 +
   1.264 +    void drainStack();
   1.265 +
   1.266 +private:
   1.267 +    void push();
   1.268 +    void pop();
   1.269 +    GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
   1.270 +
   1.271 +    // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
   1.272 +    static const int kMaxStackDepth = 12;
   1.273 +    GraphicStateEntry fEntries[kMaxStackDepth + 1];
   1.274 +    int fStackDepth;
   1.275 +    SkWStream* fContentStream;
   1.276 +};
   1.277 +
   1.278 +void GraphicStackState::drainStack() {
   1.279 +    while (fStackDepth) {
   1.280 +        pop();
   1.281 +    }
   1.282 +}
   1.283 +
   1.284 +void GraphicStackState::push() {
   1.285 +    SkASSERT(fStackDepth < kMaxStackDepth);
   1.286 +    fContentStream->writeText("q\n");
   1.287 +    fStackDepth++;
   1.288 +    fEntries[fStackDepth] = fEntries[fStackDepth - 1];
   1.289 +}
   1.290 +
   1.291 +void GraphicStackState::pop() {
   1.292 +    SkASSERT(fStackDepth > 0);
   1.293 +    fContentStream->writeText("Q\n");
   1.294 +    fStackDepth--;
   1.295 +}
   1.296 +
   1.297 +// This function initializes iter to be an iterator on the "stack" argument
   1.298 +// and then skips over the leading entries as specified in prefix.  It requires
   1.299 +// and asserts that "prefix" will be a prefix to "stack."
   1.300 +static void skip_clip_stack_prefix(const SkClipStack& prefix,
   1.301 +                                   const SkClipStack& stack,
   1.302 +                                   SkClipStack::Iter* iter) {
   1.303 +    SkClipStack::B2TIter prefixIter(prefix);
   1.304 +    iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
   1.305 +
   1.306 +    const SkClipStack::Element* prefixEntry;
   1.307 +    const SkClipStack::Element* iterEntry;
   1.308 +
   1.309 +    for (prefixEntry = prefixIter.next(); prefixEntry;
   1.310 +            prefixEntry = prefixIter.next()) {
   1.311 +        iterEntry = iter->next();
   1.312 +        SkASSERT(iterEntry);
   1.313 +        // Because of SkClipStack does internal intersection, the last clip
   1.314 +        // entry may differ.
   1.315 +        if (*prefixEntry != *iterEntry) {
   1.316 +            SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
   1.317 +            SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
   1.318 +            SkASSERT(iterEntry->getType() == prefixEntry->getType());
   1.319 +            // back up the iterator by one
   1.320 +            iter->prev();
   1.321 +            prefixEntry = prefixIter.next();
   1.322 +            break;
   1.323 +        }
   1.324 +    }
   1.325 +
   1.326 +    SkASSERT(prefixEntry == NULL);
   1.327 +}
   1.328 +
   1.329 +static void emit_clip(SkPath* clipPath, SkRect* clipRect,
   1.330 +                      SkWStream* contentStream) {
   1.331 +    SkASSERT(clipPath || clipRect);
   1.332 +
   1.333 +    SkPath::FillType clipFill;
   1.334 +    if (clipPath) {
   1.335 +        SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
   1.336 +        clipFill = clipPath->getFillType();
   1.337 +    } else {
   1.338 +        SkPDFUtils::AppendRectangle(*clipRect, contentStream);
   1.339 +        clipFill = SkPath::kWinding_FillType;
   1.340 +    }
   1.341 +
   1.342 +    NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
   1.343 +    NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
   1.344 +    if (clipFill == SkPath::kEvenOdd_FillType) {
   1.345 +        contentStream->writeText("W* n\n");
   1.346 +    } else {
   1.347 +        contentStream->writeText("W n\n");
   1.348 +    }
   1.349 +}
   1.350 +
   1.351 +#ifdef SK_PDF_USE_PATHOPS
   1.352 +/* Calculate an inverted path's equivalent non-inverted path, given the
   1.353 + * canvas bounds.
   1.354 + * outPath may alias with invPath (since this is supported by PathOps).
   1.355 + */
   1.356 +static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
   1.357 +                                   SkPath* outPath) {
   1.358 +    SkASSERT(invPath.isInverseFillType());
   1.359 +
   1.360 +    SkPath clipPath;
   1.361 +    clipPath.addRect(bounds);
   1.362 +
   1.363 +    return Op(clipPath, invPath, kIntersect_PathOp, outPath);
   1.364 +}
   1.365 +
   1.366 +// Sanity check the numerical values of the SkRegion ops and PathOps ops
   1.367 +// enums so region_op_to_pathops_op can do a straight passthrough cast.
   1.368 +// If these are failing, it may be necessary to make region_op_to_pathops_op
   1.369 +// do more.
   1.370 +SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
   1.371 +                  region_pathop_mismatch);
   1.372 +SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
   1.373 +                  region_pathop_mismatch);
   1.374 +SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
   1.375 +                  region_pathop_mismatch);
   1.376 +SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
   1.377 +                  region_pathop_mismatch);
   1.378 +SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
   1.379 +                  (int)kReverseDifference_PathOp,
   1.380 +                  region_pathop_mismatch);
   1.381 +
   1.382 +static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
   1.383 +    SkASSERT(op >= 0);
   1.384 +    SkASSERT(op <= SkRegion::kReverseDifference_Op);
   1.385 +    return (SkPathOp)op;
   1.386 +}
   1.387 +
   1.388 +/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
   1.389 + * Returns true if successful, or false if not successful.
   1.390 + * If successful, the resulting clip is stored in outClipPath.
   1.391 + * If not successful, outClipPath is undefined, and a fallback method
   1.392 + * should be used.
   1.393 + */
   1.394 +static bool get_clip_stack_path(const SkMatrix& transform,
   1.395 +                                const SkClipStack& clipStack,
   1.396 +                                const SkRegion& clipRegion,
   1.397 +                                SkPath* outClipPath) {
   1.398 +    outClipPath->reset();
   1.399 +    outClipPath->setFillType(SkPath::kInverseWinding_FillType);
   1.400 +
   1.401 +    const SkClipStack::Element* clipEntry;
   1.402 +    SkClipStack::Iter iter;
   1.403 +    iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
   1.404 +    for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
   1.405 +        SkPath entryPath;
   1.406 +        if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
   1.407 +            outClipPath->reset();
   1.408 +            outClipPath->setFillType(SkPath::kInverseWinding_FillType);
   1.409 +            continue;
   1.410 +        } else {
   1.411 +            clipEntry->asPath(&entryPath);
   1.412 +        }
   1.413 +        entryPath.transform(transform);
   1.414 +
   1.415 +        if (SkRegion::kReplace_Op == clipEntry->getOp()) {
   1.416 +            *outClipPath = entryPath;
   1.417 +        } else {
   1.418 +            SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
   1.419 +            if (!Op(*outClipPath, entryPath, op, outClipPath)) {
   1.420 +                return false;
   1.421 +            }
   1.422 +        }
   1.423 +    }
   1.424 +
   1.425 +    if (outClipPath->isInverseFillType()) {
   1.426 +        // The bounds are slightly outset to ensure this is correct in the
   1.427 +        // face of floating-point accuracy and possible SkRegion bitmap
   1.428 +        // approximations.
   1.429 +        SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
   1.430 +        clipBounds.outset(SK_Scalar1, SK_Scalar1);
   1.431 +        if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
   1.432 +            return false;
   1.433 +        }
   1.434 +    }
   1.435 +    return true;
   1.436 +}
   1.437 +#endif
   1.438 +
   1.439 +// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
   1.440 +// graphic state stack, and the fact that we can know all the clips used
   1.441 +// on the page to optimize this.
   1.442 +void GraphicStackState::updateClip(const SkClipStack& clipStack,
   1.443 +                                   const SkRegion& clipRegion,
   1.444 +                                   const SkPoint& translation) {
   1.445 +    if (clipStack == currentEntry()->fClipStack) {
   1.446 +        return;
   1.447 +    }
   1.448 +
   1.449 +    while (fStackDepth > 0) {
   1.450 +        pop();
   1.451 +        if (clipStack == currentEntry()->fClipStack) {
   1.452 +            return;
   1.453 +        }
   1.454 +    }
   1.455 +    push();
   1.456 +
   1.457 +    currentEntry()->fClipStack = clipStack;
   1.458 +    currentEntry()->fClipRegion = clipRegion;
   1.459 +
   1.460 +    SkMatrix transform;
   1.461 +    transform.setTranslate(translation.fX, translation.fY);
   1.462 +
   1.463 +#ifdef SK_PDF_USE_PATHOPS
   1.464 +    SkPath clipPath;
   1.465 +    if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
   1.466 +        emit_clip(&clipPath, NULL, fContentStream);
   1.467 +        return;
   1.468 +    }
   1.469 +#endif
   1.470 +    // gsState->initialEntry()->fClipStack/Region specifies the clip that has
   1.471 +    // already been applied.  (If this is a top level device, then it specifies
   1.472 +    // a clip to the content area.  If this is a layer, then it specifies
   1.473 +    // the clip in effect when the layer was created.)  There's no need to
   1.474 +    // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
   1.475 +    // initial clip on the parent layer.  (This means there's a bug if the user
   1.476 +    // expands the clip and then uses any xfer mode that uses dst:
   1.477 +    // http://code.google.com/p/skia/issues/detail?id=228 )
   1.478 +    SkClipStack::Iter iter;
   1.479 +    skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
   1.480 +
   1.481 +    // If the clip stack does anything other than intersect or if it uses
   1.482 +    // an inverse fill type, we have to fall back to the clip region.
   1.483 +    bool needRegion = false;
   1.484 +    const SkClipStack::Element* clipEntry;
   1.485 +    for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
   1.486 +        if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
   1.487 +                clipEntry->isInverseFilled()) {
   1.488 +            needRegion = true;
   1.489 +            break;
   1.490 +        }
   1.491 +    }
   1.492 +
   1.493 +    if (needRegion) {
   1.494 +        SkPath clipPath;
   1.495 +        SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
   1.496 +        emit_clip(&clipPath, NULL, fContentStream);
   1.497 +    } else {
   1.498 +        skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
   1.499 +        const SkClipStack::Element* clipEntry;
   1.500 +        for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
   1.501 +            SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
   1.502 +            switch (clipEntry->getType()) {
   1.503 +                case SkClipStack::Element::kRect_Type: {
   1.504 +                    SkRect translatedClip;
   1.505 +                    transform.mapRect(&translatedClip, clipEntry->getRect());
   1.506 +                    emit_clip(NULL, &translatedClip, fContentStream);
   1.507 +                    break;
   1.508 +                }
   1.509 +                default: {
   1.510 +                    SkPath translatedPath;
   1.511 +                    clipEntry->asPath(&translatedPath);
   1.512 +                    translatedPath.transform(transform, &translatedPath);
   1.513 +                    emit_clip(&translatedPath, NULL, fContentStream);
   1.514 +                    break;
   1.515 +                }
   1.516 +            }
   1.517 +        }
   1.518 +    }
   1.519 +}
   1.520 +
   1.521 +void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
   1.522 +    if (matrix == currentEntry()->fMatrix) {
   1.523 +        return;
   1.524 +    }
   1.525 +
   1.526 +    if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
   1.527 +        SkASSERT(fStackDepth > 0);
   1.528 +        SkASSERT(fEntries[fStackDepth].fClipStack ==
   1.529 +                 fEntries[fStackDepth -1].fClipStack);
   1.530 +        pop();
   1.531 +
   1.532 +        SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
   1.533 +    }
   1.534 +    if (matrix.getType() == SkMatrix::kIdentity_Mask) {
   1.535 +        return;
   1.536 +    }
   1.537 +
   1.538 +    push();
   1.539 +    SkPDFUtils::AppendTransform(matrix, fContentStream);
   1.540 +    currentEntry()->fMatrix = matrix;
   1.541 +}
   1.542 +
   1.543 +void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
   1.544 +    // PDF treats a shader as a color, so we only set one or the other.
   1.545 +    if (state.fShaderIndex >= 0) {
   1.546 +        if (state.fShaderIndex != currentEntry()->fShaderIndex) {
   1.547 +            SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
   1.548 +            currentEntry()->fShaderIndex = state.fShaderIndex;
   1.549 +        }
   1.550 +    } else {
   1.551 +        if (state.fColor != currentEntry()->fColor ||
   1.552 +                currentEntry()->fShaderIndex >= 0) {
   1.553 +            emit_pdf_color(state.fColor, fContentStream);
   1.554 +            fContentStream->writeText("RG ");
   1.555 +            emit_pdf_color(state.fColor, fContentStream);
   1.556 +            fContentStream->writeText("rg\n");
   1.557 +            currentEntry()->fColor = state.fColor;
   1.558 +            currentEntry()->fShaderIndex = -1;
   1.559 +        }
   1.560 +    }
   1.561 +
   1.562 +    if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
   1.563 +        SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
   1.564 +        currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
   1.565 +    }
   1.566 +
   1.567 +    if (state.fTextScaleX) {
   1.568 +        if (state.fTextScaleX != currentEntry()->fTextScaleX) {
   1.569 +            SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
   1.570 +                                            SkIntToScalar(100));
   1.571 +            SkPDFScalar::Append(pdfScale, fContentStream);
   1.572 +            fContentStream->writeText(" Tz\n");
   1.573 +            currentEntry()->fTextScaleX = state.fTextScaleX;
   1.574 +        }
   1.575 +        if (state.fTextFill != currentEntry()->fTextFill) {
   1.576 +            SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
   1.577 +            SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
   1.578 +                              enum_must_match_value);
   1.579 +            SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
   1.580 +                              enum_must_match_value);
   1.581 +            fContentStream->writeDecAsText(state.fTextFill);
   1.582 +            fContentStream->writeText(" Tr\n");
   1.583 +            currentEntry()->fTextFill = state.fTextFill;
   1.584 +        }
   1.585 +    }
   1.586 +}
   1.587 +
   1.588 +SkBaseDevice* SkPDFDevice::onCreateDevice(const SkImageInfo& info, Usage usage) {
   1.589 +    SkMatrix initialTransform;
   1.590 +    initialTransform.reset();
   1.591 +    SkISize size = SkISize::Make(info.width(), info.height());
   1.592 +    return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
   1.593 +}
   1.594 +
   1.595 +
   1.596 +struct ContentEntry {
   1.597 +    GraphicStateEntry fState;
   1.598 +    SkDynamicMemoryWStream fContent;
   1.599 +    SkAutoTDelete<ContentEntry> fNext;
   1.600 +
   1.601 +    // If the stack is too deep we could get Stack Overflow.
   1.602 +    // So we manually destruct the object.
   1.603 +    ~ContentEntry() {
   1.604 +        ContentEntry* val = fNext.detach();
   1.605 +        while (val != NULL) {
   1.606 +            ContentEntry* valNext = val->fNext.detach();
   1.607 +            // When the destructor is called, fNext is NULL and exits.
   1.608 +            delete val;
   1.609 +            val = valNext;
   1.610 +        }
   1.611 +    }
   1.612 +};
   1.613 +
   1.614 +// A helper class to automatically finish a ContentEntry at the end of a
   1.615 +// drawing method and maintain the state needed between set up and finish.
   1.616 +class ScopedContentEntry {
   1.617 +public:
   1.618 +    ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
   1.619 +                       const SkPaint& paint, bool hasText = false)
   1.620 +        : fDevice(device),
   1.621 +          fContentEntry(NULL),
   1.622 +          fXfermode(SkXfermode::kSrcOver_Mode),
   1.623 +          fDstFormXObject(NULL) {
   1.624 +        init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
   1.625 +    }
   1.626 +    ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
   1.627 +                       const SkRegion& clipRegion, const SkMatrix& matrix,
   1.628 +                       const SkPaint& paint, bool hasText = false)
   1.629 +        : fDevice(device),
   1.630 +          fContentEntry(NULL),
   1.631 +          fXfermode(SkXfermode::kSrcOver_Mode),
   1.632 +          fDstFormXObject(NULL) {
   1.633 +        init(clipStack, clipRegion, matrix, paint, hasText);
   1.634 +    }
   1.635 +
   1.636 +    ~ScopedContentEntry() {
   1.637 +        if (fContentEntry) {
   1.638 +            SkPath* shape = &fShape;
   1.639 +            if (shape->isEmpty()) {
   1.640 +                shape = NULL;
   1.641 +            }
   1.642 +            fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
   1.643 +        }
   1.644 +        SkSafeUnref(fDstFormXObject);
   1.645 +    }
   1.646 +
   1.647 +    ContentEntry* entry() { return fContentEntry; }
   1.648 +
   1.649 +    /* Returns true when we explicitly need the shape of the drawing. */
   1.650 +    bool needShape() {
   1.651 +        switch (fXfermode) {
   1.652 +            case SkXfermode::kClear_Mode:
   1.653 +            case SkXfermode::kSrc_Mode:
   1.654 +            case SkXfermode::kSrcIn_Mode:
   1.655 +            case SkXfermode::kSrcOut_Mode:
   1.656 +            case SkXfermode::kDstIn_Mode:
   1.657 +            case SkXfermode::kDstOut_Mode:
   1.658 +            case SkXfermode::kSrcATop_Mode:
   1.659 +            case SkXfermode::kDstATop_Mode:
   1.660 +            case SkXfermode::kModulate_Mode:
   1.661 +                return true;
   1.662 +            default:
   1.663 +                return false;
   1.664 +        }
   1.665 +    }
   1.666 +
   1.667 +    /* Returns true unless we only need the shape of the drawing. */
   1.668 +    bool needSource() {
   1.669 +        if (fXfermode == SkXfermode::kClear_Mode) {
   1.670 +            return false;
   1.671 +        }
   1.672 +        return true;
   1.673 +    }
   1.674 +
   1.675 +    /* If the shape is different than the alpha component of the content, then
   1.676 +     * setShape should be called with the shape.  In particular, images and
   1.677 +     * devices have rectangular shape.
   1.678 +     */
   1.679 +    void setShape(const SkPath& shape) {
   1.680 +        fShape = shape;
   1.681 +    }
   1.682 +
   1.683 +private:
   1.684 +    SkPDFDevice* fDevice;
   1.685 +    ContentEntry* fContentEntry;
   1.686 +    SkXfermode::Mode fXfermode;
   1.687 +    SkPDFFormXObject* fDstFormXObject;
   1.688 +    SkPath fShape;
   1.689 +
   1.690 +    void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
   1.691 +              const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
   1.692 +        // Shape has to be flatten before we get here.
   1.693 +        if (matrix.hasPerspective()) {
   1.694 +            NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
   1.695 +            return;
   1.696 +        }
   1.697 +        if (paint.getXfermode()) {
   1.698 +            paint.getXfermode()->asMode(&fXfermode);
   1.699 +        }
   1.700 +        fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
   1.701 +                                                   matrix, paint, hasText,
   1.702 +                                                   &fDstFormXObject);
   1.703 +    }
   1.704 +};
   1.705 +
   1.706 +////////////////////////////////////////////////////////////////////////////////
   1.707 +
   1.708 +static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
   1.709 +                                         const SkMatrix* initialTransform) {
   1.710 +    SkImageInfo info;
   1.711 +    if (initialTransform) {
   1.712 +        // Compute the size of the drawing area.
   1.713 +        SkVector drawingSize;
   1.714 +        SkMatrix inverse;
   1.715 +        drawingSize.set(SkIntToScalar(contentSize.fWidth),
   1.716 +                        SkIntToScalar(contentSize.fHeight));
   1.717 +        if (!initialTransform->invert(&inverse)) {
   1.718 +            // This shouldn't happen, initial transform should be invertible.
   1.719 +            SkASSERT(false);
   1.720 +            inverse.reset();
   1.721 +        }
   1.722 +        inverse.mapVectors(&drawingSize, 1);
   1.723 +        SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
   1.724 +        info = SkImageInfo::MakeUnknown(abs(size.fWidth), abs(size.fHeight));
   1.725 +    } else {
   1.726 +        info = SkImageInfo::MakeUnknown(abs(contentSize.fWidth),
   1.727 +                                        abs(contentSize.fHeight));
   1.728 +    }
   1.729 +
   1.730 +    SkBitmap bitmap;
   1.731 +    bitmap.setConfig(info);
   1.732 +    return bitmap;
   1.733 +}
   1.734 +
   1.735 +// TODO(vandebo) change pageSize to SkSize.
   1.736 +// TODO: inherit from SkBaseDevice instead of SkBitmapDevice
   1.737 +SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
   1.738 +                         const SkMatrix& initialTransform)
   1.739 +    : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
   1.740 +      fPageSize(pageSize),
   1.741 +      fContentSize(contentSize),
   1.742 +      fLastContentEntry(NULL),
   1.743 +      fLastMarginContentEntry(NULL),
   1.744 +      fClipStack(NULL),
   1.745 +      fEncoder(NULL),
   1.746 +      fRasterDpi(72.0f) {
   1.747 +    // Just report that PDF does not supports perspective in the
   1.748 +    // initial transform.
   1.749 +    NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
   1.750 +
   1.751 +    // Skia generally uses the top left as the origin but PDF natively has the
   1.752 +    // origin at the bottom left. This matrix corrects for that.  But that only
   1.753 +    // needs to be done once, we don't do it when layering.
   1.754 +    fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
   1.755 +    fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
   1.756 +    fInitialTransform.preConcat(initialTransform);
   1.757 +
   1.758 +    SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
   1.759 +    fExistingClipRegion.setRect(existingClip);
   1.760 +
   1.761 +    this->init();
   1.762 +}
   1.763 +
   1.764 +// TODO(vandebo) change layerSize to SkSize.
   1.765 +SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
   1.766 +                         const SkClipStack& existingClipStack,
   1.767 +                         const SkRegion& existingClipRegion)
   1.768 +    : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
   1.769 +      fPageSize(layerSize),
   1.770 +      fContentSize(layerSize),
   1.771 +      fExistingClipStack(existingClipStack),
   1.772 +      fExistingClipRegion(existingClipRegion),
   1.773 +      fLastContentEntry(NULL),
   1.774 +      fLastMarginContentEntry(NULL),
   1.775 +      fClipStack(NULL),
   1.776 +      fEncoder(NULL),
   1.777 +      fRasterDpi(72.0f) {
   1.778 +    fInitialTransform.reset();
   1.779 +    this->init();
   1.780 +}
   1.781 +
   1.782 +SkPDFDevice::~SkPDFDevice() {
   1.783 +    this->cleanUp(true);
   1.784 +}
   1.785 +
   1.786 +void SkPDFDevice::init() {
   1.787 +    fAnnotations = NULL;
   1.788 +    fResourceDict = NULL;
   1.789 +    fContentEntries.free();
   1.790 +    fLastContentEntry = NULL;
   1.791 +    fMarginContentEntries.free();
   1.792 +    fLastMarginContentEntry = NULL;
   1.793 +    fDrawingArea = kContent_DrawingArea;
   1.794 +    if (fFontGlyphUsage.get() == NULL) {
   1.795 +        fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
   1.796 +    }
   1.797 +}
   1.798 +
   1.799 +void SkPDFDevice::cleanUp(bool clearFontUsage) {
   1.800 +    fGraphicStateResources.unrefAll();
   1.801 +    fXObjectResources.unrefAll();
   1.802 +    fFontResources.unrefAll();
   1.803 +    fShaderResources.unrefAll();
   1.804 +    SkSafeUnref(fAnnotations);
   1.805 +    SkSafeUnref(fResourceDict);
   1.806 +    fNamedDestinations.deleteAll();
   1.807 +
   1.808 +    if (clearFontUsage) {
   1.809 +        fFontGlyphUsage->reset();
   1.810 +    }
   1.811 +}
   1.812 +
   1.813 +void SkPDFDevice::clear(SkColor color) {
   1.814 +    this->cleanUp(true);
   1.815 +    this->init();
   1.816 +
   1.817 +    SkPaint paint;
   1.818 +    paint.setColor(color);
   1.819 +    paint.setStyle(SkPaint::kFill_Style);
   1.820 +    SkMatrix identity;
   1.821 +    identity.reset();
   1.822 +    ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
   1.823 +                               identity, paint);
   1.824 +    internalDrawPaint(paint, content.entry());
   1.825 +}
   1.826 +
   1.827 +void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
   1.828 +    SkPaint newPaint = paint;
   1.829 +    newPaint.setStyle(SkPaint::kFill_Style);
   1.830 +    ScopedContentEntry content(this, d, newPaint);
   1.831 +    internalDrawPaint(newPaint, content.entry());
   1.832 +}
   1.833 +
   1.834 +void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
   1.835 +                                    ContentEntry* contentEntry) {
   1.836 +    if (!contentEntry) {
   1.837 +        return;
   1.838 +    }
   1.839 +    SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
   1.840 +                                 SkIntToScalar(this->height()));
   1.841 +    SkMatrix inverse;
   1.842 +    if (!contentEntry->fState.fMatrix.invert(&inverse)) {
   1.843 +        return;
   1.844 +    }
   1.845 +    inverse.mapRect(&bbox);
   1.846 +
   1.847 +    SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
   1.848 +    SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
   1.849 +                          &contentEntry->fContent);
   1.850 +}
   1.851 +
   1.852 +void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
   1.853 +                             size_t count, const SkPoint* points,
   1.854 +                             const SkPaint& passedPaint) {
   1.855 +    if (count == 0) {
   1.856 +        return;
   1.857 +    }
   1.858 +
   1.859 +    if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
   1.860 +        return;
   1.861 +    }
   1.862 +
   1.863 +    // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
   1.864 +    // We only use this when there's a path effect because of the overhead
   1.865 +    // of multiple calls to setUpContentEntry it causes.
   1.866 +    if (passedPaint.getPathEffect()) {
   1.867 +        if (d.fClip->isEmpty()) {
   1.868 +            return;
   1.869 +        }
   1.870 +        SkDraw pointDraw(d);
   1.871 +        pointDraw.fDevice = this;
   1.872 +        pointDraw.drawPoints(mode, count, points, passedPaint, true);
   1.873 +        return;
   1.874 +    }
   1.875 +
   1.876 +    const SkPaint* paint = &passedPaint;
   1.877 +    SkPaint modifiedPaint;
   1.878 +
   1.879 +    if (mode == SkCanvas::kPoints_PointMode &&
   1.880 +            paint->getStrokeCap() != SkPaint::kRound_Cap) {
   1.881 +        modifiedPaint = *paint;
   1.882 +        paint = &modifiedPaint;
   1.883 +        if (paint->getStrokeWidth()) {
   1.884 +            // PDF won't draw a single point with square/butt caps because the
   1.885 +            // orientation is ambiguous.  Draw a rectangle instead.
   1.886 +            modifiedPaint.setStyle(SkPaint::kFill_Style);
   1.887 +            SkScalar strokeWidth = paint->getStrokeWidth();
   1.888 +            SkScalar halfStroke = SkScalarHalf(strokeWidth);
   1.889 +            for (size_t i = 0; i < count; i++) {
   1.890 +                SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
   1.891 +                r.inset(-halfStroke, -halfStroke);
   1.892 +                drawRect(d, r, modifiedPaint);
   1.893 +            }
   1.894 +            return;
   1.895 +        } else {
   1.896 +            modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
   1.897 +        }
   1.898 +    }
   1.899 +
   1.900 +    ScopedContentEntry content(this, d, *paint);
   1.901 +    if (!content.entry()) {
   1.902 +        return;
   1.903 +    }
   1.904 +
   1.905 +    switch (mode) {
   1.906 +        case SkCanvas::kPolygon_PointMode:
   1.907 +            SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
   1.908 +                               &content.entry()->fContent);
   1.909 +            for (size_t i = 1; i < count; i++) {
   1.910 +                SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
   1.911 +                                       &content.entry()->fContent);
   1.912 +            }
   1.913 +            SkPDFUtils::StrokePath(&content.entry()->fContent);
   1.914 +            break;
   1.915 +        case SkCanvas::kLines_PointMode:
   1.916 +            for (size_t i = 0; i < count/2; i++) {
   1.917 +                SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
   1.918 +                                   &content.entry()->fContent);
   1.919 +                SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
   1.920 +                                       points[i * 2 + 1].fY,
   1.921 +                                       &content.entry()->fContent);
   1.922 +                SkPDFUtils::StrokePath(&content.entry()->fContent);
   1.923 +            }
   1.924 +            break;
   1.925 +        case SkCanvas::kPoints_PointMode:
   1.926 +            SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
   1.927 +            for (size_t i = 0; i < count; i++) {
   1.928 +                SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
   1.929 +                                   &content.entry()->fContent);
   1.930 +                SkPDFUtils::ClosePath(&content.entry()->fContent);
   1.931 +                SkPDFUtils::StrokePath(&content.entry()->fContent);
   1.932 +            }
   1.933 +            break;
   1.934 +        default:
   1.935 +            SkASSERT(false);
   1.936 +    }
   1.937 +}
   1.938 +
   1.939 +void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
   1.940 +                           const SkPaint& paint) {
   1.941 +    SkRect r = rect;
   1.942 +    r.sort();
   1.943 +
   1.944 +    if (paint.getPathEffect()) {
   1.945 +        if (d.fClip->isEmpty()) {
   1.946 +            return;
   1.947 +        }
   1.948 +        SkPath path;
   1.949 +        path.addRect(r);
   1.950 +        drawPath(d, path, paint, NULL, true);
   1.951 +        return;
   1.952 +    }
   1.953 +
   1.954 +    if (handleRectAnnotation(r, *d.fMatrix, paint)) {
   1.955 +        return;
   1.956 +    }
   1.957 +
   1.958 +    ScopedContentEntry content(this, d, paint);
   1.959 +    if (!content.entry()) {
   1.960 +        return;
   1.961 +    }
   1.962 +    SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
   1.963 +    SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
   1.964 +                          &content.entry()->fContent);
   1.965 +}
   1.966 +
   1.967 +void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect,
   1.968 +                            const SkPaint& paint) {
   1.969 +    SkPath  path;
   1.970 +    path.addRRect(rrect);
   1.971 +    this->drawPath(draw, path, paint, NULL, true);
   1.972 +}
   1.973 +
   1.974 +void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
   1.975 +                           const SkPaint& paint, const SkMatrix* prePathMatrix,
   1.976 +                           bool pathIsMutable) {
   1.977 +    SkPath modifiedPath;
   1.978 +    SkPath* pathPtr = const_cast<SkPath*>(&origPath);
   1.979 +
   1.980 +    SkMatrix matrix = *d.fMatrix;
   1.981 +    if (prePathMatrix) {
   1.982 +        if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
   1.983 +            if (!pathIsMutable) {
   1.984 +                pathPtr = &modifiedPath;
   1.985 +                pathIsMutable = true;
   1.986 +            }
   1.987 +            origPath.transform(*prePathMatrix, pathPtr);
   1.988 +        } else {
   1.989 +            if (!matrix.preConcat(*prePathMatrix)) {
   1.990 +                // TODO(edisonn): report somehow why we failed?
   1.991 +                return;
   1.992 +            }
   1.993 +        }
   1.994 +    }
   1.995 +
   1.996 +    if (paint.getPathEffect()) {
   1.997 +        if (d.fClip->isEmpty()) {
   1.998 +            return;
   1.999 +        }
  1.1000 +        if (!pathIsMutable) {
  1.1001 +            pathPtr = &modifiedPath;
  1.1002 +            pathIsMutable = true;
  1.1003 +        }
  1.1004 +        bool fill = paint.getFillPath(origPath, pathPtr);
  1.1005 +
  1.1006 +        SkPaint noEffectPaint(paint);
  1.1007 +        noEffectPaint.setPathEffect(NULL);
  1.1008 +        if (fill) {
  1.1009 +            noEffectPaint.setStyle(SkPaint::kFill_Style);
  1.1010 +        } else {
  1.1011 +            noEffectPaint.setStyle(SkPaint::kStroke_Style);
  1.1012 +            noEffectPaint.setStrokeWidth(0);
  1.1013 +        }
  1.1014 +        drawPath(d, *pathPtr, noEffectPaint, NULL, true);
  1.1015 +        return;
  1.1016 +    }
  1.1017 +
  1.1018 +#ifdef SK_PDF_USE_PATHOPS
  1.1019 +    if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
  1.1020 +        return;
  1.1021 +    }
  1.1022 +#endif
  1.1023 +
  1.1024 +    if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
  1.1025 +        return;
  1.1026 +    }
  1.1027 +
  1.1028 +    ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
  1.1029 +    if (!content.entry()) {
  1.1030 +        return;
  1.1031 +    }
  1.1032 +    SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
  1.1033 +                         &content.entry()->fContent);
  1.1034 +    SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
  1.1035 +                          &content.entry()->fContent);
  1.1036 +}
  1.1037 +
  1.1038 +void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
  1.1039 +                                 const SkRect* src, const SkRect& dst,
  1.1040 +                                 const SkPaint& paint,
  1.1041 +                                 SkCanvas::DrawBitmapRectFlags flags) {
  1.1042 +    // TODO: this code path must be updated to respect the flags parameter
  1.1043 +    SkMatrix    matrix;
  1.1044 +    SkRect      bitmapBounds, tmpSrc, tmpDst;
  1.1045 +    SkBitmap    tmpBitmap;
  1.1046 +
  1.1047 +    bitmapBounds.isetWH(bitmap.width(), bitmap.height());
  1.1048 +
  1.1049 +    // Compute matrix from the two rectangles
  1.1050 +    if (src) {
  1.1051 +        tmpSrc = *src;
  1.1052 +    } else {
  1.1053 +        tmpSrc = bitmapBounds;
  1.1054 +    }
  1.1055 +    matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
  1.1056 +
  1.1057 +    const SkBitmap* bitmapPtr = &bitmap;
  1.1058 +
  1.1059 +    // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
  1.1060 +    // needed (if the src was clipped). No check needed if src==null.
  1.1061 +    if (src) {
  1.1062 +        if (!bitmapBounds.contains(*src)) {
  1.1063 +            if (!tmpSrc.intersect(bitmapBounds)) {
  1.1064 +                return; // nothing to draw
  1.1065 +            }
  1.1066 +            // recompute dst, based on the smaller tmpSrc
  1.1067 +            matrix.mapRect(&tmpDst, tmpSrc);
  1.1068 +        }
  1.1069 +
  1.1070 +        // since we may need to clamp to the borders of the src rect within
  1.1071 +        // the bitmap, we extract a subset.
  1.1072 +        // TODO: make sure this is handled in drawBitmap and remove from here.
  1.1073 +        SkIRect srcIR;
  1.1074 +        tmpSrc.roundOut(&srcIR);
  1.1075 +        if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
  1.1076 +            return;
  1.1077 +        }
  1.1078 +        bitmapPtr = &tmpBitmap;
  1.1079 +
  1.1080 +        // Since we did an extract, we need to adjust the matrix accordingly
  1.1081 +        SkScalar dx = 0, dy = 0;
  1.1082 +        if (srcIR.fLeft > 0) {
  1.1083 +            dx = SkIntToScalar(srcIR.fLeft);
  1.1084 +        }
  1.1085 +        if (srcIR.fTop > 0) {
  1.1086 +            dy = SkIntToScalar(srcIR.fTop);
  1.1087 +        }
  1.1088 +        if (dx || dy) {
  1.1089 +            matrix.preTranslate(dx, dy);
  1.1090 +        }
  1.1091 +    }
  1.1092 +    this->drawBitmap(draw, *bitmapPtr, matrix, paint);
  1.1093 +}
  1.1094 +
  1.1095 +void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
  1.1096 +                             const SkMatrix& matrix, const SkPaint& paint) {
  1.1097 +    if (d.fClip->isEmpty()) {
  1.1098 +        return;
  1.1099 +    }
  1.1100 +
  1.1101 +    SkMatrix transform = matrix;
  1.1102 +    transform.postConcat(*d.fMatrix);
  1.1103 +    this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
  1.1104 +                             paint);
  1.1105 +}
  1.1106 +
  1.1107 +void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
  1.1108 +                             int x, int y, const SkPaint& paint) {
  1.1109 +    if (d.fClip->isEmpty()) {
  1.1110 +        return;
  1.1111 +    }
  1.1112 +
  1.1113 +    SkMatrix matrix;
  1.1114 +    matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
  1.1115 +    this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
  1.1116 +                             paint);
  1.1117 +}
  1.1118 +
  1.1119 +void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
  1.1120 +                           SkScalar x, SkScalar y, const SkPaint& paint) {
  1.1121 +    NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
  1.1122 +    if (paint.getMaskFilter() != NULL) {
  1.1123 +        // Don't pretend we support drawing MaskFilters, it makes for artifacts
  1.1124 +        // making text unreadable (e.g. same text twice when using CSS shadows).
  1.1125 +        return;
  1.1126 +    }
  1.1127 +    SkPaint textPaint = calculate_text_paint(paint);
  1.1128 +    ScopedContentEntry content(this, d, textPaint, true);
  1.1129 +    if (!content.entry()) {
  1.1130 +        return;
  1.1131 +    }
  1.1132 +
  1.1133 +    SkGlyphStorage storage(0);
  1.1134 +    uint16_t* glyphIDs = NULL;
  1.1135 +    size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
  1.1136 +                                            &glyphIDs);
  1.1137 +    textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
  1.1138 +
  1.1139 +    SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
  1.1140 +    align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
  1.1141 +    content.entry()->fContent.writeText("BT\n");
  1.1142 +    set_text_transform(x, y, textPaint.getTextSkewX(),
  1.1143 +                       &content.entry()->fContent);
  1.1144 +    size_t consumedGlyphCount = 0;
  1.1145 +    while (numGlyphs > consumedGlyphCount) {
  1.1146 +        updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
  1.1147 +        SkPDFFont* font = content.entry()->fState.fFont;
  1.1148 +        size_t availableGlyphs =
  1.1149 +            font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
  1.1150 +                                          numGlyphs - consumedGlyphCount);
  1.1151 +        fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
  1.1152 +                                        availableGlyphs);
  1.1153 +        SkString encodedString =
  1.1154 +            SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
  1.1155 +                                      availableGlyphs, font->multiByteGlyphs());
  1.1156 +        content.entry()->fContent.writeText(encodedString.c_str());
  1.1157 +        consumedGlyphCount += availableGlyphs;
  1.1158 +        content.entry()->fContent.writeText(" Tj\n");
  1.1159 +    }
  1.1160 +    content.entry()->fContent.writeText("ET\n");
  1.1161 +}
  1.1162 +
  1.1163 +void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
  1.1164 +                              const SkScalar pos[], SkScalar constY,
  1.1165 +                              int scalarsPerPos, const SkPaint& paint) {
  1.1166 +    NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
  1.1167 +    if (paint.getMaskFilter() != NULL) {
  1.1168 +        // Don't pretend we support drawing MaskFilters, it makes for artifacts
  1.1169 +        // making text unreadable (e.g. same text twice when using CSS shadows).
  1.1170 +        return;
  1.1171 +    }
  1.1172 +    SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
  1.1173 +    SkPaint textPaint = calculate_text_paint(paint);
  1.1174 +    ScopedContentEntry content(this, d, textPaint, true);
  1.1175 +    if (!content.entry()) {
  1.1176 +        return;
  1.1177 +    }
  1.1178 +
  1.1179 +#ifdef SK_BUILD_FOR_ANDROID
  1.1180 +    /*
  1.1181 +     * In the case that we have enabled fallback fonts on Android we need to
  1.1182 +     * take the following steps to ensure that the PDF draws all characters,
  1.1183 +     * regardless of their underlying font file, correctly.
  1.1184 +     *
  1.1185 +     * 1. Convert input into GlyphID encoding if it currently is not
  1.1186 +     * 2. Iterate over the glyphIDs and identify the actual typeface that each
  1.1187 +     *    glyph resolves to
  1.1188 +     * 3. Iterate over those typefaces and recursively call this function with
  1.1189 +     *    only the glyphs (and their positions) that the typeface is capable of
  1.1190 +     *    resolving.
  1.1191 +     */
  1.1192 +    if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
  1.1193 +        uint16_t* glyphIDs = NULL;
  1.1194 +        SkGlyphStorage tmpStorage(0);
  1.1195 +        size_t numGlyphs = 0;
  1.1196 +
  1.1197 +        // convert to glyphIDs
  1.1198 +        if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
  1.1199 +            numGlyphs = len / 2;
  1.1200 +            glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
  1.1201 +        } else {
  1.1202 +            numGlyphs = paint.textToGlyphs(text, len, NULL);
  1.1203 +            tmpStorage.reset(numGlyphs);
  1.1204 +            paint.textToGlyphs(text, len, tmpStorage.get());
  1.1205 +            glyphIDs = tmpStorage.get();
  1.1206 +        }
  1.1207 +
  1.1208 +        // if no typeface is provided in the paint get the default
  1.1209 +        SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
  1.1210 +        if (NULL == origFace.get()) {
  1.1211 +            origFace.reset(SkTypeface::RefDefault());
  1.1212 +        }
  1.1213 +        const uint16_t origGlyphCount = origFace->countGlyphs();
  1.1214 +
  1.1215 +        // keep a list of the already visited typefaces and some data about them
  1.1216 +        SkTDArray<TypefaceFallbackData> visitedTypefaces;
  1.1217 +
  1.1218 +        // find all the typefaces needed to resolve this run of text
  1.1219 +        bool usesOriginalTypeface = false;
  1.1220 +        for (uint16_t x = 0; x < numGlyphs; ++x) {
  1.1221 +            // optimization that checks to see if original typeface can resolve
  1.1222 +            // the glyph
  1.1223 +            if (glyphIDs[x] < origGlyphCount) {
  1.1224 +                usesOriginalTypeface = true;
  1.1225 +                continue;
  1.1226 +            }
  1.1227 +
  1.1228 +            // find the fallback typeface that supports this glyph
  1.1229 +            TypefaceFallbackData data;
  1.1230 +            data.typeface =
  1.1231 +                    SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
  1.1232 +                                            paint.getPaintOptionsAndroid(),
  1.1233 +                                            &data.lowerBounds,
  1.1234 +                                            &data.upperBounds);
  1.1235 +            // add the typeface and its data if we don't have it
  1.1236 +            if (data.typeface && !visitedTypefaces.contains(data)) {
  1.1237 +                visitedTypefaces.push(data);
  1.1238 +            }
  1.1239 +        }
  1.1240 +
  1.1241 +        // if the original font was used then add it to the list as well
  1.1242 +        if (usesOriginalTypeface) {
  1.1243 +            TypefaceFallbackData* data = visitedTypefaces.push();
  1.1244 +            data->typeface = origFace.get();
  1.1245 +            data->lowerBounds = 0;
  1.1246 +            data->upperBounds = origGlyphCount;
  1.1247 +        }
  1.1248 +
  1.1249 +        // keep a scratch glyph and pos storage
  1.1250 +        SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
  1.1251 +        SkScalar* tmpPos = posStorage.get();
  1.1252 +        SkGlyphStorage glyphStorage(numGlyphs);
  1.1253 +        uint16_t* tmpGlyphIDs = glyphStorage.get();
  1.1254 +
  1.1255 +        // loop through all the valid typefaces, trim the glyphs to only those
  1.1256 +        // resolved by the typeface, and then draw that run of glyphs
  1.1257 +        for (int x = 0; x < visitedTypefaces.count(); ++x) {
  1.1258 +            const TypefaceFallbackData& data = visitedTypefaces[x];
  1.1259 +
  1.1260 +            int tmpGlyphCount = 0;
  1.1261 +            for (uint16_t y = 0; y < numGlyphs; ++y) {
  1.1262 +                if (glyphIDs[y] >= data.lowerBounds &&
  1.1263 +                        glyphIDs[y] < data.upperBounds) {
  1.1264 +                    tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
  1.1265 +                    memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
  1.1266 +                           &(pos[y * scalarsPerPos]),
  1.1267 +                           scalarsPerPos * sizeof(SkScalar));
  1.1268 +                    tmpGlyphCount++;
  1.1269 +                }
  1.1270 +            }
  1.1271 +
  1.1272 +            // recursively call this function with the right typeface
  1.1273 +            SkPaint tmpPaint = paint;
  1.1274 +            tmpPaint.setTypeface(data.typeface);
  1.1275 +            tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
  1.1276 +
  1.1277 +            // turn off fallback chaining
  1.1278 +            SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
  1.1279 +            paintOpts.setUseFontFallbacks(false);
  1.1280 +            tmpPaint.setPaintOptionsAndroid(paintOpts);
  1.1281 +
  1.1282 +            this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
  1.1283 +                              scalarsPerPos, tmpPaint);
  1.1284 +        }
  1.1285 +        return;
  1.1286 +    }
  1.1287 +#endif
  1.1288 +
  1.1289 +    SkGlyphStorage storage(0);
  1.1290 +    uint16_t* glyphIDs = NULL;
  1.1291 +    size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
  1.1292 +                                            &glyphIDs);
  1.1293 +    textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
  1.1294 +
  1.1295 +    SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
  1.1296 +    content.entry()->fContent.writeText("BT\n");
  1.1297 +    updateFont(textPaint, glyphIDs[0], content.entry());
  1.1298 +    for (size_t i = 0; i < numGlyphs; i++) {
  1.1299 +        SkPDFFont* font = content.entry()->fState.fFont;
  1.1300 +        uint16_t encodedValue = glyphIDs[i];
  1.1301 +        if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
  1.1302 +            updateFont(textPaint, glyphIDs[i], content.entry());
  1.1303 +            i--;
  1.1304 +            continue;
  1.1305 +        }
  1.1306 +        fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
  1.1307 +        SkScalar x = pos[i * scalarsPerPos];
  1.1308 +        SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
  1.1309 +        align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
  1.1310 +        set_text_transform(x, y, textPaint.getTextSkewX(),
  1.1311 +                           &content.entry()->fContent);
  1.1312 +        SkString encodedString =
  1.1313 +            SkPDFString::FormatString(&encodedValue, 1,
  1.1314 +                                      font->multiByteGlyphs());
  1.1315 +        content.entry()->fContent.writeText(encodedString.c_str());
  1.1316 +        content.entry()->fContent.writeText(" Tj\n");
  1.1317 +    }
  1.1318 +    content.entry()->fContent.writeText("ET\n");
  1.1319 +}
  1.1320 +
  1.1321 +void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
  1.1322 +                                 const SkPath& path, const SkMatrix* matrix,
  1.1323 +                                 const SkPaint& paint) {
  1.1324 +    if (d.fClip->isEmpty()) {
  1.1325 +        return;
  1.1326 +    }
  1.1327 +    d.drawTextOnPath((const char*)text, len, path, matrix, paint);
  1.1328 +}
  1.1329 +
  1.1330 +void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
  1.1331 +                               int vertexCount, const SkPoint verts[],
  1.1332 +                               const SkPoint texs[], const SkColor colors[],
  1.1333 +                               SkXfermode* xmode, const uint16_t indices[],
  1.1334 +                               int indexCount, const SkPaint& paint) {
  1.1335 +    if (d.fClip->isEmpty()) {
  1.1336 +        return;
  1.1337 +    }
  1.1338 +    // TODO: implement drawVertices
  1.1339 +}
  1.1340 +
  1.1341 +void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
  1.1342 +                             int x, int y, const SkPaint& paint) {
  1.1343 +    // our onCreateDevice() always creates SkPDFDevice subclasses.
  1.1344 +    SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
  1.1345 +    if (pdfDevice->isContentEmpty()) {
  1.1346 +        return;
  1.1347 +    }
  1.1348 +
  1.1349 +    SkMatrix matrix;
  1.1350 +    matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
  1.1351 +    ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
  1.1352 +    if (!content.entry()) {
  1.1353 +        return;
  1.1354 +    }
  1.1355 +    if (content.needShape()) {
  1.1356 +        SkPath shape;
  1.1357 +        shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
  1.1358 +                                       SkIntToScalar(device->width()),
  1.1359 +                                       SkIntToScalar(device->height())));
  1.1360 +        content.setShape(shape);
  1.1361 +    }
  1.1362 +    if (!content.needSource()) {
  1.1363 +        return;
  1.1364 +    }
  1.1365 +
  1.1366 +    SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
  1.1367 +    SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
  1.1368 +                                &content.entry()->fContent);
  1.1369 +
  1.1370 +    // Merge glyph sets from the drawn device.
  1.1371 +    fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
  1.1372 +}
  1.1373 +
  1.1374 +void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
  1.1375 +    INHERITED::onAttachToCanvas(canvas);
  1.1376 +
  1.1377 +    // Canvas promises that this ptr is valid until onDetachFromCanvas is called
  1.1378 +    fClipStack = canvas->getClipStack();
  1.1379 +}
  1.1380 +
  1.1381 +void SkPDFDevice::onDetachFromCanvas() {
  1.1382 +    INHERITED::onDetachFromCanvas();
  1.1383 +
  1.1384 +    fClipStack = NULL;
  1.1385 +}
  1.1386 +
  1.1387 +ContentEntry* SkPDFDevice::getLastContentEntry() {
  1.1388 +    if (fDrawingArea == kContent_DrawingArea) {
  1.1389 +        return fLastContentEntry;
  1.1390 +    } else {
  1.1391 +        return fLastMarginContentEntry;
  1.1392 +    }
  1.1393 +}
  1.1394 +
  1.1395 +SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
  1.1396 +    if (fDrawingArea == kContent_DrawingArea) {
  1.1397 +        return &fContentEntries;
  1.1398 +    } else {
  1.1399 +        return &fMarginContentEntries;
  1.1400 +    }
  1.1401 +}
  1.1402 +
  1.1403 +void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
  1.1404 +    if (fDrawingArea == kContent_DrawingArea) {
  1.1405 +        fLastContentEntry = contentEntry;
  1.1406 +    } else {
  1.1407 +        fLastMarginContentEntry = contentEntry;
  1.1408 +    }
  1.1409 +}
  1.1410 +
  1.1411 +void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
  1.1412 +    // A ScopedContentEntry only exists during the course of a draw call, so
  1.1413 +    // this can't be called while a ScopedContentEntry exists.
  1.1414 +    fDrawingArea = drawingArea;
  1.1415 +}
  1.1416 +
  1.1417 +SkPDFResourceDict* SkPDFDevice::getResourceDict() {
  1.1418 +    if (NULL == fResourceDict) {
  1.1419 +        fResourceDict = SkNEW(SkPDFResourceDict);
  1.1420 +
  1.1421 +        if (fGraphicStateResources.count()) {
  1.1422 +            for (int i = 0; i < fGraphicStateResources.count(); i++) {
  1.1423 +                fResourceDict->insertResourceAsReference(
  1.1424 +                        SkPDFResourceDict::kExtGState_ResourceType,
  1.1425 +                        i, fGraphicStateResources[i]);
  1.1426 +            }
  1.1427 +        }
  1.1428 +
  1.1429 +        if (fXObjectResources.count()) {
  1.1430 +            for (int i = 0; i < fXObjectResources.count(); i++) {
  1.1431 +                fResourceDict->insertResourceAsReference(
  1.1432 +                        SkPDFResourceDict::kXObject_ResourceType,
  1.1433 +                        i, fXObjectResources[i]);
  1.1434 +            }
  1.1435 +        }
  1.1436 +
  1.1437 +        if (fFontResources.count()) {
  1.1438 +            for (int i = 0; i < fFontResources.count(); i++) {
  1.1439 +                fResourceDict->insertResourceAsReference(
  1.1440 +                        SkPDFResourceDict::kFont_ResourceType,
  1.1441 +                        i, fFontResources[i]);
  1.1442 +            }
  1.1443 +        }
  1.1444 +
  1.1445 +        if (fShaderResources.count()) {
  1.1446 +            SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
  1.1447 +            for (int i = 0; i < fShaderResources.count(); i++) {
  1.1448 +                fResourceDict->insertResourceAsReference(
  1.1449 +                        SkPDFResourceDict::kPattern_ResourceType,
  1.1450 +                        i, fShaderResources[i]);
  1.1451 +            }
  1.1452 +        }
  1.1453 +    }
  1.1454 +    return fResourceDict;
  1.1455 +}
  1.1456 +
  1.1457 +const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
  1.1458 +    return fFontResources;
  1.1459 +}
  1.1460 +
  1.1461 +SkPDFArray* SkPDFDevice::copyMediaBox() const {
  1.1462 +    // should this be a singleton?
  1.1463 +    SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
  1.1464 +
  1.1465 +    SkPDFArray* mediaBox = SkNEW(SkPDFArray);
  1.1466 +    mediaBox->reserve(4);
  1.1467 +    mediaBox->append(zero.get());
  1.1468 +    mediaBox->append(zero.get());
  1.1469 +    mediaBox->appendInt(fPageSize.fWidth);
  1.1470 +    mediaBox->appendInt(fPageSize.fHeight);
  1.1471 +    return mediaBox;
  1.1472 +}
  1.1473 +
  1.1474 +SkStream* SkPDFDevice::content() const {
  1.1475 +    SkMemoryStream* result = new SkMemoryStream;
  1.1476 +    result->setData(this->copyContentToData())->unref();
  1.1477 +    return result;
  1.1478 +}
  1.1479 +
  1.1480 +void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
  1.1481 +        SkWStream* data) const {
  1.1482 +    // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
  1.1483 +    // right thing to pass here.
  1.1484 +    GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
  1.1485 +    while (entry != NULL) {
  1.1486 +        SkPoint translation;
  1.1487 +        translation.iset(this->getOrigin());
  1.1488 +        translation.negate();
  1.1489 +        gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
  1.1490 +                           translation);
  1.1491 +        gsState.updateMatrix(entry->fState.fMatrix);
  1.1492 +        gsState.updateDrawingState(entry->fState);
  1.1493 +
  1.1494 +        SkAutoDataUnref copy(entry->fContent.copyToData());
  1.1495 +        data->write(copy->data(), copy->size());
  1.1496 +        entry = entry->fNext.get();
  1.1497 +    }
  1.1498 +    gsState.drainStack();
  1.1499 +}
  1.1500 +
  1.1501 +SkData* SkPDFDevice::copyContentToData() const {
  1.1502 +    SkDynamicMemoryWStream data;
  1.1503 +    if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
  1.1504 +        SkPDFUtils::AppendTransform(fInitialTransform, &data);
  1.1505 +    }
  1.1506 +
  1.1507 +    // TODO(aayushkumar): Apply clip along the margins.  Currently, webkit
  1.1508 +    // colors the contentArea white before it starts drawing into it and
  1.1509 +    // that currently acts as our clip.
  1.1510 +    // Also, think about adding a transform here (or assume that the values
  1.1511 +    // sent across account for that)
  1.1512 +    SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
  1.1513 +
  1.1514 +    // If the content area is the entire page, then we don't need to clip
  1.1515 +    // the content area (PDF area clips to the page size).  Otherwise,
  1.1516 +    // we have to clip to the content area; we've already applied the
  1.1517 +    // initial transform, so just clip to the device size.
  1.1518 +    if (fPageSize != fContentSize) {
  1.1519 +        SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
  1.1520 +                                  SkIntToScalar(this->height()));
  1.1521 +        emit_clip(NULL, &r, &data);
  1.1522 +    }
  1.1523 +
  1.1524 +    SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
  1.1525 +
  1.1526 +    // potentially we could cache this SkData, and only rebuild it if we
  1.1527 +    // see that our state has changed.
  1.1528 +    return data.copyToData();
  1.1529 +}
  1.1530 +
  1.1531 +#ifdef SK_PDF_USE_PATHOPS
  1.1532 +/* Draws an inverse filled path by using Path Ops to compute the positive
  1.1533 + * inverse using the current clip as the inverse bounds.
  1.1534 + * Return true if this was an inverse path and was properly handled,
  1.1535 + * otherwise returns false and the normal drawing routine should continue,
  1.1536 + * either as a (incorrect) fallback or because the path was not inverse
  1.1537 + * in the first place.
  1.1538 + */
  1.1539 +bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
  1.1540 +                                    const SkPaint& paint, bool pathIsMutable,
  1.1541 +                                    const SkMatrix* prePathMatrix) {
  1.1542 +    if (!origPath.isInverseFillType()) {
  1.1543 +        return false;
  1.1544 +    }
  1.1545 +
  1.1546 +    if (d.fClip->isEmpty()) {
  1.1547 +        return false;
  1.1548 +    }
  1.1549 +
  1.1550 +    SkPath modifiedPath;
  1.1551 +    SkPath* pathPtr = const_cast<SkPath*>(&origPath);
  1.1552 +    SkPaint noInversePaint(paint);
  1.1553 +
  1.1554 +    // Merge stroking operations into final path.
  1.1555 +    if (SkPaint::kStroke_Style == paint.getStyle() ||
  1.1556 +        SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
  1.1557 +        bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
  1.1558 +        if (doFillPath) {
  1.1559 +            noInversePaint.setStyle(SkPaint::kFill_Style);
  1.1560 +            noInversePaint.setStrokeWidth(0);
  1.1561 +            pathPtr = &modifiedPath;
  1.1562 +        } else {
  1.1563 +            // To be consistent with the raster output, hairline strokes
  1.1564 +            // are rendered as non-inverted.
  1.1565 +            modifiedPath.toggleInverseFillType();
  1.1566 +            drawPath(d, modifiedPath, paint, NULL, true);
  1.1567 +            return true;
  1.1568 +        }
  1.1569 +    }
  1.1570 +
  1.1571 +    // Get bounds of clip in current transform space
  1.1572 +    // (clip bounds are given in device space).
  1.1573 +    SkRect bounds;
  1.1574 +    SkMatrix transformInverse;
  1.1575 +    SkMatrix totalMatrix = *d.fMatrix;
  1.1576 +    if (prePathMatrix) {
  1.1577 +        totalMatrix.preConcat(*prePathMatrix);
  1.1578 +    }
  1.1579 +    if (!totalMatrix.invert(&transformInverse)) {
  1.1580 +        return false;
  1.1581 +    }
  1.1582 +    bounds.set(d.fClip->getBounds());
  1.1583 +    transformInverse.mapRect(&bounds);
  1.1584 +
  1.1585 +    // Extend the bounds by the line width (plus some padding)
  1.1586 +    // so the edge doesn't cause a visible stroke.
  1.1587 +    bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
  1.1588 +                  paint.getStrokeWidth() + SK_Scalar1);
  1.1589 +
  1.1590 +    if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
  1.1591 +        return false;
  1.1592 +    }
  1.1593 +
  1.1594 +    drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
  1.1595 +    return true;
  1.1596 +}
  1.1597 +#endif
  1.1598 +
  1.1599 +bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
  1.1600 +                                       const SkPaint& p) {
  1.1601 +    SkAnnotation* annotationInfo = p.getAnnotation();
  1.1602 +    if (!annotationInfo) {
  1.1603 +        return false;
  1.1604 +    }
  1.1605 +    SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
  1.1606 +    if (urlData) {
  1.1607 +        handleLinkToURL(urlData, r, matrix);
  1.1608 +        return p.getAnnotation() != NULL;
  1.1609 +    }
  1.1610 +    SkData* linkToName = annotationInfo->find(
  1.1611 +            SkAnnotationKeys::Link_Named_Dest_Key());
  1.1612 +    if (linkToName) {
  1.1613 +        handleLinkToNamedDest(linkToName, r, matrix);
  1.1614 +        return p.getAnnotation() != NULL;
  1.1615 +    }
  1.1616 +    return false;
  1.1617 +}
  1.1618 +
  1.1619 +bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
  1.1620 +                                        const SkMatrix& matrix,
  1.1621 +                                        const SkPaint& paint) {
  1.1622 +    SkAnnotation* annotationInfo = paint.getAnnotation();
  1.1623 +    if (!annotationInfo) {
  1.1624 +        return false;
  1.1625 +    }
  1.1626 +    SkData* nameData = annotationInfo->find(
  1.1627 +            SkAnnotationKeys::Define_Named_Dest_Key());
  1.1628 +    if (nameData) {
  1.1629 +        for (size_t i = 0; i < count; i++) {
  1.1630 +            defineNamedDestination(nameData, points[i], matrix);
  1.1631 +        }
  1.1632 +        return paint.getAnnotation() != NULL;
  1.1633 +    }
  1.1634 +    return false;
  1.1635 +}
  1.1636 +
  1.1637 +SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
  1.1638 +                                             const SkMatrix& matrix) {
  1.1639 +    SkMatrix transform = matrix;
  1.1640 +    transform.postConcat(fInitialTransform);
  1.1641 +    SkRect translatedRect;
  1.1642 +    transform.mapRect(&translatedRect, r);
  1.1643 +
  1.1644 +    if (NULL == fAnnotations) {
  1.1645 +        fAnnotations = SkNEW(SkPDFArray);
  1.1646 +    }
  1.1647 +    SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
  1.1648 +    annotation->insertName("Subtype", "Link");
  1.1649 +    fAnnotations->append(annotation);
  1.1650 +
  1.1651 +    SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
  1.1652 +    border->reserve(3);
  1.1653 +    border->appendInt(0);  // Horizontal corner radius.
  1.1654 +    border->appendInt(0);  // Vertical corner radius.
  1.1655 +    border->appendInt(0);  // Width, 0 = no border.
  1.1656 +    annotation->insert("Border", border.get());
  1.1657 +
  1.1658 +    SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
  1.1659 +    rect->reserve(4);
  1.1660 +    rect->appendScalar(translatedRect.fLeft);
  1.1661 +    rect->appendScalar(translatedRect.fTop);
  1.1662 +    rect->appendScalar(translatedRect.fRight);
  1.1663 +    rect->appendScalar(translatedRect.fBottom);
  1.1664 +    annotation->insert("Rect", rect.get());
  1.1665 +
  1.1666 +    return annotation;
  1.1667 +}
  1.1668 +
  1.1669 +void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
  1.1670 +                                  const SkMatrix& matrix) {
  1.1671 +    SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
  1.1672 +
  1.1673 +    SkString url(static_cast<const char *>(urlData->data()),
  1.1674 +                 urlData->size() - 1);
  1.1675 +    SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
  1.1676 +    action->insertName("S", "URI");
  1.1677 +    action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
  1.1678 +    annotation->insert("A", action.get());
  1.1679 +}
  1.1680 +
  1.1681 +void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
  1.1682 +                                        const SkMatrix& matrix) {
  1.1683 +    SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
  1.1684 +    SkString name(static_cast<const char *>(nameData->data()),
  1.1685 +                  nameData->size() - 1);
  1.1686 +    annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
  1.1687 +}
  1.1688 +
  1.1689 +struct NamedDestination {
  1.1690 +    const SkData* nameData;
  1.1691 +    SkPoint point;
  1.1692 +
  1.1693 +    NamedDestination(const SkData* nameData, const SkPoint& point)
  1.1694 +        : nameData(nameData), point(point) {
  1.1695 +        nameData->ref();
  1.1696 +    }
  1.1697 +
  1.1698 +    ~NamedDestination() {
  1.1699 +        nameData->unref();
  1.1700 +    }
  1.1701 +};
  1.1702 +
  1.1703 +void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
  1.1704 +                                         const SkMatrix& matrix) {
  1.1705 +    SkMatrix transform = matrix;
  1.1706 +    transform.postConcat(fInitialTransform);
  1.1707 +    SkPoint translatedPoint;
  1.1708 +    transform.mapXY(point.x(), point.y(), &translatedPoint);
  1.1709 +    fNamedDestinations.push(
  1.1710 +        SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
  1.1711 +}
  1.1712 +
  1.1713 +void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
  1.1714 +    int nDest = fNamedDestinations.count();
  1.1715 +    for (int i = 0; i < nDest; i++) {
  1.1716 +        NamedDestination* dest = fNamedDestinations[i];
  1.1717 +        SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
  1.1718 +        pdfDest->reserve(5);
  1.1719 +        pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
  1.1720 +        pdfDest->appendName("XYZ");
  1.1721 +        pdfDest->appendScalar(dest->point.x());
  1.1722 +        pdfDest->appendScalar(dest->point.y());
  1.1723 +        pdfDest->appendInt(0);  // Leave zoom unchanged
  1.1724 +        dict->insert(static_cast<const char *>(dest->nameData->data()),
  1.1725 +                     pdfDest);
  1.1726 +    }
  1.1727 +}
  1.1728 +
  1.1729 +SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
  1.1730 +    SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
  1.1731 +    // We always draw the form xobjects that we create back into the device, so
  1.1732 +    // we simply preserve the font usage instead of pulling it out and merging
  1.1733 +    // it back in later.
  1.1734 +    cleanUp(false);  // Reset this device to have no content.
  1.1735 +    init();
  1.1736 +    return xobject;
  1.1737 +}
  1.1738 +
  1.1739 +void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
  1.1740 +                                          SkPDFFormXObject* mask,
  1.1741 +                                          const SkClipStack* clipStack,
  1.1742 +                                          const SkRegion& clipRegion,
  1.1743 +                                          SkXfermode::Mode mode,
  1.1744 +                                          bool invertClip) {
  1.1745 +    if (clipRegion.isEmpty() && !invertClip) {
  1.1746 +        return;
  1.1747 +    }
  1.1748 +
  1.1749 +    SkAutoTUnref<SkPDFGraphicState> sMaskGS(
  1.1750 +        SkPDFGraphicState::GetSMaskGraphicState(
  1.1751 +            mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
  1.1752 +
  1.1753 +    SkMatrix identity;
  1.1754 +    identity.reset();
  1.1755 +    SkPaint paint;
  1.1756 +    paint.setXfermodeMode(mode);
  1.1757 +    ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
  1.1758 +    if (!content.entry()) {
  1.1759 +        return;
  1.1760 +    }
  1.1761 +    SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
  1.1762 +                                  &content.entry()->fContent);
  1.1763 +    SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
  1.1764 +
  1.1765 +    sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
  1.1766 +    SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
  1.1767 +                                  &content.entry()->fContent);
  1.1768 +}
  1.1769 +
  1.1770 +ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
  1.1771 +                                             const SkRegion& clipRegion,
  1.1772 +                                             const SkMatrix& matrix,
  1.1773 +                                             const SkPaint& paint,
  1.1774 +                                             bool hasText,
  1.1775 +                                             SkPDFFormXObject** dst) {
  1.1776 +    *dst = NULL;
  1.1777 +    if (clipRegion.isEmpty()) {
  1.1778 +        return NULL;
  1.1779 +    }
  1.1780 +
  1.1781 +    // The clip stack can come from an SkDraw where it is technically optional.
  1.1782 +    SkClipStack synthesizedClipStack;
  1.1783 +    if (clipStack == NULL) {
  1.1784 +        if (clipRegion == fExistingClipRegion) {
  1.1785 +            clipStack = &fExistingClipStack;
  1.1786 +        } else {
  1.1787 +            // GraphicStackState::updateClip expects the clip stack to have
  1.1788 +            // fExistingClip as a prefix, so start there, then set the clip
  1.1789 +            // to the passed region.
  1.1790 +            synthesizedClipStack = fExistingClipStack;
  1.1791 +            SkPath clipPath;
  1.1792 +            clipRegion.getBoundaryPath(&clipPath);
  1.1793 +            synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
  1.1794 +                                             false);
  1.1795 +            clipStack = &synthesizedClipStack;
  1.1796 +        }
  1.1797 +    }
  1.1798 +
  1.1799 +    SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
  1.1800 +    if (paint.getXfermode()) {
  1.1801 +        paint.getXfermode()->asMode(&xfermode);
  1.1802 +    }
  1.1803 +
  1.1804 +    // For the following modes, we want to handle source and destination
  1.1805 +    // separately, so make an object of what's already there.
  1.1806 +    if (xfermode == SkXfermode::kClear_Mode       ||
  1.1807 +            xfermode == SkXfermode::kSrc_Mode     ||
  1.1808 +            xfermode == SkXfermode::kSrcIn_Mode   ||
  1.1809 +            xfermode == SkXfermode::kDstIn_Mode   ||
  1.1810 +            xfermode == SkXfermode::kSrcOut_Mode  ||
  1.1811 +            xfermode == SkXfermode::kDstOut_Mode  ||
  1.1812 +            xfermode == SkXfermode::kSrcATop_Mode ||
  1.1813 +            xfermode == SkXfermode::kDstATop_Mode ||
  1.1814 +            xfermode == SkXfermode::kModulate_Mode) {
  1.1815 +        if (!isContentEmpty()) {
  1.1816 +            *dst = createFormXObjectFromDevice();
  1.1817 +            SkASSERT(isContentEmpty());
  1.1818 +        } else if (xfermode != SkXfermode::kSrc_Mode &&
  1.1819 +                   xfermode != SkXfermode::kSrcOut_Mode) {
  1.1820 +            // Except for Src and SrcOut, if there isn't anything already there,
  1.1821 +            // then we're done.
  1.1822 +            return NULL;
  1.1823 +        }
  1.1824 +    }
  1.1825 +    // TODO(vandebo): Figure out how/if we can handle the following modes:
  1.1826 +    // Xor, Plus.
  1.1827 +
  1.1828 +    // Dst xfer mode doesn't draw source at all.
  1.1829 +    if (xfermode == SkXfermode::kDst_Mode) {
  1.1830 +        return NULL;
  1.1831 +    }
  1.1832 +
  1.1833 +    ContentEntry* entry;
  1.1834 +    SkAutoTDelete<ContentEntry> newEntry;
  1.1835 +
  1.1836 +    ContentEntry* lastContentEntry = getLastContentEntry();
  1.1837 +    if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
  1.1838 +        entry = lastContentEntry;
  1.1839 +    } else {
  1.1840 +        newEntry.reset(new ContentEntry);
  1.1841 +        entry = newEntry.get();
  1.1842 +    }
  1.1843 +
  1.1844 +    populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
  1.1845 +                                       hasText, &entry->fState);
  1.1846 +    if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
  1.1847 +            entry->fState.compareInitialState(lastContentEntry->fState)) {
  1.1848 +        return lastContentEntry;
  1.1849 +    }
  1.1850 +
  1.1851 +    SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
  1.1852 +    if (!lastContentEntry) {
  1.1853 +        contentEntries->reset(entry);
  1.1854 +        setLastContentEntry(entry);
  1.1855 +    } else if (xfermode == SkXfermode::kDstOver_Mode) {
  1.1856 +        entry->fNext.reset(contentEntries->detach());
  1.1857 +        contentEntries->reset(entry);
  1.1858 +    } else {
  1.1859 +        lastContentEntry->fNext.reset(entry);
  1.1860 +        setLastContentEntry(entry);
  1.1861 +    }
  1.1862 +    newEntry.detach();
  1.1863 +    return entry;
  1.1864 +}
  1.1865 +
  1.1866 +void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
  1.1867 +                                     SkPDFFormXObject* dst,
  1.1868 +                                     SkPath* shape) {
  1.1869 +    if (xfermode != SkXfermode::kClear_Mode       &&
  1.1870 +            xfermode != SkXfermode::kSrc_Mode     &&
  1.1871 +            xfermode != SkXfermode::kDstOver_Mode &&
  1.1872 +            xfermode != SkXfermode::kSrcIn_Mode   &&
  1.1873 +            xfermode != SkXfermode::kDstIn_Mode   &&
  1.1874 +            xfermode != SkXfermode::kSrcOut_Mode  &&
  1.1875 +            xfermode != SkXfermode::kDstOut_Mode  &&
  1.1876 +            xfermode != SkXfermode::kSrcATop_Mode &&
  1.1877 +            xfermode != SkXfermode::kDstATop_Mode &&
  1.1878 +            xfermode != SkXfermode::kModulate_Mode) {
  1.1879 +        SkASSERT(!dst);
  1.1880 +        return;
  1.1881 +    }
  1.1882 +    if (xfermode == SkXfermode::kDstOver_Mode) {
  1.1883 +        SkASSERT(!dst);
  1.1884 +        ContentEntry* firstContentEntry = getContentEntries()->get();
  1.1885 +        if (firstContentEntry->fContent.getOffset() == 0) {
  1.1886 +            // For DstOver, an empty content entry was inserted before the rest
  1.1887 +            // of the content entries. If nothing was drawn, it needs to be
  1.1888 +            // removed.
  1.1889 +            SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
  1.1890 +            contentEntries->reset(firstContentEntry->fNext.detach());
  1.1891 +        }
  1.1892 +        return;
  1.1893 +    }
  1.1894 +    if (!dst) {
  1.1895 +        SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
  1.1896 +                 xfermode == SkXfermode::kSrcOut_Mode);
  1.1897 +        return;
  1.1898 +    }
  1.1899 +
  1.1900 +    ContentEntry* contentEntries = getContentEntries()->get();
  1.1901 +    SkASSERT(dst);
  1.1902 +    SkASSERT(!contentEntries->fNext.get());
  1.1903 +    // Changing the current content into a form-xobject will destroy the clip
  1.1904 +    // objects which is fine since the xobject will already be clipped. However
  1.1905 +    // if source has shape, we need to clip it too, so a copy of the clip is
  1.1906 +    // saved.
  1.1907 +    SkClipStack clipStack = contentEntries->fState.fClipStack;
  1.1908 +    SkRegion clipRegion = contentEntries->fState.fClipRegion;
  1.1909 +
  1.1910 +    SkMatrix identity;
  1.1911 +    identity.reset();
  1.1912 +    SkPaint stockPaint;
  1.1913 +
  1.1914 +    SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
  1.1915 +    if (isContentEmpty()) {
  1.1916 +        // If nothing was drawn and there's no shape, then the draw was a
  1.1917 +        // no-op, but dst needs to be restored for that to be true.
  1.1918 +        // If there is shape, then an empty source with Src, SrcIn, SrcOut,
  1.1919 +        // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
  1.1920 +        // reduces to Dst.
  1.1921 +        if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
  1.1922 +                xfermode == SkXfermode::kSrcATop_Mode) {
  1.1923 +            ScopedContentEntry content(this, &fExistingClipStack,
  1.1924 +                                       fExistingClipRegion, identity,
  1.1925 +                                       stockPaint);
  1.1926 +            SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
  1.1927 +                                        &content.entry()->fContent);
  1.1928 +            return;
  1.1929 +        } else {
  1.1930 +            xfermode = SkXfermode::kClear_Mode;
  1.1931 +        }
  1.1932 +    } else {
  1.1933 +        SkASSERT(!fContentEntries->fNext.get());
  1.1934 +        srcFormXObject.reset(createFormXObjectFromDevice());
  1.1935 +    }
  1.1936 +
  1.1937 +    // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
  1.1938 +    // without alpha.
  1.1939 +    if (xfermode == SkXfermode::kSrcATop_Mode) {
  1.1940 +        // TODO(vandebo): In order to properly support SrcATop we have to track
  1.1941 +        // the shape of what's been drawn at all times. It's the intersection of
  1.1942 +        // the non-transparent parts of the device and the outlines (shape) of
  1.1943 +        // all images and devices drawn.
  1.1944 +        drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
  1.1945 +                                &fExistingClipStack, fExistingClipRegion,
  1.1946 +                                SkXfermode::kSrcOver_Mode, true);
  1.1947 +    } else {
  1.1948 +        SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
  1.1949 +        SkPDFFormXObject* dstMask = srcFormXObject.get();
  1.1950 +        if (shape != NULL) {
  1.1951 +            // Draw shape into a form-xobject.
  1.1952 +            SkDraw d;
  1.1953 +            d.fMatrix = &identity;
  1.1954 +            d.fClip = &clipRegion;
  1.1955 +            d.fClipStack = &clipStack;
  1.1956 +            SkPaint filledPaint;
  1.1957 +            filledPaint.setColor(SK_ColorBLACK);
  1.1958 +            filledPaint.setStyle(SkPaint::kFill_Style);
  1.1959 +            this->drawPath(d, *shape, filledPaint, NULL, true);
  1.1960 +
  1.1961 +            dstMaskStorage.reset(createFormXObjectFromDevice());
  1.1962 +            dstMask = dstMaskStorage.get();
  1.1963 +        }
  1.1964 +        drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
  1.1965 +                                &fExistingClipStack, fExistingClipRegion,
  1.1966 +                                SkXfermode::kSrcOver_Mode, true);
  1.1967 +    }
  1.1968 +
  1.1969 +    if (xfermode == SkXfermode::kClear_Mode) {
  1.1970 +        return;
  1.1971 +    } else if (xfermode == SkXfermode::kSrc_Mode ||
  1.1972 +            xfermode == SkXfermode::kDstATop_Mode) {
  1.1973 +        ScopedContentEntry content(this, &fExistingClipStack,
  1.1974 +                                   fExistingClipRegion, identity, stockPaint);
  1.1975 +        if (content.entry()) {
  1.1976 +            SkPDFUtils::DrawFormXObject(
  1.1977 +                    this->addXObjectResource(srcFormXObject.get()),
  1.1978 +                    &content.entry()->fContent);
  1.1979 +        }
  1.1980 +        if (xfermode == SkXfermode::kSrc_Mode) {
  1.1981 +            return;
  1.1982 +        }
  1.1983 +    } else if (xfermode == SkXfermode::kSrcATop_Mode) {
  1.1984 +        ScopedContentEntry content(this, &fExistingClipStack,
  1.1985 +                                   fExistingClipRegion, identity, stockPaint);
  1.1986 +        if (content.entry()) {
  1.1987 +            SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
  1.1988 +                                        &content.entry()->fContent);
  1.1989 +        }
  1.1990 +    }
  1.1991 +
  1.1992 +    SkASSERT(xfermode == SkXfermode::kSrcIn_Mode   ||
  1.1993 +             xfermode == SkXfermode::kDstIn_Mode   ||
  1.1994 +             xfermode == SkXfermode::kSrcOut_Mode  ||
  1.1995 +             xfermode == SkXfermode::kDstOut_Mode  ||
  1.1996 +             xfermode == SkXfermode::kSrcATop_Mode ||
  1.1997 +             xfermode == SkXfermode::kDstATop_Mode ||
  1.1998 +             xfermode == SkXfermode::kModulate_Mode);
  1.1999 +
  1.2000 +    if (xfermode == SkXfermode::kSrcIn_Mode ||
  1.2001 +            xfermode == SkXfermode::kSrcOut_Mode ||
  1.2002 +            xfermode == SkXfermode::kSrcATop_Mode) {
  1.2003 +        drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
  1.2004 +                                &fExistingClipStack, fExistingClipRegion,
  1.2005 +                                SkXfermode::kSrcOver_Mode,
  1.2006 +                                xfermode == SkXfermode::kSrcOut_Mode);
  1.2007 +    } else {
  1.2008 +        SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
  1.2009 +        if (xfermode == SkXfermode::kModulate_Mode) {
  1.2010 +            drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
  1.2011 +                                    dst, &fExistingClipStack,
  1.2012 +                                    fExistingClipRegion,
  1.2013 +                                    SkXfermode::kSrcOver_Mode, false);
  1.2014 +            mode = SkXfermode::kMultiply_Mode;
  1.2015 +        }
  1.2016 +        drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
  1.2017 +                                &fExistingClipStack, fExistingClipRegion, mode,
  1.2018 +                                xfermode == SkXfermode::kDstOut_Mode);
  1.2019 +    }
  1.2020 +}
  1.2021 +
  1.2022 +bool SkPDFDevice::isContentEmpty() {
  1.2023 +    ContentEntry* contentEntries = getContentEntries()->get();
  1.2024 +    if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
  1.2025 +        SkASSERT(!contentEntries || !contentEntries->fNext.get());
  1.2026 +        return true;
  1.2027 +    }
  1.2028 +    return false;
  1.2029 +}
  1.2030 +
  1.2031 +void SkPDFDevice::populateGraphicStateEntryFromPaint(
  1.2032 +        const SkMatrix& matrix,
  1.2033 +        const SkClipStack& clipStack,
  1.2034 +        const SkRegion& clipRegion,
  1.2035 +        const SkPaint& paint,
  1.2036 +        bool hasText,
  1.2037 +        GraphicStateEntry* entry) {
  1.2038 +    SkASSERT(paint.getPathEffect() == NULL);
  1.2039 +
  1.2040 +    NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
  1.2041 +    NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
  1.2042 +
  1.2043 +    entry->fMatrix = matrix;
  1.2044 +    entry->fClipStack = clipStack;
  1.2045 +    entry->fClipRegion = clipRegion;
  1.2046 +    entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
  1.2047 +    entry->fShaderIndex = -1;
  1.2048 +
  1.2049 +    // PDF treats a shader as a color, so we only set one or the other.
  1.2050 +    SkAutoTUnref<SkPDFObject> pdfShader;
  1.2051 +    const SkShader* shader = paint.getShader();
  1.2052 +    SkColor color = paint.getColor();
  1.2053 +    if (shader) {
  1.2054 +        // PDF positions patterns relative to the initial transform, so
  1.2055 +        // we need to apply the current transform to the shader parameters.
  1.2056 +        SkMatrix transform = matrix;
  1.2057 +        transform.postConcat(fInitialTransform);
  1.2058 +
  1.2059 +        // PDF doesn't support kClamp_TileMode, so we simulate it by making
  1.2060 +        // a pattern the size of the current clip.
  1.2061 +        SkIRect bounds = clipRegion.getBounds();
  1.2062 +
  1.2063 +        // We need to apply the initial transform to bounds in order to get
  1.2064 +        // bounds in a consistent coordinate system.
  1.2065 +        SkRect boundsTemp;
  1.2066 +        boundsTemp.set(bounds);
  1.2067 +        fInitialTransform.mapRect(&boundsTemp);
  1.2068 +        boundsTemp.roundOut(&bounds);
  1.2069 +
  1.2070 +        pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
  1.2071 +
  1.2072 +        if (pdfShader.get()) {
  1.2073 +            // pdfShader has been canonicalized so we can directly compare
  1.2074 +            // pointers.
  1.2075 +            int resourceIndex = fShaderResources.find(pdfShader.get());
  1.2076 +            if (resourceIndex < 0) {
  1.2077 +                resourceIndex = fShaderResources.count();
  1.2078 +                fShaderResources.push(pdfShader.get());
  1.2079 +                pdfShader.get()->ref();
  1.2080 +            }
  1.2081 +            entry->fShaderIndex = resourceIndex;
  1.2082 +        } else {
  1.2083 +            // A color shader is treated as an invalid shader so we don't have
  1.2084 +            // to set a shader just for a color.
  1.2085 +            SkShader::GradientInfo gradientInfo;
  1.2086 +            SkColor gradientColor;
  1.2087 +            gradientInfo.fColors = &gradientColor;
  1.2088 +            gradientInfo.fColorOffsets = NULL;
  1.2089 +            gradientInfo.fColorCount = 1;
  1.2090 +            if (shader->asAGradient(&gradientInfo) ==
  1.2091 +                    SkShader::kColor_GradientType) {
  1.2092 +                entry->fColor = SkColorSetA(gradientColor, 0xFF);
  1.2093 +                color = gradientColor;
  1.2094 +            }
  1.2095 +        }
  1.2096 +    }
  1.2097 +
  1.2098 +    SkAutoTUnref<SkPDFGraphicState> newGraphicState;
  1.2099 +    if (color == paint.getColor()) {
  1.2100 +        newGraphicState.reset(
  1.2101 +                SkPDFGraphicState::GetGraphicStateForPaint(paint));
  1.2102 +    } else {
  1.2103 +        SkPaint newPaint = paint;
  1.2104 +        newPaint.setColor(color);
  1.2105 +        newGraphicState.reset(
  1.2106 +                SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
  1.2107 +    }
  1.2108 +    int resourceIndex = addGraphicStateResource(newGraphicState.get());
  1.2109 +    entry->fGraphicStateIndex = resourceIndex;
  1.2110 +
  1.2111 +    if (hasText) {
  1.2112 +        entry->fTextScaleX = paint.getTextScaleX();
  1.2113 +        entry->fTextFill = paint.getStyle();
  1.2114 +    } else {
  1.2115 +        entry->fTextScaleX = 0;
  1.2116 +    }
  1.2117 +}
  1.2118 +
  1.2119 +int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
  1.2120 +    // Assumes that gs has been canonicalized (so we can directly compare
  1.2121 +    // pointers).
  1.2122 +    int result = fGraphicStateResources.find(gs);
  1.2123 +    if (result < 0) {
  1.2124 +        result = fGraphicStateResources.count();
  1.2125 +        fGraphicStateResources.push(gs);
  1.2126 +        gs->ref();
  1.2127 +    }
  1.2128 +    return result;
  1.2129 +}
  1.2130 +
  1.2131 +int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
  1.2132 +    // Assumes that xobject has been canonicalized (so we can directly compare
  1.2133 +    // pointers).
  1.2134 +    int result = fXObjectResources.find(xObject);
  1.2135 +    if (result < 0) {
  1.2136 +        result = fXObjectResources.count();
  1.2137 +        fXObjectResources.push(xObject);
  1.2138 +        xObject->ref();
  1.2139 +    }
  1.2140 +    return result;
  1.2141 +}
  1.2142 +
  1.2143 +void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
  1.2144 +                             ContentEntry* contentEntry) {
  1.2145 +    SkTypeface* typeface = paint.getTypeface();
  1.2146 +    if (contentEntry->fState.fFont == NULL ||
  1.2147 +            contentEntry->fState.fTextSize != paint.getTextSize() ||
  1.2148 +            !contentEntry->fState.fFont->hasGlyph(glyphID)) {
  1.2149 +        int fontIndex = getFontResourceIndex(typeface, glyphID);
  1.2150 +        contentEntry->fContent.writeText("/");
  1.2151 +        contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
  1.2152 +                SkPDFResourceDict::kFont_ResourceType,
  1.2153 +                fontIndex).c_str());
  1.2154 +        contentEntry->fContent.writeText(" ");
  1.2155 +        SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
  1.2156 +        contentEntry->fContent.writeText(" Tf\n");
  1.2157 +        contentEntry->fState.fFont = fFontResources[fontIndex];
  1.2158 +    }
  1.2159 +}
  1.2160 +
  1.2161 +int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
  1.2162 +    SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
  1.2163 +                                                               glyphID));
  1.2164 +    int resourceIndex = fFontResources.find(newFont.get());
  1.2165 +    if (resourceIndex < 0) {
  1.2166 +        resourceIndex = fFontResources.count();
  1.2167 +        fFontResources.push(newFont.get());
  1.2168 +        newFont.get()->ref();
  1.2169 +    }
  1.2170 +    return resourceIndex;
  1.2171 +}
  1.2172 +
  1.2173 +void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
  1.2174 +                                     const SkClipStack* clipStack,
  1.2175 +                                     const SkRegion& origClipRegion,
  1.2176 +                                     const SkBitmap& origBitmap,
  1.2177 +                                     const SkIRect* srcRect,
  1.2178 +                                     const SkPaint& paint) {
  1.2179 +    SkMatrix matrix = origMatrix;
  1.2180 +    SkRegion perspectiveBounds;
  1.2181 +    const SkRegion* clipRegion = &origClipRegion;
  1.2182 +    SkBitmap perspectiveBitmap;
  1.2183 +    const SkBitmap* bitmap = &origBitmap;
  1.2184 +    SkBitmap tmpSubsetBitmap;
  1.2185 +
  1.2186 +    // Rasterize the bitmap using perspective in a new bitmap.
  1.2187 +    if (origMatrix.hasPerspective()) {
  1.2188 +        if (fRasterDpi == 0) {
  1.2189 +            return;
  1.2190 +        }
  1.2191 +        SkBitmap* subsetBitmap;
  1.2192 +        if (srcRect) {
  1.2193 +            if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
  1.2194 +               return;
  1.2195 +            }
  1.2196 +            subsetBitmap = &tmpSubsetBitmap;
  1.2197 +        } else {
  1.2198 +            subsetBitmap = &tmpSubsetBitmap;
  1.2199 +            *subsetBitmap = origBitmap;
  1.2200 +        }
  1.2201 +        srcRect = NULL;
  1.2202 +
  1.2203 +        // Transform the bitmap in the new space, without taking into
  1.2204 +        // account the initial transform.
  1.2205 +        SkPath perspectiveOutline;
  1.2206 +        perspectiveOutline.addRect(
  1.2207 +                SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
  1.2208 +                               SkIntToScalar(subsetBitmap->height())));
  1.2209 +        perspectiveOutline.transform(origMatrix);
  1.2210 +
  1.2211 +        // TODO(edisonn): perf - use current clip too.
  1.2212 +        // Retrieve the bounds of the new shape.
  1.2213 +        SkRect bounds = perspectiveOutline.getBounds();
  1.2214 +
  1.2215 +        // Transform the bitmap in the new space, taking into
  1.2216 +        // account the initial transform.
  1.2217 +        SkMatrix total = origMatrix;
  1.2218 +        total.postConcat(fInitialTransform);
  1.2219 +        total.postScale(SkIntToScalar(fRasterDpi) /
  1.2220 +                            SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
  1.2221 +                        SkIntToScalar(fRasterDpi) /
  1.2222 +                            SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
  1.2223 +        SkPath physicalPerspectiveOutline;
  1.2224 +        physicalPerspectiveOutline.addRect(
  1.2225 +                SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
  1.2226 +                               SkIntToScalar(subsetBitmap->height())));
  1.2227 +        physicalPerspectiveOutline.transform(total);
  1.2228 +
  1.2229 +        SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
  1.2230 +                              bounds.width();
  1.2231 +        SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
  1.2232 +                              bounds.height();
  1.2233 +
  1.2234 +        // TODO(edisonn): A better approach would be to use a bitmap shader
  1.2235 +        // (in clamp mode) and draw a rect over the entire bounding box. Then
  1.2236 +        // intersect perspectiveOutline to the clip. That will avoid introducing
  1.2237 +        // alpha to the image while still giving good behavior at the edge of
  1.2238 +        // the image.  Avoiding alpha will reduce the pdf size and generation
  1.2239 +        // CPU time some.
  1.2240 +
  1.2241 +        const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
  1.2242 +        const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
  1.2243 +        if (!perspectiveBitmap.allocPixels(SkImageInfo::MakeN32Premul(w, h))) {
  1.2244 +            return;
  1.2245 +        }
  1.2246 +        perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
  1.2247 +
  1.2248 +        SkBitmapDevice device(perspectiveBitmap);
  1.2249 +        SkCanvas canvas(&device);
  1.2250 +
  1.2251 +        SkScalar deltaX = bounds.left();
  1.2252 +        SkScalar deltaY = bounds.top();
  1.2253 +
  1.2254 +        SkMatrix offsetMatrix = origMatrix;
  1.2255 +        offsetMatrix.postTranslate(-deltaX, -deltaY);
  1.2256 +        offsetMatrix.postScale(scaleX, scaleY);
  1.2257 +
  1.2258 +        // Translate the draw in the new canvas, so we perfectly fit the
  1.2259 +        // shape in the bitmap.
  1.2260 +        canvas.setMatrix(offsetMatrix);
  1.2261 +
  1.2262 +        canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
  1.2263 +
  1.2264 +        // Make sure the final bits are in the bitmap.
  1.2265 +        canvas.flush();
  1.2266 +
  1.2267 +        // In the new space, we use the identity matrix translated
  1.2268 +        // and scaled to reflect DPI.
  1.2269 +        matrix.setScale(1 / scaleX, 1 / scaleY);
  1.2270 +        matrix.postTranslate(deltaX, deltaY);
  1.2271 +
  1.2272 +        perspectiveBounds.setRect(
  1.2273 +                SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
  1.2274 +                                  SkScalarFloorToInt(bounds.y()),
  1.2275 +                                  SkScalarCeilToInt(bounds.width()),
  1.2276 +                                  SkScalarCeilToInt(bounds.height())));
  1.2277 +        clipRegion = &perspectiveBounds;
  1.2278 +        srcRect = NULL;
  1.2279 +        bitmap = &perspectiveBitmap;
  1.2280 +    }
  1.2281 +
  1.2282 +    SkMatrix scaled;
  1.2283 +    // Adjust for origin flip.
  1.2284 +    scaled.setScale(SK_Scalar1, -SK_Scalar1);
  1.2285 +    scaled.postTranslate(0, SK_Scalar1);
  1.2286 +    // Scale the image up from 1x1 to WxH.
  1.2287 +    SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
  1.2288 +    scaled.postScale(SkIntToScalar(subset.width()),
  1.2289 +                     SkIntToScalar(subset.height()));
  1.2290 +    scaled.postConcat(matrix);
  1.2291 +    ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
  1.2292 +    if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
  1.2293 +        return;
  1.2294 +    }
  1.2295 +    if (content.needShape()) {
  1.2296 +        SkPath shape;
  1.2297 +        shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
  1.2298 +                                     SkIntToScalar( subset.height())));
  1.2299 +        shape.transform(matrix);
  1.2300 +        content.setShape(shape);
  1.2301 +    }
  1.2302 +    if (!content.needSource()) {
  1.2303 +        return;
  1.2304 +    }
  1.2305 +
  1.2306 +    SkAutoTUnref<SkPDFImage> image(
  1.2307 +        SkPDFImage::CreateImage(*bitmap, subset, fEncoder));
  1.2308 +    if (!image) {
  1.2309 +        return;
  1.2310 +    }
  1.2311 +
  1.2312 +    SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
  1.2313 +                                &content.entry()->fContent);
  1.2314 +}
  1.2315 +
  1.2316 +bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
  1.2317 +                               SkCanvas::Config8888) {
  1.2318 +    return false;
  1.2319 +}
  1.2320 +
  1.2321 +bool SkPDFDevice::allowImageFilter(const SkImageFilter*) {
  1.2322 +    return false;
  1.2323 +}

mercurial