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