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