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

Sat, 03 Jan 2015 20:18:00 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Sat, 03 Jan 2015 20:18:00 +0100
branch
TOR_BUG_3246
changeset 7
129ffea94266
permissions
-rw-r--r--

Conditionally enable double key logic according to:
private browsing mode or privacy.thirdparty.isolate preference and
implement in GetCookieStringCommon and FindCookie where it counts...
With some reservations of how to convince FindCookie users to test
condition and pass a nullptr when disabling double key logic.

     2 /*
     3  * Copyright 2011 Google Inc.
     4  *
     5  * Use of this source code is governed by a BSD-style license that can be
     6  * found in the LICENSE file.
     7  */
    10 #include "SkPDFShader.h"
    12 #include "SkData.h"
    13 #include "SkPDFCatalog.h"
    14 #include "SkPDFDevice.h"
    15 #include "SkPDFFormXObject.h"
    16 #include "SkPDFGraphicState.h"
    17 #include "SkPDFResourceDict.h"
    18 #include "SkPDFUtils.h"
    19 #include "SkScalar.h"
    20 #include "SkStream.h"
    21 #include "SkTemplates.h"
    22 #include "SkThread.h"
    23 #include "SkTSet.h"
    24 #include "SkTypes.h"
    26 static bool inverseTransformBBox(const SkMatrix& matrix, SkRect* bbox) {
    27     SkMatrix inverse;
    28     if (!matrix.invert(&inverse)) {
    29         return false;
    30     }
    31     inverse.mapRect(bbox);
    32     return true;
    33 }
    35 static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) {
    36     SkVector    vec = pts[1] - pts[0];
    37     SkScalar    mag = vec.length();
    38     SkScalar    inv = mag ? SkScalarInvert(mag) : 0;
    40     vec.scale(inv);
    41     matrix->setSinCos(vec.fY, vec.fX);
    42     matrix->preScale(mag, mag);
    43     matrix->postTranslate(pts[0].fX, pts[0].fY);
    44 }
    46 /* Assumes t + startOffset is on the stack and does a linear interpolation on t
    47    between startOffset and endOffset from prevColor to curColor (for each color
    48    component), leaving the result in component order on the stack. It assumes
    49    there are always 3 components per color.
    50    @param range                  endOffset - startOffset
    51    @param curColor[components]   The current color components.
    52    @param prevColor[components]  The previous color components.
    53    @param result                 The result ps function.
    54  */
    55 static void interpolateColorCode(SkScalar range, SkScalar* curColor,
    56                                  SkScalar* prevColor, SkString* result) {
    57     SkASSERT(range != SkIntToScalar(0));
    58     static const int kColorComponents = 3;
    60     // Figure out how to scale each color component.
    61     SkScalar multiplier[kColorComponents];
    62     for (int i = 0; i < kColorComponents; i++) {
    63         multiplier[i] = SkScalarDiv(curColor[i] - prevColor[i], range);
    64     }
    66     // Calculate when we no longer need to keep a copy of the input parameter t.
    67     // If the last component to use t is i, then dupInput[0..i - 1] = true
    68     // and dupInput[i .. components] = false.
    69     bool dupInput[kColorComponents];
    70     dupInput[kColorComponents - 1] = false;
    71     for (int i = kColorComponents - 2; i >= 0; i--) {
    72         dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
    73     }
    75     if (!dupInput[0] && multiplier[0] == 0) {
    76         result->append("pop ");
    77     }
    79     for (int i = 0; i < kColorComponents; i++) {
    80         // If the next components needs t and this component will consume a
    81         // copy, make another copy.
    82         if (dupInput[i] && multiplier[i] != 0) {
    83             result->append("dup ");
    84         }
    86         if (multiplier[i] == 0) {
    87             result->appendScalar(prevColor[i]);
    88             result->append(" ");
    89         } else {
    90             if (multiplier[i] != 1) {
    91                 result->appendScalar(multiplier[i]);
    92                 result->append(" mul ");
    93             }
    94             if (prevColor[i] != 0) {
    95                 result->appendScalar(prevColor[i]);
    96                 result->append(" add ");
    97             }
    98         }
   100         if (dupInput[i]) {
   101             result->append("exch\n");
   102         }
   103     }
   104 }
   106 /* Generate Type 4 function code to map t=[0,1) to the passed gradient,
   107    clamping at the edges of the range.  The generated code will be of the form:
   108        if (t < 0) {
   109            return colorData[0][r,g,b];
   110        } else {
   111            if (t < info.fColorOffsets[1]) {
   112                return linearinterpolation(colorData[0][r,g,b],
   113                                           colorData[1][r,g,b]);
   114            } else {
   115                if (t < info.fColorOffsets[2]) {
   116                    return linearinterpolation(colorData[1][r,g,b],
   117                                               colorData[2][r,g,b]);
   118                } else {
   120                 ...    } else {
   121                            return colorData[info.fColorCount - 1][r,g,b];
   122                        }
   123                 ...
   124            }
   125        }
   126  */
   127 static void gradientFunctionCode(const SkShader::GradientInfo& info,
   128                                  SkString* result) {
   129     /* We want to linearly interpolate from the previous color to the next.
   130        Scale the colors from 0..255 to 0..1 and determine the multipliers
   131        for interpolation.
   132        C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}.
   133      */
   134     static const int kColorComponents = 3;
   135     typedef SkScalar ColorTuple[kColorComponents];
   136     SkAutoSTMalloc<4, ColorTuple> colorDataAlloc(info.fColorCount);
   137     ColorTuple *colorData = colorDataAlloc.get();
   138     const SkScalar scale = SkScalarInvert(SkIntToScalar(255));
   139     for (int i = 0; i < info.fColorCount; i++) {
   140         colorData[i][0] = SkScalarMul(SkColorGetR(info.fColors[i]), scale);
   141         colorData[i][1] = SkScalarMul(SkColorGetG(info.fColors[i]), scale);
   142         colorData[i][2] = SkScalarMul(SkColorGetB(info.fColors[i]), scale);
   143     }
   145     // Clamp the initial color.
   146     result->append("dup 0 le {pop ");
   147     result->appendScalar(colorData[0][0]);
   148     result->append(" ");
   149     result->appendScalar(colorData[0][1]);
   150     result->append(" ");
   151     result->appendScalar(colorData[0][2]);
   152     result->append(" }\n");
   154     // The gradient colors.
   155     int gradients = 0;
   156     for (int i = 1 ; i < info.fColorCount; i++) {
   157         if (info.fColorOffsets[i] == info.fColorOffsets[i - 1]) {
   158             continue;
   159         }
   160         gradients++;
   162         result->append("{dup ");
   163         result->appendScalar(info.fColorOffsets[i]);
   164         result->append(" le {");
   165         if (info.fColorOffsets[i - 1] != 0) {
   166             result->appendScalar(info.fColorOffsets[i - 1]);
   167             result->append(" sub\n");
   168         }
   170         interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
   171                              colorData[i], colorData[i - 1], result);
   172         result->append("}\n");
   173     }
   175     // Clamp the final color.
   176     result->append("{pop ");
   177     result->appendScalar(colorData[info.fColorCount - 1][0]);
   178     result->append(" ");
   179     result->appendScalar(colorData[info.fColorCount - 1][1]);
   180     result->append(" ");
   181     result->appendScalar(colorData[info.fColorCount - 1][2]);
   183     for (int i = 0 ; i < gradients + 1; i++) {
   184         result->append("} ifelse\n");
   185     }
   186 }
   188 /* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
   189 static void tileModeCode(SkShader::TileMode mode, SkString* result) {
   190     if (mode == SkShader::kRepeat_TileMode) {
   191         result->append("dup truncate sub\n");  // Get the fractional part.
   192         result->append("dup 0 le {1 add} if\n");  // Map (-1,0) => (0,1)
   193         return;
   194     }
   196     if (mode == SkShader::kMirror_TileMode) {
   197         // Map t mod 2 into [0, 1, 1, 0].
   198         //               Code                     Stack
   199         result->append("abs "                 // Map negative to positive.
   200                        "dup "                 // t.s t.s
   201                        "truncate "            // t.s t
   202                        "dup "                 // t.s t t
   203                        "cvi "                 // t.s t T
   204                        "2 mod "               // t.s t (i mod 2)
   205                        "1 eq "                // t.s t true|false
   206                        "3 1 roll "            // true|false t.s t
   207                        "sub "                 // true|false 0.s
   208                        "exch "                // 0.s true|false
   209                        "{1 exch sub} if\n");  // 1 - 0.s|0.s
   210     }
   211 }
   213 /**
   214  *  Returns PS function code that applies inverse perspective
   215  *  to a x, y point.
   216  *  The function assumes that the stack has at least two elements,
   217  *  and that the top 2 elements are numeric values.
   218  *  After executing this code on a PS stack, the last 2 elements are updated
   219  *  while the rest of the stack is preserved intact.
   220  *  inversePerspectiveMatrix is the inverse perspective matrix.
   221  */
   222 static SkString apply_perspective_to_coordinates(
   223         const SkMatrix& inversePerspectiveMatrix) {
   224     SkString code;
   225     if (!inversePerspectiveMatrix.hasPerspective()) {
   226         return code;
   227     }
   229     // Perspective matrix should be:
   230     // 1   0  0
   231     // 0   1  0
   232     // p0 p1 p2
   234     const SkScalar p0 = inversePerspectiveMatrix[SkMatrix::kMPersp0];
   235     const SkScalar p1 = inversePerspectiveMatrix[SkMatrix::kMPersp1];
   236     const SkScalar p2 = inversePerspectiveMatrix[SkMatrix::kMPersp2];
   238     // y = y / (p2 + p0 x + p1 y)
   239     // x = x / (p2 + p0 x + p1 y)
   241     // Input on stack: x y
   242     code.append(" dup ");               // x y y
   243     code.appendScalar(p1);              // x y y p1
   244     code.append(" mul "                 // x y y*p1
   245                 " 2 index ");           // x y y*p1 x
   246     code.appendScalar(p0);              // x y y p1 x p0
   247     code.append(" mul ");               // x y y*p1 x*p0
   248     code.appendScalar(p2);              // x y y p1 x*p0 p2
   249     code.append(" add "                 // x y y*p1 x*p0+p2
   250                 "add "                  // x y y*p1+x*p0+p2
   251                 "3 1 roll "             // y*p1+x*p0+p2 x y
   252                 "2 index "              // z x y y*p1+x*p0+p2
   253                 "div "                  // y*p1+x*p0+p2 x y/(y*p1+x*p0+p2)
   254                 "3 1 roll "             // y/(y*p1+x*p0+p2) y*p1+x*p0+p2 x
   255                 "exch "                 // y/(y*p1+x*p0+p2) x y*p1+x*p0+p2
   256                 "div "                  // y/(y*p1+x*p0+p2) x/(y*p1+x*p0+p2)
   257                 "exch\n");              // x/(y*p1+x*p0+p2) y/(y*p1+x*p0+p2)
   258     return code;
   259 }
   261 static SkString linearCode(const SkShader::GradientInfo& info,
   262                            const SkMatrix& perspectiveRemover) {
   263     SkString function("{");
   265     function.append(apply_perspective_to_coordinates(perspectiveRemover));
   267     function.append("pop\n");  // Just ditch the y value.
   268     tileModeCode(info.fTileMode, &function);
   269     gradientFunctionCode(info, &function);
   270     function.append("}");
   271     return function;
   272 }
   274 static SkString radialCode(const SkShader::GradientInfo& info,
   275                            const SkMatrix& perspectiveRemover) {
   276     SkString function("{");
   278     function.append(apply_perspective_to_coordinates(perspectiveRemover));
   280     // Find the distance from the origin.
   281     function.append("dup "      // x y y
   282                     "mul "      // x y^2
   283                     "exch "     // y^2 x
   284                     "dup "      // y^2 x x
   285                     "mul "      // y^2 x^2
   286                     "add "      // y^2+x^2
   287                     "sqrt\n");  // sqrt(y^2+x^2)
   289     tileModeCode(info.fTileMode, &function);
   290     gradientFunctionCode(info, &function);
   291     function.append("}");
   292     return function;
   293 }
   295 /* The math here is all based on the description in Two_Point_Radial_Gradient,
   296    with one simplification, the coordinate space has been scaled so that
   297    Dr = 1.  This means we don't need to scale the entire equation by 1/Dr^2.
   298  */
   299 static SkString twoPointRadialCode(const SkShader::GradientInfo& info,
   300                                    const SkMatrix& perspectiveRemover) {
   301     SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
   302     SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
   303     SkScalar sr = info.fRadius[0];
   304     SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
   305     bool posRoot = info.fRadius[1] > info.fRadius[0];
   307     // We start with a stack of (x y), copy it and then consume one copy in
   308     // order to calculate b and the other to calculate c.
   309     SkString function("{");
   311     function.append(apply_perspective_to_coordinates(perspectiveRemover));
   313     function.append("2 copy ");
   315     // Calculate -b and b^2.
   316     function.appendScalar(dy);
   317     function.append(" mul exch ");
   318     function.appendScalar(dx);
   319     function.append(" mul add ");
   320     function.appendScalar(sr);
   321     function.append(" sub 2 mul neg dup dup mul\n");
   323     // Calculate c
   324     function.append("4 2 roll dup mul exch dup mul add ");
   325     function.appendScalar(SkScalarMul(sr, sr));
   326     function.append(" sub\n");
   328     // Calculate the determinate
   329     function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
   330     function.append(" mul sub abs sqrt\n");
   332     // And then the final value of t.
   333     if (posRoot) {
   334         function.append("sub ");
   335     } else {
   336         function.append("add ");
   337     }
   338     function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
   339     function.append(" div\n");
   341     tileModeCode(info.fTileMode, &function);
   342     gradientFunctionCode(info, &function);
   343     function.append("}");
   344     return function;
   345 }
   347 /* Conical gradient shader, based on the Canvas spec for radial gradients
   348    See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient
   349  */
   350 static SkString twoPointConicalCode(const SkShader::GradientInfo& info,
   351                                     const SkMatrix& perspectiveRemover) {
   352     SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX;
   353     SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY;
   354     SkScalar r0 = info.fRadius[0];
   355     SkScalar dr = info.fRadius[1] - info.fRadius[0];
   356     SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) -
   357                  SkScalarMul(dr, dr);
   359     // First compute t, if the pixel falls outside the cone, then we'll end
   360     // with 'false' on the stack, otherwise we'll push 'true' with t below it
   362     // We start with a stack of (x y), copy it and then consume one copy in
   363     // order to calculate b and the other to calculate c.
   364     SkString function("{");
   366     function.append(apply_perspective_to_coordinates(perspectiveRemover));
   368     function.append("2 copy ");
   370     // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr).
   371     function.appendScalar(dy);
   372     function.append(" mul exch ");
   373     function.appendScalar(dx);
   374     function.append(" mul add ");
   375     function.appendScalar(SkScalarMul(r0, dr));
   376     function.append(" add -2 mul dup dup mul\n");
   378     // c = x^2 + y^2 + radius0^2
   379     function.append("4 2 roll dup mul exch dup mul add ");
   380     function.appendScalar(SkScalarMul(r0, r0));
   381     function.append(" sub dup 4 1 roll\n");
   383     // Contents of the stack at this point: c, b, b^2, c
   385     // if a = 0, then we collapse to a simpler linear case
   386     if (a == 0) {
   388         // t = -c/b
   389         function.append("pop pop div neg dup ");
   391         // compute radius(t)
   392         function.appendScalar(dr);
   393         function.append(" mul ");
   394         function.appendScalar(r0);
   395         function.append(" add\n");
   397         // if r(t) < 0, then it's outside the cone
   398         function.append("0 lt {pop false} {true} ifelse\n");
   400     } else {
   402         // quadratic case: the Canvas spec wants the largest
   403         // root t for which radius(t) > 0
   405         // compute the discriminant (b^2 - 4ac)
   406         function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
   407         function.append(" mul sub dup\n");
   409         // if d >= 0, proceed
   410         function.append("0 ge {\n");
   412         // an intermediate value we'll use to compute the roots:
   413         // q = -0.5 * (b +/- sqrt(d))
   414         function.append("sqrt exch dup 0 lt {exch -1 mul} if");
   415         function.append(" add -0.5 mul dup\n");
   417         // first root = q / a
   418         function.appendScalar(a);
   419         function.append(" div\n");
   421         // second root = c / q
   422         function.append("3 1 roll div\n");
   424         // put the larger root on top of the stack
   425         function.append("2 copy gt {exch} if\n");
   427         // compute radius(t) for larger root
   428         function.append("dup ");
   429         function.appendScalar(dr);
   430         function.append(" mul ");
   431         function.appendScalar(r0);
   432         function.append(" add\n");
   434         // if r(t) > 0, we have our t, pop off the smaller root and we're done
   435         function.append(" 0 gt {exch pop true}\n");
   437         // otherwise, throw out the larger one and try the smaller root
   438         function.append("{pop dup\n");
   439         function.appendScalar(dr);
   440         function.append(" mul ");
   441         function.appendScalar(r0);
   442         function.append(" add\n");
   444         // if r(t) < 0, push false, otherwise the smaller root is our t
   445         function.append("0 le {pop false} {true} ifelse\n");
   446         function.append("} ifelse\n");
   448         // d < 0, clear the stack and push false
   449         function.append("} {pop pop pop false} ifelse\n");
   450     }
   452     // if the pixel is in the cone, proceed to compute a color
   453     function.append("{");
   454     tileModeCode(info.fTileMode, &function);
   455     gradientFunctionCode(info, &function);
   457     // otherwise, just write black
   458     function.append("} {0 0 0} ifelse }");
   460     return function;
   461 }
   463 static SkString sweepCode(const SkShader::GradientInfo& info,
   464                           const SkMatrix& perspectiveRemover) {
   465     SkString function("{exch atan 360 div\n");
   466     tileModeCode(info.fTileMode, &function);
   467     gradientFunctionCode(info, &function);
   468     function.append("}");
   469     return function;
   470 }
   472 class SkPDFShader::State {
   473 public:
   474     SkShader::GradientType fType;
   475     SkShader::GradientInfo fInfo;
   476     SkAutoFree fColorData;    // This provides storage for arrays in fInfo.
   477     SkMatrix fCanvasTransform;
   478     SkMatrix fShaderTransform;
   479     SkIRect fBBox;
   481     SkBitmap fImage;
   482     uint32_t fPixelGeneration;
   483     SkShader::TileMode fImageTileModes[2];
   485     State(const SkShader& shader, const SkMatrix& canvasTransform,
   486           const SkIRect& bbox);
   488     bool operator==(const State& b) const;
   490     SkPDFShader::State* CreateAlphaToLuminosityState() const;
   491     SkPDFShader::State* CreateOpaqueState() const;
   493     bool GradientHasAlpha() const;
   495 private:
   496     State(const State& other);
   497     State operator=(const State& rhs);
   498     void AllocateGradientInfoStorage();
   499 };
   501 class SkPDFFunctionShader : public SkPDFDict, public SkPDFShader {
   502     SK_DECLARE_INST_COUNT(SkPDFFunctionShader)
   503 public:
   504     explicit SkPDFFunctionShader(SkPDFShader::State* state);
   505     virtual ~SkPDFFunctionShader() {
   506         if (isValid()) {
   507             RemoveShader(this);
   508         }
   509         fResources.unrefAll();
   510     }
   512     virtual bool isValid() { return fResources.count() > 0; }
   514     void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
   515                       SkTSet<SkPDFObject*>* newResourceObjects) {
   516         GetResourcesHelper(&fResources,
   517                            knownResourceObjects,
   518                            newResourceObjects);
   519     }
   521 private:
   522     static SkPDFObject* RangeObject();
   524     SkTDArray<SkPDFObject*> fResources;
   525     SkAutoTDelete<const SkPDFShader::State> fState;
   527     SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain);
   528     typedef SkPDFDict INHERITED;
   529 };
   531 /**
   532  * A shader for PDF gradients. This encapsulates the function shader
   533  * inside a tiling pattern while providing a common pattern interface.
   534  * The encapsulation allows the use of a SMask for transparency gradients.
   535  */
   536 class SkPDFAlphaFunctionShader : public SkPDFStream, public SkPDFShader {
   537 public:
   538     explicit SkPDFAlphaFunctionShader(SkPDFShader::State* state);
   539     virtual ~SkPDFAlphaFunctionShader() {
   540         if (isValid()) {
   541             RemoveShader(this);
   542         }
   543     }
   545     virtual bool isValid() {
   546         return fColorShader.get() != NULL;
   547     }
   549 private:
   550     SkAutoTDelete<const SkPDFShader::State> fState;
   552     SkPDFGraphicState* CreateSMaskGraphicState();
   554     void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
   555                       SkTSet<SkPDFObject*>* newResourceObjects) {
   556         fResourceDict->getReferencedResources(knownResourceObjects,
   557                                               newResourceObjects,
   558                                               true);
   559     }
   561     SkAutoTUnref<SkPDFObject> fColorShader;
   562     SkAutoTUnref<SkPDFResourceDict> fResourceDict;
   563 };
   565 class SkPDFImageShader : public SkPDFStream, public SkPDFShader {
   566 public:
   567     explicit SkPDFImageShader(SkPDFShader::State* state);
   568     virtual ~SkPDFImageShader() {
   569         if (isValid()) {
   570             RemoveShader(this);
   571         }
   572         fResources.unrefAll();
   573     }
   575     virtual bool isValid() { return size() > 0; }
   577     void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
   578                       SkTSet<SkPDFObject*>* newResourceObjects) {
   579         GetResourcesHelper(&fResources.toArray(),
   580                            knownResourceObjects,
   581                            newResourceObjects);
   582     }
   584 private:
   585     SkTSet<SkPDFObject*> fResources;
   586     SkAutoTDelete<const SkPDFShader::State> fState;
   587 };
   589 SkPDFShader::SkPDFShader() {}
   591 // static
   592 SkPDFObject* SkPDFShader::GetPDFShaderByState(State* inState) {
   593     SkPDFObject* result;
   595     SkAutoTDelete<State> shaderState(inState);
   596     if (shaderState.get()->fType == SkShader::kNone_GradientType &&
   597             shaderState.get()->fImage.isNull()) {
   598         // TODO(vandebo) This drops SKComposeShader on the floor.  We could
   599         // handle compose shader by pulling things up to a layer, drawing with
   600         // the first shader, applying the xfer mode and drawing again with the
   601         // second shader, then applying the layer to the original drawing.
   602         return NULL;
   603     }
   605     ShaderCanonicalEntry entry(NULL, shaderState.get());
   606     int index = CanonicalShaders().find(entry);
   607     if (index >= 0) {
   608         result = CanonicalShaders()[index].fPDFShader;
   609         result->ref();
   610         return result;
   611     }
   613     bool valid = false;
   614     // The PDFShader takes ownership of the shaderSate.
   615     if (shaderState.get()->fType == SkShader::kNone_GradientType) {
   616         SkPDFImageShader* imageShader =
   617             new SkPDFImageShader(shaderState.detach());
   618         valid = imageShader->isValid();
   619         result = imageShader;
   620     } else {
   621         if (shaderState.get()->GradientHasAlpha()) {
   622             SkPDFAlphaFunctionShader* gradientShader =
   623                 SkNEW_ARGS(SkPDFAlphaFunctionShader, (shaderState.detach()));
   624             valid = gradientShader->isValid();
   625             result = gradientShader;
   626         } else {
   627             SkPDFFunctionShader* functionShader =
   628                 SkNEW_ARGS(SkPDFFunctionShader, (shaderState.detach()));
   629             valid = functionShader->isValid();
   630             result = functionShader;
   631         }
   632     }
   633     if (!valid) {
   634         delete result;
   635         return NULL;
   636     }
   637     entry.fPDFShader = result;
   638     CanonicalShaders().push(entry);
   639     return result;  // return the reference that came from new.
   640 }
   642 // static
   643 void SkPDFShader::RemoveShader(SkPDFObject* shader) {
   644     SkAutoMutexAcquire lock(CanonicalShadersMutex());
   645     ShaderCanonicalEntry entry(shader, NULL);
   646     int index = CanonicalShaders().find(entry);
   647     SkASSERT(index >= 0);
   648     CanonicalShaders().removeShuffle(index);
   649 }
   651 // static
   652 SkPDFObject* SkPDFShader::GetPDFShader(const SkShader& shader,
   653                                        const SkMatrix& matrix,
   654                                        const SkIRect& surfaceBBox) {
   655     SkAutoMutexAcquire lock(CanonicalShadersMutex());
   656     return GetPDFShaderByState(
   657             SkNEW_ARGS(State, (shader, matrix, surfaceBBox)));
   658 }
   660 // static
   661 SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::CanonicalShaders() {
   662     // This initialization is only thread safe with gcc.
   663     static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
   664     return gCanonicalShaders;
   665 }
   667 // static
   668 SkBaseMutex& SkPDFShader::CanonicalShadersMutex() {
   669     // This initialization is only thread safe with gcc or when
   670     // POD-style mutex initialization is used.
   671     SK_DECLARE_STATIC_MUTEX(gCanonicalShadersMutex);
   672     return gCanonicalShadersMutex;
   673 }
   675 // static
   676 SkPDFObject* SkPDFFunctionShader::RangeObject() {
   677     // This initialization is only thread safe with gcc.
   678     static SkPDFArray* range = NULL;
   679     // This method is only used with CanonicalShadersMutex, so it's safe to
   680     // populate domain.
   681     if (range == NULL) {
   682         range = new SkPDFArray;
   683         range->reserve(6);
   684         range->appendInt(0);
   685         range->appendInt(1);
   686         range->appendInt(0);
   687         range->appendInt(1);
   688         range->appendInt(0);
   689         range->appendInt(1);
   690     }
   691     return range;
   692 }
   694 static SkPDFResourceDict* get_gradient_resource_dict(
   695         SkPDFObject* functionShader,
   696         SkPDFObject* gState) {
   697     SkPDFResourceDict* dict = new SkPDFResourceDict();
   699     if (functionShader != NULL) {
   700         dict->insertResourceAsReference(
   701                 SkPDFResourceDict::kPattern_ResourceType, 0, functionShader);
   702     }
   703     if (gState != NULL) {
   704         dict->insertResourceAsReference(
   705                 SkPDFResourceDict::kExtGState_ResourceType, 0, gState);
   706     }
   708     return dict;
   709 }
   711 static void populate_tiling_pattern_dict(SkPDFDict* pattern,
   712                                       SkRect& bbox, SkPDFDict* resources,
   713                                       const SkMatrix& matrix) {
   714     const int kTiling_PatternType = 1;
   715     const int kColoredTilingPattern_PaintType = 1;
   716     const int kConstantSpacing_TilingType = 1;
   718     pattern->insertName("Type", "Pattern");
   719     pattern->insertInt("PatternType", kTiling_PatternType);
   720     pattern->insertInt("PaintType", kColoredTilingPattern_PaintType);
   721     pattern->insertInt("TilingType", kConstantSpacing_TilingType);
   722     pattern->insert("BBox", SkPDFUtils::RectToArray(bbox))->unref();
   723     pattern->insertScalar("XStep", bbox.width());
   724     pattern->insertScalar("YStep", bbox.height());
   725     pattern->insert("Resources", resources);
   726     if (!matrix.isIdentity()) {
   727         pattern->insert("Matrix", SkPDFUtils::MatrixToArray(matrix))->unref();
   728     }
   729 }
   731 /**
   732  * Creates a content stream which fills the pattern P0 across bounds.
   733  * @param gsIndex A graphics state resource index to apply, or <0 if no
   734  * graphics state to apply.
   735  */
   736 static SkStream* create_pattern_fill_content(int gsIndex, SkRect& bounds) {
   737     SkDynamicMemoryWStream content;
   738     if (gsIndex >= 0) {
   739         SkPDFUtils::ApplyGraphicState(gsIndex, &content);
   740     }
   741     SkPDFUtils::ApplyPattern(0, &content);
   742     SkPDFUtils::AppendRectangle(bounds, &content);
   743     SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType,
   744                           &content);
   746     return content.detachAsStream();
   747 }
   749 /**
   750  * Creates a ExtGState with the SMask set to the luminosityShader in
   751  * luminosity mode. The shader pattern extends to the bbox.
   752  */
   753 SkPDFGraphicState* SkPDFAlphaFunctionShader::CreateSMaskGraphicState() {
   754     SkRect bbox;
   755     bbox.set(fState.get()->fBBox);
   757     SkAutoTUnref<SkPDFObject> luminosityShader(
   758             SkPDFShader::GetPDFShaderByState(
   759                  fState->CreateAlphaToLuminosityState()));
   761     SkAutoTUnref<SkStream> alphaStream(create_pattern_fill_content(-1, bbox));
   763     SkAutoTUnref<SkPDFResourceDict>
   764         resources(get_gradient_resource_dict(luminosityShader, NULL));
   766     SkAutoTUnref<SkPDFFormXObject> alphaMask(
   767             new SkPDFFormXObject(alphaStream.get(), bbox, resources.get()));
   769     return SkPDFGraphicState::GetSMaskGraphicState(
   770             alphaMask.get(), false,
   771             SkPDFGraphicState::kLuminosity_SMaskMode);
   772 }
   774 SkPDFAlphaFunctionShader::SkPDFAlphaFunctionShader(SkPDFShader::State* state)
   775         : fState(state) {
   776     SkRect bbox;
   777     bbox.set(fState.get()->fBBox);
   779     fColorShader.reset(
   780             SkPDFShader::GetPDFShaderByState(state->CreateOpaqueState()));
   782     // Create resource dict with alpha graphics state as G0 and
   783     // pattern shader as P0, then write content stream.
   784     SkAutoTUnref<SkPDFGraphicState> alphaGs(CreateSMaskGraphicState());
   785     fResourceDict.reset(
   786             get_gradient_resource_dict(fColorShader.get(), alphaGs.get()));
   788     SkAutoTUnref<SkStream> colorStream(
   789             create_pattern_fill_content(0, bbox));
   790     setData(colorStream.get());
   792     populate_tiling_pattern_dict(this, bbox, fResourceDict.get(),
   793                                  SkMatrix::I());
   794 }
   796 // Finds affine and persp such that in = affine * persp.
   797 // but it returns the inverse of perspective matrix.
   798 static bool split_perspective(const SkMatrix in, SkMatrix* affine,
   799                               SkMatrix* perspectiveInverse) {
   800     const SkScalar p2 = in[SkMatrix::kMPersp2];
   802     if (SkScalarNearlyZero(p2)) {
   803         return false;
   804     }
   806     const SkScalar zero = SkIntToScalar(0);
   807     const SkScalar one = SkIntToScalar(1);
   809     const SkScalar sx = in[SkMatrix::kMScaleX];
   810     const SkScalar kx = in[SkMatrix::kMSkewX];
   811     const SkScalar tx = in[SkMatrix::kMTransX];
   812     const SkScalar ky = in[SkMatrix::kMSkewY];
   813     const SkScalar sy = in[SkMatrix::kMScaleY];
   814     const SkScalar ty = in[SkMatrix::kMTransY];
   815     const SkScalar p0 = in[SkMatrix::kMPersp0];
   816     const SkScalar p1 = in[SkMatrix::kMPersp1];
   818     // Perspective matrix would be:
   819     // 1  0  0
   820     // 0  1  0
   821     // p0 p1 p2
   822     // But we need the inverse of persp.
   823     perspectiveInverse->setAll(one,          zero,       zero,
   824                                zero,         one,        zero,
   825                                -p0/p2,     -p1/p2,     1/p2);
   827     affine->setAll(sx - p0 * tx / p2,       kx - p1 * tx / p2,      tx / p2,
   828                    ky - p0 * ty / p2,       sy - p1 * ty / p2,      ty / p2,
   829                    zero,                    zero,                   one);
   831     return true;
   832 }
   834 SkPDFFunctionShader::SkPDFFunctionShader(SkPDFShader::State* state)
   835         : SkPDFDict("Pattern"),
   836           fState(state) {
   837     SkString (*codeFunction)(const SkShader::GradientInfo& info,
   838                              const SkMatrix& perspectiveRemover) = NULL;
   839     SkPoint transformPoints[2];
   841     // Depending on the type of the gradient, we want to transform the
   842     // coordinate space in different ways.
   843     const SkShader::GradientInfo* info = &fState.get()->fInfo;
   844     transformPoints[0] = info->fPoint[0];
   845     transformPoints[1] = info->fPoint[1];
   846     switch (fState.get()->fType) {
   847         case SkShader::kLinear_GradientType:
   848             codeFunction = &linearCode;
   849             break;
   850         case SkShader::kRadial_GradientType:
   851             transformPoints[1] = transformPoints[0];
   852             transformPoints[1].fX += info->fRadius[0];
   853             codeFunction = &radialCode;
   854             break;
   855         case SkShader::kRadial2_GradientType: {
   856             // Bail out if the radii are the same.  Empty fResources signals
   857             // an error and isValid will return false.
   858             if (info->fRadius[0] == info->fRadius[1]) {
   859                 return;
   860             }
   861             transformPoints[1] = transformPoints[0];
   862             SkScalar dr = info->fRadius[1] - info->fRadius[0];
   863             transformPoints[1].fX += dr;
   864             codeFunction = &twoPointRadialCode;
   865             break;
   866         }
   867         case SkShader::kConical_GradientType: {
   868             transformPoints[1] = transformPoints[0];
   869             transformPoints[1].fX += SK_Scalar1;
   870             codeFunction = &twoPointConicalCode;
   871             break;
   872         }
   873         case SkShader::kSweep_GradientType:
   874             transformPoints[1] = transformPoints[0];
   875             transformPoints[1].fX += SK_Scalar1;
   876             codeFunction = &sweepCode;
   877             break;
   878         case SkShader::kColor_GradientType:
   879         case SkShader::kNone_GradientType:
   880         default:
   881             return;
   882     }
   884     // Move any scaling (assuming a unit gradient) or translation
   885     // (and rotation for linear gradient), of the final gradient from
   886     // info->fPoints to the matrix (updating bbox appropriately).  Now
   887     // the gradient can be drawn on on the unit segment.
   888     SkMatrix mapperMatrix;
   889     unitToPointsMatrix(transformPoints, &mapperMatrix);
   891     SkMatrix finalMatrix = fState.get()->fCanvasTransform;
   892     finalMatrix.preConcat(fState.get()->fShaderTransform);
   893     finalMatrix.preConcat(mapperMatrix);
   895     // Preserves as much as posible in the final matrix, and only removes
   896     // the perspective. The inverse of the perspective is stored in
   897     // perspectiveInverseOnly matrix and has 3 useful numbers
   898     // (p0, p1, p2), while everything else is either 0 or 1.
   899     // In this way the shader will handle it eficiently, with minimal code.
   900     SkMatrix perspectiveInverseOnly = SkMatrix::I();
   901     if (finalMatrix.hasPerspective()) {
   902         if (!split_perspective(finalMatrix,
   903                                &finalMatrix, &perspectiveInverseOnly)) {
   904             return;
   905         }
   906     }
   908     SkRect bbox;
   909     bbox.set(fState.get()->fBBox);
   910     if (!inverseTransformBBox(finalMatrix, &bbox)) {
   911         return;
   912     }
   914     SkAutoTUnref<SkPDFArray> domain(new SkPDFArray);
   915     domain->reserve(4);
   916     domain->appendScalar(bbox.fLeft);
   917     domain->appendScalar(bbox.fRight);
   918     domain->appendScalar(bbox.fTop);
   919     domain->appendScalar(bbox.fBottom);
   921     SkString functionCode;
   922     // The two point radial gradient further references fState.get()->fInfo
   923     // in translating from x, y coordinates to the t parameter. So, we have
   924     // to transform the points and radii according to the calculated matrix.
   925     if (fState.get()->fType == SkShader::kRadial2_GradientType) {
   926         SkShader::GradientInfo twoPointRadialInfo = *info;
   927         SkMatrix inverseMapperMatrix;
   928         if (!mapperMatrix.invert(&inverseMapperMatrix)) {
   929             return;
   930         }
   931         inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
   932         twoPointRadialInfo.fRadius[0] =
   933             inverseMapperMatrix.mapRadius(info->fRadius[0]);
   934         twoPointRadialInfo.fRadius[1] =
   935             inverseMapperMatrix.mapRadius(info->fRadius[1]);
   936         functionCode = codeFunction(twoPointRadialInfo, perspectiveInverseOnly);
   937     } else {
   938         functionCode = codeFunction(*info, perspectiveInverseOnly);
   939     }
   941     SkAutoTUnref<SkPDFDict> pdfShader(new SkPDFDict);
   942     pdfShader->insertInt("ShadingType", 1);
   943     pdfShader->insertName("ColorSpace", "DeviceRGB");
   944     pdfShader->insert("Domain", domain.get());
   946     SkPDFStream* function = makePSFunction(functionCode, domain.get());
   947     pdfShader->insert("Function", new SkPDFObjRef(function))->unref();
   948     fResources.push(function);  // Pass ownership to resource list.
   950     insertInt("PatternType", 2);
   951     insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
   952     insert("Shading", pdfShader.get());
   953 }
   955 SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) {
   956     fState.get()->fImage.lockPixels();
   958     // The image shader pattern cell will be drawn into a separate device
   959     // in pattern cell space (no scaling on the bitmap, though there may be
   960     // translations so that all content is in the device, coordinates > 0).
   962     // Map clip bounds to shader space to ensure the device is large enough
   963     // to handle fake clamping.
   964     SkMatrix finalMatrix = fState.get()->fCanvasTransform;
   965     finalMatrix.preConcat(fState.get()->fShaderTransform);
   966     SkRect deviceBounds;
   967     deviceBounds.set(fState.get()->fBBox);
   968     if (!inverseTransformBBox(finalMatrix, &deviceBounds)) {
   969         return;
   970     }
   972     const SkBitmap* image = &fState.get()->fImage;
   973     SkRect bitmapBounds;
   974     image->getBounds(&bitmapBounds);
   976     // For tiling modes, the bounds should be extended to include the bitmap,
   977     // otherwise the bitmap gets clipped out and the shader is empty and awful.
   978     // For clamp modes, we're only interested in the clip region, whether
   979     // or not the main bitmap is in it.
   980     SkShader::TileMode tileModes[2];
   981     tileModes[0] = fState.get()->fImageTileModes[0];
   982     tileModes[1] = fState.get()->fImageTileModes[1];
   983     if (tileModes[0] != SkShader::kClamp_TileMode ||
   984             tileModes[1] != SkShader::kClamp_TileMode) {
   985         deviceBounds.join(bitmapBounds);
   986     }
   988     SkMatrix unflip;
   989     unflip.setTranslate(0, SkScalarRoundToScalar(deviceBounds.height()));
   990     unflip.preScale(SK_Scalar1, -SK_Scalar1);
   991     SkISize size = SkISize::Make(SkScalarRoundToInt(deviceBounds.width()),
   992                                  SkScalarRoundToInt(deviceBounds.height()));
   993     // TODO(edisonn): should we pass here the DCT encoder of the destination device?
   994     // TODO(edisonn): NYI Perspective, use SkPDFDeviceFlattener.
   995     SkPDFDevice pattern(size, size, unflip);
   996     SkCanvas canvas(&pattern);
   998     SkRect patternBBox;
   999     image->getBounds(&patternBBox);
  1001     // Translate the canvas so that the bitmap origin is at (0, 0).
  1002     canvas.translate(-deviceBounds.left(), -deviceBounds.top());
  1003     patternBBox.offset(-deviceBounds.left(), -deviceBounds.top());
  1004     // Undo the translation in the final matrix
  1005     finalMatrix.preTranslate(deviceBounds.left(), deviceBounds.top());
  1007     // If the bitmap is out of bounds (i.e. clamp mode where we only see the
  1008     // stretched sides), canvas will clip this out and the extraneous data
  1009     // won't be saved to the PDF.
  1010     canvas.drawBitmap(*image, 0, 0);
  1012     SkScalar width = SkIntToScalar(image->width());
  1013     SkScalar height = SkIntToScalar(image->height());
  1015     // Tiling is implied.  First we handle mirroring.
  1016     if (tileModes[0] == SkShader::kMirror_TileMode) {
  1017         SkMatrix xMirror;
  1018         xMirror.setScale(-1, 1);
  1019         xMirror.postTranslate(2 * width, 0);
  1020         canvas.drawBitmapMatrix(*image, xMirror);
  1021         patternBBox.fRight += width;
  1023     if (tileModes[1] == SkShader::kMirror_TileMode) {
  1024         SkMatrix yMirror;
  1025         yMirror.setScale(SK_Scalar1, -SK_Scalar1);
  1026         yMirror.postTranslate(0, 2 * height);
  1027         canvas.drawBitmapMatrix(*image, yMirror);
  1028         patternBBox.fBottom += height;
  1030     if (tileModes[0] == SkShader::kMirror_TileMode &&
  1031             tileModes[1] == SkShader::kMirror_TileMode) {
  1032         SkMatrix mirror;
  1033         mirror.setScale(-1, -1);
  1034         mirror.postTranslate(2 * width, 2 * height);
  1035         canvas.drawBitmapMatrix(*image, mirror);
  1038     // Then handle Clamping, which requires expanding the pattern canvas to
  1039     // cover the entire surfaceBBox.
  1041     // If both x and y are in clamp mode, we start by filling in the corners.
  1042     // (Which are just a rectangles of the corner colors.)
  1043     if (tileModes[0] == SkShader::kClamp_TileMode &&
  1044             tileModes[1] == SkShader::kClamp_TileMode) {
  1045         SkPaint paint;
  1046         SkRect rect;
  1047         rect = SkRect::MakeLTRB(deviceBounds.left(), deviceBounds.top(), 0, 0);
  1048         if (!rect.isEmpty()) {
  1049             paint.setColor(image->getColor(0, 0));
  1050             canvas.drawRect(rect, paint);
  1053         rect = SkRect::MakeLTRB(width, deviceBounds.top(),
  1054                                 deviceBounds.right(), 0);
  1055         if (!rect.isEmpty()) {
  1056             paint.setColor(image->getColor(image->width() - 1, 0));
  1057             canvas.drawRect(rect, paint);
  1060         rect = SkRect::MakeLTRB(width, height,
  1061                                 deviceBounds.right(), deviceBounds.bottom());
  1062         if (!rect.isEmpty()) {
  1063             paint.setColor(image->getColor(image->width() - 1,
  1064                                            image->height() - 1));
  1065             canvas.drawRect(rect, paint);
  1068         rect = SkRect::MakeLTRB(deviceBounds.left(), height,
  1069                                 0, deviceBounds.bottom());
  1070         if (!rect.isEmpty()) {
  1071             paint.setColor(image->getColor(0, image->height() - 1));
  1072             canvas.drawRect(rect, paint);
  1076     // Then expand the left, right, top, then bottom.
  1077     if (tileModes[0] == SkShader::kClamp_TileMode) {
  1078         SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, image->height());
  1079         if (deviceBounds.left() < 0) {
  1080             SkBitmap left;
  1081             SkAssertResult(image->extractSubset(&left, subset));
  1083             SkMatrix leftMatrix;
  1084             leftMatrix.setScale(-deviceBounds.left(), 1);
  1085             leftMatrix.postTranslate(deviceBounds.left(), 0);
  1086             canvas.drawBitmapMatrix(left, leftMatrix);
  1088             if (tileModes[1] == SkShader::kMirror_TileMode) {
  1089                 leftMatrix.postScale(SK_Scalar1, -SK_Scalar1);
  1090                 leftMatrix.postTranslate(0, 2 * height);
  1091                 canvas.drawBitmapMatrix(left, leftMatrix);
  1093             patternBBox.fLeft = 0;
  1096         if (deviceBounds.right() > width) {
  1097             SkBitmap right;
  1098             subset.offset(image->width() - 1, 0);
  1099             SkAssertResult(image->extractSubset(&right, subset));
  1101             SkMatrix rightMatrix;
  1102             rightMatrix.setScale(deviceBounds.right() - width, 1);
  1103             rightMatrix.postTranslate(width, 0);
  1104             canvas.drawBitmapMatrix(right, rightMatrix);
  1106             if (tileModes[1] == SkShader::kMirror_TileMode) {
  1107                 rightMatrix.postScale(SK_Scalar1, -SK_Scalar1);
  1108                 rightMatrix.postTranslate(0, 2 * height);
  1109                 canvas.drawBitmapMatrix(right, rightMatrix);
  1111             patternBBox.fRight = deviceBounds.width();
  1115     if (tileModes[1] == SkShader::kClamp_TileMode) {
  1116         SkIRect subset = SkIRect::MakeXYWH(0, 0, image->width(), 1);
  1117         if (deviceBounds.top() < 0) {
  1118             SkBitmap top;
  1119             SkAssertResult(image->extractSubset(&top, subset));
  1121             SkMatrix topMatrix;
  1122             topMatrix.setScale(SK_Scalar1, -deviceBounds.top());
  1123             topMatrix.postTranslate(0, deviceBounds.top());
  1124             canvas.drawBitmapMatrix(top, topMatrix);
  1126             if (tileModes[0] == SkShader::kMirror_TileMode) {
  1127                 topMatrix.postScale(-1, 1);
  1128                 topMatrix.postTranslate(2 * width, 0);
  1129                 canvas.drawBitmapMatrix(top, topMatrix);
  1131             patternBBox.fTop = 0;
  1134         if (deviceBounds.bottom() > height) {
  1135             SkBitmap bottom;
  1136             subset.offset(0, image->height() - 1);
  1137             SkAssertResult(image->extractSubset(&bottom, subset));
  1139             SkMatrix bottomMatrix;
  1140             bottomMatrix.setScale(SK_Scalar1, deviceBounds.bottom() - height);
  1141             bottomMatrix.postTranslate(0, height);
  1142             canvas.drawBitmapMatrix(bottom, bottomMatrix);
  1144             if (tileModes[0] == SkShader::kMirror_TileMode) {
  1145                 bottomMatrix.postScale(-1, 1);
  1146                 bottomMatrix.postTranslate(2 * width, 0);
  1147                 canvas.drawBitmapMatrix(bottom, bottomMatrix);
  1149             patternBBox.fBottom = deviceBounds.height();
  1153     // Put the canvas into the pattern stream (fContent).
  1154     SkAutoTUnref<SkStream> content(pattern.content());
  1155     setData(content.get());
  1156     SkPDFResourceDict* resourceDict = pattern.getResourceDict();
  1157     resourceDict->getReferencedResources(fResources, &fResources, false);
  1159     populate_tiling_pattern_dict(this, patternBBox,
  1160                                  pattern.getResourceDict(), finalMatrix);
  1162     fState.get()->fImage.unlockPixels();
  1165 SkPDFStream* SkPDFFunctionShader::makePSFunction(const SkString& psCode,
  1166                                                  SkPDFArray* domain) {
  1167     SkAutoDataUnref funcData(SkData::NewWithCopy(psCode.c_str(),
  1168                                                  psCode.size()));
  1169     SkPDFStream* result = new SkPDFStream(funcData.get());
  1170     result->insertInt("FunctionType", 4);
  1171     result->insert("Domain", domain);
  1172     result->insert("Range", RangeObject());
  1173     return result;
  1176 SkPDFShader::ShaderCanonicalEntry::ShaderCanonicalEntry(SkPDFObject* pdfShader,
  1177                                                         const State* state)
  1178     : fPDFShader(pdfShader),
  1179       fState(state) {
  1182 bool SkPDFShader::ShaderCanonicalEntry::operator==(
  1183         const ShaderCanonicalEntry& b) const {
  1184     return fPDFShader == b.fPDFShader ||
  1185            (fState != NULL && b.fState != NULL && *fState == *b.fState);
  1188 bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
  1189     if (fType != b.fType ||
  1190             fCanvasTransform != b.fCanvasTransform ||
  1191             fShaderTransform != b.fShaderTransform ||
  1192             fBBox != b.fBBox) {
  1193         return false;
  1196     if (fType == SkShader::kNone_GradientType) {
  1197         if (fPixelGeneration != b.fPixelGeneration ||
  1198                 fPixelGeneration == 0 ||
  1199                 fImageTileModes[0] != b.fImageTileModes[0] ||
  1200                 fImageTileModes[1] != b.fImageTileModes[1]) {
  1201             return false;
  1203     } else {
  1204         if (fInfo.fColorCount != b.fInfo.fColorCount ||
  1205                 memcmp(fInfo.fColors, b.fInfo.fColors,
  1206                        sizeof(SkColor) * fInfo.fColorCount) != 0 ||
  1207                 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
  1208                        sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
  1209                 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
  1210                 fInfo.fTileMode != b.fInfo.fTileMode) {
  1211             return false;
  1214         switch (fType) {
  1215             case SkShader::kLinear_GradientType:
  1216                 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
  1217                     return false;
  1219                 break;
  1220             case SkShader::kRadial_GradientType:
  1221                 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
  1222                     return false;
  1224                 break;
  1225             case SkShader::kRadial2_GradientType:
  1226             case SkShader::kConical_GradientType:
  1227                 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
  1228                         fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
  1229                         fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
  1230                     return false;
  1232                 break;
  1233             case SkShader::kSweep_GradientType:
  1234             case SkShader::kNone_GradientType:
  1235             case SkShader::kColor_GradientType:
  1236                 break;
  1239     return true;
  1242 SkPDFShader::State::State(const SkShader& shader,
  1243                           const SkMatrix& canvasTransform, const SkIRect& bbox)
  1244         : fCanvasTransform(canvasTransform),
  1245           fBBox(bbox),
  1246           fPixelGeneration(0) {
  1247     fInfo.fColorCount = 0;
  1248     fInfo.fColors = NULL;
  1249     fInfo.fColorOffsets = NULL;
  1250     fShaderTransform = shader.getLocalMatrix();
  1251     fImageTileModes[0] = fImageTileModes[1] = SkShader::kClamp_TileMode;
  1253     fType = shader.asAGradient(&fInfo);
  1255     if (fType == SkShader::kNone_GradientType) {
  1256         SkShader::BitmapType bitmapType;
  1257         SkMatrix matrix;
  1258         bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes);
  1259         if (bitmapType != SkShader::kDefault_BitmapType) {
  1260             fImage.reset();
  1261             return;
  1263         SkASSERT(matrix.isIdentity());
  1264         fPixelGeneration = fImage.getGenerationID();
  1265     } else {
  1266         AllocateGradientInfoStorage();
  1267         shader.asAGradient(&fInfo);
  1271 SkPDFShader::State::State(const SkPDFShader::State& other)
  1272   : fType(other.fType),
  1273     fCanvasTransform(other.fCanvasTransform),
  1274     fShaderTransform(other.fShaderTransform),
  1275     fBBox(other.fBBox)
  1277     // Only gradients supported for now, since that is all that is used.
  1278     // If needed, image state copy constructor can be added here later.
  1279     SkASSERT(fType != SkShader::kNone_GradientType);
  1281     if (fType != SkShader::kNone_GradientType) {
  1282         fInfo = other.fInfo;
  1284         AllocateGradientInfoStorage();
  1285         for (int i = 0; i < fInfo.fColorCount; i++) {
  1286             fInfo.fColors[i] = other.fInfo.fColors[i];
  1287             fInfo.fColorOffsets[i] = other.fInfo.fColorOffsets[i];
  1292 /**
  1293  * Create a copy of this gradient state with alpha assigned to RGB luminousity.
  1294  * Only valid for gradient states.
  1295  */
  1296 SkPDFShader::State* SkPDFShader::State::CreateAlphaToLuminosityState() const {
  1297     SkASSERT(fType != SkShader::kNone_GradientType);
  1299     SkPDFShader::State* newState = new SkPDFShader::State(*this);
  1301     for (int i = 0; i < fInfo.fColorCount; i++) {
  1302         SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
  1303         newState->fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha);
  1306     return newState;
  1309 /**
  1310  * Create a copy of this gradient state with alpha set to fully opaque
  1311  * Only valid for gradient states.
  1312  */
  1313 SkPDFShader::State* SkPDFShader::State::CreateOpaqueState() const {
  1314     SkASSERT(fType != SkShader::kNone_GradientType);
  1316     SkPDFShader::State* newState = new SkPDFShader::State(*this);
  1317     for (int i = 0; i < fInfo.fColorCount; i++) {
  1318         newState->fInfo.fColors[i] = SkColorSetA(fInfo.fColors[i],
  1319                                                  SK_AlphaOPAQUE);
  1322     return newState;
  1325 /**
  1326  * Returns true if state is a gradient and the gradient has alpha.
  1327  */
  1328 bool SkPDFShader::State::GradientHasAlpha() const {
  1329     if (fType == SkShader::kNone_GradientType) {
  1330         return false;
  1333     for (int i = 0; i < fInfo.fColorCount; i++) {
  1334         SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
  1335         if (alpha != SK_AlphaOPAQUE) {
  1336             return true;
  1339     return false;
  1342 void SkPDFShader::State::AllocateGradientInfoStorage() {
  1343     fColorData.set(sk_malloc_throw(
  1344                fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
  1345     fInfo.fColors = reinterpret_cast<SkColor*>(fColorData.get());
  1346     fInfo.fColorOffsets =
  1347             reinterpret_cast<SkScalar*>(fInfo.fColors + fInfo.fColorCount);

mercurial