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