Home | History | Annotate | Download | only in core
      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef SkBitmap_DEFINED
     18 #define SkBitmap_DEFINED
     19 
     20 #include "Sk64.h"
     21 #include "SkColor.h"
     22 #include "SkPoint.h"
     23 #include "SkRefCnt.h"
     24 
     25 struct SkIRect;
     26 class SkColorTable;
     27 class SkPaint;
     28 class SkPixelRef;
     29 class SkRegion;
     30 class SkFlattenableReadBuffer;
     31 class SkFlattenableWriteBuffer;
     32 
     33 // This is an opaque class, not interpreted by skia
     34 class SkGpuTexture;
     35 
     36 /** \class SkBitmap
     37 
     38     The SkBitmap class specifies a raster bitmap. A bitmap has an integer width
     39     and height, and a format (config), and a pointer to the actual pixels.
     40     Bitmaps can be drawn into a SkCanvas, but they are also used to specify the
     41     target of a SkCanvas' drawing operations.
     42     A const SkBitmap exposes getAddr(), which lets a caller write its pixels;
     43     the constness is considered to apply to the bitmap's configuration, not
     44     its contents.
     45 */
     46 class SK_API SkBitmap {
     47 public:
     48     class Allocator;
     49 
     50     enum Config {
     51         kNo_Config,         //!< bitmap has not been configured
     52         /**
     53          *  1-bit per pixel, (0 is transparent, 1 is opaque)
     54          *  Valid as a destination (target of a canvas), but not valid as a src.
     55          *  i.e. you can draw into a 1-bit bitmap, but you cannot draw from one.
     56          */
     57         kA1_Config,
     58         kA8_Config,         //!< 8-bits per pixel, with only alpha specified (0 is transparent, 0xFF is opaque)
     59         kIndex8_Config,     //!< 8-bits per pixel, using SkColorTable to specify the colors
     60         kRGB_565_Config,    //!< 16-bits per pixel, (see SkColorPriv.h for packing)
     61         kARGB_4444_Config,  //!< 16-bits per pixel, (see SkColorPriv.h for packing)
     62         kARGB_8888_Config,  //!< 32-bits per pixel, (see SkColorPriv.h for packing)
     63         /**
     64          *  Custom compressed format, not supported on all platforms.
     65          *  Cannot be used as a destination (target of a canvas).
     66          *  i.e. you may be able to draw from one, but you cannot draw into one.
     67          */
     68         kRLE_Index8_Config,
     69 
     70         kConfigCount
     71     };
     72 
     73     /** Default construct creates a bitmap with zero width and height, and no pixels.
     74         Its config is set to kNo_Config.
     75     */
     76     SkBitmap();
     77     /** Constructor initializes the new bitmap by copying the src bitmap. All fields are copied,
     78         but ownership of the pixels remains with the src bitmap.
     79     */
     80     SkBitmap(const SkBitmap& src);
     81     /** Decrements our (shared) pixel ownership if needed.
     82     */
     83     ~SkBitmap();
     84 
     85     /** Copies the src bitmap into this bitmap. Ownership of the src bitmap's pixels remains
     86         with the src bitmap.
     87     */
     88     SkBitmap& operator=(const SkBitmap& src);
     89     /** Swap the fields of the two bitmaps. This routine is guaranteed to never fail or throw.
     90     */
     91     //  This method is not exported to java.
     92     void swap(SkBitmap& other);
     93 
     94     /** Return true iff the bitmap has empty dimensions.
     95     */
     96     bool empty() const { return 0 == fWidth || 0 == fHeight; }
     97 
     98     /** Return true iff the bitmap has no pixels nor a pixelref. Note: this can
     99         return true even if the dimensions of the bitmap are > 0 (see empty()).
    100     */
    101     bool isNull() const { return NULL == fPixels && NULL == fPixelRef; }
    102 
    103     /** Return the config for the bitmap.
    104     */
    105     Config  config() const { return (Config)fConfig; }
    106     /** DEPRECATED, use config()
    107     */
    108     Config  getConfig() const { return this->config(); }
    109     /** Return the bitmap's width, in pixels.
    110     */
    111     int width() const { return fWidth; }
    112     /** Return the bitmap's height, in pixels.
    113     */
    114     int height() const { return fHeight; }
    115     /** Return the number of bytes between subsequent rows of the bitmap.
    116     */
    117     int rowBytes() const { return fRowBytes; }
    118 
    119     /** Return the shift amount per pixel (i.e. 0 for 1-byte per pixel, 1 for
    120         2-bytes per pixel configs, 2 for 4-bytes per pixel configs). Return 0
    121         for configs that are not at least 1-byte per pixel (e.g. kA1_Config
    122         or kNo_Config)
    123     */
    124     int shiftPerPixel() const { return fBytesPerPixel >> 1; }
    125 
    126     /** Return the number of bytes per pixel based on the config. If the config
    127         does not have at least 1 byte per (e.g. kA1_Config) then 0 is returned.
    128     */
    129     int bytesPerPixel() const { return fBytesPerPixel; }
    130 
    131     /** Return the rowbytes expressed as a number of pixels (like width and
    132         height). Note, for 1-byte per pixel configs like kA8_Config, this will
    133         return the same as rowBytes(). Is undefined for configs that are less
    134         than 1-byte per pixel (e.g. kA1_Config)
    135     */
    136     int rowBytesAsPixels() const { return fRowBytes >> (fBytesPerPixel >> 1); }
    137 
    138     /** Return the address of the pixels for this SkBitmap.
    139     */
    140     void* getPixels() const { return fPixels; }
    141 
    142     /** Return the byte size of the pixels, based on the height and rowBytes.
    143         Note this truncates the result to 32bits. Call getSize64() to detect
    144         if the real size exceeds 32bits.
    145     */
    146     size_t getSize() const { return fHeight * fRowBytes; }
    147 
    148     /** Return the number of bytes from the pointer returned by getPixels()
    149         to the end of the allocated space in the buffer. Required in
    150         cases where extractBitmap has been called.
    151     */
    152     size_t getSafeSize() const ;
    153 
    154     /** Return the byte size of the pixels, based on the height and rowBytes.
    155         This routine is slightly slower than getSize(), but does not truncate
    156         the answer to 32bits.
    157     */
    158     Sk64 getSize64() const {
    159         Sk64 size;
    160         size.setMul(fHeight, fRowBytes);
    161         return size;
    162     }
    163 
    164     /** Same as getSafeSize(), but does not truncate the answer to 32bits.
    165     */
    166     Sk64 getSafeSize64() const ;
    167 
    168     /** Returns true if the bitmap is opaque (has no translucent/transparent pixels).
    169     */
    170     bool isOpaque() const;
    171     /** Specify if this bitmap's pixels are all opaque or not. Is only meaningful for configs
    172         that support per-pixel alpha (RGB32, A1, A8).
    173     */
    174     void setIsOpaque(bool);
    175 
    176     /** Reset the bitmap to its initial state (see default constructor). If we are a (shared)
    177         owner of the pixels, that ownership is decremented.
    178     */
    179     void reset();
    180 
    181     /** Given a config and a width, this computes the optimal rowBytes value. This is called automatically
    182         if you pass 0 for rowBytes to setConfig().
    183     */
    184     static int ComputeRowBytes(Config c, int width);
    185 
    186     /** Return the bytes-per-pixel for the specified config. If the config is
    187         not at least 1-byte per pixel, return 0, including for kNo_Config.
    188     */
    189     static int ComputeBytesPerPixel(Config c);
    190 
    191     /** Return the shift-per-pixel for the specified config. If the config is
    192      not at least 1-byte per pixel, return 0, including for kNo_Config.
    193      */
    194     static int ComputeShiftPerPixel(Config c) {
    195         return ComputeBytesPerPixel(c) >> 1;
    196     }
    197 
    198     static Sk64 ComputeSize64(Config, int width, int height);
    199     static size_t ComputeSize(Config, int width, int height);
    200 
    201     /** Set the bitmap's config and dimensions. If rowBytes is 0, then
    202         ComputeRowBytes() is called to compute the optimal value. This resets
    203         any pixel/colortable ownership, just like reset().
    204     */
    205     void setConfig(Config, int width, int height, int rowBytes = 0);
    206     /** Use this to assign a new pixel address for an existing bitmap. This
    207         will automatically release any pixelref previously installed. Only call
    208         this if you are handling ownership/lifetime of the pixel memory.
    209 
    210         If the bitmap retains a reference to the colortable (assuming it is
    211         not null) it will take care of incrementing the reference count.
    212 
    213         @param pixels   Address for the pixels, managed by the caller.
    214         @param ctable   ColorTable (or null) that matches the specified pixels
    215     */
    216     void setPixels(void* p, SkColorTable* ctable = NULL);
    217 
    218     /** Copies the bitmap's pixels to the location pointed at by dst and returns
    219         true if possible, returns false otherwise.
    220 
    221         In the event that the bitmap's stride is equal to dstRowBytes, and if
    222         it is greater than strictly required by the bitmap's current config
    223         (this may happen if the bitmap is an extracted subset of another), then
    224         this function will copy bytes past the eand of each row, excluding the
    225         last row. No copies are made outside of the declared size of dst,
    226         however.
    227 
    228         Always returns false for RLE formats.
    229 
    230         @param dst      Location of destination buffer.
    231         @param dstSize  Size of destination buffer. Must be large enough to hold
    232                         pixels using indicated stride.
    233         @param dstRowBytes  Width of each line in the buffer. If -1, uses
    234                             bitmap's internal stride.
    235     */
    236     bool copyPixelsTo(void* const dst, size_t dstSize, int dstRowBytes = -1)
    237          const;
    238 
    239     /** Copies the pixels at location src to the bitmap's pixel buffer.
    240         Returns true if copy if possible (bitmap buffer is large enough),
    241         false otherwise.
    242 
    243         Like copyPixelsTo, this function may write values beyond the end of
    244         each row, although never outside the defined buffer.
    245 
    246         Always returns false for RLE formats.
    247 
    248         @param src      Location of the source buffer.
    249         @param srcSize  Height of source buffer in pixels.
    250         @param srcRowBytes  Width of each line in the buffer. If -1, uses i
    251                             bitmap's internal stride.
    252     */
    253     bool copyPixelsFrom(const void* const src, size_t srcSize,
    254                         int srcRowBytes = -1);
    255 
    256     /** Use the standard HeapAllocator to create the pixelref that manages the
    257         pixel memory. It will be sized based on the current width/height/config.
    258         If this is called multiple times, a new pixelref object will be created
    259         each time.
    260 
    261         If the bitmap retains a reference to the colortable (assuming it is
    262         not null) it will take care of incrementing the reference count.
    263 
    264         @param ctable   ColorTable (or null) to use with the pixels that will
    265                         be allocated. Only used if config == Index8_Config
    266         @return true if the allocation succeeds. If not the pixelref field of
    267                      the bitmap will be unchanged.
    268     */
    269     bool allocPixels(SkColorTable* ctable = NULL) {
    270         return this->allocPixels(NULL, ctable);
    271     }
    272 
    273     /** Use the specified Allocator to create the pixelref that manages the
    274         pixel memory. It will be sized based on the current width/height/config.
    275         If this is called multiple times, a new pixelref object will be created
    276         each time.
    277 
    278         If the bitmap retains a reference to the colortable (assuming it is
    279         not null) it will take care of incrementing the reference count.
    280 
    281         @param allocator The Allocator to use to create a pixelref that can
    282                          manage the pixel memory for the current
    283                          width/height/config. If allocator is NULL, the standard
    284                          HeapAllocator will be used.
    285         @param ctable   ColorTable (or null) to use with the pixels that will
    286                         be allocated. Only used if config == Index8_Config.
    287                         If it is non-null and the config is not Index8, it will
    288                         be ignored.
    289         @return true if the allocation succeeds. If not the pixelref field of
    290                      the bitmap will be unchanged.
    291     */
    292     bool allocPixels(Allocator* allocator, SkColorTable* ctable);
    293 
    294     /** Return the current pixelref object, if any
    295     */
    296     SkPixelRef* pixelRef() const { return fPixelRef; }
    297     /** Return the offset into the pixelref, if any. Will return 0 if there is
    298         no pixelref installed.
    299     */
    300     size_t pixelRefOffset() const { return fPixelRefOffset; }
    301     /** Assign a pixelref and optional offset. Pixelrefs are reference counted,
    302         so the existing one (if any) will be unref'd and the new one will be
    303         ref'd.
    304     */
    305     SkPixelRef* setPixelRef(SkPixelRef* pr, size_t offset = 0);
    306 
    307     /** Call this to ensure that the bitmap points to the current pixel address
    308         in the pixelref. Balance it with a call to unlockPixels(). These calls
    309         are harmless if there is no pixelref.
    310     */
    311     void lockPixels() const;
    312     /** When you are finished access the pixel memory, call this to balance a
    313         previous call to lockPixels(). This allows pixelrefs that implement
    314         cached/deferred image decoding to know when there are active clients of
    315         a given image.
    316     */
    317     void unlockPixels() const;
    318 
    319     /** Call this to be sure that the bitmap is valid enough to be drawn (i.e.
    320         it has non-null pixels, and if required by its config, it has a
    321         non-null colortable. Returns true if all of the above are met.
    322     */
    323     bool readyToDraw() const {
    324         return this->getPixels() != NULL &&
    325                ((this->config() != kIndex8_Config &&
    326                  this->config() != kRLE_Index8_Config) ||
    327                        fColorTable != NULL);
    328     }
    329 
    330     /** Returns the pixelRef's texture, or NULL
    331      */
    332     SkGpuTexture* getTexture() const;
    333 
    334     /** Return the bitmap's colortable (if any). Does not affect the colortable's
    335         reference count.
    336     */
    337     SkColorTable* getColorTable() const { return fColorTable; }
    338 
    339     /** Returns a non-zero, unique value corresponding to the pixels in our
    340         pixelref (or raw pixels set via setPixels). Each time the pixels are
    341         changed (and notifyPixelsChanged is called), a different generation ID
    342         will be returned.
    343     */
    344     uint32_t getGenerationID() const;
    345 
    346     /** Call this if you have changed the contents of the pixels. This will in-
    347         turn cause a different generation ID value to be returned from
    348         getGenerationID().
    349     */
    350     void notifyPixelsChanged() const;
    351 
    352     /** Initialize the bitmap's pixels with the specified color+alpha, automatically converting into the correct format
    353         for the bitmap's config. If the config is kRGB_565_Config, then the alpha value is ignored.
    354         If the config is kA8_Config, then the r,g,b parameters are ignored.
    355     */
    356     void eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const;
    357     /** Initialize the bitmap's pixels with the specified color+alpha, automatically converting into the correct format
    358         for the bitmap's config. If the config is kRGB_565_Config, then the alpha value is presumed
    359         to be 0xFF. If the config is kA8_Config, then the r,g,b parameters are ignored and the
    360         pixels are all set to 0xFF.
    361     */
    362     void eraseRGB(U8CPU r, U8CPU g, U8CPU b) const {
    363         this->eraseARGB(0xFF, r, g, b);
    364     }
    365     /** Initialize the bitmap's pixels with the specified color, automatically converting into the correct format
    366         for the bitmap's config. If the config is kRGB_565_Config, then the color's alpha value is presumed
    367         to be 0xFF. If the config is kA8_Config, then only the color's alpha value is used.
    368     */
    369     void eraseColor(SkColor c) const {
    370         this->eraseARGB(SkColorGetA(c), SkColorGetR(c), SkColorGetG(c),
    371                         SkColorGetB(c));
    372     }
    373 
    374     /** Scroll (a subset of) the contents of this bitmap by dx/dy. If there are
    375         no pixels allocated (i.e. getPixels() returns null) the method will
    376         still update the inval region (if present).
    377 
    378         @param subset The subset of the bitmap to scroll/move. To scroll the
    379                       entire contents, specify [0, 0, width, height] or just
    380                       pass null.
    381         @param dx The amount to scroll in X
    382         @param dy The amount to scroll in Y
    383         @param inval Optional (may be null). Returns the area of the bitmap that
    384                      was scrolled away. E.g. if dx = dy = 0, then inval would
    385                      be set to empty. If dx >= width or dy >= height, then
    386                      inval would be set to the entire bounds of the bitmap.
    387         @return true if the scroll was doable. Will return false if the bitmap
    388                      uses an unsupported config for scrolling (only kA8,
    389                      kIndex8, kRGB_565, kARGB_4444, kARGB_8888 are supported).
    390                      If no pixels are present (i.e. getPixels() returns false)
    391                      inval will still be updated, and true will be returned.
    392     */
    393     bool scrollRect(const SkIRect* subset, int dx, int dy,
    394                     SkRegion* inval = NULL) const;
    395 
    396     /**
    397      *  Return the SkColor of the specified pixel.  In most cases this will
    398      *  require un-premultiplying the color.  Alpha only configs (A1 and A8)
    399      *  return black with the appropriate alpha set.  The value is undefined
    400      *  for kNone_Config or if x or y are out of bounds, or if the bitmap
    401      *  does not have any pixels (or has not be locked with lockPixels()).
    402      */
    403     SkColor getColor(int x, int y) const;
    404 
    405     /** Returns the address of the specified pixel. This performs a runtime
    406         check to know the size of the pixels, and will return the same answer
    407         as the corresponding size-specific method (e.g. getAddr16). Since the
    408         check happens at runtime, it is much slower than using a size-specific
    409         version. Unlike the size-specific methods, this routine also checks if
    410         getPixels() returns null, and returns that. The size-specific routines
    411         perform a debugging assert that getPixels() is not null, but they do
    412         not do any runtime checks.
    413     */
    414     void* getAddr(int x, int y) const;
    415 
    416     /** Returns the address of the pixel specified by x,y for 32bit pixels.
    417      *  In debug build, this asserts that the pixels are allocated and locked,
    418      *  and that the config is 32-bit, however none of these checks are performed
    419      *  in the release build.
    420      */
    421     inline uint32_t* getAddr32(int x, int y) const;
    422 
    423     /** Returns the address of the pixel specified by x,y for 16bit pixels.
    424      *  In debug build, this asserts that the pixels are allocated and locked,
    425      *  and that the config is 16-bit, however none of these checks are performed
    426      *  in the release build.
    427      */
    428     inline uint16_t* getAddr16(int x, int y) const;
    429 
    430     /** Returns the address of the pixel specified by x,y for 8bit pixels.
    431      *  In debug build, this asserts that the pixels are allocated and locked,
    432      *  and that the config is 8-bit, however none of these checks are performed
    433      *  in the release build.
    434      */
    435     inline uint8_t* getAddr8(int x, int y) const;
    436 
    437     /** Returns the address of the byte containing the pixel specified by x,y
    438      *  for 1bit pixels.
    439      *  In debug build, this asserts that the pixels are allocated and locked,
    440      *  and that the config is 1-bit, however none of these checks are performed
    441      *  in the release build.
    442      */
    443     inline uint8_t* getAddr1(int x, int y) const;
    444 
    445     /** Returns the color corresponding to the pixel specified by x,y for
    446      *  colortable based bitmaps.
    447      *  In debug build, this asserts that the pixels are allocated and locked,
    448      *  that the config is kIndex8, and that the colortable is allocated,
    449      *  however none of these checks are performed in the release build.
    450      */
    451     inline SkPMColor getIndex8Color(int x, int y) const;
    452 
    453     /** Set dst to be a setset of this bitmap. If possible, it will share the
    454         pixel memory, and just point into a subset of it. However, if the config
    455         does not support this, a local copy will be made and associated with
    456         the dst bitmap. If the subset rectangle, intersected with the bitmap's
    457         dimensions is empty, or if there is an unsupported config, false will be
    458         returned and dst will be untouched.
    459         @param dst  The bitmap that will be set to a subset of this bitmap
    460         @param subset The rectangle of pixels in this bitmap that dst will
    461                       reference.
    462         @return true if the subset copy was successfully made.
    463     */
    464     bool extractSubset(SkBitmap* dst, const SkIRect& subset) const;
    465 
    466     /** Makes a deep copy of this bitmap, respecting the requested config.
    467         Returns false if either there is an error (i.e. the src does not have
    468         pixels) or the request cannot be satisfied (e.g. the src has per-pixel
    469         alpha, and the requested config does not support alpha).
    470         @param dst The bitmap to be sized and allocated
    471         @param c The desired config for dst
    472         @param allocator Allocator used to allocate the pixelref for the dst
    473                          bitmap. If this is null, the standard HeapAllocator
    474                          will be used.
    475         @return true if the copy could be made.
    476     */
    477     bool copyTo(SkBitmap* dst, Config c, Allocator* allocator = NULL) const;
    478 
    479     /** Returns true if this bitmap can be deep copied into the requested config
    480         by calling copyTo().
    481      */
    482     bool canCopyTo(Config newConfig) const;
    483 
    484     bool hasMipMap() const;
    485     void buildMipMap(bool forceRebuild = false);
    486     void freeMipMap();
    487 
    488     /** Given scale factors sx, sy, determine the miplevel available in the
    489         bitmap, and return it (this is the amount to shift matrix iterators
    490         by). If dst is not null, it is set to the correct level.
    491     */
    492     int extractMipLevel(SkBitmap* dst, SkFixed sx, SkFixed sy);
    493 
    494     bool extractAlpha(SkBitmap* dst) const {
    495         return this->extractAlpha(dst, NULL, NULL, NULL);
    496     }
    497 
    498     bool extractAlpha(SkBitmap* dst, const SkPaint* paint,
    499                       SkIPoint* offset) const {
    500         return this->extractAlpha(dst, paint, NULL, offset);
    501     }
    502 
    503     /** Set dst to contain alpha layer of this bitmap. If destination bitmap
    504         fails to be initialized, e.g. because allocator can't allocate pixels
    505         for it, dst will not be modified and false will be returned.
    506 
    507         @param dst The bitmap to be filled with alpha layer
    508         @param paint The paint to draw with
    509         @param allocator Allocator used to allocate the pixelref for the dst
    510                          bitmap. If this is null, the standard HeapAllocator
    511                          will be used.
    512         @param offset If not null, it is set to top-left coordinate to position
    513                       the returned bitmap so that it visually lines up with the
    514                       original
    515     */
    516     bool extractAlpha(SkBitmap* dst, const SkPaint* paint, Allocator* allocator,
    517                       SkIPoint* offset) const;
    518 
    519     void flatten(SkFlattenableWriteBuffer&) const;
    520     void unflatten(SkFlattenableReadBuffer&);
    521 
    522     SkDEBUGCODE(void validate() const;)
    523 
    524     class Allocator : public SkRefCnt {
    525     public:
    526         /** Allocate the pixel memory for the bitmap, given its dimensions and
    527             config. Return true on success, where success means either setPixels
    528             or setPixelRef was called. The pixels need not be locked when this
    529             returns. If the config requires a colortable, it also must be
    530             installed via setColorTable. If false is returned, the bitmap and
    531             colortable should be left unchanged.
    532         */
    533         virtual bool allocPixelRef(SkBitmap*, SkColorTable*) = 0;
    534     };
    535 
    536     /** Subclass of Allocator that returns a pixelref that allocates its pixel
    537         memory from the heap. This is the default Allocator invoked by
    538         allocPixels().
    539     */
    540     class HeapAllocator : public Allocator {
    541     public:
    542         virtual bool allocPixelRef(SkBitmap*, SkColorTable*);
    543     };
    544 
    545     class RLEPixels {
    546     public:
    547         RLEPixels(int width, int height);
    548         virtual ~RLEPixels();
    549 
    550         uint8_t* packedAtY(int y) const {
    551             SkASSERT((unsigned)y < (unsigned)fHeight);
    552             return fYPtrs[y];
    553         }
    554 
    555         // called by subclasses during creation
    556         void setPackedAtY(int y, uint8_t* addr) {
    557             SkASSERT((unsigned)y < (unsigned)fHeight);
    558             fYPtrs[y] = addr;
    559         }
    560 
    561     private:
    562         uint8_t** fYPtrs;
    563         int       fHeight;
    564     };
    565 
    566 private:
    567     struct MipMap;
    568     mutable MipMap* fMipMap;
    569 
    570     mutable SkPixelRef* fPixelRef;
    571     mutable size_t      fPixelRefOffset;
    572     mutable int         fPixelLockCount;
    573     // either user-specified (in which case it is not treated as mutable)
    574     // or a cache of the returned value from fPixelRef->lockPixels()
    575     mutable void*       fPixels;
    576     mutable SkColorTable* fColorTable;    // only meaningful for kIndex8
    577     // When there is no pixel ref (setPixels was called) we still need a
    578     // gen id for SkDevice implementations that may cache a copy of the
    579     // pixels (e.g. as a gpu texture)
    580     mutable int         fRawPixelGenerationID;
    581 
    582     enum Flags {
    583         kImageIsOpaque_Flag  = 0x01
    584     };
    585 
    586     uint32_t    fRowBytes;
    587     uint32_t    fWidth;
    588     uint32_t    fHeight;
    589     uint8_t     fConfig;
    590     uint8_t     fFlags;
    591     uint8_t     fBytesPerPixel; // based on config
    592 
    593     /* Internal computations for safe size.
    594     */
    595     static Sk64 ComputeSafeSize64(Config config,
    596                                   uint32_t width,
    597                                   uint32_t height,
    598                                   uint32_t rowBytes);
    599     static size_t ComputeSafeSize(Config   config,
    600                                   uint32_t width,
    601                                   uint32_t height,
    602                                   uint32_t rowBytes);
    603 
    604     /*  Unreference any pixelrefs or colortables
    605     */
    606     void freePixels();
    607     void updatePixelsFromRef() const;
    608 
    609     static SkFixed ComputeMipLevel(SkFixed sx, SkFixed dy);
    610 };
    611 
    612 /** \class SkColorTable
    613 
    614     SkColorTable holds an array SkPMColors (premultiplied 32-bit colors) used by
    615     8-bit bitmaps, where the bitmap bytes are interpreted as indices into the colortable.
    616 */
    617 class SkColorTable : public SkRefCnt {
    618 public:
    619     /** Makes a deep copy of colors.
    620      */
    621     SkColorTable(const SkColorTable& src);
    622     /** Preallocates the colortable to have 'count' colors, which
    623      *  are initially set to 0.
    624     */
    625     explicit SkColorTable(int count);
    626     explicit SkColorTable(SkFlattenableReadBuffer&);
    627     SkColorTable(const SkPMColor colors[], int count);
    628     virtual ~SkColorTable();
    629 
    630     enum Flags {
    631         kColorsAreOpaque_Flag   = 0x01  //!< if set, all of the colors in the table are opaque (alpha==0xFF)
    632     };
    633     /** Returns the flag bits for the color table. These can be changed with setFlags().
    634     */
    635     unsigned getFlags() const { return fFlags; }
    636     /** Set the flags for the color table. See the Flags enum for possible values.
    637     */
    638     void    setFlags(unsigned flags);
    639 
    640     bool isOpaque() const { return (fFlags & kColorsAreOpaque_Flag) != 0; }
    641     void setIsOpaque(bool isOpaque);
    642 
    643     /** Returns the number of colors in the table.
    644     */
    645     int count() const { return fCount; }
    646 
    647     /** Returns the specified color from the table. In the debug build, this asserts that
    648         the index is in range (0 <= index < count).
    649     */
    650     SkPMColor operator[](int index) const {
    651         SkASSERT(fColors != NULL && (unsigned)index < fCount);
    652         return fColors[index];
    653     }
    654 
    655     /** Specify the number of colors in the color table. This does not initialize the colors
    656         to any value, just allocates memory for them. To initialize the values, either call
    657         setColors(array, count), or follow setCount(count) with a call to
    658         lockColors()/{set the values}/unlockColors(true).
    659     */
    660 //    void    setColors(int count) { this->setColors(NULL, count); }
    661 //    void    setColors(const SkPMColor[], int count);
    662 
    663     /** Return the array of colors for reading and/or writing. This must be
    664         balanced by a call to unlockColors(changed?), telling the colortable if
    665         the colors were changed during the lock.
    666     */
    667     SkPMColor* lockColors() {
    668         SkDEBUGCODE(fColorLockCount += 1;)
    669         return fColors;
    670     }
    671     /** Balancing call to lockColors(). If the colors have been changed, pass true.
    672     */
    673     void unlockColors(bool changed);
    674 
    675     /** Similar to lockColors(), lock16BitCache() returns the array of
    676         RGB16 colors that mirror the 32bit colors. However, this function
    677         will return null if kColorsAreOpaque_Flag is not set.
    678         Also, unlike lockColors(), the returned array here cannot be modified.
    679     */
    680     const uint16_t* lock16BitCache();
    681     /** Balancing call to lock16BitCache().
    682     */
    683     void unlock16BitCache() {
    684         SkASSERT(f16BitCacheLockCount > 0);
    685         SkDEBUGCODE(f16BitCacheLockCount -= 1);
    686     }
    687 
    688     void flatten(SkFlattenableWriteBuffer&) const;
    689 
    690 private:
    691     SkPMColor*  fColors;
    692     uint16_t*   f16BitCache;
    693     uint16_t    fCount;
    694     uint8_t     fFlags;
    695     SkDEBUGCODE(int fColorLockCount;)
    696     SkDEBUGCODE(int f16BitCacheLockCount;)
    697 
    698     void inval16BitCache();
    699 };
    700 
    701 class SkAutoLockPixels {
    702 public:
    703     SkAutoLockPixels(const SkBitmap& bitmap) : fBitmap(bitmap) {
    704         bitmap.lockPixels();
    705     }
    706     ~SkAutoLockPixels() {
    707         fBitmap.unlockPixels();
    708     }
    709 
    710 private:
    711     const SkBitmap& fBitmap;
    712 };
    713 
    714 /** Helper class that performs the lock/unlockColors calls on a colortable.
    715     The destructor will call unlockColors(false) if it has a bitmap's colortable
    716 */
    717 class SkAutoLockColors : public SkNoncopyable {
    718 public:
    719     /** Initialize with no bitmap. Call lockColors(bitmap) to lock bitmap's
    720         colortable
    721      */
    722     SkAutoLockColors() : fCTable(NULL), fColors(NULL) {}
    723     /** Initialize with bitmap, locking its colortable if present
    724      */
    725     explicit SkAutoLockColors(const SkBitmap& bm) {
    726         fCTable = bm.getColorTable();
    727         fColors = fCTable ? fCTable->lockColors() : NULL;
    728     }
    729     /** Initialize with a colortable (may be null)
    730      */
    731     explicit SkAutoLockColors(SkColorTable* ctable) {
    732         fCTable = ctable;
    733         fColors = ctable ? ctable->lockColors() : NULL;
    734     }
    735     ~SkAutoLockColors() {
    736         if (fCTable) {
    737             fCTable->unlockColors(false);
    738         }
    739     }
    740 
    741     /** Return the currently locked colors, or NULL if no bitmap's colortable
    742         is currently locked.
    743     */
    744     const SkPMColor* colors() const { return fColors; }
    745 
    746     /** Locks the table and returns is colors (assuming ctable is not null) and
    747         unlocks the previous table if one was present
    748      */
    749     const SkPMColor* lockColors(SkColorTable* ctable) {
    750         if (fCTable) {
    751             fCTable->unlockColors(false);
    752         }
    753         fCTable = ctable;
    754         fColors = ctable ? ctable->lockColors() : NULL;
    755         return fColors;
    756     }
    757 
    758     const SkPMColor* lockColors(const SkBitmap& bm) {
    759         return this->lockColors(bm.getColorTable());
    760     }
    761 
    762 private:
    763     SkColorTable*    fCTable;
    764     const SkPMColor* fColors;
    765 };
    766 
    767 ///////////////////////////////////////////////////////////////////////////////
    768 
    769 inline uint32_t* SkBitmap::getAddr32(int x, int y) const {
    770     SkASSERT(fPixels);
    771     SkASSERT(fConfig == kARGB_8888_Config);
    772     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    773     return (uint32_t*)((char*)fPixels + y * fRowBytes + (x << 2));
    774 }
    775 
    776 inline uint16_t* SkBitmap::getAddr16(int x, int y) const {
    777     SkASSERT(fPixels);
    778     SkASSERT(fConfig == kRGB_565_Config || fConfig == kARGB_4444_Config);
    779     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    780     return (uint16_t*)((char*)fPixels + y * fRowBytes + (x << 1));
    781 }
    782 
    783 inline uint8_t* SkBitmap::getAddr8(int x, int y) const {
    784     SkASSERT(fPixels);
    785     SkASSERT(fConfig == kA8_Config || fConfig == kIndex8_Config);
    786     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    787     return (uint8_t*)fPixels + y * fRowBytes + x;
    788 }
    789 
    790 inline SkPMColor SkBitmap::getIndex8Color(int x, int y) const {
    791     SkASSERT(fPixels);
    792     SkASSERT(fConfig == kIndex8_Config);
    793     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    794     SkASSERT(fColorTable);
    795     return (*fColorTable)[*((const uint8_t*)fPixels + y * fRowBytes + x)];
    796 }
    797 
    798 // returns the address of the byte that contains the x coordinate
    799 inline uint8_t* SkBitmap::getAddr1(int x, int y) const {
    800     SkASSERT(fPixels);
    801     SkASSERT(fConfig == kA1_Config);
    802     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    803     return (uint8_t*)fPixels + y * fRowBytes + (x >> 3);
    804 }
    805 
    806 #endif
    807