1
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 */
8
9
10#include "SkPDFShader.h"
11
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"
25
26static 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}
34
35static 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;
39
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}
45
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 */
55static void interpolateColorCode(SkScalar range, SkScalar* curColor,
56                                 SkScalar* prevColor, SkString* result) {
57    SkASSERT(range != SkIntToScalar(0));
58    static const int kColorComponents = 3;
59
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    }
65
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    }
74
75    if (!dupInput[0] && multiplier[0] == 0) {
76        result->append("pop ");
77    }
78
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        }
85
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        }
99
100        if (dupInput[i]) {
101            result->append("exch\n");
102        }
103    }
104}
105
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 {
119
120                ...    } else {
121                           return colorData[info.fColorCount - 1][r,g,b];
122                       }
123                ...
124           }
125       }
126 */
127static 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    }
144
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");
153
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++;
161
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        }
169
170        interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
171                             colorData[i], colorData[i - 1], result);
172        result->append("}\n");
173    }
174
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]);
182
183    for (int i = 0 ; i < gradients + 1; i++) {
184        result->append("} ifelse\n");
185    }
186}
187
188/* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
189static 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    }
195
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}
212
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 */
222static SkString apply_perspective_to_coordinates(
223        const SkMatrix& inversePerspectiveMatrix) {
224    SkString code;
225    if (!inversePerspectiveMatrix.hasPerspective()) {
226        return code;
227    }
228
229    // Perspective matrix should be:
230    // 1   0  0
231    // 0   1  0
232    // p0 p1 p2
233
234    const SkScalar p0 = inversePerspectiveMatrix[SkMatrix::kMPersp0];
235    const SkScalar p1 = inversePerspectiveMatrix[SkMatrix::kMPersp1];
236    const SkScalar p2 = inversePerspectiveMatrix[SkMatrix::kMPersp2];
237
238    // y = y / (p2 + p0 x + p1 y)
239    // x = x / (p2 + p0 x + p1 y)
240
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}
260
261static SkString linearCode(const SkShader::GradientInfo& info,
262                           const SkMatrix& perspectiveRemover) {
263    SkString function("{");
264
265    function.append(apply_perspective_to_coordinates(perspectiveRemover));
266
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}
273
274static SkString radialCode(const SkShader::GradientInfo& info,
275                           const SkMatrix& perspectiveRemover) {
276    SkString function("{");
277
278    function.append(apply_perspective_to_coordinates(perspectiveRemover));
279
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)
288
289    tileModeCode(info.fTileMode, &function);
290    gradientFunctionCode(info, &function);
291    function.append("}");
292    return function;
293}
294
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 */
299static 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];
306
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("{");
310
311    function.append(apply_perspective_to_coordinates(perspectiveRemover));
312
313    function.append("2 copy ");
314
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");
322
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");
327
328    // Calculate the determinate
329    function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
330    function.append(" mul sub abs sqrt\n");
331
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");
340
341    tileModeCode(info.fTileMode, &function);
342    gradientFunctionCode(info, &function);
343    function.append("}");
344    return function;
345}
346
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 */
350static 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);
358
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
361
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("{");
365
366    function.append(apply_perspective_to_coordinates(perspectiveRemover));
367
368    function.append("2 copy ");
369
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");
377
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");
382
383    // Contents of the stack at this point: c, b, b^2, c
384
385    // if a = 0, then we collapse to a simpler linear case
386    if (a == 0) {
387
388        // t = -c/b
389        function.append("pop pop div neg dup ");
390
391        // compute radius(t)
392        function.appendScalar(dr);
393        function.append(" mul ");
394        function.appendScalar(r0);
395        function.append(" add\n");
396
397        // if r(t) < 0, then it's outside the cone
398        function.append("0 lt {pop false} {true} ifelse\n");
399
400    } else {
401
402        // quadratic case: the Canvas spec wants the largest
403        // root t for which radius(t) > 0
404
405        // compute the discriminant (b^2 - 4ac)
406        function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
407        function.append(" mul sub dup\n");
408
409        // if d >= 0, proceed
410        function.append("0 ge {\n");
411
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");
416
417        // first root = q / a
418        function.appendScalar(a);
419        function.append(" div\n");
420
421        // second root = c / q
422        function.append("3 1 roll div\n");
423
424        // put the larger root on top of the stack
425        function.append("2 copy gt {exch} if\n");
426
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");
433
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");
436
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");
443
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");
447
448        // d < 0, clear the stack and push false
449        function.append("} {pop pop pop false} ifelse\n");
450    }
451
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);
456
457    // otherwise, just write black
458    function.append("} {0 0 0} ifelse }");
459
460    return function;
461}
462
463static 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}
471
472class SkPDFShader::State {
473public:
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;
480
481    SkBitmap fImage;
482    uint32_t fPixelGeneration;
483    SkShader::TileMode fImageTileModes[2];
484
485    State(const SkShader& shader, const SkMatrix& canvasTransform,
486          const SkIRect& bbox);
487
488    bool operator==(const State& b) const;
489
490    SkPDFShader::State* CreateAlphaToLuminosityState() const;
491    SkPDFShader::State* CreateOpaqueState() const;
492
493    bool GradientHasAlpha() const;
494
495private:
496    State(const State& other);
497    State operator=(const State& rhs);
498    void AllocateGradientInfoStorage();
499};
500
501class SkPDFFunctionShader : public SkPDFDict, public SkPDFShader {
502    SK_DECLARE_INST_COUNT(SkPDFFunctionShader)
503public:
504    explicit SkPDFFunctionShader(SkPDFShader::State* state);
505    virtual ~SkPDFFunctionShader() {
506        if (isValid()) {
507            RemoveShader(this);
508        }
509        fResources.unrefAll();
510    }
511
512    virtual bool isValid() { return fResources.count() > 0; }
513
514    void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
515                      SkTSet<SkPDFObject*>* newResourceObjects) {
516        GetResourcesHelper(&fResources,
517                           knownResourceObjects,
518                           newResourceObjects);
519    }
520
521private:
522    static SkPDFObject* RangeObject();
523
524    SkTDArray<SkPDFObject*> fResources;
525    SkAutoTDelete<const SkPDFShader::State> fState;
526
527    SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain);
528    typedef SkPDFDict INHERITED;
529};
530
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 */
536class SkPDFAlphaFunctionShader : public SkPDFStream, public SkPDFShader {
537public:
538    explicit SkPDFAlphaFunctionShader(SkPDFShader::State* state);
539    virtual ~SkPDFAlphaFunctionShader() {
540        if (isValid()) {
541            RemoveShader(this);
542        }
543    }
544
545    virtual bool isValid() {
546        return fColorShader.get() != NULL;
547    }
548
549private:
550    SkAutoTDelete<const SkPDFShader::State> fState;
551
552    SkPDFGraphicState* CreateSMaskGraphicState();
553
554    void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
555                      SkTSet<SkPDFObject*>* newResourceObjects) {
556        fResourceDict->getReferencedResources(knownResourceObjects,
557                                              newResourceObjects,
558                                              true);
559    }
560
561    SkAutoTUnref<SkPDFObject> fColorShader;
562    SkAutoTUnref<SkPDFResourceDict> fResourceDict;
563};
564
565class SkPDFImageShader : public SkPDFStream, public SkPDFShader {
566public:
567    explicit SkPDFImageShader(SkPDFShader::State* state);
568    virtual ~SkPDFImageShader() {
569        if (isValid()) {
570            RemoveShader(this);
571        }
572        fResources.unrefAll();
573    }
574
575    virtual bool isValid() { return size() > 0; }
576
577    void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
578                      SkTSet<SkPDFObject*>* newResourceObjects) {
579        GetResourcesHelper(&fResources.toArray(),
580                           knownResourceObjects,
581                           newResourceObjects);
582    }
583
584private:
585    SkTSet<SkPDFObject*> fResources;
586    SkAutoTDelete<const SkPDFShader::State> fState;
587};
588
589SkPDFShader::SkPDFShader() {}
590
591// static
592SkPDFObject* SkPDFShader::GetPDFShaderByState(State* inState) {
593    SkPDFObject* result;
594
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    }
604
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    }
612
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}
641
642// static
643void 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}
650
651// static
652SkPDFObject* 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}
659
660// static
661SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::CanonicalShaders() {
662    SkPDFShader::CanonicalShadersMutex().assertHeld();
663    static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
664    return gCanonicalShaders;
665}
666
667SK_DECLARE_STATIC_MUTEX(gCanonicalShadersMutex);
668// static
669SkBaseMutex& SkPDFShader::CanonicalShadersMutex() {
670    return gCanonicalShadersMutex;
671}
672
673// static
674SkPDFObject* SkPDFFunctionShader::RangeObject() {
675    SkPDFShader::CanonicalShadersMutex().assertHeld();
676    static SkPDFArray* range = NULL;
677    // This method is only used with CanonicalShadersMutex, so it's safe to
678    // populate domain.
679    if (range == NULL) {
680        range = new SkPDFArray;
681        range->reserve(6);
682        range->appendInt(0);
683        range->appendInt(1);
684        range->appendInt(0);
685        range->appendInt(1);
686        range->appendInt(0);
687        range->appendInt(1);
688    }
689    return range;
690}
691
692static SkPDFResourceDict* get_gradient_resource_dict(
693        SkPDFObject* functionShader,
694        SkPDFObject* gState) {
695    SkPDFResourceDict* dict = new SkPDFResourceDict();
696
697    if (functionShader != NULL) {
698        dict->insertResourceAsReference(
699                SkPDFResourceDict::kPattern_ResourceType, 0, functionShader);
700    }
701    if (gState != NULL) {
702        dict->insertResourceAsReference(
703                SkPDFResourceDict::kExtGState_ResourceType, 0, gState);
704    }
705
706    return dict;
707}
708
709static void populate_tiling_pattern_dict(SkPDFDict* pattern,
710                                      SkRect& bbox, SkPDFDict* resources,
711                                      const SkMatrix& matrix) {
712    const int kTiling_PatternType = 1;
713    const int kColoredTilingPattern_PaintType = 1;
714    const int kConstantSpacing_TilingType = 1;
715
716    pattern->insertName("Type", "Pattern");
717    pattern->insertInt("PatternType", kTiling_PatternType);
718    pattern->insertInt("PaintType", kColoredTilingPattern_PaintType);
719    pattern->insertInt("TilingType", kConstantSpacing_TilingType);
720    pattern->insert("BBox", SkPDFUtils::RectToArray(bbox))->unref();
721    pattern->insertScalar("XStep", bbox.width());
722    pattern->insertScalar("YStep", bbox.height());
723    pattern->insert("Resources", resources);
724    if (!matrix.isIdentity()) {
725        pattern->insert("Matrix", SkPDFUtils::MatrixToArray(matrix))->unref();
726    }
727}
728
729/**
730 * Creates a content stream which fills the pattern P0 across bounds.
731 * @param gsIndex A graphics state resource index to apply, or <0 if no
732 * graphics state to apply.
733 */
734static SkStream* create_pattern_fill_content(int gsIndex, SkRect& bounds) {
735    SkDynamicMemoryWStream content;
736    if (gsIndex >= 0) {
737        SkPDFUtils::ApplyGraphicState(gsIndex, &content);
738    }
739    SkPDFUtils::ApplyPattern(0, &content);
740    SkPDFUtils::AppendRectangle(bounds, &content);
741    SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType,
742                          &content);
743
744    return content.detachAsStream();
745}
746
747/**
748 * Creates a ExtGState with the SMask set to the luminosityShader in
749 * luminosity mode. The shader pattern extends to the bbox.
750 */
751SkPDFGraphicState* SkPDFAlphaFunctionShader::CreateSMaskGraphicState() {
752    SkRect bbox;
753    bbox.set(fState.get()->fBBox);
754
755    SkAutoTUnref<SkPDFObject> luminosityShader(
756            SkPDFShader::GetPDFShaderByState(
757                 fState->CreateAlphaToLuminosityState()));
758
759    SkAutoTUnref<SkStream> alphaStream(create_pattern_fill_content(-1, bbox));
760
761    SkAutoTUnref<SkPDFResourceDict>
762        resources(get_gradient_resource_dict(luminosityShader, NULL));
763
764    SkAutoTUnref<SkPDFFormXObject> alphaMask(
765            new SkPDFFormXObject(alphaStream.get(), bbox, resources.get()));
766
767    return SkPDFGraphicState::GetSMaskGraphicState(
768            alphaMask.get(), false,
769            SkPDFGraphicState::kLuminosity_SMaskMode);
770}
771
772SkPDFAlphaFunctionShader::SkPDFAlphaFunctionShader(SkPDFShader::State* state)
773        : fState(state) {
774    SkRect bbox;
775    bbox.set(fState.get()->fBBox);
776
777    fColorShader.reset(
778            SkPDFShader::GetPDFShaderByState(state->CreateOpaqueState()));
779
780    // Create resource dict with alpha graphics state as G0 and
781    // pattern shader as P0, then write content stream.
782    SkAutoTUnref<SkPDFGraphicState> alphaGs(CreateSMaskGraphicState());
783    fResourceDict.reset(
784            get_gradient_resource_dict(fColorShader.get(), alphaGs.get()));
785
786    SkAutoTUnref<SkStream> colorStream(
787            create_pattern_fill_content(0, bbox));
788    setData(colorStream.get());
789
790    populate_tiling_pattern_dict(this, bbox, fResourceDict.get(),
791                                 SkMatrix::I());
792}
793
794// Finds affine and persp such that in = affine * persp.
795// but it returns the inverse of perspective matrix.
796static bool split_perspective(const SkMatrix in, SkMatrix* affine,
797                              SkMatrix* perspectiveInverse) {
798    const SkScalar p2 = in[SkMatrix::kMPersp2];
799
800    if (SkScalarNearlyZero(p2)) {
801        return false;
802    }
803
804    const SkScalar zero = SkIntToScalar(0);
805    const SkScalar one = SkIntToScalar(1);
806
807    const SkScalar sx = in[SkMatrix::kMScaleX];
808    const SkScalar kx = in[SkMatrix::kMSkewX];
809    const SkScalar tx = in[SkMatrix::kMTransX];
810    const SkScalar ky = in[SkMatrix::kMSkewY];
811    const SkScalar sy = in[SkMatrix::kMScaleY];
812    const SkScalar ty = in[SkMatrix::kMTransY];
813    const SkScalar p0 = in[SkMatrix::kMPersp0];
814    const SkScalar p1 = in[SkMatrix::kMPersp1];
815
816    // Perspective matrix would be:
817    // 1  0  0
818    // 0  1  0
819    // p0 p1 p2
820    // But we need the inverse of persp.
821    perspectiveInverse->setAll(one,          zero,       zero,
822                               zero,         one,        zero,
823                               -p0/p2,     -p1/p2,     1/p2);
824
825    affine->setAll(sx - p0 * tx / p2,       kx - p1 * tx / p2,      tx / p2,
826                   ky - p0 * ty / p2,       sy - p1 * ty / p2,      ty / p2,
827                   zero,                    zero,                   one);
828
829    return true;
830}
831
832SkPDFFunctionShader::SkPDFFunctionShader(SkPDFShader::State* state)
833        : SkPDFDict("Pattern"),
834          fState(state) {
835    SkString (*codeFunction)(const SkShader::GradientInfo& info,
836                             const SkMatrix& perspectiveRemover) = NULL;
837    SkPoint transformPoints[2];
838
839    // Depending on the type of the gradient, we want to transform the
840    // coordinate space in different ways.
841    const SkShader::GradientInfo* info = &fState.get()->fInfo;
842    transformPoints[0] = info->fPoint[0];
843    transformPoints[1] = info->fPoint[1];
844    switch (fState.get()->fType) {
845        case SkShader::kLinear_GradientType:
846            codeFunction = &linearCode;
847            break;
848        case SkShader::kRadial_GradientType:
849            transformPoints[1] = transformPoints[0];
850            transformPoints[1].fX += info->fRadius[0];
851            codeFunction = &radialCode;
852            break;
853        case SkShader::kRadial2_GradientType: {
854            // Bail out if the radii are the same.  Empty fResources signals
855            // an error and isValid will return false.
856            if (info->fRadius[0] == info->fRadius[1]) {
857                return;
858            }
859            transformPoints[1] = transformPoints[0];
860            SkScalar dr = info->fRadius[1] - info->fRadius[0];
861            transformPoints[1].fX += dr;
862            codeFunction = &twoPointRadialCode;
863            break;
864        }
865        case SkShader::kConical_GradientType: {
866            transformPoints[1] = transformPoints[0];
867            transformPoints[1].fX += SK_Scalar1;
868            codeFunction = &twoPointConicalCode;
869            break;
870        }
871        case SkShader::kSweep_GradientType:
872            transformPoints[1] = transformPoints[0];
873            transformPoints[1].fX += SK_Scalar1;
874            codeFunction = &sweepCode;
875            break;
876        case SkShader::kColor_GradientType:
877        case SkShader::kNone_GradientType:
878        default:
879            return;
880    }
881
882    // Move any scaling (assuming a unit gradient) or translation
883    // (and rotation for linear gradient), of the final gradient from
884    // info->fPoints to the matrix (updating bbox appropriately).  Now
885    // the gradient can be drawn on on the unit segment.
886    SkMatrix mapperMatrix;
887    unitToPointsMatrix(transformPoints, &mapperMatrix);
888
889    SkMatrix finalMatrix = fState.get()->fCanvasTransform;
890    finalMatrix.preConcat(fState.get()->fShaderTransform);
891    finalMatrix.preConcat(mapperMatrix);
892
893    // Preserves as much as posible in the final matrix, and only removes
894    // the perspective. The inverse of the perspective is stored in
895    // perspectiveInverseOnly matrix and has 3 useful numbers
896    // (p0, p1, p2), while everything else is either 0 or 1.
897    // In this way the shader will handle it eficiently, with minimal code.
898    SkMatrix perspectiveInverseOnly = SkMatrix::I();
899    if (finalMatrix.hasPerspective()) {
900        if (!split_perspective(finalMatrix,
901                               &finalMatrix, &perspectiveInverseOnly)) {
902            return;
903        }
904    }
905
906    SkRect bbox;
907    bbox.set(fState.get()->fBBox);
908    if (!inverseTransformBBox(finalMatrix, &bbox)) {
909        return;
910    }
911
912    SkAutoTUnref<SkPDFArray> domain(new SkPDFArray);
913    domain->reserve(4);
914    domain->appendScalar(bbox.fLeft);
915    domain->appendScalar(bbox.fRight);
916    domain->appendScalar(bbox.fTop);
917    domain->appendScalar(bbox.fBottom);
918
919    SkString functionCode;
920    // The two point radial gradient further references fState.get()->fInfo
921    // in translating from x, y coordinates to the t parameter. So, we have
922    // to transform the points and radii according to the calculated matrix.
923    if (fState.get()->fType == SkShader::kRadial2_GradientType) {
924        SkShader::GradientInfo twoPointRadialInfo = *info;
925        SkMatrix inverseMapperMatrix;
926        if (!mapperMatrix.invert(&inverseMapperMatrix)) {
927            return;
928        }
929        inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
930        twoPointRadialInfo.fRadius[0] =
931            inverseMapperMatrix.mapRadius(info->fRadius[0]);
932        twoPointRadialInfo.fRadius[1] =
933            inverseMapperMatrix.mapRadius(info->fRadius[1]);
934        functionCode = codeFunction(twoPointRadialInfo, perspectiveInverseOnly);
935    } else {
936        functionCode = codeFunction(*info, perspectiveInverseOnly);
937    }
938
939    SkAutoTUnref<SkPDFDict> pdfShader(new SkPDFDict);
940    pdfShader->insertInt("ShadingType", 1);
941    pdfShader->insertName("ColorSpace", "DeviceRGB");
942    pdfShader->insert("Domain", domain.get());
943
944    SkPDFStream* function = makePSFunction(functionCode, domain.get());
945    pdfShader->insert("Function", new SkPDFObjRef(function))->unref();
946    fResources.push(function);  // Pass ownership to resource list.
947
948    insertInt("PatternType", 2);
949    insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
950    insert("Shading", pdfShader.get());
951}
952
953SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) {
954    fState.get()->fImage.lockPixels();
955
956    // The image shader pattern cell will be drawn into a separate device
957    // in pattern cell space (no scaling on the bitmap, though there may be
958    // translations so that all content is in the device, coordinates > 0).
959
960    // Map clip bounds to shader space to ensure the device is large enough
961    // to handle fake clamping.
962    SkMatrix finalMatrix = fState.get()->fCanvasTransform;
963    finalMatrix.preConcat(fState.get()->fShaderTransform);
964    SkRect deviceBounds;
965    deviceBounds.set(fState.get()->fBBox);
966    if (!inverseTransformBBox(finalMatrix, &deviceBounds)) {
967        return;
968    }
969
970    const SkBitmap* image = &fState.get()->fImage;
971    SkRect bitmapBounds;
972    image->getBounds(&bitmapBounds);
973
974    // For tiling modes, the bounds should be extended to include the bitmap,
975    // otherwise the bitmap gets clipped out and the shader is empty and awful.
976    // For clamp modes, we're only interested in the clip region, whether
977    // or not the main bitmap is in it.
978    SkShader::TileMode tileModes[2];
979    tileModes[0] = fState.get()->fImageTileModes[0];
980    tileModes[1] = fState.get()->fImageTileModes[1];
981    if (tileModes[0] != SkShader::kClamp_TileMode ||
982            tileModes[1] != SkShader::kClamp_TileMode) {
983        deviceBounds.join(bitmapBounds);
984    }
985
986    SkMatrix unflip;
987    unflip.setTranslate(0, SkScalarRoundToScalar(deviceBounds.height()));
988    unflip.preScale(SK_Scalar1, -SK_Scalar1);
989    SkISize size = SkISize::Make(SkScalarRoundToInt(deviceBounds.width()),
990                                 SkScalarRoundToInt(deviceBounds.height()));
991    // TODO(edisonn): should we pass here the DCT encoder of the destination device?
992    // TODO(edisonn): NYI Perspective, use SkPDFDeviceFlattener.
993    SkPDFDevice pattern(size, size, unflip);
994    SkCanvas canvas(&pattern);
995
996    SkRect patternBBox;
997    image->getBounds(&patternBBox);
998
999    // Translate the canvas so that the bitmap origin is at (0, 0).
1000    canvas.translate(-deviceBounds.left(), -deviceBounds.top());
1001    patternBBox.offset(-deviceBounds.left(), -deviceBounds.top());
1002    // Undo the translation in the final matrix
1003    finalMatrix.preTranslate(deviceBounds.left(), deviceBounds.top());
1004
1005    // If the bitmap is out of bounds (i.e. clamp mode where we only see the
1006    // stretched sides), canvas will clip this out and the extraneous data
1007    // won't be saved to the PDF.
1008    canvas.drawBitmap(*image, 0, 0);
1009
1010    SkScalar width = SkIntToScalar(image->width());
1011    SkScalar height = SkIntToScalar(image->height());
1012
1013    // Tiling is implied.  First we handle mirroring.
1014    if (tileModes[0] == SkShader::kMirror_TileMode) {
1015        SkMatrix xMirror;
1016        xMirror.setScale(-1, 1);
1017        xMirror.postTranslate(2 * width, 0);
1018        canvas.drawBitmapMatrix(*image, xMirror);
1019        patternBBox.fRight += width;
1020    }
1021    if (tileModes[1] == SkShader::kMirror_TileMode) {
1022        SkMatrix yMirror;
1023        yMirror.setScale(SK_Scalar1, -SK_Scalar1);
1024        yMirror.postTranslate(0, 2 * height);
1025        canvas.drawBitmapMatrix(*image, yMirror);
1026        patternBBox.fBottom += height;
1027    }
1028    if (tileModes[0] == SkShader::kMirror_TileMode &&
1029            tileModes[1] == SkShader::kMirror_TileMode) {
1030        SkMatrix mirror;
1031        mirror.setScale(-1, -1);
1032        mirror.postTranslate(2 * width, 2 * height);
1033        canvas.drawBitmapMatrix(*image, mirror);
1034    }
1035
1036    // Then handle Clamping, which requires expanding the pattern canvas to
1037    // cover the entire surfaceBBox.
1038
1039    // If both x and y are in clamp mode, we start by filling in the corners.
1040    // (Which are just a rectangles of the corner colors.)
1041    if (tileModes[0] == SkShader::kClamp_TileMode &&
1042            tileModes[1] == SkShader::kClamp_TileMode) {
1043        SkPaint paint;
1044        SkRect rect;
1045        rect = SkRect::MakeLTRB(deviceBounds.left(), deviceBounds.top(), 0, 0);
1046        if (!rect.isEmpty()) {
1047            paint.setColor(image->getColor(0, 0));
1048            canvas.drawRect(rect, paint);
1049        }
1050
1051        rect = SkRect::MakeLTRB(width, deviceBounds.top(),
1052                                deviceBounds.right(), 0);
1053        if (!rect.isEmpty()) {
1054            paint.setColor(image->getColor(image->width() - 1, 0));
1055            canvas.drawRect(rect, paint);
1056        }
1057
1058        rect = SkRect::MakeLTRB(width, height,
1059                                deviceBounds.right(), deviceBounds.bottom());
1060        if (!rect.isEmpty()) {
1061            paint.setColor(image->getColor(image->width() - 1,
1062                                           image->height() - 1));
1063            canvas.drawRect(rect, paint);
1064        }
1065
1066        rect = SkRect::MakeLTRB(deviceBounds.left(), height,
1067                                0, deviceBounds.bottom());
1068        if (!rect.isEmpty()) {
1069            paint.setColor(image->getColor(0, image->height() - 1));
1070            canvas.drawRect(rect, paint);
1071        }
1072    }
1073
1074    // Then expand the left, right, top, then bottom.
1075    if (tileModes[0] == SkShader::kClamp_TileMode) {
1076        SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, image->height());
1077        if (deviceBounds.left() < 0) {
1078            SkBitmap left;
1079            SkAssertResult(image->extractSubset(&left, subset));
1080
1081            SkMatrix leftMatrix;
1082            leftMatrix.setScale(-deviceBounds.left(), 1);
1083            leftMatrix.postTranslate(deviceBounds.left(), 0);
1084            canvas.drawBitmapMatrix(left, leftMatrix);
1085
1086            if (tileModes[1] == SkShader::kMirror_TileMode) {
1087                leftMatrix.postScale(SK_Scalar1, -SK_Scalar1);
1088                leftMatrix.postTranslate(0, 2 * height);
1089                canvas.drawBitmapMatrix(left, leftMatrix);
1090            }
1091            patternBBox.fLeft = 0;
1092        }
1093
1094        if (deviceBounds.right() > width) {
1095            SkBitmap right;
1096            subset.offset(image->width() - 1, 0);
1097            SkAssertResult(image->extractSubset(&right, subset));
1098
1099            SkMatrix rightMatrix;
1100            rightMatrix.setScale(deviceBounds.right() - width, 1);
1101            rightMatrix.postTranslate(width, 0);
1102            canvas.drawBitmapMatrix(right, rightMatrix);
1103
1104            if (tileModes[1] == SkShader::kMirror_TileMode) {
1105                rightMatrix.postScale(SK_Scalar1, -SK_Scalar1);
1106                rightMatrix.postTranslate(0, 2 * height);
1107                canvas.drawBitmapMatrix(right, rightMatrix);
1108            }
1109            patternBBox.fRight = deviceBounds.width();
1110        }
1111    }
1112
1113    if (tileModes[1] == SkShader::kClamp_TileMode) {
1114        SkIRect subset = SkIRect::MakeXYWH(0, 0, image->width(), 1);
1115        if (deviceBounds.top() < 0) {
1116            SkBitmap top;
1117            SkAssertResult(image->extractSubset(&top, subset));
1118
1119            SkMatrix topMatrix;
1120            topMatrix.setScale(SK_Scalar1, -deviceBounds.top());
1121            topMatrix.postTranslate(0, deviceBounds.top());
1122            canvas.drawBitmapMatrix(top, topMatrix);
1123
1124            if (tileModes[0] == SkShader::kMirror_TileMode) {
1125                topMatrix.postScale(-1, 1);
1126                topMatrix.postTranslate(2 * width, 0);
1127                canvas.drawBitmapMatrix(top, topMatrix);
1128            }
1129            patternBBox.fTop = 0;
1130        }
1131
1132        if (deviceBounds.bottom() > height) {
1133            SkBitmap bottom;
1134            subset.offset(0, image->height() - 1);
1135            SkAssertResult(image->extractSubset(&bottom, subset));
1136
1137            SkMatrix bottomMatrix;
1138            bottomMatrix.setScale(SK_Scalar1, deviceBounds.bottom() - height);
1139            bottomMatrix.postTranslate(0, height);
1140            canvas.drawBitmapMatrix(bottom, bottomMatrix);
1141
1142            if (tileModes[0] == SkShader::kMirror_TileMode) {
1143                bottomMatrix.postScale(-1, 1);
1144                bottomMatrix.postTranslate(2 * width, 0);
1145                canvas.drawBitmapMatrix(bottom, bottomMatrix);
1146            }
1147            patternBBox.fBottom = deviceBounds.height();
1148        }
1149    }
1150
1151    // Put the canvas into the pattern stream (fContent).
1152    SkAutoTUnref<SkStream> content(pattern.content());
1153    setData(content.get());
1154    SkPDFResourceDict* resourceDict = pattern.getResourceDict();
1155    resourceDict->getReferencedResources(fResources, &fResources, false);
1156
1157    populate_tiling_pattern_dict(this, patternBBox,
1158                                 pattern.getResourceDict(), finalMatrix);
1159
1160    fState.get()->fImage.unlockPixels();
1161}
1162
1163SkPDFStream* SkPDFFunctionShader::makePSFunction(const SkString& psCode, SkPDFArray* domain) {
1164    SkAutoDataUnref funcData(SkData::NewWithCopy(psCode.c_str(), psCode.size()));
1165    SkPDFStream* result = new SkPDFStream(funcData.get());
1166    result->insertInt("FunctionType", 4);
1167    result->insert("Domain", domain);
1168    result->insert("Range", RangeObject());
1169    return result;
1170}
1171
1172SkPDFShader::ShaderCanonicalEntry::ShaderCanonicalEntry(SkPDFObject* pdfShader, const State* state)
1173    : fPDFShader(pdfShader)
1174    , fState(state)
1175{}
1176
1177bool SkPDFShader::ShaderCanonicalEntry::operator==(const ShaderCanonicalEntry& b) const {
1178    return fPDFShader == b.fPDFShader ||
1179           (fState != NULL && b.fState != NULL && *fState == *b.fState);
1180}
1181
1182bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
1183    if (fType != b.fType ||
1184            fCanvasTransform != b.fCanvasTransform ||
1185            fShaderTransform != b.fShaderTransform ||
1186            fBBox != b.fBBox) {
1187        return false;
1188    }
1189
1190    if (fType == SkShader::kNone_GradientType) {
1191        if (fPixelGeneration != b.fPixelGeneration ||
1192                fPixelGeneration == 0 ||
1193                fImageTileModes[0] != b.fImageTileModes[0] ||
1194                fImageTileModes[1] != b.fImageTileModes[1]) {
1195            return false;
1196        }
1197    } else {
1198        if (fInfo.fColorCount != b.fInfo.fColorCount ||
1199                memcmp(fInfo.fColors, b.fInfo.fColors,
1200                       sizeof(SkColor) * fInfo.fColorCount) != 0 ||
1201                memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
1202                       sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
1203                fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
1204                fInfo.fTileMode != b.fInfo.fTileMode) {
1205            return false;
1206        }
1207
1208        switch (fType) {
1209            case SkShader::kLinear_GradientType:
1210                if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
1211                    return false;
1212                }
1213                break;
1214            case SkShader::kRadial_GradientType:
1215                if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
1216                    return false;
1217                }
1218                break;
1219            case SkShader::kRadial2_GradientType:
1220            case SkShader::kConical_GradientType:
1221                if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
1222                        fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
1223                        fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
1224                    return false;
1225                }
1226                break;
1227            case SkShader::kSweep_GradientType:
1228            case SkShader::kNone_GradientType:
1229            case SkShader::kColor_GradientType:
1230                break;
1231        }
1232    }
1233    return true;
1234}
1235
1236SkPDFShader::State::State(const SkShader& shader,
1237                          const SkMatrix& canvasTransform, const SkIRect& bbox)
1238        : fCanvasTransform(canvasTransform),
1239          fBBox(bbox),
1240          fPixelGeneration(0) {
1241    fInfo.fColorCount = 0;
1242    fInfo.fColors = NULL;
1243    fInfo.fColorOffsets = NULL;
1244    fShaderTransform = shader.getLocalMatrix();
1245    fImageTileModes[0] = fImageTileModes[1] = SkShader::kClamp_TileMode;
1246
1247    fType = shader.asAGradient(&fInfo);
1248
1249    if (fType == SkShader::kNone_GradientType) {
1250        SkShader::BitmapType bitmapType;
1251        SkMatrix matrix;
1252        bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes);
1253        if (bitmapType != SkShader::kDefault_BitmapType) {
1254            fImage.reset();
1255            return;
1256        }
1257        SkASSERT(matrix.isIdentity());
1258        fPixelGeneration = fImage.getGenerationID();
1259    } else {
1260        AllocateGradientInfoStorage();
1261        shader.asAGradient(&fInfo);
1262    }
1263}
1264
1265SkPDFShader::State::State(const SkPDFShader::State& other)
1266  : fType(other.fType),
1267    fCanvasTransform(other.fCanvasTransform),
1268    fShaderTransform(other.fShaderTransform),
1269    fBBox(other.fBBox)
1270{
1271    // Only gradients supported for now, since that is all that is used.
1272    // If needed, image state copy constructor can be added here later.
1273    SkASSERT(fType != SkShader::kNone_GradientType);
1274
1275    if (fType != SkShader::kNone_GradientType) {
1276        fInfo = other.fInfo;
1277
1278        AllocateGradientInfoStorage();
1279        for (int i = 0; i < fInfo.fColorCount; i++) {
1280            fInfo.fColors[i] = other.fInfo.fColors[i];
1281            fInfo.fColorOffsets[i] = other.fInfo.fColorOffsets[i];
1282        }
1283    }
1284}
1285
1286/**
1287 * Create a copy of this gradient state with alpha assigned to RGB luminousity.
1288 * Only valid for gradient states.
1289 */
1290SkPDFShader::State* SkPDFShader::State::CreateAlphaToLuminosityState() const {
1291    SkASSERT(fType != SkShader::kNone_GradientType);
1292
1293    SkPDFShader::State* newState = new SkPDFShader::State(*this);
1294
1295    for (int i = 0; i < fInfo.fColorCount; i++) {
1296        SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1297        newState->fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha);
1298    }
1299
1300    return newState;
1301}
1302
1303/**
1304 * Create a copy of this gradient state with alpha set to fully opaque
1305 * Only valid for gradient states.
1306 */
1307SkPDFShader::State* SkPDFShader::State::CreateOpaqueState() const {
1308    SkASSERT(fType != SkShader::kNone_GradientType);
1309
1310    SkPDFShader::State* newState = new SkPDFShader::State(*this);
1311    for (int i = 0; i < fInfo.fColorCount; i++) {
1312        newState->fInfo.fColors[i] = SkColorSetA(fInfo.fColors[i],
1313                                                 SK_AlphaOPAQUE);
1314    }
1315
1316    return newState;
1317}
1318
1319/**
1320 * Returns true if state is a gradient and the gradient has alpha.
1321 */
1322bool SkPDFShader::State::GradientHasAlpha() const {
1323    if (fType == SkShader::kNone_GradientType) {
1324        return false;
1325    }
1326
1327    for (int i = 0; i < fInfo.fColorCount; i++) {
1328        SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1329        if (alpha != SK_AlphaOPAQUE) {
1330            return true;
1331        }
1332    }
1333    return false;
1334}
1335
1336void SkPDFShader::State::AllocateGradientInfoStorage() {
1337    fColorData.set(sk_malloc_throw(
1338               fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
1339    fInfo.fColors = reinterpret_cast<SkColor*>(fColorData.get());
1340    fInfo.fColorOffsets =
1341            reinterpret_cast<SkScalar*>(fInfo.fColors + fInfo.fColorCount);
1342}
1343