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 "src/core/SkDevice.h"
9 
10 #include "include/core/SkColorFilter.h"
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkImageFilter.h"
13 #include "include/core/SkPathMeasure.h"
14 #include "include/core/SkRSXform.h"
15 #include "include/core/SkShader.h"
16 #include "include/core/SkVertices.h"
17 #include "include/private/SkTo.h"
18 #include "src/core/SkDraw.h"
19 #include "src/core/SkGlyphRun.h"
20 #include "src/core/SkImageFilterCache.h"
21 #include "src/core/SkImagePriv.h"
22 #include "src/core/SkLatticeIter.h"
23 #include "src/core/SkMakeUnique.h"
24 #include "src/core/SkMatrixPriv.h"
25 #include "src/core/SkPathPriv.h"
26 #include "src/core/SkRasterClip.h"
27 #include "src/core/SkSpecialImage.h"
28 #include "src/core/SkTLazy.h"
29 #include "src/core/SkTextBlobPriv.h"
30 #include "src/core/SkUtils.h"
31 #include "src/image/SkImage_Base.h"
32 #include "src/shaders/SkLocalMatrixShader.h"
33 #include "src/utils/SkPatchUtils.h"
34 
SkBaseDevice(const SkImageInfo & info,const SkSurfaceProps & surfaceProps)35 SkBaseDevice::SkBaseDevice(const SkImageInfo& info, const SkSurfaceProps& surfaceProps)
36     : fInfo(info)
37     , fSurfaceProps(surfaceProps)
38 {
39     fOrigin = {0, 0};
40     fCTM.reset();
41 }
42 
setOrigin(const SkMatrix & globalCTM,int x,int y)43 void SkBaseDevice::setOrigin(const SkMatrix& globalCTM, int x, int y) {
44     fOrigin.set(x, y);
45     fCTM = globalCTM;
46     fCTM.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
47 }
48 
setGlobalCTM(const SkMatrix & ctm)49 void SkBaseDevice::setGlobalCTM(const SkMatrix& ctm) {
50     fCTM = ctm;
51     if (fOrigin.fX | fOrigin.fY) {
52         fCTM.postTranslate(-SkIntToScalar(fOrigin.fX), -SkIntToScalar(fOrigin.fY));
53     }
54 }
55 
clipIsWideOpen() const56 bool SkBaseDevice::clipIsWideOpen() const {
57     if (ClipType::kRect == this->onGetClipType()) {
58         SkRegion rgn;
59         this->onAsRgnClip(&rgn);
60         SkASSERT(rgn.isRect());
61         return rgn.getBounds() == SkIRect::MakeWH(this->width(), this->height());
62     } else {
63         return false;
64     }
65 }
66 
AdjustGeometry(TileUsage tileUsage,SkPixelGeometry geo)67 SkPixelGeometry SkBaseDevice::CreateInfo::AdjustGeometry(TileUsage tileUsage, SkPixelGeometry geo) {
68     switch (tileUsage) {
69         case kPossible_TileUsage:
70             // (we think) for compatibility with old clients, we assume this layer can support LCD
71             // even though they may not have marked it as opaque... seems like we should update
72             // our callers (reed/robertphilips).
73             break;
74         case kNever_TileUsage:
75             geo = kUnknown_SkPixelGeometry;
76             break;
77     }
78     return geo;
79 }
80 
is_int(float x)81 static inline bool is_int(float x) {
82     return x == (float) sk_float_round2int(x);
83 }
84 
drawRegion(const SkRegion & region,const SkPaint & paint)85 void SkBaseDevice::drawRegion(const SkRegion& region, const SkPaint& paint) {
86     const SkMatrix& ctm = this->ctm();
87     bool isNonTranslate = ctm.getType() & ~(SkMatrix::kTranslate_Mask);
88     bool complexPaint = paint.getStyle() != SkPaint::kFill_Style || paint.getMaskFilter() ||
89                         paint.getPathEffect();
90     bool antiAlias = paint.isAntiAlias() && (!is_int(ctm.getTranslateX()) ||
91                                              !is_int(ctm.getTranslateY()));
92     if (isNonTranslate || complexPaint || antiAlias) {
93         SkPath path;
94         region.getBoundaryPath(&path);
95         path.setIsVolatile(true);
96         return this->drawPath(path, paint, true);
97     }
98 
99     SkRegion::Iterator it(region);
100     while (!it.done()) {
101         this->drawRect(SkRect::Make(it.rect()), paint);
102         it.next();
103     }
104 }
105 
drawArc(const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const SkPaint & paint)106 void SkBaseDevice::drawArc(const SkRect& oval, SkScalar startAngle,
107                            SkScalar sweepAngle, bool useCenter, const SkPaint& paint) {
108     SkPath path;
109     bool isFillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
110     SkPathPriv::CreateDrawArcPath(&path, oval, startAngle, sweepAngle, useCenter,
111                                   isFillNoPathEffect);
112     this->drawPath(path, paint);
113 }
114 
drawDRRect(const SkRRect & outer,const SkRRect & inner,const SkPaint & paint)115 void SkBaseDevice::drawDRRect(const SkRRect& outer,
116                               const SkRRect& inner, const SkPaint& paint) {
117     SkPath path;
118     path.addRRect(outer);
119     path.addRRect(inner);
120     path.setFillType(SkPath::kEvenOdd_FillType);
121     path.setIsVolatile(true);
122 
123     this->drawPath(path, paint, true);
124 }
125 
drawPatch(const SkPoint cubics[12],const SkColor colors[4],const SkPoint texCoords[4],SkBlendMode bmode,const SkPaint & paint)126 void SkBaseDevice::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
127                              const SkPoint texCoords[4], SkBlendMode bmode, const SkPaint& paint) {
128     SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &this->ctm());
129     auto vertices = SkPatchUtils::MakeVertices(cubics, colors, texCoords, lod.width(), lod.height(),
130                                                this->imageInfo().colorSpace());
131     if (vertices) {
132         this->drawVertices(vertices.get(), nullptr, 0, bmode, paint);
133     }
134 }
135 
drawImageRect(const SkImage * image,const SkRect * src,const SkRect & dst,const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)136 void SkBaseDevice::drawImageRect(const SkImage* image, const SkRect* src,
137                                  const SkRect& dst, const SkPaint& paint,
138                                  SkCanvas::SrcRectConstraint constraint) {
139     SkBitmap bm;
140     if (as_IB(image)->getROPixels(&bm)) {
141         this->drawBitmapRect(bm, src, dst, paint, constraint);
142     }
143 }
144 
drawImageNine(const SkImage * image,const SkIRect & center,const SkRect & dst,const SkPaint & paint)145 void SkBaseDevice::drawImageNine(const SkImage* image, const SkIRect& center,
146                                  const SkRect& dst, const SkPaint& paint) {
147     SkLatticeIter iter(image->width(), image->height(), center, dst);
148 
149     SkRect srcR, dstR;
150     while (iter.next(&srcR, &dstR)) {
151         this->drawImageRect(image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
152     }
153 }
154 
drawBitmapNine(const SkBitmap & bitmap,const SkIRect & center,const SkRect & dst,const SkPaint & paint)155 void SkBaseDevice::drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
156                                   const SkRect& dst, const SkPaint& paint) {
157     SkLatticeIter iter(bitmap.width(), bitmap.height(), center, dst);
158 
159     SkRect srcR, dstR;
160     while (iter.next(&srcR, &dstR)) {
161         this->drawBitmapRect(bitmap, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
162     }
163 }
164 
drawImageLattice(const SkImage * image,const SkCanvas::Lattice & lattice,const SkRect & dst,const SkPaint & paint)165 void SkBaseDevice::drawImageLattice(const SkImage* image,
166                                     const SkCanvas::Lattice& lattice, const SkRect& dst,
167                                     const SkPaint& paint) {
168     SkLatticeIter iter(lattice, dst);
169 
170     SkRect srcR, dstR;
171     SkColor c;
172     bool isFixedColor = false;
173     const SkImageInfo info = SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType);
174 
175     while (iter.next(&srcR, &dstR, &isFixedColor, &c)) {
176           if (isFixedColor || (srcR.width() <= 1.0f && srcR.height() <= 1.0f &&
177                                image->readPixels(info, &c, 4, srcR.fLeft, srcR.fTop))) {
178               // Fast draw with drawRect, if this is a patch containing a single color
179               // or if this is a patch containing a single pixel.
180               if (0 != c || !paint.isSrcOver()) {
181                    SkPaint paintCopy(paint);
182                    int alpha = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
183                    paintCopy.setColor(SkColorSetA(c, alpha));
184                    this->drawRect(dstR, paintCopy);
185               }
186         } else {
187             this->drawImageRect(image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
188         }
189     }
190 }
191 
drawBitmapLattice(const SkBitmap & bitmap,const SkCanvas::Lattice & lattice,const SkRect & dst,const SkPaint & paint)192 void SkBaseDevice::drawBitmapLattice(const SkBitmap& bitmap,
193                                      const SkCanvas::Lattice& lattice, const SkRect& dst,
194                                      const SkPaint& paint) {
195     SkLatticeIter iter(lattice, dst);
196 
197     SkRect srcR, dstR;
198     while (iter.next(&srcR, &dstR)) {
199         this->drawBitmapRect(bitmap, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
200     }
201 }
202 
quad_to_tris(SkPoint tris[6],const SkPoint quad[4])203 static SkPoint* quad_to_tris(SkPoint tris[6], const SkPoint quad[4]) {
204     tris[0] = quad[0];
205     tris[1] = quad[1];
206     tris[2] = quad[2];
207 
208     tris[3] = quad[0];
209     tris[4] = quad[2];
210     tris[5] = quad[3];
211 
212     return tris + 6;
213 }
214 
drawAtlas(const SkImage * atlas,const SkRSXform xform[],const SkRect tex[],const SkColor colors[],int quadCount,SkBlendMode mode,const SkPaint & paint)215 void SkBaseDevice::drawAtlas(const SkImage* atlas, const SkRSXform xform[],
216                              const SkRect tex[], const SkColor colors[], int quadCount,
217                              SkBlendMode mode, const SkPaint& paint) {
218     const int triCount = quadCount << 1;
219     const int vertexCount = triCount * 3;
220     uint32_t flags = SkVertices::kHasTexCoords_BuilderFlag;
221     if (colors) {
222         flags |= SkVertices::kHasColors_BuilderFlag;
223     }
224     SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, vertexCount, 0, flags);
225 
226     SkPoint* vPos = builder.positions();
227     SkPoint* vTex = builder.texCoords();
228     SkColor* vCol = builder.colors();
229     for (int i = 0; i < quadCount; ++i) {
230         SkPoint tmp[4];
231         xform[i].toQuad(tex[i].width(), tex[i].height(), tmp);
232         vPos = quad_to_tris(vPos, tmp);
233 
234         tex[i].toQuad(tmp);
235         vTex = quad_to_tris(vTex, tmp);
236 
237         if (colors) {
238             sk_memset32(vCol, colors[i], 6);
239             vCol += 6;
240         }
241     }
242     SkPaint p(paint);
243     p.setShader(atlas->makeShader());
244     this->drawVertices(builder.detach().get(), nullptr, 0, mode, p);
245 }
246 
247 
drawEdgeAAQuad(const SkRect & r,const SkPoint clip[4],SkCanvas::QuadAAFlags aa,const SkColor4f & color,SkBlendMode mode)248 void SkBaseDevice::drawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], SkCanvas::QuadAAFlags aa,
249                                   const SkColor4f& color, SkBlendMode mode) {
250     SkPaint paint;
251     paint.setColor4f(color);
252     paint.setBlendMode(mode);
253     paint.setAntiAlias(aa == SkCanvas::kAll_QuadAAFlags);
254 
255     if (clip) {
256         // Draw the clip directly as a quad since it's a filled color with no local coords
257         SkPath clipPath;
258         clipPath.addPoly(clip, 4, true);
259         this->drawPath(clipPath, paint);
260     } else {
261         this->drawRect(r, paint);
262     }
263 }
264 
drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[],int count,const SkPoint dstClips[],const SkMatrix preViewMatrices[],const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)265 void SkBaseDevice::drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[], int count,
266                                       const SkPoint dstClips[], const SkMatrix preViewMatrices[],
267                                       const SkPaint& paint,
268                                       SkCanvas::SrcRectConstraint constraint) {
269     SkASSERT(paint.getStyle() == SkPaint::kFill_Style);
270     SkASSERT(!paint.getPathEffect());
271 
272     SkPaint entryPaint = paint;
273     const SkMatrix baseCTM = this->ctm();
274     int clipIndex = 0;
275     for (int i = 0; i < count; ++i) {
276         // TODO: Handle per-edge AA. Right now this mirrors the SkiaRenderer component of Chrome
277         // which turns off antialiasing unless all four edges should be antialiased. This avoids
278         // seaming in tiled composited layers.
279         entryPaint.setAntiAlias(images[i].fAAFlags == SkCanvas::kAll_QuadAAFlags);
280         entryPaint.setAlphaf(paint.getAlphaf() * images[i].fAlpha);
281 
282         bool needsRestore = false;
283         SkASSERT(images[i].fMatrixIndex < 0 || preViewMatrices);
284         if (images[i].fMatrixIndex >= 0) {
285             this->save();
286             this->setGlobalCTM(SkMatrix::Concat(
287                     baseCTM, preViewMatrices[images[i].fMatrixIndex]));
288             needsRestore = true;
289         }
290 
291         SkASSERT(!images[i].fHasClip || dstClips);
292         if (images[i].fHasClip) {
293             // Since drawImageRect requires a srcRect, the dst clip is implemented as a true clip
294             if (!needsRestore) {
295                 this->save();
296                 needsRestore = true;
297             }
298             SkPath clipPath;
299             clipPath.addPoly(dstClips + clipIndex, 4, true);
300             this->clipPath(clipPath, SkClipOp::kIntersect, entryPaint.isAntiAlias());
301             clipIndex += 4;
302         }
303         this->drawImageRect(images[i].fImage.get(), &images[i].fSrcRect, images[i].fDstRect,
304                             entryPaint, constraint);
305         if (needsRestore) {
306             this->restore(baseCTM);
307         }
308     }
309 }
310 
311 ///////////////////////////////////////////////////////////////////////////////////////////////////
312 
drawDrawable(SkDrawable * drawable,const SkMatrix * matrix,SkCanvas * canvas)313 void SkBaseDevice::drawDrawable(SkDrawable* drawable, const SkMatrix* matrix, SkCanvas* canvas) {
314     drawable->draw(canvas, matrix);
315 }
316 
317 ///////////////////////////////////////////////////////////////////////////////////////////////////
318 
drawSpecial(SkSpecialImage *,int x,int y,const SkPaint &,SkImage *,const SkMatrix &)319 void SkBaseDevice::drawSpecial(SkSpecialImage*, int x, int y, const SkPaint&,
320                                SkImage*, const SkMatrix&) {}
makeSpecial(const SkBitmap &)321 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkBitmap&) { return nullptr; }
makeSpecial(const SkImage *)322 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkImage*) { return nullptr; }
snapSpecial(const SkIRect &,bool)323 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial(const SkIRect&, bool) { return nullptr; }
snapSpecial()324 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial() {
325     return this->snapSpecial(SkIRect::MakeWH(this->width(), this->height()));
326 }
327 
328 ///////////////////////////////////////////////////////////////////////////////////////////////////
329 
readPixels(const SkPixmap & pm,int x,int y)330 bool SkBaseDevice::readPixels(const SkPixmap& pm, int x, int y) {
331     return this->onReadPixels(pm, x, y);
332 }
333 
writePixels(const SkPixmap & pm,int x,int y)334 bool SkBaseDevice::writePixels(const SkPixmap& pm, int x, int y) {
335     return this->onWritePixels(pm, x, y);
336 }
337 
onWritePixels(const SkPixmap &,int,int)338 bool SkBaseDevice::onWritePixels(const SkPixmap&, int, int) {
339     return false;
340 }
341 
onReadPixels(const SkPixmap &,int x,int y)342 bool SkBaseDevice::onReadPixels(const SkPixmap&, int x, int y) {
343     return false;
344 }
345 
accessPixels(SkPixmap * pmap)346 bool SkBaseDevice::accessPixels(SkPixmap* pmap) {
347     SkPixmap tempStorage;
348     if (nullptr == pmap) {
349         pmap = &tempStorage;
350     }
351     return this->onAccessPixels(pmap);
352 }
353 
peekPixels(SkPixmap * pmap)354 bool SkBaseDevice::peekPixels(SkPixmap* pmap) {
355     SkPixmap tempStorage;
356     if (nullptr == pmap) {
357         pmap = &tempStorage;
358     }
359     return this->onPeekPixels(pmap);
360 }
361 
362 //////////////////////////////////////////////////////////////////////////////////////////
363 
364 #include "src/core/SkUtils.h"
365 
drawGlyphRunRSXform(const SkFont & font,const SkGlyphID glyphs[],const SkRSXform xform[],int count,SkPoint origin,const SkPaint & paint)366 void SkBaseDevice::drawGlyphRunRSXform(const SkFont& font, const SkGlyphID glyphs[],
367                                        const SkRSXform xform[], int count, SkPoint origin,
368                                        const SkPaint& paint) {
369     const SkMatrix originalCTM = this->ctm();
370     if (!originalCTM.isFinite() || !SkScalarIsFinite(font.getSize()) ||
371         !SkScalarIsFinite(font.getScaleX()) ||
372         !SkScalarIsFinite(font.getSkewX())) {
373         return;
374     }
375 
376     SkPoint sharedPos{0, 0};    // we're at the origin
377     SkGlyphID glyphID;
378     SkGlyphRun glyphRun{
379         font,
380         SkSpan<const SkPoint>{&sharedPos, 1},
381         SkSpan<const SkGlyphID>{&glyphID, 1},
382         SkSpan<const char>{},
383         SkSpan<const uint32_t>{}
384     };
385 
386     for (int i = 0; i < count; i++) {
387         glyphID = glyphs[i];
388         // now "glyphRun" is pointing at the current glyphID
389 
390         SkMatrix ctm;
391         ctm.setRSXform(xform[i]).postTranslate(origin.fX, origin.fY);
392 
393         // We want to rotate each glyph by the rsxform, but we don't want to rotate "space"
394         // (i.e. the shader that cares about the ctm) so we have to undo our little ctm trick
395         // with a localmatrixshader so that the shader draws as if there was no change to the ctm.
396         SkPaint transformingPaint{paint};
397         auto shader = transformingPaint.getShader();
398         if (shader) {
399             SkMatrix inverse;
400             if (ctm.invert(&inverse)) {
401                 transformingPaint.setShader(shader->makeWithLocalMatrix(inverse));
402             } else {
403                 transformingPaint.setShader(nullptr);  // can't handle this xform
404             }
405         }
406 
407         ctm.setConcat(originalCTM, ctm);
408         this->setCTM(ctm);
409 
410         this->drawGlyphRunList(SkGlyphRunList{glyphRun, transformingPaint});
411     }
412     this->setCTM(originalCTM);
413 }
414 
415 //////////////////////////////////////////////////////////////////////////////////////////
416 
makeSurface(SkImageInfo const &,SkSurfaceProps const &)417 sk_sp<SkSurface> SkBaseDevice::makeSurface(SkImageInfo const&, SkSurfaceProps const&) {
418     return nullptr;
419 }
420 
421 //////////////////////////////////////////////////////////////////////////////////////////
422 
LogDrawScaleFactor(const SkMatrix & view,const SkMatrix & srcToDst,SkFilterQuality filterQuality)423 void SkBaseDevice::LogDrawScaleFactor(const SkMatrix& view, const SkMatrix& srcToDst,
424                                       SkFilterQuality filterQuality) {
425 #if SK_HISTOGRAMS_ENABLED
426     SkMatrix matrix = SkMatrix::Concat(view, srcToDst);
427     enum ScaleFactor {
428         kUpscale_ScaleFactor,
429         kNoScale_ScaleFactor,
430         kDownscale_ScaleFactor,
431         kLargeDownscale_ScaleFactor,
432 
433         kLast_ScaleFactor = kLargeDownscale_ScaleFactor
434     };
435 
436     float rawScaleFactor = matrix.getMinScale();
437 
438     ScaleFactor scaleFactor;
439     if (rawScaleFactor < 0.5f) {
440         scaleFactor = kLargeDownscale_ScaleFactor;
441     } else if (rawScaleFactor < 1.0f) {
442         scaleFactor = kDownscale_ScaleFactor;
443     } else if (rawScaleFactor > 1.0f) {
444         scaleFactor = kUpscale_ScaleFactor;
445     } else {
446         scaleFactor = kNoScale_ScaleFactor;
447     }
448 
449     switch (filterQuality) {
450         case kNone_SkFilterQuality:
451             SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.NoneFilterQuality", scaleFactor,
452                                      kLast_ScaleFactor + 1);
453             break;
454         case kLow_SkFilterQuality:
455             SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.LowFilterQuality", scaleFactor,
456                                      kLast_ScaleFactor + 1);
457             break;
458         case kMedium_SkFilterQuality:
459             SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.MediumFilterQuality", scaleFactor,
460                                      kLast_ScaleFactor + 1);
461             break;
462         case kHigh_SkFilterQuality:
463             SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.HighFilterQuality", scaleFactor,
464                                      kLast_ScaleFactor + 1);
465             break;
466     }
467 
468     // Also log filter quality independent scale factor.
469     SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.AnyFilterQuality", scaleFactor,
470                              kLast_ScaleFactor + 1);
471 
472     // Also log an overall histogram of filter quality.
473     SK_HISTOGRAM_ENUMERATION("FilterQuality", filterQuality, kLast_SkFilterQuality + 1);
474 #endif
475 }
476