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