SkBitmapDevice.cpp revision fa24d344882b8009a1fe25cf110c0e75e552a6ff
1/*
2 * Copyright 2013 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 "SkBitmapDevice.h"
9#include "SkDraw.h"
10#include "SkImageFilter.h"
11#include "SkImageFilterCache.h"
12#include "SkMallocPixelRef.h"
13#include "SkMatrix.h"
14#include "SkPaint.h"
15#include "SkPath.h"
16#include "SkPixelRef.h"
17#include "SkPixmap.h"
18#include "SkRasterClip.h"
19#include "SkRasterHandleAllocator.h"
20#include "SkShader.h"
21#include "SkSpecialImage.h"
22#include "SkSurface.h"
23
24class SkColorTable;
25
26static bool valid_for_bitmap_device(const SkImageInfo& info,
27                                    SkAlphaType* newAlphaType) {
28    if (info.width() < 0 || info.height() < 0) {
29        return false;
30    }
31
32    // TODO: can we stop supporting kUnknown in SkBitmkapDevice?
33    if (kUnknown_SkColorType == info.colorType()) {
34        if (newAlphaType) {
35            *newAlphaType = kUnknown_SkAlphaType;
36        }
37        return true;
38    }
39
40    switch (info.alphaType()) {
41        case kPremul_SkAlphaType:
42        case kOpaque_SkAlphaType:
43            break;
44        default:
45            return false;
46    }
47
48    SkAlphaType canonicalAlphaType = info.alphaType();
49
50    switch (info.colorType()) {
51        case kAlpha_8_SkColorType:
52            break;
53        case kRGB_565_SkColorType:
54            canonicalAlphaType = kOpaque_SkAlphaType;
55            break;
56        case kN32_SkColorType:
57            break;
58        case kRGBA_F16_SkColorType:
59            break;
60        default:
61            return false;
62    }
63
64    if (newAlphaType) {
65        *newAlphaType = canonicalAlphaType;
66    }
67    return true;
68}
69
70SkBitmapDevice::SkBitmapDevice(const SkBitmap& bitmap)
71    : INHERITED(bitmap.info(), SkSurfaceProps(SkSurfaceProps::kLegacyFontHost_InitType))
72    , fBitmap(bitmap)
73    , fRCStack(bitmap.width(), bitmap.height())
74{
75    SkASSERT(valid_for_bitmap_device(bitmap.info(), nullptr));
76    fBitmap.lockPixels();
77}
78
79SkBitmapDevice* SkBitmapDevice::Create(const SkImageInfo& info) {
80    return Create(info, SkSurfaceProps(SkSurfaceProps::kLegacyFontHost_InitType));
81}
82
83SkBitmapDevice::SkBitmapDevice(const SkBitmap& bitmap, const SkSurfaceProps& surfaceProps,
84                               SkRasterHandleAllocator::Handle hndl)
85    : INHERITED(bitmap.info(), surfaceProps)
86    , fBitmap(bitmap)
87    , fRasterHandle(hndl)
88    , fRCStack(bitmap.width(), bitmap.height())
89{
90    SkASSERT(valid_for_bitmap_device(bitmap.info(), nullptr));
91    fBitmap.lockPixels();
92}
93
94SkBitmapDevice* SkBitmapDevice::Create(const SkImageInfo& origInfo,
95                                       const SkSurfaceProps& surfaceProps,
96                                       SkRasterHandleAllocator* allocator) {
97    SkAlphaType newAT = origInfo.alphaType();
98    if (!valid_for_bitmap_device(origInfo, &newAT)) {
99        return nullptr;
100    }
101
102    SkRasterHandleAllocator::Handle hndl = nullptr;
103    const SkImageInfo info = origInfo.makeAlphaType(newAT);
104    SkBitmap bitmap;
105
106    if (kUnknown_SkColorType == info.colorType()) {
107        if (!bitmap.setInfo(info)) {
108            return nullptr;
109        }
110    } else if (allocator) {
111        hndl = allocator->allocBitmap(info, &bitmap);
112        if (!hndl) {
113            return nullptr;
114        }
115    } else if (info.isOpaque()) {
116        // If this bitmap is opaque, we don't have any sensible default color,
117        // so we just return uninitialized pixels.
118        if (!bitmap.tryAllocPixels(info)) {
119            return nullptr;
120        }
121    } else {
122        // This bitmap has transparency, so we'll zero the pixels (to transparent).
123        // We use a ZeroedPRFactory as a faster alloc-then-eraseColor(SK_ColorTRANSPARENT).
124        SkMallocPixelRef::ZeroedPRFactory factory;
125        if (!bitmap.tryAllocPixels(info, &factory, nullptr/*color table*/)) {
126            return nullptr;
127        }
128    }
129
130    return new SkBitmapDevice(bitmap, surfaceProps, hndl);
131}
132
133void SkBitmapDevice::setNewSize(const SkISize& size) {
134    SkASSERT(!fBitmap.pixelRef());
135    fBitmap.setInfo(fBitmap.info().makeWH(size.fWidth, size.fHeight));
136    this->privateResize(fBitmap.info().width(), fBitmap.info().height());
137
138    fRCStack.setNewSize(size.fWidth, size.fHeight);
139}
140
141void SkBitmapDevice::replaceBitmapBackendForRasterSurface(const SkBitmap& bm) {
142    SkASSERT(bm.width() == fBitmap.width());
143    SkASSERT(bm.height() == fBitmap.height());
144    fBitmap = bm;   // intent is to use bm's pixelRef (and rowbytes/config)
145    fBitmap.lockPixels();
146    this->privateResize(fBitmap.info().width(), fBitmap.info().height());
147}
148
149SkBaseDevice* SkBitmapDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint*) {
150    const SkSurfaceProps surfaceProps(this->surfaceProps().flags(), cinfo.fPixelGeometry);
151    return SkBitmapDevice::Create(cinfo.fInfo, surfaceProps, cinfo.fAllocator);
152}
153
154bool SkBitmapDevice::onAccessPixels(SkPixmap* pmap) {
155    if (this->onPeekPixels(pmap)) {
156        fBitmap.notifyPixelsChanged();
157        return true;
158    }
159    return false;
160}
161
162bool SkBitmapDevice::onPeekPixels(SkPixmap* pmap) {
163    const SkImageInfo info = fBitmap.info();
164    if (fBitmap.getPixels() && (kUnknown_SkColorType != info.colorType())) {
165        SkColorTable* ctable = nullptr;
166        pmap->reset(fBitmap.info(), fBitmap.getPixels(), fBitmap.rowBytes(), ctable);
167        return true;
168    }
169    return false;
170}
171
172bool SkBitmapDevice::onWritePixels(const SkImageInfo& srcInfo, const void* srcPixels,
173                                   size_t srcRowBytes, int x, int y) {
174    // since we don't stop creating un-pixeled devices yet, check for no pixels here
175    if (nullptr == fBitmap.getPixels()) {
176        return false;
177    }
178
179    if (fBitmap.writePixels(SkPixmap(srcInfo, srcPixels, srcRowBytes), x, y)) {
180        fBitmap.notifyPixelsChanged();
181        return true;
182    }
183    return false;
184}
185
186bool SkBitmapDevice::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
187                                  int x, int y) {
188    return fBitmap.readPixels(dstInfo, dstPixels, dstRowBytes, x, y);
189}
190
191///////////////////////////////////////////////////////////////////////////////
192
193#ifdef SK_USE_DEVICE_CLIPPING
194class ModifiedDraw : public SkDraw {
195public:
196    ModifiedDraw(const SkMatrix& cmt, const SkRasterClip& rc, const SkDraw& draw) : SkDraw(draw) {
197        SkASSERT(cmt == *draw.fMatrix);
198        fRC = &rc;
199    }
200};
201#define PREPARE_DRAW(draw)  ModifiedDraw(this->ctm(), fRCStack.rc(), draw)
202#else
203#define PREPARE_DRAW(draw)  draw
204#endif
205
206void SkBitmapDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
207    PREPARE_DRAW(draw).drawPaint(paint);
208}
209
210void SkBitmapDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode, size_t count,
211                                const SkPoint pts[], const SkPaint& paint) {
212    PREPARE_DRAW(draw).drawPoints(mode, count, pts, paint, nullptr);
213}
214
215void SkBitmapDevice::drawRect(const SkDraw& draw, const SkRect& r, const SkPaint& paint) {
216    PREPARE_DRAW(draw).drawRect(r, paint);
217}
218
219void SkBitmapDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
220    SkPath path;
221    path.addOval(oval);
222    // call the VIRTUAL version, so any subclasses who do handle drawPath aren't
223    // required to override drawOval.
224    this->drawPath(draw, path, paint, nullptr, true);
225}
226
227void SkBitmapDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
228#ifdef SK_IGNORE_BLURRED_RRECT_OPT
229    SkPath  path;
230
231    path.addRRect(rrect);
232    // call the VIRTUAL version, so any subclasses who do handle drawPath aren't
233    // required to override drawRRect.
234    this->drawPath(draw, path, paint, nullptr, true);
235#else
236    PREPARE_DRAW(draw).drawRRect(rrect, paint);
237#endif
238}
239
240void SkBitmapDevice::drawPath(const SkDraw& draw, const SkPath& path,
241                              const SkPaint& paint, const SkMatrix* prePathMatrix,
242                              bool pathIsMutable) {
243    PREPARE_DRAW(draw).drawPath(path, paint, prePathMatrix, pathIsMutable);
244}
245
246void SkBitmapDevice::drawBitmap(const SkDraw& draw, const SkBitmap& bitmap,
247                                const SkMatrix& matrix, const SkPaint& paint) {
248    LogDrawScaleFactor(SkMatrix::Concat(*draw.fMatrix, matrix), paint.getFilterQuality());
249    PREPARE_DRAW(draw).drawBitmap(bitmap, matrix, nullptr, paint);
250}
251
252static inline bool CanApplyDstMatrixAsCTM(const SkMatrix& m, const SkPaint& paint) {
253    if (!paint.getMaskFilter()) {
254        return true;
255    }
256
257    // Some mask filters parameters (sigma) depend on the CTM/scale.
258    return m.getType() <= SkMatrix::kTranslate_Mask;
259}
260
261void SkBitmapDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
262                                    const SkRect* src, const SkRect& dst,
263                                    const SkPaint& paint, SkCanvas::SrcRectConstraint constraint) {
264    SkMatrix    matrix;
265    SkRect      bitmapBounds, tmpSrc, tmpDst;
266    SkBitmap    tmpBitmap;
267
268    bitmapBounds.isetWH(bitmap.width(), bitmap.height());
269
270    // Compute matrix from the two rectangles
271    if (src) {
272        tmpSrc = *src;
273    } else {
274        tmpSrc = bitmapBounds;
275    }
276    matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
277
278    LogDrawScaleFactor(SkMatrix::Concat(*draw.fMatrix, matrix), paint.getFilterQuality());
279
280    const SkRect* dstPtr = &dst;
281    const SkBitmap* bitmapPtr = &bitmap;
282
283    // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
284    // needed (if the src was clipped). No check needed if src==null.
285    if (src) {
286        if (!bitmapBounds.contains(*src)) {
287            if (!tmpSrc.intersect(bitmapBounds)) {
288                return; // nothing to draw
289            }
290            // recompute dst, based on the smaller tmpSrc
291            matrix.mapRect(&tmpDst, tmpSrc);
292            dstPtr = &tmpDst;
293        }
294    }
295
296    if (src && !src->contains(bitmapBounds) &&
297        SkCanvas::kFast_SrcRectConstraint == constraint &&
298        paint.getFilterQuality() != kNone_SkFilterQuality) {
299        // src is smaller than the bounds of the bitmap, and we are filtering, so we don't know
300        // how much more of the bitmap we need, so we can't use extractSubset or drawBitmap,
301        // but we must use a shader w/ dst bounds (which can access all of the bitmap needed).
302        goto USE_SHADER;
303    }
304
305    if (src) {
306        // since we may need to clamp to the borders of the src rect within
307        // the bitmap, we extract a subset.
308        const SkIRect srcIR = tmpSrc.roundOut();
309        if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
310            return;
311        }
312        bitmapPtr = &tmpBitmap;
313
314        // Since we did an extract, we need to adjust the matrix accordingly
315        SkScalar dx = 0, dy = 0;
316        if (srcIR.fLeft > 0) {
317            dx = SkIntToScalar(srcIR.fLeft);
318        }
319        if (srcIR.fTop > 0) {
320            dy = SkIntToScalar(srcIR.fTop);
321        }
322        if (dx || dy) {
323            matrix.preTranslate(dx, dy);
324        }
325
326        SkRect extractedBitmapBounds;
327        extractedBitmapBounds.isetWH(bitmapPtr->width(), bitmapPtr->height());
328        if (extractedBitmapBounds == tmpSrc) {
329            // no fractional part in src, we can just call drawBitmap
330            goto USE_DRAWBITMAP;
331        }
332    } else {
333        USE_DRAWBITMAP:
334        // We can go faster by just calling drawBitmap, which will concat the
335        // matrix with the CTM, and try to call drawSprite if it can. If not,
336        // it will make a shader and call drawRect, as we do below.
337        if (CanApplyDstMatrixAsCTM(matrix, paint)) {
338            PREPARE_DRAW(draw).drawBitmap(*bitmapPtr, matrix, dstPtr, paint);
339            return;
340        }
341    }
342
343    USE_SHADER:
344
345    // TODO(herb): Move this over to SkArenaAlloc when arena alloc has a facility to return sk_sps.
346    // Since the shader need only live for our stack-frame, pass in a custom allocator. This
347    // can save malloc calls, and signals to SkMakeBitmapShader to not try to copy the bitmap
348    // if its mutable, since that precaution is not needed (give the short lifetime of the shader).
349
350    // construct a shader, so we can call drawRect with the dst
351    auto s = SkMakeBitmapShader(*bitmapPtr, SkShader::kClamp_TileMode, SkShader::kClamp_TileMode,
352                                &matrix, kNever_SkCopyPixelsMode);
353    if (!s) {
354        return;
355    }
356
357    SkPaint paintWithShader(paint);
358    paintWithShader.setStyle(SkPaint::kFill_Style);
359    paintWithShader.setShader(s);
360
361    // Call ourself, in case the subclass wanted to share this setup code
362    // but handle the drawRect code themselves.
363    this->drawRect(draw, *dstPtr, paintWithShader);
364}
365
366void SkBitmapDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
367                                int x, int y, const SkPaint& paint) {
368    PREPARE_DRAW(draw).drawSprite(bitmap, x, y, paint);
369}
370
371void SkBitmapDevice::drawText(const SkDraw& draw, const void* text, size_t len,
372                              SkScalar x, SkScalar y, const SkPaint& paint) {
373    PREPARE_DRAW(draw).drawText((const char*)text, len, x, y, paint, &fSurfaceProps);
374}
375
376void SkBitmapDevice::drawPosText(const SkDraw& draw, const void* text, size_t len,
377                                 const SkScalar xpos[], int scalarsPerPos,
378                                 const SkPoint& offset, const SkPaint& paint) {
379    PREPARE_DRAW(draw).drawPosText((const char*)text, len, xpos, scalarsPerPos, offset,
380                                   paint, &fSurfaceProps);
381}
382
383void SkBitmapDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
384                                  int vertexCount,
385                                  const SkPoint verts[], const SkPoint textures[],
386                                  const SkColor colors[], SkBlendMode bmode,
387                                  const uint16_t indices[], int indexCount,
388                                  const SkPaint& paint) {
389    PREPARE_DRAW(draw).drawVertices(vmode, vertexCount, verts, textures, colors, bmode,
390                      indices, indexCount, paint);
391}
392
393void SkBitmapDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
394                                int x, int y, const SkPaint& paint) {
395    SkASSERT(!paint.getImageFilter());
396    PREPARE_DRAW(draw).drawSprite(static_cast<SkBitmapDevice*>(device)->fBitmap, x, y, paint);
397}
398
399///////////////////////////////////////////////////////////////////////////////
400
401void SkBitmapDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
402                                 const SkPaint& paint) {
403    SkASSERT(!srcImg->isTextureBacked());
404
405    SkBitmap resultBM;
406
407    SkImageFilter* filter = paint.getImageFilter();
408    if (filter) {
409        SkIPoint offset = SkIPoint::Make(0, 0);
410        SkMatrix matrix = *draw.fMatrix;
411        matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
412        const SkIRect clipBounds = draw.fRC->getBounds().makeOffset(-x, -y);
413        sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
414        SkImageFilter::OutputProperties outputProperties(fBitmap.colorSpace());
415        SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
416
417        sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
418        if (resultImg) {
419            SkPaint tmpUnfiltered(paint);
420            tmpUnfiltered.setImageFilter(nullptr);
421            if (resultImg->getROPixels(&resultBM)) {
422                this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
423            }
424        }
425    } else {
426        if (srcImg->getROPixels(&resultBM)) {
427            this->drawSprite(draw, resultBM, x, y, paint);
428        }
429    }
430}
431
432sk_sp<SkSpecialImage> SkBitmapDevice::makeSpecial(const SkBitmap& bitmap) {
433    return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
434}
435
436sk_sp<SkSpecialImage> SkBitmapDevice::makeSpecial(const SkImage* image) {
437    return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
438                                         image->makeNonTextureImage(), fBitmap.colorSpace());
439}
440
441sk_sp<SkSpecialImage> SkBitmapDevice::snapSpecial() {
442    return this->makeSpecial(fBitmap);
443}
444
445///////////////////////////////////////////////////////////////////////////////
446
447sk_sp<SkSurface> SkBitmapDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
448    return SkSurface::MakeRaster(info, &props);
449}
450
451SkImageFilterCache* SkBitmapDevice::getImageFilterCache() {
452    SkImageFilterCache* cache = SkImageFilterCache::Get();
453    cache->ref();
454    return cache;
455}
456
457///////////////////////////////////////////////////////////////////////////////////////////////////
458
459bool SkBitmapDevice::onShouldDisableLCD(const SkPaint& paint) const {
460    if (kN32_SkColorType != fBitmap.colorType() ||
461        paint.getRasterizer() ||
462        paint.getPathEffect() ||
463        paint.isFakeBoldText() ||
464        paint.getStyle() != SkPaint::kFill_Style ||
465        !paint.isSrcOver())
466    {
467        return true;
468    }
469    return false;
470}
471
472///////////////////////////////////////////////////////////////////////////////////////////////////
473
474void SkBitmapDevice::onSave() {
475    fRCStack.save();
476}
477
478void SkBitmapDevice::onRestore() {
479    fRCStack.restore();
480}
481
482void SkBitmapDevice::onClipRect(const SkRect& rect, SkClipOp op, bool aa) {
483    fRCStack.clipRect(this->ctm(), rect, op, aa);
484}
485
486void SkBitmapDevice::onClipRRect(const SkRRect& rrect, SkClipOp op, bool aa) {
487    fRCStack.clipRRect(this->ctm(), rrect, op, aa);
488}
489
490void SkBitmapDevice::onClipPath(const SkPath& path, SkClipOp op, bool aa) {
491    fRCStack.clipPath(this->ctm(), path, op, aa);
492}
493
494void SkBitmapDevice::onClipRegion(const SkRegion& rgn, SkClipOp op) {
495    SkIPoint origin = this->getOrigin();
496    SkRegion tmp;
497    const SkRegion* ptr = &rgn;
498    if (origin.fX | origin.fY) {
499        // translate from "global/canvas" coordinates to relative to this device
500        rgn.translate(-origin.fX, -origin.fY, &tmp);
501        ptr = &tmp;
502    }
503    fRCStack.clipRegion(*ptr, op);
504}
505
506void SkBitmapDevice::onSetDeviceClipRestriction(SkIRect* mutableClipRestriction) {
507    fRCStack.setDeviceClipRestriction(mutableClipRestriction);
508    if (!mutableClipRestriction->isEmpty()) {
509        SkRegion rgn(*mutableClipRestriction);
510        fRCStack.clipRegion(rgn, SkClipOp::kIntersect);
511    }
512}
513
514void SkBitmapDevice::validateDevBounds(const SkIRect& drawClipBounds) {
515#ifdef SK_DEBUG
516    const SkIRect& stackBounds = fRCStack.rc().getBounds();
517    SkASSERT(drawClipBounds == stackBounds);
518#endif
519}
520