Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / SkGpuDevice.cpp
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "SkGpuDevice.h"
9
10 #include "effects/GrBicubicEffect.h"
11 #include "effects/GrTextureDomain.h"
12 #include "effects/GrSimpleTextureEffect.h"
13
14 #include "GrContext.h"
15 #include "GrBitmapTextContext.h"
16 #if SK_DISTANCEFIELD_FONTS
17 #include "GrDistanceFieldTextContext.h"
18 #endif
19
20 #include "SkGrTexturePixelRef.h"
21
22 #include "SkColorFilter.h"
23 #include "SkDeviceImageFilterProxy.h"
24 #include "SkDrawProcs.h"
25 #include "SkGlyphCache.h"
26 #include "SkImageFilter.h"
27 #include "SkPathEffect.h"
28 #include "SkRRect.h"
29 #include "SkStroke.h"
30 #include "SkSurface.h"
31 #include "SkTLazy.h"
32 #include "SkUtils.h"
33 #include "SkErrorInternals.h"
34
35 #define CACHE_COMPATIBLE_DEVICE_TEXTURES 1
36
37 #if 0
38     extern bool (*gShouldDrawProc)();
39     #define CHECK_SHOULD_DRAW(draw, forceI)                     \
40         do {                                                    \
41             if (gShouldDrawProc && !gShouldDrawProc()) return;  \
42             this->prepareDraw(draw, forceI);                    \
43         } while (0)
44 #else
45     #define CHECK_SHOULD_DRAW(draw, forceI) this->prepareDraw(draw, forceI)
46 #endif
47
48 // This constant represents the screen alignment criterion in texels for
49 // requiring texture domain clamping to prevent color bleeding when drawing
50 // a sub region of a larger source image.
51 #define COLOR_BLEED_TOLERANCE 0.001f
52
53 #define DO_DEFERRED_CLEAR()             \
54     do {                                \
55         if (fNeedClear) {               \
56             this->clear(SK_ColorTRANSPARENT); \
57         }                               \
58     } while (false)                     \
59
60 ///////////////////////////////////////////////////////////////////////////////
61
62 #define CHECK_FOR_ANNOTATION(paint) \
63     do { if (paint.getAnnotation()) { return; } } while (0)
64
65 ///////////////////////////////////////////////////////////////////////////////
66
67
68 class SkGpuDevice::SkAutoCachedTexture : public ::SkNoncopyable {
69 public:
70     SkAutoCachedTexture()
71         : fDevice(NULL)
72         , fTexture(NULL) {
73     }
74
75     SkAutoCachedTexture(SkGpuDevice* device,
76                         const SkBitmap& bitmap,
77                         const GrTextureParams* params,
78                         GrTexture** texture)
79         : fDevice(NULL)
80         , fTexture(NULL) {
81         SkASSERT(NULL != texture);
82         *texture = this->set(device, bitmap, params);
83     }
84
85     ~SkAutoCachedTexture() {
86         if (NULL != fTexture) {
87             GrUnlockAndUnrefCachedBitmapTexture(fTexture);
88         }
89     }
90
91     GrTexture* set(SkGpuDevice* device,
92                    const SkBitmap& bitmap,
93                    const GrTextureParams* params) {
94         if (NULL != fTexture) {
95             GrUnlockAndUnrefCachedBitmapTexture(fTexture);
96             fTexture = NULL;
97         }
98         fDevice = device;
99         GrTexture* result = (GrTexture*)bitmap.getTexture();
100         if (NULL == result) {
101             // Cannot return the native texture so look it up in our cache
102             fTexture = GrLockAndRefCachedBitmapTexture(device->context(), bitmap, params);
103             result = fTexture;
104         }
105         return result;
106     }
107
108 private:
109     SkGpuDevice* fDevice;
110     GrTexture*   fTexture;
111 };
112
113 ///////////////////////////////////////////////////////////////////////////////
114
115 struct GrSkDrawProcs : public SkDrawProcs {
116 public:
117     GrContext* fContext;
118     GrTextContext* fTextContext;
119     GrFontScaler* fFontScaler;  // cached in the skia glyphcache
120 };
121
122 ///////////////////////////////////////////////////////////////////////////////
123
124 static SkBitmap::Config grConfig2skConfig(GrPixelConfig config, bool* isOpaque) {
125     switch (config) {
126         case kAlpha_8_GrPixelConfig:
127             *isOpaque = false;
128             return SkBitmap::kA8_Config;
129         case kRGB_565_GrPixelConfig:
130             *isOpaque = true;
131             return SkBitmap::kRGB_565_Config;
132         case kRGBA_4444_GrPixelConfig:
133             *isOpaque = false;
134             return SkBitmap::kARGB_4444_Config;
135         case kSkia8888_GrPixelConfig:
136             // we don't currently have a way of knowing whether
137             // a 8888 is opaque based on the config.
138             *isOpaque = false;
139             return SkBitmap::kARGB_8888_Config;
140         default:
141             *isOpaque = false;
142             return SkBitmap::kNo_Config;
143     }
144 }
145
146 /*
147  * GrRenderTarget does not know its opaqueness, only its config, so we have
148  * to make conservative guesses when we return an "equivalent" bitmap.
149  */
150 static SkBitmap make_bitmap(GrContext* context, GrRenderTarget* renderTarget) {
151     bool isOpaque;
152     SkBitmap::Config config = grConfig2skConfig(renderTarget->config(), &isOpaque);
153
154     SkBitmap bitmap;
155     bitmap.setConfig(config, renderTarget->width(), renderTarget->height(), 0,
156                      isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
157     return bitmap;
158 }
159
160 /*
161  *  Calling SkBitmapDevice with individual params asks it to allocate pixel memory.
162  *  We never want that, so we always need to call it with a bitmap argument
163  *  (which says take my allocate (or lack thereof)).
164  *
165  *  This is a REALLY good reason to finish the clean-up of SkBaseDevice, and have
166  *  SkGpuDevice inherit from that instead of SkBitmapDevice.
167  */
168 static SkBitmap make_bitmap(SkBitmap::Config config, int width, int height, bool isOpaque) {
169     SkBitmap bm;
170     bm.setConfig(config, width, height, isOpaque);
171     return bm;
172 }
173
174 SkGpuDevice* SkGpuDevice::Create(GrSurface* surface) {
175     SkASSERT(NULL != surface);
176     if (NULL == surface->asRenderTarget() || NULL == surface->getContext()) {
177         return NULL;
178     }
179     if (surface->asTexture()) {
180         return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asTexture()));
181     } else {
182         return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asRenderTarget()));
183     }
184 }
185
186 SkGpuDevice::SkGpuDevice(GrContext* context, GrTexture* texture)
187     : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
188     this->initFromRenderTarget(context, texture->asRenderTarget(), false);
189 }
190
191 SkGpuDevice::SkGpuDevice(GrContext* context, GrRenderTarget* renderTarget)
192     : SkBitmapDevice(make_bitmap(context, renderTarget)) {
193     this->initFromRenderTarget(context, renderTarget, false);
194 }
195
196 void SkGpuDevice::initFromRenderTarget(GrContext* context,
197                                        GrRenderTarget* renderTarget,
198                                        bool cached) {
199     fDrawProcs = NULL;
200
201     fContext = context;
202     fContext->ref();
203
204 #if SK_DISTANCEFIELD_FONTS
205     fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties));
206     fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
207 #else
208     fMainTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
209     fFallbackTextContext = NULL;
210 #endif
211
212     fRenderTarget = NULL;
213     fNeedClear = false;
214
215     SkASSERT(NULL != renderTarget);
216     fRenderTarget = renderTarget;
217     fRenderTarget->ref();
218
219     // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
220     // on the RT but not vice-versa.
221     // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
222     // busting chrome (for a currently unknown reason).
223     GrSurface* surface = fRenderTarget->asTexture();
224     if (NULL == surface) {
225         surface = fRenderTarget;
226     }
227
228     SkImageInfo info;
229     surface->asImageInfo(&info);
230     SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, cached));
231
232     this->setPixelRef(pr)->unref();
233 }
234
235 SkGpuDevice::SkGpuDevice(GrContext* context,
236                          SkBitmap::Config config,
237                          int width,
238                          int height,
239                          int sampleCount)
240     : SkBitmapDevice(make_bitmap(config, width, height, false /*isOpaque*/))
241 {
242     fDrawProcs = NULL;
243
244     fContext = context;
245     fContext->ref();
246
247 #if SK_DISTANCEFIELD_FONTS
248     fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties));
249     fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
250 #else
251     fMainTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
252     fFallbackTextContext = NULL;
253 #endif
254
255     fRenderTarget = NULL;
256     fNeedClear = false;
257
258     if (config != SkBitmap::kRGB_565_Config) {
259         config = SkBitmap::kARGB_8888_Config;
260     }
261
262     GrTextureDesc desc;
263     desc.fFlags = kRenderTarget_GrTextureFlagBit;
264     desc.fWidth = width;
265     desc.fHeight = height;
266     desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
267     desc.fSampleCnt = sampleCount;
268
269     SkImageInfo info;
270     if (!GrPixelConfig2ColorType(desc.fConfig, &info.fColorType)) {
271         sk_throw();
272     }
273     info.fWidth = width;
274     info.fHeight = height;
275     info.fAlphaType = kPremul_SkAlphaType;
276
277     SkAutoTUnref<GrTexture> texture(fContext->createUncachedTexture(desc, NULL, 0));
278
279     if (NULL != texture) {
280         fRenderTarget = texture->asRenderTarget();
281         fRenderTarget->ref();
282
283         SkASSERT(NULL != fRenderTarget);
284
285         // wrap the bitmap with a pixelref to expose our texture
286         SkGrPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, texture));
287         this->setPixelRef(pr)->unref();
288     } else {
289         GrPrintf("--- failed to create gpu-offscreen [%d %d]\n",
290                  width, height);
291         SkASSERT(false);
292     }
293 }
294
295 SkGpuDevice::~SkGpuDevice() {
296     if (fDrawProcs) {
297         delete fDrawProcs;
298     }
299
300     delete fMainTextContext;
301     delete fFallbackTextContext;
302
303     // The GrContext takes a ref on the target. We don't want to cause the render
304     // target to be unnecessarily kept alive.
305     if (fContext->getRenderTarget() == fRenderTarget) {
306         fContext->setRenderTarget(NULL);
307     }
308
309     if (fContext->getClip() == &fClipData) {
310         fContext->setClip(NULL);
311     }
312
313     SkSafeUnref(fRenderTarget);
314     fContext->unref();
315 }
316
317 ///////////////////////////////////////////////////////////////////////////////
318
319 void SkGpuDevice::makeRenderTargetCurrent() {
320     DO_DEFERRED_CLEAR();
321     fContext->setRenderTarget(fRenderTarget);
322 }
323
324 ///////////////////////////////////////////////////////////////////////////////
325
326 namespace {
327 GrPixelConfig config8888_to_grconfig_and_flags(SkCanvas::Config8888 config8888, uint32_t* flags) {
328     switch (config8888) {
329         case SkCanvas::kNative_Premul_Config8888:
330             *flags = 0;
331             return kSkia8888_GrPixelConfig;
332         case SkCanvas::kNative_Unpremul_Config8888:
333             *flags = GrContext::kUnpremul_PixelOpsFlag;
334             return kSkia8888_GrPixelConfig;
335         case SkCanvas::kBGRA_Premul_Config8888:
336             *flags = 0;
337             return kBGRA_8888_GrPixelConfig;
338         case SkCanvas::kBGRA_Unpremul_Config8888:
339             *flags = GrContext::kUnpremul_PixelOpsFlag;
340             return kBGRA_8888_GrPixelConfig;
341         case SkCanvas::kRGBA_Premul_Config8888:
342             *flags = 0;
343             return kRGBA_8888_GrPixelConfig;
344         case SkCanvas::kRGBA_Unpremul_Config8888:
345             *flags = GrContext::kUnpremul_PixelOpsFlag;
346             return kRGBA_8888_GrPixelConfig;
347         default:
348             GrCrash("Unexpected Config8888.");
349             *flags = 0; // suppress warning
350             return kSkia8888_GrPixelConfig;
351     }
352 }
353 }
354
355 bool SkGpuDevice::onReadPixels(const SkBitmap& bitmap,
356                                int x, int y,
357                                SkCanvas::Config8888 config8888) {
358     DO_DEFERRED_CLEAR();
359     SkASSERT(SkBitmap::kARGB_8888_Config == bitmap.config());
360     SkASSERT(!bitmap.isNull());
361     SkASSERT(SkIRect::MakeWH(this->width(), this->height()).contains(SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height())));
362
363     SkAutoLockPixels alp(bitmap);
364     GrPixelConfig config;
365     uint32_t flags;
366     config = config8888_to_grconfig_and_flags(config8888, &flags);
367     return fContext->readRenderTargetPixels(fRenderTarget,
368                                             x, y,
369                                             bitmap.width(),
370                                             bitmap.height(),
371                                             config,
372                                             bitmap.getPixels(),
373                                             bitmap.rowBytes(),
374                                             flags);
375 }
376
377 void SkGpuDevice::writePixels(const SkBitmap& bitmap, int x, int y,
378                               SkCanvas::Config8888 config8888) {
379     SkAutoLockPixels alp(bitmap);
380     if (!bitmap.readyToDraw()) {
381         return;
382     }
383
384     GrPixelConfig config;
385     uint32_t flags;
386     if (SkBitmap::kARGB_8888_Config == bitmap.config()) {
387         config = config8888_to_grconfig_and_flags(config8888, &flags);
388     } else {
389         flags = 0;
390         config= SkBitmapConfig2GrPixelConfig(bitmap.config());
391     }
392
393     fRenderTarget->writePixels(x, y, bitmap.width(), bitmap.height(),
394                                config, bitmap.getPixels(), bitmap.rowBytes(), flags);
395 }
396
397 void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
398     INHERITED::onAttachToCanvas(canvas);
399
400     // Canvas promises that this ptr is valid until onDetachFromCanvas is called
401     fClipData.fClipStack = canvas->getClipStack();
402 }
403
404 void SkGpuDevice::onDetachFromCanvas() {
405     INHERITED::onDetachFromCanvas();
406     fClipData.fClipStack = NULL;
407 }
408
409 // call this every draw call, to ensure that the context reflects our state,
410 // and not the state from some other canvas/device
411 void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
412     SkASSERT(NULL != fClipData.fClipStack);
413
414     fContext->setRenderTarget(fRenderTarget);
415
416     SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
417
418     if (forceIdentity) {
419         fContext->setIdentityMatrix();
420     } else {
421         fContext->setMatrix(*draw.fMatrix);
422     }
423     fClipData.fOrigin = this->getOrigin();
424
425     fContext->setClip(&fClipData);
426
427     DO_DEFERRED_CLEAR();
428 }
429
430 GrRenderTarget* SkGpuDevice::accessRenderTarget() {
431     DO_DEFERRED_CLEAR();
432     return fRenderTarget;
433 }
434
435 ///////////////////////////////////////////////////////////////////////////////
436
437 SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
438 SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
439 SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
440 SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
441 SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
442                   shader_type_mismatch);
443 SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
444                   shader_type_mismatch);
445 SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
446 SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
447
448 namespace {
449
450 // converts a SkPaint to a GrPaint, ignoring the skPaint's shader
451 // justAlpha indicates that skPaint's alpha should be used rather than the color
452 // Callers may subsequently modify the GrPaint. Setting constantColor indicates
453 // that the final paint will draw the same color at every pixel. This allows
454 // an optimization where the the color filter can be applied to the skPaint's
455 // color once while converting to GrPaint and then ignored.
456 inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
457                                     const SkPaint& skPaint,
458                                     bool justAlpha,
459                                     bool constantColor,
460                                     GrPaint* grPaint) {
461
462     grPaint->setDither(skPaint.isDither());
463     grPaint->setAntiAlias(skPaint.isAntiAlias());
464
465     SkXfermode::Coeff sm;
466     SkXfermode::Coeff dm;
467
468     SkXfermode* mode = skPaint.getXfermode();
469     GrEffectRef* xferEffect = NULL;
470     if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
471         if (NULL != xferEffect) {
472             grPaint->addColorEffect(xferEffect)->unref();
473             sm = SkXfermode::kOne_Coeff;
474             dm = SkXfermode::kZero_Coeff;
475         }
476     } else {
477         //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
478 #if 0
479         return false;
480 #else
481         // Fall back to src-over
482         sm = SkXfermode::kOne_Coeff;
483         dm = SkXfermode::kISA_Coeff;
484 #endif
485     }
486     grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
487
488     if (justAlpha) {
489         uint8_t alpha = skPaint.getAlpha();
490         grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
491         // justAlpha is currently set to true only if there is a texture,
492         // so constantColor should not also be true.
493         SkASSERT(!constantColor);
494     } else {
495         grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
496     }
497
498     SkColorFilter* colorFilter = skPaint.getColorFilter();
499     if (NULL != colorFilter) {
500         // if the source color is a constant then apply the filter here once rather than per pixel
501         // in a shader.
502         if (constantColor) {
503             SkColor filtered = colorFilter->filterColor(skPaint.getColor());
504             grPaint->setColor(SkColor2GrColor(filtered));
505         } else {
506             SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
507             if (NULL != effect.get()) {
508                 grPaint->addColorEffect(effect);
509             }
510         }
511     }
512
513     return true;
514 }
515
516 // This function is similar to skPaint2GrPaintNoShader but also converts
517 // skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
518 // be used is set on grPaint and returned in param act. constantColor has the
519 // same meaning as in skPaint2GrPaintNoShader.
520 inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
521                                   const SkPaint& skPaint,
522                                   bool constantColor,
523                                   GrPaint* grPaint) {
524     SkShader* shader = skPaint.getShader();
525     if (NULL == shader) {
526         return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
527     }
528
529     // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state and require
530     // the shader to set a render target .
531     GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
532
533     // setup the shader as the first color effect on the paint
534     SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
535     if (NULL != effect.get()) {
536         grPaint->addColorEffect(effect);
537         // Now setup the rest of the paint.
538         return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
539     } else {
540         // We still don't have SkColorShader::asNewEffect() implemented.
541         SkShader::GradientInfo info;
542         SkColor                color;
543
544         info.fColors = &color;
545         info.fColorOffsets = NULL;
546         info.fColorCount = 1;
547         if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
548             SkPaint copy(skPaint);
549             copy.setShader(NULL);
550             // modulate the paint alpha by the shader's solid color alpha
551             U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
552             copy.setColor(SkColorSetA(color, newA));
553             return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
554         } else {
555             return false;
556         }
557     }
558 }
559 }
560
561 ///////////////////////////////////////////////////////////////////////////////
562
563 SkBitmap::Config SkGpuDevice::config() const {
564     if (NULL == fRenderTarget) {
565         return SkBitmap::kNo_Config;
566     }
567
568     bool isOpaque;
569     return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
570 }
571
572 void SkGpuDevice::clear(SkColor color) {
573     SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
574     fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
575     fNeedClear = false;
576 }
577
578 void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
579     CHECK_SHOULD_DRAW(draw, false);
580
581     GrPaint grPaint;
582     if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
583         return;
584     }
585
586     fContext->drawPaint(grPaint);
587 }
588
589 // must be in SkCanvas::PointMode order
590 static const GrPrimitiveType gPointMode2PrimtiveType[] = {
591     kPoints_GrPrimitiveType,
592     kLines_GrPrimitiveType,
593     kLineStrip_GrPrimitiveType
594 };
595
596 void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
597                              size_t count, const SkPoint pts[], const SkPaint& paint) {
598     CHECK_FOR_ANNOTATION(paint);
599     CHECK_SHOULD_DRAW(draw, false);
600
601     SkScalar width = paint.getStrokeWidth();
602     if (width < 0) {
603         return;
604     }
605
606     // we only handle hairlines and paints without path effects or mask filters,
607     // else we let the SkDraw call our drawPath()
608     if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
609         draw.drawPoints(mode, count, pts, paint, true);
610         return;
611     }
612
613     GrPaint grPaint;
614     if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
615         return;
616     }
617
618     fContext->drawVertices(grPaint,
619                            gPointMode2PrimtiveType[mode],
620                            SkToS32(count),
621                            (GrPoint*)pts,
622                            NULL,
623                            NULL,
624                            NULL,
625                            0);
626 }
627
628 ///////////////////////////////////////////////////////////////////////////////
629
630 void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
631                            const SkPaint& paint) {
632     CHECK_FOR_ANNOTATION(paint);
633     CHECK_SHOULD_DRAW(draw, false);
634
635     bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
636     SkScalar width = paint.getStrokeWidth();
637
638     /*
639         We have special code for hairline strokes, miter-strokes, bevel-stroke
640         and fills. Anything else we just call our path code.
641      */
642     bool usePath = doStroke && width > 0 &&
643                    (paint.getStrokeJoin() == SkPaint::kRound_Join ||
644                     (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
645     // another two reasons we might need to call drawPath...
646     if (paint.getMaskFilter() || paint.getPathEffect()) {
647         usePath = true;
648     }
649     if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
650 #if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
651         if (doStroke) {
652 #endif
653             usePath = true;
654 #if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
655         } else {
656             usePath = !fContext->getMatrix().preservesRightAngles();
657         }
658 #endif
659     }
660     // until we can both stroke and fill rectangles
661     if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
662         usePath = true;
663     }
664
665     if (usePath) {
666         SkPath path;
667         path.addRect(rect);
668         this->drawPath(draw, path, paint, NULL, true);
669         return;
670     }
671
672     GrPaint grPaint;
673     if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
674         return;
675     }
676
677     if (!doStroke) {
678         fContext->drawRect(grPaint, rect);
679     } else {
680         SkStrokeRec stroke(paint);
681         fContext->drawRect(grPaint, rect, &stroke);
682     }
683 }
684
685 ///////////////////////////////////////////////////////////////////////////////
686
687 void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
688                            const SkPaint& paint) {
689     CHECK_FOR_ANNOTATION(paint);
690     CHECK_SHOULD_DRAW(draw, false);
691
692     bool usePath = !rect.isSimple();
693     // another two reasons we might need to call drawPath...
694     if (paint.getMaskFilter() || paint.getPathEffect()) {
695         usePath = true;
696     }
697     // until we can rotate rrects...
698     if (!usePath && !fContext->getMatrix().rectStaysRect()) {
699         usePath = true;
700     }
701
702     if (usePath) {
703         SkPath path;
704         path.addRRect(rect);
705         this->drawPath(draw, path, paint, NULL, true);
706         return;
707     }
708
709     GrPaint grPaint;
710     if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
711         return;
712     }
713
714     SkStrokeRec stroke(paint);
715     fContext->drawRRect(grPaint, rect, stroke);
716 }
717
718 ///////////////////////////////////////////////////////////////////////////////
719
720 void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
721                            const SkPaint& paint) {
722     CHECK_FOR_ANNOTATION(paint);
723     CHECK_SHOULD_DRAW(draw, false);
724
725     bool usePath = false;
726     // some basic reasons we might need to call drawPath...
727     if (paint.getMaskFilter() || paint.getPathEffect()) {
728         usePath = true;
729     }
730
731     if (usePath) {
732         SkPath path;
733         path.addOval(oval);
734         this->drawPath(draw, path, paint, NULL, true);
735         return;
736     }
737
738     GrPaint grPaint;
739     if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
740         return;
741     }
742     SkStrokeRec stroke(paint);
743
744     fContext->drawOval(grPaint, oval, stroke);
745 }
746
747 #include "SkMaskFilter.h"
748 #include "SkBounder.h"
749
750 ///////////////////////////////////////////////////////////////////////////////
751
752 // helpers for applying mask filters
753 namespace {
754
755 // Draw a mask using the supplied paint. Since the coverage/geometry
756 // is already burnt into the mask this boils down to a rect draw.
757 // Return true if the mask was successfully drawn.
758 bool draw_mask(GrContext* context, const SkRect& maskRect,
759                GrPaint* grp, GrTexture* mask) {
760     GrContext::AutoMatrix am;
761     if (!am.setIdentity(context, grp)) {
762         return false;
763     }
764
765     SkMatrix matrix;
766     matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
767     matrix.postIDiv(mask->width(), mask->height());
768
769     grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
770     context->drawRect(*grp, maskRect);
771     return true;
772 }
773
774 bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
775                            SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
776                            GrPaint* grp, SkPaint::Style style) {
777     SkMask  srcM, dstM;
778
779     if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
780                             SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
781         return false;
782     }
783     SkAutoMaskFreeImage autoSrc(srcM.fImage);
784
785     if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
786         return false;
787     }
788     // this will free-up dstM when we're done (allocated in filterMask())
789     SkAutoMaskFreeImage autoDst(dstM.fImage);
790
791     if (clip.quickReject(dstM.fBounds)) {
792         return false;
793     }
794     if (bounder && !bounder->doIRect(dstM.fBounds)) {
795         return false;
796     }
797
798     // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
799     // the current clip (and identity matrix) and GrPaint settings
800     GrTextureDesc desc;
801     desc.fWidth = dstM.fBounds.width();
802     desc.fHeight = dstM.fBounds.height();
803     desc.fConfig = kAlpha_8_GrPixelConfig;
804
805     GrAutoScratchTexture ast(context, desc);
806     GrTexture* texture = ast.texture();
807
808     if (NULL == texture) {
809         return false;
810     }
811     texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
812                                dstM.fImage, dstM.fRowBytes);
813
814     SkRect maskRect = SkRect::Make(dstM.fBounds);
815
816     return draw_mask(context, maskRect, grp, texture);
817 }
818
819 // Create a mask of 'devPath' and place the result in 'mask'. Return true on
820 // success; false otherwise.
821 bool create_mask_GPU(GrContext* context,
822                      const SkRect& maskRect,
823                      const SkPath& devPath,
824                      const SkStrokeRec& stroke,
825                      bool doAA,
826                      GrAutoScratchTexture* mask) {
827     GrTextureDesc desc;
828     desc.fFlags = kRenderTarget_GrTextureFlagBit;
829     desc.fWidth = SkScalarCeilToInt(maskRect.width());
830     desc.fHeight = SkScalarCeilToInt(maskRect.height());
831     // We actually only need A8, but it often isn't supported as a
832     // render target so default to RGBA_8888
833     desc.fConfig = kRGBA_8888_GrPixelConfig;
834     if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
835         desc.fConfig = kAlpha_8_GrPixelConfig;
836     }
837
838     mask->set(context, desc);
839     if (NULL == mask->texture()) {
840         return false;
841     }
842
843     GrTexture* maskTexture = mask->texture();
844     SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
845
846     GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
847     GrContext::AutoClip ac(context, clipRect);
848
849     context->clear(NULL, 0x0, true);
850
851     GrPaint tempPaint;
852     if (doAA) {
853         tempPaint.setAntiAlias(true);
854         // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
855         // blend coeff of zero requires dual source blending support in order
856         // to properly blend partially covered pixels. This means the AA
857         // code path may not be taken. So we use a dst blend coeff of ISA. We
858         // could special case AA draws to a dst surface with known alpha=0 to
859         // use a zero dst coeff when dual source blending isn't available.
860         tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
861     }
862
863     GrContext::AutoMatrix am;
864
865     // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
866     SkMatrix translate;
867     translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
868     am.set(context, translate);
869     context->drawPath(tempPaint, devPath, stroke);
870     return true;
871 }
872
873 SkBitmap wrap_texture(GrTexture* texture) {
874     SkImageInfo info;
875     texture->asImageInfo(&info);
876
877     SkBitmap result;
878     result.setConfig(info);
879     result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
880     return result;
881 }
882
883 };
884
885 void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
886                            const SkPaint& paint, const SkMatrix* prePathMatrix,
887                            bool pathIsMutable) {
888     CHECK_FOR_ANNOTATION(paint);
889     CHECK_SHOULD_DRAW(draw, false);
890
891     GrPaint grPaint;
892     if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
893         return;
894     }
895
896     // If we have a prematrix, apply it to the path, optimizing for the case
897     // where the original path can in fact be modified in place (even though
898     // its parameter type is const).
899     SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
900     SkTLazy<SkPath> tmpPath;
901     SkTLazy<SkPath> effectPath;
902
903     if (prePathMatrix) {
904         SkPath* result = pathPtr;
905
906         if (!pathIsMutable) {
907             result = tmpPath.init();
908             pathIsMutable = true;
909         }
910         // should I push prePathMatrix on our MV stack temporarily, instead
911         // of applying it here? See SkDraw.cpp
912         pathPtr->transform(*prePathMatrix, result);
913         pathPtr = result;
914     }
915     // at this point we're done with prePathMatrix
916     SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
917
918     SkStrokeRec stroke(paint);
919     SkPathEffect* pathEffect = paint.getPathEffect();
920     const SkRect* cullRect = NULL;  // TODO: what is our bounds?
921     if (pathEffect && pathEffect->filterPath(effectPath.init(), *pathPtr, &stroke,
922                                              cullRect)) {
923         pathPtr = effectPath.get();
924         pathIsMutable = true;
925     }
926
927     if (paint.getMaskFilter()) {
928         if (!stroke.isHairlineStyle()) {
929             SkPath* strokedPath = pathIsMutable ? pathPtr : tmpPath.init();
930             if (stroke.applyToPath(strokedPath, *pathPtr)) {
931                 pathPtr = strokedPath;
932                 pathIsMutable = true;
933                 stroke.setFillStyle();
934             }
935         }
936
937         // avoid possibly allocating a new path in transform if we can
938         SkPath* devPathPtr = pathIsMutable ? pathPtr : tmpPath.init();
939
940         // transform the path into device space
941         pathPtr->transform(fContext->getMatrix(), devPathPtr);
942
943         SkRect maskRect;
944         if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
945                                                     draw.fClip->getBounds(),
946                                                     fContext->getMatrix(),
947                                                     &maskRect)) {
948             // The context's matrix may change while creating the mask, so save the CTM here to
949             // pass to filterMaskGPU.
950             const SkMatrix ctm = fContext->getMatrix();
951
952             SkIRect finalIRect;
953             maskRect.roundOut(&finalIRect);
954             if (draw.fClip->quickReject(finalIRect)) {
955                 // clipped out
956                 return;
957             }
958             if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
959                 // nothing to draw
960                 return;
961             }
962
963             if (paint.getMaskFilter()->directFilterMaskGPU(fContext, &grPaint,
964                                                            SkStrokeRec(paint), *devPathPtr)) {
965                 // the mask filter was able to draw itself directly, so there's nothing
966                 // left to do.
967                 return;
968             }
969
970             GrAutoScratchTexture mask;
971
972             if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
973                                 grPaint.isAntiAlias(), &mask)) {
974                 GrTexture* filtered;
975
976                 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
977                                                          ctm, maskRect, &filtered, true)) {
978                     // filterMaskGPU gives us ownership of a ref to the result
979                     SkAutoTUnref<GrTexture> atu(filtered);
980
981                     // If the scratch texture that we used as the filter src also holds the filter
982                     // result then we must detach so that this texture isn't recycled for a later
983                     // draw.
984                     if (filtered == mask.texture()) {
985                         mask.detach();
986                         filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
987                     }
988
989                     if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
990                         // This path is completely drawn
991                         return;
992                     }
993                 }
994             }
995         }
996
997         // draw the mask on the CPU - this is a fallthrough path in case the
998         // GPU path fails
999         SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
1000                                                           SkPaint::kFill_Style;
1001         draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
1002                               *draw.fClip, draw.fBounder, &grPaint, style);
1003         return;
1004     }
1005
1006     fContext->drawPath(grPaint, *pathPtr, stroke);
1007 }
1008
1009 static const int kBmpSmallTileSize = 1 << 10;
1010
1011 static inline int get_tile_count(const SkIRect& srcRect, int tileSize)  {
1012     int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
1013     int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
1014     return tilesX * tilesY;
1015 }
1016
1017 static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
1018     if (maxTileSize <= kBmpSmallTileSize) {
1019         return maxTileSize;
1020     }
1021
1022     size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
1023     size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
1024
1025     maxTileTotalTileSize *= maxTileSize * maxTileSize;
1026     smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
1027
1028     if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
1029         return kBmpSmallTileSize;
1030     } else {
1031         return maxTileSize;
1032     }
1033 }
1034
1035 // Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1036 // pixels from the bitmap are necessary.
1037 static void determine_clipped_src_rect(const GrContext* context,
1038                                        const SkBitmap& bitmap,
1039                                        const SkRect* srcRectPtr,
1040                                        SkIRect* clippedSrcIRect) {
1041     const GrClipData* clip = context->getClip();
1042     clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1043     SkMatrix inv;
1044     if (!context->getMatrix().invert(&inv)) {
1045         clippedSrcIRect->setEmpty();
1046         return;
1047     }
1048     SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1049     inv.mapRect(&clippedSrcRect);
1050     if (NULL != srcRectPtr) {
1051         // we've setup src space 0,0 to map to the top left of the src rect.
1052         clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
1053         if (!clippedSrcRect.intersect(*srcRectPtr)) {
1054             clippedSrcIRect->setEmpty();
1055             return;
1056         }
1057     }
1058     clippedSrcRect.roundOut(clippedSrcIRect);
1059     SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1060     if (!clippedSrcIRect->intersect(bmpBounds)) {
1061         clippedSrcIRect->setEmpty();
1062     }
1063 }
1064
1065 bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1066                                    const GrTextureParams& params,
1067                                    const SkRect* srcRectPtr,
1068                                    int maxTileSize,
1069                                    int* tileSize,
1070                                    SkIRect* clippedSrcRect) const {
1071     // if bitmap is explictly texture backed then just use the texture
1072     if (NULL != bitmap.getTexture()) {
1073         return false;
1074     }
1075
1076     // if it's larger than the max tile size, then we have no choice but tiling.
1077     if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1078         determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1079         *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1080         return true;
1081     }
1082
1083     if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1084         return false;
1085     }
1086
1087     // if the entire texture is already in our cache then no reason to tile it
1088     if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1089         return false;
1090     }
1091
1092     // At this point we know we could do the draw by uploading the entire bitmap
1093     // as a texture. However, if the texture would be large compared to the
1094     // cache size and we don't require most of it for this draw then tile to
1095     // reduce the amount of upload and cache spill.
1096
1097     // assumption here is that sw bitmap size is a good proxy for its size as
1098     // a texture
1099     size_t bmpSize = bitmap.getSize();
1100     size_t cacheSize;
1101     fContext->getTextureCacheLimits(NULL, &cacheSize);
1102     if (bmpSize < cacheSize / 2) {
1103         return false;
1104     }
1105
1106     // Figure out how much of the src we will need based on the src rect and clipping.
1107     determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1108     *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1109     size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1110                            kBmpSmallTileSize * kBmpSmallTileSize;
1111
1112     return usedTileBytes < 2 * bmpSize;
1113 }
1114
1115 void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
1116                              const SkBitmap& bitmap,
1117                              const SkMatrix& m,
1118                              const SkPaint& paint) {
1119     SkMatrix concat;
1120     SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1121     if (!m.isIdentity()) {
1122         concat.setConcat(*draw->fMatrix, m);
1123         draw.writable()->fMatrix = &concat;
1124     }
1125     this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
1126 }
1127
1128 // This method outsets 'iRect' by 'outset' all around and then clamps its extents to
1129 // 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1130 // of 'iRect' for all possible outsets/clamps.
1131 static inline void clamped_outset_with_offset(SkIRect* iRect,
1132                                               int outset,
1133                                               SkPoint* offset,
1134                                               const SkIRect& clamp) {
1135     iRect->outset(outset, outset);
1136
1137     int leftClampDelta = clamp.fLeft - iRect->fLeft;
1138     if (leftClampDelta > 0) {
1139         offset->fX -= outset - leftClampDelta;
1140         iRect->fLeft = clamp.fLeft;
1141     } else {
1142         offset->fX -= outset;
1143     }
1144
1145     int topClampDelta = clamp.fTop - iRect->fTop;
1146     if (topClampDelta > 0) {
1147         offset->fY -= outset - topClampDelta;
1148         iRect->fTop = clamp.fTop;
1149     } else {
1150         offset->fY -= outset;
1151     }
1152
1153     if (iRect->fRight > clamp.fRight) {
1154         iRect->fRight = clamp.fRight;
1155     }
1156     if (iRect->fBottom > clamp.fBottom) {
1157         iRect->fBottom = clamp.fBottom;
1158     }
1159 }
1160
1161 void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1162                                    const SkBitmap& bitmap,
1163                                    const SkRect* srcRectPtr,
1164                                    const SkSize* dstSizePtr,
1165                                    const SkPaint& paint,
1166                                    SkCanvas::DrawBitmapRectFlags flags) {
1167     CHECK_SHOULD_DRAW(draw, false);
1168
1169     SkRect srcRect;
1170     SkSize dstSize;
1171     // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1172     // in the (easier) bleed case, so update flags.
1173     if (NULL == srcRectPtr) {
1174         SkScalar w = SkIntToScalar(bitmap.width());
1175         SkScalar h = SkIntToScalar(bitmap.height());
1176         dstSize.fWidth = w;
1177         dstSize.fHeight = h;
1178         srcRect.set(0, 0, w, h);
1179         flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1180     } else {
1181         SkASSERT(NULL != dstSizePtr);
1182         srcRect = *srcRectPtr;
1183         dstSize = *dstSizePtr;
1184         if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1185             srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1186             flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1187         }
1188     }
1189
1190     if (paint.getMaskFilter()){
1191         // Convert the bitmap to a shader so that the rect can be drawn
1192         // through drawRect, which supports mask filters.
1193         SkBitmap        tmp;    // subset of bitmap, if necessary
1194         const SkBitmap* bitmapPtr = &bitmap;
1195         SkMatrix localM;
1196         if (NULL != srcRectPtr) {
1197             localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1198             localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1199                              dstSize.fHeight / srcRectPtr->height());
1200             // In bleed mode we position and trim the bitmap based on the src rect which is
1201             // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1202             // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1203             // compensate.
1204             if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1205                 SkIRect iSrc;
1206                 srcRect.roundOut(&iSrc);
1207
1208                 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1209                                                SkIntToScalar(iSrc.fTop));
1210
1211                 if (!bitmap.extractSubset(&tmp, iSrc)) {
1212                     return;     // extraction failed
1213                 }
1214                 bitmapPtr = &tmp;
1215                 srcRect.offset(-offset.fX, -offset.fY);
1216
1217                 // The source rect has changed so update the matrix
1218                 localM.preTranslate(offset.fX, offset.fY);
1219             }
1220         } else {
1221             localM.reset();
1222         }
1223
1224         SkPaint paintWithShader(paint);
1225         paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
1226             SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
1227         paintWithShader.getShader()->setLocalMatrix(localM);
1228         SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1229         this->drawRect(draw, dstRect, paintWithShader);
1230
1231         return;
1232     }
1233
1234     // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1235     // the view matrix rather than a local matrix.
1236     SkMatrix m;
1237     m.setScale(dstSize.fWidth / srcRect.width(),
1238                dstSize.fHeight / srcRect.height());
1239     fContext->concatMatrix(m);
1240
1241     GrTextureParams params;
1242     SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1243     GrTextureParams::FilterMode textureFilterMode;
1244
1245     int tileFilterPad;
1246     bool doBicubic = false;
1247
1248     switch(paintFilterLevel) {
1249         case SkPaint::kNone_FilterLevel:
1250             tileFilterPad = 0;
1251             textureFilterMode = GrTextureParams::kNone_FilterMode;
1252             break;
1253         case SkPaint::kLow_FilterLevel:
1254             tileFilterPad = 1;
1255             textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1256             break;
1257         case SkPaint::kMedium_FilterLevel:
1258             tileFilterPad = 1;
1259             if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1260                 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1261             } else {
1262                 // Don't trigger MIP level generation unnecessarily.
1263                 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1264             }
1265             break;
1266         case SkPaint::kHigh_FilterLevel:
1267             // Minification can look bad with the bicubic effect.
1268             if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
1269                 // We will install an effect that does the filtering in the shader.
1270                 textureFilterMode = GrTextureParams::kNone_FilterMode;
1271                 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1272                 doBicubic = true;
1273             } else {
1274                 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1275                 tileFilterPad = 1;
1276             }
1277             break;
1278         default:
1279             SkErrorInternals::SetError( kInvalidPaint_SkError,
1280                                         "Sorry, I don't understand the filtering "
1281                                         "mode you asked for.  Falling back to "
1282                                         "MIPMaps.");
1283             tileFilterPad = 1;
1284             textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1285             break;
1286     }
1287
1288     params.setFilterMode(textureFilterMode);
1289
1290     int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
1291     int tileSize;
1292
1293     SkIRect clippedSrcRect;
1294     if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1295                                &clippedSrcRect)) {
1296         this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1297                               doBicubic);
1298     } else {
1299         // take the simple case
1300         this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
1301     }
1302 }
1303
1304 // Break 'bitmap' into several tiles to draw it since it has already
1305 // been determined to be too large to fit in VRAM
1306 void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1307                                   const SkRect& srcRect,
1308                                   const SkIRect& clippedSrcIRect,
1309                                   const GrTextureParams& params,
1310                                   const SkPaint& paint,
1311                                   SkCanvas::DrawBitmapRectFlags flags,
1312                                   int tileSize,
1313                                   bool bicubic) {
1314     SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1315
1316     int nx = bitmap.width() / tileSize;
1317     int ny = bitmap.height() / tileSize;
1318     for (int x = 0; x <= nx; x++) {
1319         for (int y = 0; y <= ny; y++) {
1320             SkRect tileR;
1321             tileR.set(SkIntToScalar(x * tileSize),
1322                       SkIntToScalar(y * tileSize),
1323                       SkIntToScalar((x + 1) * tileSize),
1324                       SkIntToScalar((y + 1) * tileSize));
1325
1326             if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1327                 continue;
1328             }
1329
1330             if (!tileR.intersect(srcRect)) {
1331                 continue;
1332             }
1333
1334             SkBitmap tmpB;
1335             SkIRect iTileR;
1336             tileR.roundOut(&iTileR);
1337             SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1338                                            SkIntToScalar(iTileR.fTop));
1339
1340             // Adjust the context matrix to draw at the right x,y in device space
1341             SkMatrix tmpM;
1342             GrContext::AutoMatrix am;
1343             tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1344             am.setPreConcat(fContext, tmpM);
1345
1346             if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
1347                 SkIRect iClampRect;
1348
1349                 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1350                     // In bleed mode we want to always expand the tile on all edges
1351                     // but stay within the bitmap bounds
1352                     iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1353                 } else {
1354                     // In texture-domain/clamp mode we only want to expand the
1355                     // tile on edges interior to "srcRect" (i.e., we want to
1356                     // not bleed across the original clamped edges)
1357                     srcRect.roundOut(&iClampRect);
1358                 }
1359                 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1360                 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
1361             }
1362
1363             if (bitmap.extractSubset(&tmpB, iTileR)) {
1364                 // now offset it to make it "local" to our tmp bitmap
1365                 tileR.offset(-offset.fX, -offset.fY);
1366
1367                 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
1368             }
1369         }
1370     }
1371 }
1372
1373 static bool has_aligned_samples(const SkRect& srcRect,
1374                                 const SkRect& transformedRect) {
1375     // detect pixel disalignment
1376     if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1377             transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1378         SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1379             transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1380         SkScalarAbs(transformedRect.width() - srcRect.width()) <
1381             COLOR_BLEED_TOLERANCE &&
1382         SkScalarAbs(transformedRect.height() - srcRect.height()) <
1383             COLOR_BLEED_TOLERANCE) {
1384         return true;
1385     }
1386     return false;
1387 }
1388
1389 static bool may_color_bleed(const SkRect& srcRect,
1390                             const SkRect& transformedRect,
1391                             const SkMatrix& m) {
1392     // Only gets called if has_aligned_samples returned false.
1393     // So we can assume that sampling is axis aligned but not texel aligned.
1394     SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1395     SkRect innerSrcRect(srcRect), innerTransformedRect,
1396         outerTransformedRect(transformedRect);
1397     innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1398     m.mapRect(&innerTransformedRect, innerSrcRect);
1399
1400     // The gap between outerTransformedRect and innerTransformedRect
1401     // represents the projection of the source border area, which is
1402     // problematic for color bleeding.  We must check whether any
1403     // destination pixels sample the border area.
1404     outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1405     innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1406     SkIRect outer, inner;
1407     outerTransformedRect.round(&outer);
1408     innerTransformedRect.round(&inner);
1409     // If the inner and outer rects round to the same result, it means the
1410     // border does not overlap any pixel centers. Yay!
1411     return inner != outer;
1412 }
1413
1414
1415 /*
1416  *  This is called by drawBitmap(), which has to handle images that may be too
1417  *  large to be represented by a single texture.
1418  *
1419  *  internalDrawBitmap assumes that the specified bitmap will fit in a texture
1420  *  and that non-texture portion of the GrPaint has already been setup.
1421  */
1422 void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1423                                      const SkRect& srcRect,
1424                                      const GrTextureParams& params,
1425                                      const SkPaint& paint,
1426                                      SkCanvas::DrawBitmapRectFlags flags,
1427                                      bool bicubic) {
1428     SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1429              bitmap.height() <= fContext->getMaxTextureSize());
1430
1431     GrTexture* texture;
1432     SkAutoCachedTexture act(this, bitmap, &params, &texture);
1433     if (NULL == texture) {
1434         return;
1435     }
1436
1437     SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
1438     SkRect paintRect;
1439     SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1440     SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1441     paintRect.setLTRB(SkScalarMul(srcRect.fLeft,   wInv),
1442                       SkScalarMul(srcRect.fTop,    hInv),
1443                       SkScalarMul(srcRect.fRight,  wInv),
1444                       SkScalarMul(srcRect.fBottom, hInv));
1445
1446     bool needsTextureDomain = false;
1447     if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
1448         (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1449         // Need texture domain if drawing a sub rect
1450         needsTextureDomain = srcRect.width() < bitmap.width() ||
1451                              srcRect.height() < bitmap.height();
1452         if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
1453             const SkMatrix& matrix = fContext->getMatrix();
1454             // sampling is axis-aligned
1455             SkRect transformedRect;
1456             matrix.mapRect(&transformedRect, srcRect);
1457
1458             if (has_aligned_samples(srcRect, transformedRect)) {
1459                 // We could also turn off filtering here (but we already did a cache lookup with
1460                 // params).
1461                 needsTextureDomain = false;
1462             } else {
1463                 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1464             }
1465         }
1466     }
1467
1468     SkRect textureDomain = SkRect::MakeEmpty();
1469     SkAutoTUnref<GrEffectRef> effect;
1470     if (needsTextureDomain) {
1471         // Use a constrained texture domain to avoid color bleeding
1472         SkScalar left, top, right, bottom;
1473         if (srcRect.width() > SK_Scalar1) {
1474             SkScalar border = SK_ScalarHalf / texture->width();
1475             left = paintRect.left() + border;
1476             right = paintRect.right() - border;
1477         } else {
1478             left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1479         }
1480         if (srcRect.height() > SK_Scalar1) {
1481             SkScalar border = SK_ScalarHalf / texture->height();
1482             top = paintRect.top() + border;
1483             bottom = paintRect.bottom() - border;
1484         } else {
1485             top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1486         }
1487         textureDomain.setLTRB(left, top, right, bottom);
1488         if (bicubic) {
1489             effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1490         } else {
1491             effect.reset(GrTextureDomainEffect::Create(texture,
1492                                                        SkMatrix::I(),
1493                                                        textureDomain,
1494                                                        GrTextureDomain::kClamp_Mode,
1495                                                        params.filterMode()));
1496         }
1497     } else if (bicubic) {
1498         SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1499         SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1500         effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
1501     } else {
1502         effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1503     }
1504
1505     // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1506     // the rest from the SkPaint.
1507     GrPaint grPaint;
1508     grPaint.addColorEffect(effect);
1509     bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1510     if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1511         return;
1512     }
1513
1514     fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1515 }
1516
1517 static bool filter_texture(SkBaseDevice* device, GrContext* context,
1518                            GrTexture* texture, const SkImageFilter* filter,
1519                            int w, int h, const SkMatrix& ctm, SkBitmap* result,
1520                            SkIPoint* offset) {
1521     SkASSERT(filter);
1522     SkDeviceImageFilterProxy proxy(device);
1523
1524     if (filter->canFilterImageGPU()) {
1525         // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1526         // filter.  Also set the clip wide open and the matrix to identity.
1527         GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1528         return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1529     } else {
1530         return false;
1531     }
1532 }
1533
1534 void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1535                              int left, int top, const SkPaint& paint) {
1536     // drawSprite is defined to be in device coords.
1537     CHECK_SHOULD_DRAW(draw, true);
1538
1539     SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1540     if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1541         return;
1542     }
1543
1544     int w = bitmap.width();
1545     int h = bitmap.height();
1546
1547     GrTexture* texture;
1548     // draw sprite uses the default texture params
1549     SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1550
1551     SkImageFilter* filter = paint.getImageFilter();
1552     // This bitmap will own the filtered result as a texture.
1553     SkBitmap filteredBitmap;
1554
1555     if (NULL != filter) {
1556         SkIPoint offset = SkIPoint::Make(0, 0);
1557         SkMatrix matrix(*draw.fMatrix);
1558         matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1559         if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1560                            &offset)) {
1561             texture = (GrTexture*) filteredBitmap.getTexture();
1562             w = filteredBitmap.width();
1563             h = filteredBitmap.height();
1564             left += offset.x();
1565             top += offset.y();
1566         } else {
1567             return;
1568         }
1569     }
1570
1571     GrPaint grPaint;
1572     grPaint.addColorTextureEffect(texture, SkMatrix::I());
1573
1574     if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1575         return;
1576     }
1577
1578     fContext->drawRectToRect(grPaint,
1579                              SkRect::MakeXYWH(SkIntToScalar(left),
1580                                               SkIntToScalar(top),
1581                                               SkIntToScalar(w),
1582                                               SkIntToScalar(h)),
1583                              SkRect::MakeXYWH(0,
1584                                               0,
1585                                               SK_Scalar1 * w / texture->width(),
1586                                               SK_Scalar1 * h / texture->height()));
1587 }
1588
1589 void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
1590                                  const SkRect* src, const SkRect& dst,
1591                                  const SkPaint& paint,
1592                                  SkCanvas::DrawBitmapRectFlags flags) {
1593     SkMatrix    matrix;
1594     SkRect      bitmapBounds, tmpSrc;
1595
1596     bitmapBounds.set(0, 0,
1597                      SkIntToScalar(bitmap.width()),
1598                      SkIntToScalar(bitmap.height()));
1599
1600     // Compute matrix from the two rectangles
1601     if (NULL != src) {
1602         tmpSrc = *src;
1603     } else {
1604         tmpSrc = bitmapBounds;
1605     }
1606
1607     matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1608
1609     // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1610     if (NULL != src) {
1611         if (!bitmapBounds.contains(tmpSrc)) {
1612             if (!tmpSrc.intersect(bitmapBounds)) {
1613                 return; // nothing to draw
1614             }
1615         }
1616     }
1617
1618     SkRect tmpDst;
1619     matrix.mapRect(&tmpDst, tmpSrc);
1620
1621     SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1622     if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1623         // Translate so that tempDst's top left is at the origin.
1624         matrix = *origDraw.fMatrix;
1625         matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1626         draw.writable()->fMatrix = &matrix;
1627     }
1628     SkSize dstSize;
1629     dstSize.fWidth = tmpDst.width();
1630     dstSize.fHeight = tmpDst.height();
1631
1632     this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
1633 }
1634
1635 void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1636                              int x, int y, const SkPaint& paint) {
1637     // clear of the source device must occur before CHECK_SHOULD_DRAW
1638     SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1639     if (dev->fNeedClear) {
1640         // TODO: could check here whether we really need to draw at all
1641         dev->clear(0x0);
1642     }
1643
1644     // drawDevice is defined to be in device coords.
1645     CHECK_SHOULD_DRAW(draw, true);
1646
1647     GrRenderTarget* devRT = dev->accessRenderTarget();
1648     GrTexture* devTex;
1649     if (NULL == (devTex = devRT->asTexture())) {
1650         return;
1651     }
1652
1653     const SkBitmap& bm = dev->accessBitmap(false);
1654     int w = bm.width();
1655     int h = bm.height();
1656
1657     SkImageFilter* filter = paint.getImageFilter();
1658     // This bitmap will own the filtered result as a texture.
1659     SkBitmap filteredBitmap;
1660
1661     if (NULL != filter) {
1662         SkIPoint offset = SkIPoint::Make(0, 0);
1663         SkMatrix matrix(*draw.fMatrix);
1664         matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1665         if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1666                            &offset)) {
1667             devTex = filteredBitmap.getTexture();
1668             w = filteredBitmap.width();
1669             h = filteredBitmap.height();
1670             x += offset.fX;
1671             y += offset.fY;
1672         } else {
1673             return;
1674         }
1675     }
1676
1677     GrPaint grPaint;
1678     grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1679
1680     if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1681         return;
1682     }
1683
1684     SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1685                                       SkIntToScalar(y),
1686                                       SkIntToScalar(w),
1687                                       SkIntToScalar(h));
1688
1689     // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1690     // scratch texture).
1691     SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1692                                     SK_Scalar1 * h / devTex->height());
1693
1694     fContext->drawRectToRect(grPaint, dstRect, srcRect);
1695 }
1696
1697 bool SkGpuDevice::canHandleImageFilter(const SkImageFilter* filter) {
1698     return filter->canFilterImageGPU();
1699 }
1700
1701 bool SkGpuDevice::filterImage(const SkImageFilter* filter, const SkBitmap& src,
1702                               const SkMatrix& ctm,
1703                               SkBitmap* result, SkIPoint* offset) {
1704     // want explicitly our impl, so guard against a subclass of us overriding it
1705     if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1706         return false;
1707     }
1708
1709     SkAutoLockPixels alp(src, !src.getTexture());
1710     if (!src.getTexture() && !src.readyToDraw()) {
1711         return false;
1712     }
1713
1714     GrTexture* texture;
1715     // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1716     // must be pushed upstack.
1717     SkAutoCachedTexture act(this, src, NULL, &texture);
1718
1719     return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1720                           offset);
1721 }
1722
1723 ///////////////////////////////////////////////////////////////////////////////
1724
1725 // must be in SkCanvas::VertexMode order
1726 static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1727     kTriangles_GrPrimitiveType,
1728     kTriangleStrip_GrPrimitiveType,
1729     kTriangleFan_GrPrimitiveType,
1730 };
1731
1732 void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1733                               int vertexCount, const SkPoint vertices[],
1734                               const SkPoint texs[], const SkColor colors[],
1735                               SkXfermode* xmode,
1736                               const uint16_t indices[], int indexCount,
1737                               const SkPaint& paint) {
1738     CHECK_SHOULD_DRAW(draw, false);
1739
1740     GrPaint grPaint;
1741     // we ignore the shader if texs is null.
1742     if (NULL == texs) {
1743         if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1744             return;
1745         }
1746     } else {
1747         if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1748             return;
1749         }
1750     }
1751
1752     if (NULL != xmode && NULL != texs && NULL != colors) {
1753         if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1754             SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1755 #if 0
1756             return
1757 #endif
1758         }
1759     }
1760
1761     SkAutoSTMalloc<128, GrColor> convertedColors(0);
1762     if (NULL != colors) {
1763         // need to convert byte order and from non-PM to PM
1764         convertedColors.reset(vertexCount);
1765         for (int i = 0; i < vertexCount; ++i) {
1766             convertedColors[i] = SkColor2GrColor(colors[i]);
1767         }
1768         colors = convertedColors.get();
1769     }
1770     fContext->drawVertices(grPaint,
1771                            gVertexMode2PrimitiveType[vmode],
1772                            vertexCount,
1773                            (GrPoint*) vertices,
1774                            (GrPoint*) texs,
1775                            colors,
1776                            indices,
1777                            indexCount);
1778 }
1779
1780 ///////////////////////////////////////////////////////////////////////////////
1781
1782 void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1783                           size_t byteLength, SkScalar x, SkScalar y,
1784                           const SkPaint& paint) {
1785     CHECK_SHOULD_DRAW(draw, false);
1786
1787     if (fMainTextContext->canDraw(paint)) {
1788         GrPaint grPaint;
1789         if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1790             return;
1791         }
1792
1793         SkDEBUGCODE(this->validate();)
1794
1795         fMainTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1796     } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
1797         GrPaint grPaint;
1798         if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1799             return;
1800         }
1801
1802         SkDEBUGCODE(this->validate();)
1803
1804         fFallbackTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1805     } else {
1806         // this guy will just call our drawPath()
1807         draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1808     }
1809 }
1810
1811 void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1812                              size_t byteLength, const SkScalar pos[],
1813                              SkScalar constY, int scalarsPerPos,
1814                              const SkPaint& paint) {
1815     CHECK_SHOULD_DRAW(draw, false);
1816
1817     if (fMainTextContext->canDraw(paint)) {
1818         GrPaint grPaint;
1819         if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1820             return;
1821         }
1822
1823         SkDEBUGCODE(this->validate();)
1824
1825         fMainTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
1826                                       constY, scalarsPerPos);
1827     } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
1828         GrPaint grPaint;
1829         if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1830             return;
1831         }
1832
1833         SkDEBUGCODE(this->validate();)
1834
1835         fFallbackTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
1836                                           constY, scalarsPerPos);
1837     } else {
1838         draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
1839                                  scalarsPerPos, paint);
1840     }
1841 }
1842
1843 void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1844                                 size_t len, const SkPath& path,
1845                                 const SkMatrix* m, const SkPaint& paint) {
1846     CHECK_SHOULD_DRAW(draw, false);
1847
1848     SkASSERT(draw.fDevice == this);
1849     draw.drawTextOnPath((const char*)text, len, path, m, paint);
1850 }
1851
1852 ///////////////////////////////////////////////////////////////////////////////
1853
1854 bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1855     if (!paint.isLCDRenderText()) {
1856         // we're cool with the paint as is
1857         return false;
1858     }
1859
1860     if (paint.getShader() ||
1861         paint.getXfermode() || // unless its srcover
1862         paint.getMaskFilter() ||
1863         paint.getRasterizer() ||
1864         paint.getColorFilter() ||
1865         paint.getPathEffect() ||
1866         paint.isFakeBoldText() ||
1867         paint.getStyle() != SkPaint::kFill_Style) {
1868         // turn off lcd
1869         flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1870         flags->fHinting = paint.getHinting();
1871         return true;
1872     }
1873     // we're cool with the paint as is
1874     return false;
1875 }
1876
1877 void SkGpuDevice::flush() {
1878     DO_DEFERRED_CLEAR();
1879     fContext->resolveRenderTarget(fRenderTarget);
1880 }
1881
1882 ///////////////////////////////////////////////////////////////////////////////
1883
1884 SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1885                                                     int width, int height,
1886                                                     bool isOpaque,
1887                                                     Usage usage) {
1888     GrTextureDesc desc;
1889     desc.fConfig = fRenderTarget->config();
1890     desc.fFlags = kRenderTarget_GrTextureFlagBit;
1891     desc.fWidth = width;
1892     desc.fHeight = height;
1893     desc.fSampleCnt = fRenderTarget->numSamples();
1894
1895     SkAutoTUnref<GrTexture> texture;
1896     // Skia's convention is to only clear a device if it is non-opaque.
1897     bool needClear = !isOpaque;
1898
1899 #if CACHE_COMPATIBLE_DEVICE_TEXTURES
1900     // layers are never draw in repeat modes, so we can request an approx
1901     // match and ignore any padding.
1902     const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1903                                                 GrContext::kApprox_ScratchTexMatch :
1904                                                 GrContext::kExact_ScratchTexMatch;
1905     texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1906 #else
1907     texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1908 #endif
1909     if (NULL != texture.get()) {
1910         return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1911     } else {
1912         GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1913         return NULL;
1914     }
1915 }
1916
1917 SkSurface* SkGpuDevice::newSurface(const SkImageInfo& info) {
1918     return SkSurface::NewRenderTarget(fContext, info, fRenderTarget->numSamples());
1919 }
1920
1921 SkGpuDevice::SkGpuDevice(GrContext* context,
1922                          GrTexture* texture,
1923                          bool needClear)
1924     : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1925
1926     SkASSERT(texture && texture->asRenderTarget());
1927     // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1928     // cache. We pass true for the third argument so that it will get unlocked.
1929     this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1930     fNeedClear = needClear;
1931 }