1 /* 2 * Copyright 2016 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 #ifndef SkAutoPixmapStorage_DEFINED 9 #define SkAutoPixmapStorage_DEFINED 10 11 #include "SkMalloc.h" 12 #include "SkPixmap.h" 13 14 class SK_API SkAutoPixmapStorage : public SkPixmap { 15 public: 16 SkAutoPixmapStorage(); 17 ~SkAutoPixmapStorage(); 18 19 /** 20 * Try to allocate memory for the pixels needed to match the specified Info. On success 21 * return true and fill out the pixmap to point to that memory. The storage will be freed 22 * when this object is destroyed, or if another call to tryAlloc() or alloc() is made. 23 * 24 * On failure, return false and reset() the pixmap to empty. 25 */ 26 bool tryAlloc(const SkImageInfo&); 27 28 /** 29 * Allocate memory for the pixels needed to match the specified Info and fill out the pixmap 30 * to point to that memory. The storage will be freed when this object is destroyed, 31 * or if another call to tryAlloc() or alloc() is made. 32 * 33 * If the memory cannot be allocated, calls sk_throw(). 34 */ 35 void alloc(const SkImageInfo&); 36 37 /** 38 * Gets the size and optionally the rowBytes that would be allocated by SkAutoPixmapStorage if 39 * alloc/tryAlloc was called. 40 */ 41 static size_t AllocSize(const SkImageInfo& info, size_t* rowBytes); 42 43 /** 44 * Returns an SkData object wrapping the allocated pixels memory, and resets the pixmap. 45 * If the storage hasn't been allocated, the result is NULL. 46 */ 47 const SkData* SK_WARN_UNUSED_RESULT detachPixelsAsData(); 48 49 // We wrap these so we can clear our internal storage 50 reset()51 void reset() { 52 this->freeStorage(); 53 this->INHERITED::reset(); 54 } 55 void reset(const SkImageInfo& info, const void* addr, size_t rb, SkColorTable* ctable = NULL) { 56 this->freeStorage(); 57 this->INHERITED::reset(info, addr, rb, ctable); 58 } reset(const SkImageInfo & info)59 void reset(const SkImageInfo& info) { 60 this->freeStorage(); 61 this->INHERITED::reset(info); 62 } reset(const SkMask & mask)63 bool SK_WARN_UNUSED_RESULT reset(const SkMask& mask) { 64 this->freeStorage(); 65 return this->INHERITED::reset(mask); 66 } 67 68 private: 69 void* fStorage; 70 freeStorage()71 void freeStorage() { 72 sk_free(fStorage); 73 fStorage = nullptr; 74 } 75 76 typedef SkPixmap INHERITED; 77 }; 78 79 #endif 80