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