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