• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "SkPDFShader.h"
18 
19 #include "SkCanvas.h"
20 #include "SkPDFCatalog.h"
21 #include "SkPDFDevice.h"
22 #include "SkPDFTypes.h"
23 #include "SkPDFUtils.h"
24 #include "SkScalar.h"
25 #include "SkStream.h"
26 #include "SkTemplates.h"
27 #include "SkThread.h"
28 #include "SkTypes.h"
29 
transformBBox(const SkMatrix & matrix,SkRect * bbox)30 static void transformBBox(const SkMatrix& matrix, SkRect* bbox) {
31     SkMatrix inverse;
32     inverse.reset();
33     matrix.invert(&inverse);
34     inverse.mapRect(bbox);
35 }
36 
unitToPointsMatrix(const SkPoint pts[2],SkMatrix * matrix)37 static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) {
38     SkVector    vec = pts[1] - pts[0];
39     SkScalar    mag = vec.length();
40     SkScalar    inv = mag ? SkScalarInvert(mag) : 0;
41 
42     vec.scale(inv);
43     matrix->setSinCos(vec.fY, vec.fX);
44     matrix->preTranslate(pts[0].fX, pts[0].fY);
45     matrix->preScale(mag, mag);
46 }
47 
48 /* Assumes t + startOffset is on the stack and does a linear interpolation on t
49    between startOffset and endOffset from prevColor to curColor (for each color
50    component), leaving the result in component order on the stack.
51    @param range                  endOffset - startOffset
52    @param curColor[components]   The current color components.
53    @param prevColor[components]  The previous color components.
54    @param result                 The result ps function.
55  */
interpolateColorCode(SkScalar range,SkScalar * curColor,SkScalar * prevColor,int components,SkString * result)56 static void interpolateColorCode(SkScalar range, SkScalar* curColor,
57                                  SkScalar* prevColor, int components,
58                                  SkString* result) {
59     // Figure out how to scale each color component.
60     SkAutoSTMalloc<4, SkScalar> multiplierAlloc(components);
61     SkScalar *multiplier = multiplierAlloc.get();
62     for (int i = 0; i < components; 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     SkAutoSTMalloc<4, bool> dupInputAlloc(components);
70     bool *dupInput = dupInputAlloc.get();
71     dupInput[components - 1] = false;
72     for (int i = components - 2; i >= 0; i--) {
73         dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
74     }
75 
76     if (!dupInput[0] && multiplier[0] == 0) {
77         result->append("pop ");
78     }
79 
80     for (int i = 0; i < components; i++) {
81         // If the next components needs t, make a copy.
82         if (dupInput[i]) {
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  */
gradientFunctionCode(const SkShader::GradientInfo & info,SkString * result)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     }
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     for (int i = 1 ; i < info.fColorCount; i++) {
156         result->append("{dup ");
157         result->appendScalar(info.fColorOffsets[i]);
158         result->append(" le {");
159         if (info.fColorOffsets[i - 1] != 0) {
160             result->appendScalar(info.fColorOffsets[i - 1]);
161             result->append(" sub\n");
162         }
163 
164         interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
165                              colorData[i], colorData[i - 1], kColorComponents,
166                              result);
167         result->append("}\n");
168     }
169 
170     // Clamp the final color.
171     result->append("{pop ");
172     result->appendScalar(colorData[info.fColorCount - 1][0]);
173     result->append(" ");
174     result->appendScalar(colorData[info.fColorCount - 1][1]);
175     result->append(" ");
176     result->appendScalar(colorData[info.fColorCount - 1][2]);
177 
178     for (int i = 0 ; i < info.fColorCount; i++) {
179         result->append("} ifelse\n");
180     }
181 }
182 
183 /* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
tileModeCode(SkShader::TileMode mode,SkString * result)184 static void tileModeCode(SkShader::TileMode mode, SkString* result) {
185     if (mode == SkShader::kRepeat_TileMode) {
186         result->append("dup truncate sub\n");  // Get the fractional part.
187         result->append("dup 0 le {1 add} if\n");  // Map (-1,0) => (0,1)
188         return;
189     }
190 
191     if (mode == SkShader::kMirror_TileMode) {
192         // Map t mod 2 into [0, 1, 1, 0].
193         //               Code                     Stack
194         result->append("abs "                 // Map negative to positive.
195                        "dup "                 // t.s t.s
196                        "truncate "            // t.s t
197                        "dup "                 // t.s t t
198                        "cvi "                 // t.s t T
199                        "2 mod "               // t.s t (i mod 2)
200                        "1 eq "                // t.s t true|false
201                        "3 1 roll "            // true|false t.s t
202                        "sub "                 // true|false 0.s
203                        "exch "                // 0.s true|false
204                        "{1 exch sub} if\n");  // 1 - 0.s|0.s
205     }
206 }
207 
linearCode(const SkShader::GradientInfo & info)208 static SkString linearCode(const SkShader::GradientInfo& info) {
209     SkString function("{pop\n"); // Just ditch the y value.
210     tileModeCode(info.fTileMode, &function);
211     gradientFunctionCode(info, &function);
212     function.append("}");
213     return function;
214 }
215 
radialCode(const SkShader::GradientInfo & info)216 static SkString radialCode(const SkShader::GradientInfo& info) {
217     SkString function("{");
218     // Find the distance from the origin.
219     function.append("dup "      // x y y
220                     "mul "      // x y^2
221                     "exch "     // y^2 x
222                     "dup "      // y^2 x x
223                     "mul "      // y^2 x^2
224                     "add "      // y^2+x^2
225                     "sqrt\n");  // sqrt(y^2+x^2)
226 
227     tileModeCode(info.fTileMode, &function);
228     gradientFunctionCode(info, &function);
229     function.append("}");
230     return function;
231 }
232 
233 /* The math here is all based on the description in Two_Point_Radial_Gradient,
234    with one simplification, the coordinate space has been scaled so that
235    Dr = 1.  This means we don't need to scale the entire equation by 1/Dr^2.
236  */
twoPointRadialCode(const SkShader::GradientInfo & info)237 static SkString twoPointRadialCode(const SkShader::GradientInfo& info) {
238     SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
239     SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
240     SkScalar sr = info.fRadius[0];
241     SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
242     bool posRoot = info.fRadius[1] > info.fRadius[0];
243 
244     // We start with a stack of (x y), copy it and then consume one copy in
245     // order to calculate b and the other to calculate c.
246     SkString function("{");
247     function.append("2 copy ");
248 
249     // Calculate -b and b^2.
250     function.appendScalar(dy);
251     function.append(" mul exch ");
252     function.appendScalar(dx);
253     function.append(" mul add ");
254     function.appendScalar(sr);
255     function.append(" sub 2 mul neg dup dup mul\n");
256 
257     // Calculate c
258     function.append("4 2 roll dup mul exch dup mul add ");
259     function.appendScalar(SkScalarMul(sr, sr));
260     function.append(" sub\n");
261 
262     // Calculate the determinate
263     function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
264     function.append(" mul sub abs sqrt\n");
265 
266     // And then the final value of t.
267     if (posRoot) {
268         function.append("sub ");
269     } else {
270         function.append("add ");
271     }
272     function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
273     function.append(" div\n");
274 
275     tileModeCode(info.fTileMode, &function);
276     gradientFunctionCode(info, &function);
277     function.append("}");
278     return function;
279 }
280 
sweepCode(const SkShader::GradientInfo & info)281 static SkString sweepCode(const SkShader::GradientInfo& info) {
282     SkString function("{exch atan 360 div\n");
283     tileModeCode(info.fTileMode, &function);
284     gradientFunctionCode(info, &function);
285     function.append("}");
286     return function;
287 }
288 
~SkPDFShader()289 SkPDFShader::~SkPDFShader() {
290     SkAutoMutexAcquire lock(canonicalShadersMutex());
291     ShaderCanonicalEntry entry(this, fState.get());
292     int index = canonicalShaders().find(entry);
293     SkASSERT(index >= 0);
294     canonicalShaders().removeShuffle(index);
295     fResources.unrefAll();
296 }
297 
emitObject(SkWStream * stream,SkPDFCatalog * catalog,bool indirect)298 void SkPDFShader::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
299                              bool indirect) {
300     if (indirect)
301         return emitIndirectObject(stream, catalog);
302 
303     fContent->emitObject(stream, catalog, indirect);
304 }
305 
getOutputSize(SkPDFCatalog * catalog,bool indirect)306 size_t SkPDFShader::getOutputSize(SkPDFCatalog* catalog, bool indirect) {
307     if (indirect)
308         return getIndirectOutputSize(catalog);
309 
310     return fContent->getOutputSize(catalog, indirect);
311 }
312 
getResources(SkTDArray<SkPDFObject * > * resourceList)313 void SkPDFShader::getResources(SkTDArray<SkPDFObject*>* resourceList) {
314     resourceList->setReserve(resourceList->count() + fResources.count());
315     for (int i = 0; i < fResources.count(); i++) {
316         resourceList->push(fResources[i]);
317         fResources[i]->ref();
318     }
319 }
320 
321 // static
getPDFShader(const SkShader & shader,const SkMatrix & matrix,const SkIRect & surfaceBBox)322 SkPDFShader* SkPDFShader::getPDFShader(const SkShader& shader,
323                                        const SkMatrix& matrix,
324                                        const SkIRect& surfaceBBox) {
325     SkRefPtr<SkPDFShader> pdfShader;
326     SkAutoMutexAcquire lock(canonicalShadersMutex());
327     SkAutoTDelete<State> shaderState(new State(shader, matrix, surfaceBBox));
328 
329     ShaderCanonicalEntry entry(NULL, shaderState.get());
330     int index = canonicalShaders().find(entry);
331     if (index >= 0) {
332         SkPDFShader* result = canonicalShaders()[index].fPDFShader;
333         result->ref();
334         return result;
335     }
336     // The PDFShader takes ownership of the shaderSate.
337     pdfShader = new SkPDFShader(shaderState.detach());
338     // Check for a valid shader.
339     if (pdfShader->fContent.get() == NULL) {
340         pdfShader->unref();
341         return NULL;
342     }
343     entry.fPDFShader = pdfShader.get();
344     canonicalShaders().push(entry);
345     return pdfShader.get();  // return the reference that came from new.
346 }
347 
348 // static
canonicalShaders()349 SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::canonicalShaders() {
350     // This initialization is only thread safe with gcc.
351     static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
352     return gCanonicalShaders;
353 }
354 
355 // static
canonicalShadersMutex()356 SkMutex& SkPDFShader::canonicalShadersMutex() {
357     // This initialization is only thread safe with gcc.
358     static SkMutex gCanonicalShadersMutex;
359     return gCanonicalShadersMutex;
360 }
361 
362 // static
rangeObject()363 SkPDFObject* SkPDFShader::rangeObject() {
364     // This initialization is only thread safe with gcc.
365     static SkPDFArray* range = NULL;
366     // This method is only used with canonicalShadersMutex, so it's safe to
367     // populate domain.
368     if (range == NULL) {
369         range = new SkPDFArray;
370         range->reserve(6);
371         range->append(new SkPDFInt(0))->unref();
372         range->append(new SkPDFInt(1))->unref();
373         range->append(new SkPDFInt(0))->unref();
374         range->append(new SkPDFInt(1))->unref();
375         range->append(new SkPDFInt(0))->unref();
376         range->append(new SkPDFInt(1))->unref();
377     }
378     return range;
379 }
380 
SkPDFShader(State * state)381 SkPDFShader::SkPDFShader(State* state) : fState(state) {
382     if (fState.get()->fType == SkShader::kNone_GradientType) {
383         doImageShader();
384     } else {
385         doFunctionShader();
386     }
387 }
388 
doFunctionShader()389 void SkPDFShader::doFunctionShader() {
390     SkString (*codeFunction)(const SkShader::GradientInfo& info) = NULL;
391     SkPoint transformPoints[2];
392 
393     // Depending on the type of the gradient, we want to transform the
394     // coordinate space in different ways.
395     const SkShader::GradientInfo* info = &fState.get()->fInfo;
396     transformPoints[0] = info->fPoint[0];
397     transformPoints[1] = info->fPoint[1];
398     switch (fState.get()->fType) {
399         case SkShader::kLinear_GradientType:
400             codeFunction = &linearCode;
401             break;
402         case SkShader::kRadial_GradientType:
403             transformPoints[1] = transformPoints[0];
404             transformPoints[1].fX += info->fRadius[0];
405             codeFunction = &radialCode;
406             break;
407         case SkShader::kRadial2_GradientType: {
408             // Bail out if the radii are the same.  Not setting fContent will
409             // cause the higher level code to detect the resulting object
410             // as invalid.
411             if (info->fRadius[0] == info->fRadius[1]) {
412                 return;
413             }
414             transformPoints[1] = transformPoints[0];
415             SkScalar dr = info->fRadius[1] - info->fRadius[0];
416             transformPoints[1].fX += dr;
417             codeFunction = &twoPointRadialCode;
418             break;
419         }
420         case SkShader::kSweep_GradientType:
421             transformPoints[1] = transformPoints[0];
422             transformPoints[1].fX += 1;
423             codeFunction = &sweepCode;
424             break;
425         case SkShader::kColor_GradientType:
426         case SkShader::kNone_GradientType:
427             SkASSERT(false);
428             return;
429     }
430 
431     // Move any scaling (assuming a unit gradient) or translation
432     // (and rotation for linear gradient), of the final gradient from
433     // info->fPoints to the matrix (updating bbox appropriately).  Now
434     // the gradient can be drawn on on the unit segment.
435     SkMatrix mapperMatrix;
436     unitToPointsMatrix(transformPoints, &mapperMatrix);
437     SkMatrix finalMatrix = fState.get()->fCanvasTransform;
438     finalMatrix.preConcat(mapperMatrix);
439     finalMatrix.preConcat(fState.get()->fShaderTransform);
440     SkRect bbox;
441     bbox.set(fState.get()->fBBox);
442     transformBBox(finalMatrix, &bbox);
443 
444     SkRefPtr<SkPDFArray> domain = new SkPDFArray;
445     domain->unref();  // SkRefPtr and new both took a reference.
446     domain->reserve(4);
447     domain->append(new SkPDFScalar(bbox.fLeft))->unref();
448     domain->append(new SkPDFScalar(bbox.fRight))->unref();
449     domain->append(new SkPDFScalar(bbox.fTop))->unref();
450     domain->append(new SkPDFScalar(bbox.fBottom))->unref();
451 
452     SkString functionCode;
453     // The two point radial gradient further references fState.get()->fInfo
454     // in translating from x, y coordinates to the t parameter. So, we have
455     // to transform the points and radii according to the calculated matrix.
456     if (fState.get()->fType == SkShader::kRadial2_GradientType) {
457         SkShader::GradientInfo twoPointRadialInfo = *info;
458         SkMatrix inverseMapperMatrix;
459         mapperMatrix.invert(&inverseMapperMatrix);
460         inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
461         twoPointRadialInfo.fRadius[0] =
462             inverseMapperMatrix.mapRadius(info->fRadius[0]);
463         twoPointRadialInfo.fRadius[1] =
464             inverseMapperMatrix.mapRadius(info->fRadius[1]);
465         functionCode = codeFunction(twoPointRadialInfo);
466     } else {
467         functionCode = codeFunction(*info);
468     }
469 
470     SkRefPtr<SkPDFStream> function = makePSFunction(functionCode, domain.get());
471     // Pass one reference to fResources, SkRefPtr and new both took a reference.
472     fResources.push(function.get());
473 
474     SkRefPtr<SkPDFDict> pdfShader = new SkPDFDict;
475     pdfShader->unref();  // SkRefPtr and new both took a reference.
476     pdfShader->insert("ShadingType", new SkPDFInt(1))->unref();
477     pdfShader->insert("ColorSpace", new SkPDFName("DeviceRGB"))->unref();
478     pdfShader->insert("Domain", domain.get());
479     pdfShader->insert("Function", new SkPDFObjRef(function.get()))->unref();
480 
481     fContent = new SkPDFDict("Pattern");
482     fContent->unref();  // SkRefPtr and new both took a reference.
483     fContent->insert("PatternType", new SkPDFInt(2))->unref();
484     fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
485     fContent->insert("Shading", pdfShader.get());
486 }
487 
488 // SkShader* shader, SkMatrix matrix, const SkRect& surfaceBBox
doImageShader()489 void SkPDFShader::doImageShader() {
490     fState.get()->fImage.lockPixels();
491 
492     SkMatrix finalMatrix = fState.get()->fCanvasTransform;
493     finalMatrix.preConcat(fState.get()->fShaderTransform);
494     SkRect surfaceBBox;
495     surfaceBBox.set(fState.get()->fBBox);
496     transformBBox(finalMatrix, &surfaceBBox);
497 
498     SkMatrix unflip;
499     unflip.setTranslate(0, SkScalarRound(surfaceBBox.height()));
500     unflip.preScale(1, -1);
501     SkISize size = SkISize::Make(SkScalarRound(surfaceBBox.width()),
502                                  SkScalarRound(surfaceBBox.height()));
503     SkPDFDevice pattern(size, size, unflip);
504     SkCanvas canvas(&pattern);
505     canvas.translate(-surfaceBBox.fLeft, -surfaceBBox.fTop);
506     finalMatrix.preTranslate(surfaceBBox.fLeft, surfaceBBox.fTop);
507 
508     const SkBitmap* image = &fState.get()->fImage;
509     int width = image->width();
510     int height = image->height();
511     SkShader::TileMode tileModes[2];
512     tileModes[0] = fState.get()->fImageTileModes[0];
513     tileModes[1] = fState.get()->fImageTileModes[1];
514 
515     canvas.drawBitmap(*image, 0, 0);
516     SkRect patternBBox = SkRect::MakeXYWH(-surfaceBBox.fLeft, -surfaceBBox.fTop,
517                                           width, height);
518 
519     // Tiling is implied.  First we handle mirroring.
520     if (tileModes[0] == SkShader::kMirror_TileMode) {
521         SkMatrix xMirror;
522         xMirror.setScale(-1, 1);
523         xMirror.postTranslate(2 * width, 0);
524         canvas.drawBitmapMatrix(*image, xMirror);
525         patternBBox.fRight += width;
526     }
527     if (tileModes[1] == SkShader::kMirror_TileMode) {
528         SkMatrix yMirror;
529         yMirror.setScale(1, -1);
530         yMirror.postTranslate(0, 2 * height);
531         canvas.drawBitmapMatrix(*image, yMirror);
532         patternBBox.fBottom += height;
533     }
534     if (tileModes[0] == SkShader::kMirror_TileMode &&
535             tileModes[1] == SkShader::kMirror_TileMode) {
536         SkMatrix mirror;
537         mirror.setScale(-1, -1);
538         mirror.postTranslate(2 * width, 2 * height);
539         canvas.drawBitmapMatrix(*image, mirror);
540     }
541 
542     // Then handle Clamping, which requires expanding the pattern canvas to
543     // cover the entire surfaceBBox.
544 
545     // If both x and y are in clamp mode, we start by filling in the corners.
546     // (Which are just a rectangles of the corner colors.)
547     if (tileModes[0] == SkShader::kClamp_TileMode &&
548             tileModes[1] == SkShader::kClamp_TileMode) {
549         SkPaint paint;
550         SkRect rect;
551         rect = SkRect::MakeLTRB(surfaceBBox.fLeft, surfaceBBox.fTop, 0, 0);
552         if (!rect.isEmpty()) {
553             paint.setColor(image->getColor(0, 0));
554             canvas.drawRect(rect, paint);
555         }
556 
557         rect = SkRect::MakeLTRB(width, surfaceBBox.fTop, surfaceBBox.fRight, 0);
558         if (!rect.isEmpty()) {
559             paint.setColor(image->getColor(width - 1, 0));
560             canvas.drawRect(rect, paint);
561         }
562 
563         rect = SkRect::MakeLTRB(width, height, surfaceBBox.fRight,
564                                 surfaceBBox.fBottom);
565         if (!rect.isEmpty()) {
566             paint.setColor(image->getColor(width - 1, height - 1));
567             canvas.drawRect(rect, paint);
568         }
569 
570         rect = SkRect::MakeLTRB(surfaceBBox.fLeft, height, 0,
571                                 surfaceBBox.fBottom);
572         if (!rect.isEmpty()) {
573             paint.setColor(image->getColor(0, height - 1));
574             canvas.drawRect(rect, paint);
575         }
576     }
577 
578     // Then expand the left, right, top, then bottom.
579     if (tileModes[0] == SkShader::kClamp_TileMode) {
580         SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, height);
581         if (surfaceBBox.fLeft < 0) {
582             SkBitmap left;
583             SkAssertResult(image->extractSubset(&left, subset));
584 
585             SkMatrix leftMatrix;
586             leftMatrix.setScale(-surfaceBBox.fLeft, 1);
587             leftMatrix.postTranslate(surfaceBBox.fLeft, 0);
588             canvas.drawBitmapMatrix(left, leftMatrix);
589 
590             if (tileModes[1] == SkShader::kMirror_TileMode) {
591                 leftMatrix.postScale(1, -1);
592                 leftMatrix.postTranslate(0, 2 * height);
593                 canvas.drawBitmapMatrix(left, leftMatrix);
594             }
595             patternBBox.fLeft = 0;
596         }
597 
598         if (surfaceBBox.fRight > width) {
599             SkBitmap right;
600             subset.offset(width - 1, 0);
601             SkAssertResult(image->extractSubset(&right, subset));
602 
603             SkMatrix rightMatrix;
604             rightMatrix.setScale(surfaceBBox.fRight - width, 1);
605             rightMatrix.postTranslate(width, 0);
606             canvas.drawBitmapMatrix(right, rightMatrix);
607 
608             if (tileModes[1] == SkShader::kMirror_TileMode) {
609                 rightMatrix.postScale(1, -1);
610                 rightMatrix.postTranslate(0, 2 * height);
611                 canvas.drawBitmapMatrix(right, rightMatrix);
612             }
613             patternBBox.fRight = surfaceBBox.width();
614         }
615     }
616 
617     if (tileModes[1] == SkShader::kClamp_TileMode) {
618         SkIRect subset = SkIRect::MakeXYWH(0, 0, width, 1);
619         if (surfaceBBox.fTop < 0) {
620             SkBitmap top;
621             SkAssertResult(image->extractSubset(&top, subset));
622 
623             SkMatrix topMatrix;
624             topMatrix.setScale(1, -surfaceBBox.fTop);
625             topMatrix.postTranslate(0, surfaceBBox.fTop);
626             canvas.drawBitmapMatrix(top, topMatrix);
627 
628             if (tileModes[0] == SkShader::kMirror_TileMode) {
629                 topMatrix.postScale(-1, 1);
630                 topMatrix.postTranslate(2 * width, 0);
631                 canvas.drawBitmapMatrix(top, topMatrix);
632             }
633             patternBBox.fTop = 0;
634         }
635 
636         if (surfaceBBox.fBottom > height) {
637             SkBitmap bottom;
638             subset.offset(0, height - 1);
639             SkAssertResult(image->extractSubset(&bottom, subset));
640 
641             SkMatrix bottomMatrix;
642             bottomMatrix.setScale(1, surfaceBBox.fBottom - height);
643             bottomMatrix.postTranslate(0, height);
644             canvas.drawBitmapMatrix(bottom, bottomMatrix);
645 
646             if (tileModes[0] == SkShader::kMirror_TileMode) {
647                 bottomMatrix.postScale(-1, 1);
648                 bottomMatrix.postTranslate(2 * width, 0);
649                 canvas.drawBitmapMatrix(bottom, bottomMatrix);
650             }
651             patternBBox.fBottom = surfaceBBox.height();
652         }
653     }
654 
655     SkRefPtr<SkPDFArray> patternBBoxArray = new SkPDFArray;
656     patternBBoxArray->unref();  // SkRefPtr and new both took a reference.
657     patternBBoxArray->reserve(4);
658     patternBBoxArray->append(new SkPDFScalar(patternBBox.fLeft))->unref();
659     patternBBoxArray->append(new SkPDFScalar(patternBBox.fTop))->unref();
660     patternBBoxArray->append(new SkPDFScalar(patternBBox.fRight))->unref();
661     patternBBoxArray->append(new SkPDFScalar(patternBBox.fBottom))->unref();
662 
663     // Put the canvas into the pattern stream (fContent).
664     SkRefPtr<SkStream> content = pattern.content();
665     content->unref();  // SkRefPtr and content() both took a reference.
666     pattern.getResources(&fResources);
667 
668     fContent = new SkPDFStream(content.get());
669     fContent->unref();  // SkRefPtr and new both took a reference.
670     fContent->insert("Type", new SkPDFName("Pattern"))->unref();
671     fContent->insert("PatternType", new SkPDFInt(1))->unref();
672     fContent->insert("PaintType", new SkPDFInt(1))->unref();
673     fContent->insert("TilingType", new SkPDFInt(1))->unref();
674     fContent->insert("BBox", patternBBoxArray.get());
675     fContent->insert("XStep", new SkPDFScalar(patternBBox.width()))->unref();
676     fContent->insert("YStep", new SkPDFScalar(patternBBox.height()))->unref();
677     fContent->insert("Resources", pattern.getResourceDict().get());
678     fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
679 
680     fState.get()->fImage.unlockPixels();
681 }
682 
makePSFunction(const SkString & psCode,SkPDFArray * domain)683 SkPDFStream* SkPDFShader::makePSFunction(const SkString& psCode,
684                                          SkPDFArray* domain) {
685     SkRefPtr<SkMemoryStream> funcStream =
686         new SkMemoryStream(psCode.c_str(), psCode.size(), true);
687     funcStream->unref();  // SkRefPtr and new both took a reference.
688 
689     SkPDFStream* result = new SkPDFStream(funcStream.get());
690     result->insert("FunctionType", new SkPDFInt(4))->unref();
691     result->insert("Domain", domain);
692     result->insert("Range", rangeObject());
693     return result;
694 }
695 
operator ==(const SkPDFShader::State & b) const696 bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
697     if (fType != b.fType ||
698             fCanvasTransform != b.fCanvasTransform ||
699             fShaderTransform != b.fShaderTransform ||
700             fBBox != b.fBBox) {
701         return false;
702     }
703 
704     if (fType == SkShader::kNone_GradientType) {
705         if (fPixelGeneration != b.fPixelGeneration ||
706                 fPixelGeneration == 0 ||
707                 fImageTileModes[0] != b.fImageTileModes[0] ||
708                 fImageTileModes[1] != b.fImageTileModes[1]) {
709             return false;
710         }
711     } else {
712         if (fInfo.fColorCount != b.fInfo.fColorCount ||
713                 memcmp(fInfo.fColors, b.fInfo.fColors,
714                        sizeof(SkColor) * fInfo.fColorCount) != 0 ||
715                 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
716                        sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
717                 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
718                 fInfo.fTileMode != b.fInfo.fTileMode) {
719             return false;
720         }
721 
722         switch (fType) {
723             case SkShader::kLinear_GradientType:
724                 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
725                     return false;
726                 }
727                 break;
728             case SkShader::kRadial_GradientType:
729                 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
730                     return false;
731                 }
732                 break;
733             case SkShader::kRadial2_GradientType:
734                 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
735                         fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
736                         fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
737                     return false;
738                 }
739                 break;
740             case SkShader::kSweep_GradientType:
741             case SkShader::kNone_GradientType:
742             case SkShader::kColor_GradientType:
743                 break;
744         }
745     }
746     return true;
747 }
748 
State(const SkShader & shader,const SkMatrix & canvasTransform,const SkIRect & bbox)749 SkPDFShader::State::State(const SkShader& shader,
750                           const SkMatrix& canvasTransform, const SkIRect& bbox)
751         : fCanvasTransform(canvasTransform),
752           fBBox(bbox) {
753 
754     fInfo.fColorCount = 0;
755     fInfo.fColors = NULL;
756     fInfo.fColorOffsets = NULL;
757     shader.getLocalMatrix(&fShaderTransform);
758 
759     fType = shader.asAGradient(&fInfo);
760 
761     if (fType == SkShader::kNone_GradientType) {
762         SkShader::BitmapType bitmapType;
763         SkMatrix matrix;
764         bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes, NULL);
765         if (bitmapType != SkShader::kDefault_BitmapType) {
766             fImage.reset();
767             return;
768         }
769         SkASSERT(matrix.isIdentity());
770         fPixelGeneration = fImage.getGenerationID();
771     } else {
772         fColorData.set(sk_malloc_throw(
773                     fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
774         fInfo.fColors = (SkColor*)fColorData.get();
775         fInfo.fColorOffsets = (SkScalar*)(fInfo.fColors + fInfo.fColorCount);
776         shader.asAGradient(&fInfo);
777     }
778 }
779