SkCachingPixelRef.cpp revision 83787d0ff0a2b2f839a4a3ce6dadd033f83fe643
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 "SkCachingPixelRef.h"
9#include "SkBitmapCache.h"
10#include "SkRect.h"
11
12bool SkCachingPixelRef::Install(SkImageGenerator* generator,
13                                SkBitmap* dst) {
14    SkImageInfo info;
15    SkASSERT(dst != NULL);
16    if ((NULL == generator)
17        || !(generator->getInfo(&info))
18        || !dst->setInfo(info)) {
19        SkDELETE(generator);
20        return false;
21    }
22    SkAutoTUnref<SkCachingPixelRef> ref(SkNEW_ARGS(SkCachingPixelRef,
23                                           (info, generator, dst->rowBytes())));
24    dst->setPixelRef(ref);
25    return true;
26}
27
28SkCachingPixelRef::SkCachingPixelRef(const SkImageInfo& info,
29                                     SkImageGenerator* generator,
30                                     size_t rowBytes)
31    : INHERITED(info)
32    , fImageGenerator(generator)
33    , fErrorInDecoding(false)
34    , fRowBytes(rowBytes) {
35    SkASSERT(fImageGenerator != NULL);
36}
37SkCachingPixelRef::~SkCachingPixelRef() {
38    SkDELETE(fImageGenerator);
39    // Assert always unlock before unref.
40}
41
42bool SkCachingPixelRef::onNewLockPixels(LockRec* rec) {
43    if (fErrorInDecoding) {
44        return false;  // don't try again.
45    }
46
47    const SkImageInfo& info = this->info();
48    if (!SkBitmapCache::Find(
49                this->getGenerationID(), info.bounds(), &fLockedBitmap)) {
50        // Cache has been purged, must re-decode.
51        if (!fLockedBitmap.tryAllocPixels(info, fRowBytes)) {
52            fErrorInDecoding = true;
53            return false;
54        }
55        const SkImageGenerator::Result result = fImageGenerator->getPixels(info,
56                fLockedBitmap.getPixels(), fRowBytes);
57        switch (result) {
58            case SkImageGenerator::kIncompleteInput:
59            case SkImageGenerator::kSuccess:
60                break;
61            default:
62                fErrorInDecoding = true;
63                return false;
64        }
65        fLockedBitmap.setImmutable();
66        SkBitmapCache::Add(this, info.bounds(), fLockedBitmap);
67    }
68
69    // Now bitmap should contain a concrete PixelRef of the decoded image.
70    void* pixels = fLockedBitmap.getPixels();
71    SkASSERT(pixels != NULL);
72    rec->fPixels = pixels;
73    rec->fColorTable = NULL;
74    rec->fRowBytes = fLockedBitmap.rowBytes();
75    return true;
76}
77
78void SkCachingPixelRef::onUnlockPixels() {
79    fLockedBitmap.reset();
80}
81