Skip to main content

skia_safe/core/
bitmap.rs

1use std::{ffi, fmt, ptr};
2
3use skia_bindings::{self as sb, SkBitmap};
4
5use crate::{
6    AlphaType, Color, Color4f, ColorSpace, ColorType, IPoint, IRect, ISize, Image, ImageInfo,
7    Matrix, Paint, PixelRef, Pixmap, SamplingOptions, Shader, TileMode, prelude::*,
8};
9
10/// [`Bitmap`] describes a two-dimensional raster pixel array. [`Bitmap`] is built on [`ImageInfo`],
11/// containing integer width and height, [`ColorType`] and [`AlphaType`] describing the pixel
12/// format, and [`ColorSpace`] describing the range of colors. [`Bitmap`] points to [`PixelRef`],
13/// which describes the physical array of pixels. [`ImageInfo`] bounds may be located anywhere fully
14/// inside [`PixelRef`] bounds.
15///
16/// [`Bitmap`] can be drawn using [`crate::Canvas`]. [`Bitmap`] can be a drawing destination for
17/// [`crate::Canvas`] draw member functions. [`Bitmap`] flexibility as a pixel container limits some
18/// optimizations available to the target platform.
19///
20/// If pixel array is primarily read-only, use [`Image`] for better performance.
21///
22/// If pixel array is primarily written to, use [`crate::Surface`] for better performance.
23///
24/// Declaring [`Bitmap`] const prevents altering [`ImageInfo`]: the [`Bitmap`] height, width, and so
25/// on cannot change. It does not affect [`PixelRef`]: a caller may write its pixels. Declaring
26/// [`Bitmap`] const affects [`Bitmap`] configuration, not its contents.
27///
28/// [`Bitmap`] is not thread safe. Each thread must have its own copy of [`Bitmap`] fields, although
29/// threads may share the underlying pixel array.
30pub type Bitmap = Handle<SkBitmap>;
31
32impl NativeDrop for SkBitmap {
33    fn drop(&mut self) {
34        unsafe { sb::C_SkBitmap_destruct(self) }
35    }
36}
37
38impl NativeClone for SkBitmap {
39    /// Copies settings from `self` to returned [`Bitmap`]. Shares pixels if `self` has pixels
40    /// allocated, so both bitmaps reference the same pixels.
41    ///
42    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_copy_const_SkBitmap>
43    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_copy_operator>
44    fn clone(&self) -> Self {
45        unsafe { SkBitmap::new1(self) }
46    }
47}
48
49impl Default for Bitmap {
50    /// See [`Bitmap::new()`].
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56impl fmt::Debug for Bitmap {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.debug_struct("Bitmap")
59            .field("pixmap", self.pixmap())
60            .finish()
61    }
62}
63
64impl Bitmap {
65    /// Creates an empty [`Bitmap`] without pixels, with [`ColorType::Unknown`], [`AlphaType::Unknown`],
66    /// and with a width and height of zero. [`PixelRef`] origin is set to `(0, 0)`.
67    ///
68    /// Use [`Self::set_info()`] to associate [`ColorType`], [`AlphaType`], width, and height after
69    /// [`Bitmap`] has been created.
70    ///
71    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_empty_constructor>
72    pub fn new() -> Self {
73        Self::construct(|bitmap| unsafe { sb::C_SkBitmap_Construct(bitmap) })
74    }
75
76    /// Swaps the fields of the two bitmaps.
77    ///
78    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_swap>
79    pub fn swap(&mut self, other: &mut Self) {
80        unsafe { self.native_mut().swap(other.native_mut()) }
81    }
82
83    /// Returns a constant reference to the [`Pixmap`] holding the [`Bitmap`] pixel address, row
84    /// bytes, and [`ImageInfo`].
85    pub fn pixmap(&self) -> &Pixmap {
86        Pixmap::from_native_ref(&self.native().fPixmap)
87    }
88
89    /// Returns width, height, [`AlphaType`], [`ColorType`], and [`ColorSpace`].
90    pub fn info(&self) -> &ImageInfo {
91        self.pixmap().info()
92    }
93
94    /// Returns pixel count in each row. Should be equal or less than `row_bytes()` /
95    /// `info().bytes_per_pixel()`.
96    ///
97    /// May be less than `pixel_ref().width()`. Will not exceed `pixel_ref().width()` less
98    /// `pixel_ref_origin().x`.
99    pub fn width(&self) -> i32 {
100        self.pixmap().width()
101    }
102
103    /// Returns pixel row count.
104    ///
105    /// Maybe be less than `pixel_ref().height()`. Will not exceed `pixel_ref().height()` less
106    /// `pixel_ref_origin().y`.
107    pub fn height(&self) -> i32 {
108        self.pixmap().height()
109    }
110
111    pub fn color_type(&self) -> ColorType {
112        self.pixmap().color_type()
113    }
114
115    pub fn alpha_type(&self) -> AlphaType {
116        self.pixmap().alpha_type()
117    }
118
119    /// Returns [`ColorSpace`], the range of colors, associated with [`ImageInfo`]. The returned
120    /// [`ColorSpace`] is immutable.
121    pub fn color_space(&self) -> Option<ColorSpace> {
122        ColorSpace::from_unshared_ptr(unsafe { self.native().colorSpace() })
123    }
124
125    /// Returns number of bytes per pixel required by [`ColorType`].
126    ///
127    /// Returns zero if `color_type()` is [`ColorType::Unknown`].
128    pub fn bytes_per_pixel(&self) -> usize {
129        self.info().bytes_per_pixel()
130    }
131
132    /// Returns number of pixels that fit on row. Should be greater than or equal to `width()`.
133    pub fn row_bytes_as_pixels(&self) -> usize {
134        self.pixmap().row_bytes_as_pixels()
135    }
136
137    /// Returns bit shift converting row bytes to row pixels.
138    ///
139    /// Returns zero for [`ColorType::Unknown`].
140    pub fn shift_per_pixel(&self) -> usize {
141        self.pixmap().shift_per_pixel()
142    }
143
144    /// Returns `true` if either `width()` or `height()` are zero.
145    ///
146    /// Does not check if [`PixelRef`] is `None`; call `draws_nothing()` to check `width()`,
147    /// `height()`, and [`PixelRef`].
148    pub fn is_empty(&self) -> bool {
149        self.pixmap().is_empty()
150    }
151
152    /// Returns `true` if [`PixelRef`] is `None`.
153    ///
154    /// Does not check if `width()` or `height()` are zero; call `draws_nothing()` to check
155    /// `width()`, `height()`, and [`PixelRef`].
156    pub fn is_null(&self) -> bool {
157        self.native().fPixelRef.fPtr.is_null()
158    }
159
160    /// Returns `true` if `width()` or `height()` are zero, or if [`PixelRef`] is `None`.
161    ///
162    /// If `true`, [`Bitmap`] has no effect when drawn or drawn into.
163    pub fn draws_nothing(&self) -> bool {
164        self.is_empty() || self.is_null()
165    }
166
167    /// Returns row bytes, the interval from one pixel row to the next. Row bytes is at least as
168    /// large as: `width()` * `info().bytes_per_pixel()`.
169    ///
170    /// Returns zero if `color_type()` is [`ColorType::Unknown`], or if row bytes supplied to
171    /// `set_info()` is not large enough to hold a row of pixels.
172    pub fn row_bytes(&self) -> usize {
173        self.pixmap().row_bytes()
174    }
175
176    /// Sets [`AlphaType`], if `alpha_type` is compatible with [`ColorType`]. Returns `true` unless
177    /// `alpha_type` is [`AlphaType::Unknown`] and current [`AlphaType`] is not [`AlphaType::Unknown`].
178    ///
179    /// Returns `true` if [`ColorType`] is [`ColorType::Unknown`]. `alpha_type` is ignored, and
180    /// [`AlphaType`] remains [`AlphaType::Unknown`].
181    ///
182    /// Returns `true` if [`ColorType`] is [`ColorType::RGB565`] or [`ColorType::Gray8`].
183    /// `alpha_type` is ignored, and [`AlphaType`] remains [`AlphaType::Opaque`].
184    ///
185    /// If [`ColorType`] is [`ColorType::ARGB4444`], [`ColorType::RGBA8888`],
186    /// [`ColorType::BGRA8888`], or [`ColorType::RGBAF16`]: returns `true` unless `alpha_type` is
187    /// [`AlphaType::Unknown`] and [`AlphaType`] is not [`AlphaType::Unknown`]. If [`AlphaType`] is
188    /// [`AlphaType::Unknown`], `alpha_type` is ignored.
189    ///
190    /// If [`ColorType`] is [`ColorType::Alpha8`], returns `true` unless `alpha_type` is
191    /// [`AlphaType::Unknown`] and [`AlphaType`] is not [`AlphaType::Unknown`]. If [`AlphaType`] is
192    /// kUnknown_SkAlphaType, `alpha_type` is ignored. If `alpha_type` is [`AlphaType::Unpremul`],
193    /// it is treated as [`AlphaType::Premul`].
194    ///
195    /// This changes [`AlphaType`] in [`PixelRef`]; all bitmaps sharing [`PixelRef`] are affected.
196    ///
197    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_setAlphaType>
198    pub fn set_alpha_type(&mut self, alpha_type: AlphaType) -> bool {
199        unsafe { self.native_mut().setAlphaType(alpha_type) }
200    }
201
202    /// Sets the [`ColorSpace`] associated with this [`Bitmap`].
203    ///
204    /// The raw pixel data is not altered by this call; no conversion is
205    /// performed.
206    ///
207    /// This changes [`ColorSpace`] in [`PixelRef`]; all bitmaps sharing [`PixelRef`]
208    /// are affected.
209    pub fn set_color_space(&mut self, color_space: impl Into<Option<ColorSpace>>) {
210        unsafe {
211            sb::C_SkBitmap_setColorSpace(self.native_mut(), color_space.into().into_ptr_or_null())
212        }
213    }
214
215    /// Returns pixel address, the base address corresponding to the pixel origin.
216    pub fn pixels(&mut self) -> *mut ffi::c_void {
217        self.pixmap().writable_addr()
218    }
219
220    /// Returns minimum memory required for pixel storage.  
221    /// Does not include unused memory on last row when `row_bytes_as_pixels()` exceeds `width()`.  
222    /// Returns [`usize::MAX`] if result does not fit in `usize`.  
223    /// Returns zero if `height()` or `width()` is 0.  
224    /// Returns `height()` times `row_bytes()` if `color_type()` is [`ColorType::Unknown`].
225    pub fn compute_byte_size(&self) -> usize {
226        self.pixmap().compute_byte_size()
227    }
228
229    /// Returns `true` if pixels can not change.
230    ///
231    /// Most immutable [`Bitmap`] checks trigger an assert only on debug builds.
232    ///
233    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_isImmutable>
234    pub fn is_immutable(&self) -> bool {
235        unsafe { self.native().isImmutable() }
236    }
237
238    /// Sets internal flag to mark [`Bitmap`] as immutable. Once set, pixels can not change. Any
239    /// other bitmap sharing the same [`PixelRef`] are also marked as immutable.
240    ///
241    /// Once [`PixelRef`] is marked immutable, the setting cannot be cleared.
242    ///
243    /// Writing to immutable [`Bitmap`] pixels triggers an assert on debug builds.
244    ///
245    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_setImmutable>
246    pub fn set_immutable(&mut self) {
247        unsafe { self.native_mut().setImmutable() }
248    }
249
250    /// Returns `true` if [`AlphaType`] is set to hint that all pixels are opaque; their alpha value
251    /// is implicitly or explicitly `1.0`. If `true`, and all pixels are not opaque, Skia may draw
252    /// incorrectly.
253    ///
254    /// Does not check if [`ColorType`] allows alpha, or if any pixel value has transparency.
255    pub fn is_opaque(&self) -> bool {
256        self.pixmap().is_opaque()
257    }
258
259    /// Resets to its initial state; all fields are set to zero, as if [`Bitmap`] had
260    /// been initialized by [`Bitmap::new()`].
261    ///
262    /// Sets width, height, row bytes to zero; pixel address to `None`; [`ColorType`] to
263    /// [`ColorType::Unknown`]; and [`AlphaType`] to [`AlphaType::Unknown`].
264    ///
265    /// If [`PixelRef`] is allocated, its reference count is decreased by one, releasing its memory
266    /// if [`Bitmap`] is the sole owner.
267    ///
268    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_reset>
269    pub fn reset(&mut self) {
270        unsafe { self.native_mut().reset() }
271    }
272
273    /// Returns `true `if all pixels are opaque. [`ColorType`] determines how pixels are encoded, and
274    /// whether pixel describes alpha. Returns `true` for [`ColorType`] without alpha in each pixel;
275    /// for other [`ColorType`], returns `true` if all pixels have alpha values equivalent to 1.0 or
276    /// greater.
277    ///
278    /// Returns `false` for [`ColorType::Unknown`].
279    pub fn compute_is_opaque(bm: &Self) -> bool {
280        unsafe { sb::C_SkBitmap_ComputeIsOpaque(bm.native()) }
281    }
282
283    /// Returns `IRect { 0, 0, width(), height() }`.
284    ///
285    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_getBounds>
286    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_getBounds_2>
287    pub fn bounds(&self) -> IRect {
288        self.info().bounds()
289    }
290
291    /// Returns `ISize { width(), height() }`.
292    pub fn dimensions(&self) -> ISize {
293        self.info().dimensions()
294    }
295
296    /// Returns the bounds of this bitmap, offset by its [`PixelRef`] origin.
297    pub fn get_subset(&self) -> IRect {
298        let origin = self.pixel_ref_origin();
299        IRect::from_xywh(origin.x, origin.y, self.width(), self.height())
300    }
301
302    /// Sets width, height, [`AlphaType`], [`ColorType`], [`ColorSpace`], and optional `row_bytes`.
303    /// Frees pixels, and returns `true` if successful.
304    ///
305    /// `row_bytes` must equal or exceed `image_info.min_row_bytes()`. If `image_info.color_space()`
306    /// is [`ColorType::Unknown`], `row_bytes` is ignored and treated as zero; for all other
307    /// [`ColorSpace`] values, `row_bytes` of zero is treated as `image_info.min_row_bytes()`.
308    ///
309    /// Calls `reset()` and returns `false` if:
310    /// - rowBytes exceeds 31 bits
311    /// - `image_info.width()` is negative
312    /// - `image_info.height()` is negative
313    /// - `row_bytes` is positive and less than `image_info.width()` times
314    ///   `image_info.bytes_per_pixel()`
315    ///
316    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_setInfo>
317    #[must_use]
318    pub fn set_info(
319        &mut self,
320        image_info: &ImageInfo,
321        row_bytes: impl Into<Option<usize>>,
322    ) -> bool {
323        unsafe {
324            self.native_mut()
325                .setInfo(image_info.native(), row_bytes.into().unwrap_or(0))
326        }
327    }
328
329    /// Sets [`ImageInfo`] to info following the rules in `set_info()` and allocates pixel memory.
330    /// Memory is zeroed.
331    ///
332    /// Returns `false` and calls `reset()` if [`ImageInfo`] could not be set, or memory could not
333    /// be allocated, or memory could not optionally be zeroed.
334    ///
335    /// On most platforms, allocating pixel memory may succeed even though there is not sufficient
336    /// memory to hold pixels; allocation does not take place until the pixels are written to. The
337    /// actual behavior depends on the platform implementation of `calloc()`.
338    #[must_use]
339    pub fn try_alloc_pixels_flags(&mut self, image_info: &ImageInfo) -> bool {
340        unsafe {
341            self.native_mut().tryAllocPixelsFlags(
342                image_info.native(),
343                sb::SkBitmap_AllocFlags_kZeroPixels_AllocFlag as _,
344            )
345        }
346    }
347
348    /// Sets [`ImageInfo`] to info following the rules in `set_info()` and allocates pixel memory.
349    /// Memory is zeroed.
350    ///
351    /// Returns `false` and calls `reset()` if [`ImageInfo`] could not be set, or memory could not be
352    /// allocated, or memory could not optionally be zeroed.
353    ///
354    /// On most platforms, allocating pixel memory may succeed even though there is not sufficient
355    /// memory to hold pixels; allocation does not take place until the pixels are written to. The
356    /// actual behavior depends on the platform implementation of `calloc()`.
357    ///
358    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_allocPixelsFlags>
359    pub fn alloc_pixels_flags(&mut self, image_info: &ImageInfo) {
360        if !self.try_alloc_pixels_flags(image_info) {
361            panic!("Bitmap::alloc_pixels_flags failed");
362        }
363    }
364
365    /// Sets [`ImageInfo`] to info following the rules in `set_info()` and allocates pixel memory.
366    /// `row_bytes` must equal or exceed `info.width()` times `info.bytes_per_pixel()`, or equal
367    /// `None`. Pass in `None` for `row_bytes` to compute the minimum valid value.
368    ///
369    /// Returns `false` and calls `reset()` if [`ImageInfo`] could not be set, or memory could not be
370    /// allocated.
371    ///
372    /// On most platforms, allocating pixel memory may succeed even though there is not sufficient
373    /// memory to hold pixels; allocation does not take place until the pixels are written to. The
374    /// actual behavior depends on the platform implementation of `malloc()`.
375    #[must_use]
376    pub fn try_alloc_pixels_info(
377        &mut self,
378        image_info: &ImageInfo,
379        row_bytes: impl Into<Option<usize>>,
380    ) -> bool {
381        let row_bytes = row_bytes
382            .into()
383            .unwrap_or_else(|| image_info.min_row_bytes());
384        unsafe {
385            self.native_mut()
386                .tryAllocPixels(image_info.native(), row_bytes)
387        }
388    }
389
390    /// Sets [`ImageInfo`] to info following the rules in `set_info()` and allocates pixel memory.
391    /// `row_bytes` must equal or exceed `info.width()` times `info.bytes_per_pixel()`, or equal
392    /// `None`. Pass in `None` for `row_bytes` to compute the minimum valid value.
393    ///
394    /// Aborts execution if [`ImageInfo`] could not be set, or memory could
395    /// be allocated.
396    ///
397    /// On most platforms, allocating pixel memory may succeed even though there is not sufficient
398    /// memory to hold pixels; allocation does not take place until the pixels are written to. The
399    /// actual behavior depends on the platform implementation of `malloc()`.
400    ///
401    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_allocPixels>
402    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_allocPixels_2>
403    pub fn alloc_pixels_info(
404        &mut self,
405        image_info: &ImageInfo,
406        row_bytes: impl Into<Option<usize>>,
407    ) {
408        if !self.try_alloc_pixels_info(image_info, row_bytes.into()) {
409            panic!("Bitmap::alloc_pixels_info failed");
410        }
411    }
412
413    /// Sets [`ImageInfo`] to width, height, and native color type; and allocates pixel memory. If
414    /// `is_opaque` is `true`, sets [`ImageInfo`] to [`AlphaType::Opaque`]; otherwise, sets to
415    /// [`AlphaType::Premul`].
416    ///
417    /// Calls `reset()` and returns `false` if width exceeds 29 bits or is negative, or height is
418    /// negative.
419    ///
420    /// Returns `false` if allocation fails.
421    ///
422    /// Use to create [`Bitmap`] that matches [`crate::PMColor`], the native pixel arrangement on
423    /// the platform. [`Bitmap`] drawn to output device skips converting its pixel format.
424    #[must_use]
425    pub fn try_alloc_n32_pixels(
426        &mut self,
427        (width, height): (i32, i32),
428        is_opaque: impl Into<Option<bool>>,
429    ) -> bool {
430        unsafe {
431            sb::C_SkBitmap_tryAllocN32Pixels(
432                self.native_mut(),
433                width,
434                height,
435                is_opaque.into().unwrap_or(false),
436            )
437        }
438    }
439
440    /// Sets [`ImageInfo`] to width, height, and native color type; and allocates pixel memory. If
441    /// `is_opaque` is `true`, sets [`ImageInfo`] to [`AlphaType::Opaque`]; otherwise, sets to
442    /// [`AlphaType::Premul`].
443    ///
444    /// Aborts if width exceeds 29 bits or is negative, or height is negative, or allocation fails.
445    ///
446    /// Use to create [`Bitmap`] that matches [`crate::PMColor`], the native pixel arrangement on
447    /// the platform. [`Bitmap`] drawn to output device skips converting its pixel format.
448    ///
449    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_allocN32Pixels>
450    pub fn alloc_n32_pixels(
451        &mut self,
452        (width, height): (i32, i32),
453        is_opaque: impl Into<Option<bool>>,
454    ) {
455        if !self.try_alloc_n32_pixels((width, height), is_opaque.into().unwrap_or(false)) {
456            panic!("Bitmap::alloc_n32_pixels_failed");
457        }
458    }
459
460    // TODO: wrap installPixels with releaseProc.
461
462    /// Sets [`ImageInfo`] to info following the rules in `set_info()`, and creates [`PixelRef`]
463    /// containing `pixels` and `row_bytes`.
464    ///
465    /// If [`ImageInfo`] could not be set, or `row_bytes` is less than `info.min_row_bytes(): calls
466    /// `reset()`, and returns `false`.
467    ///
468    /// Otherwise, if pixels equals `ptr::null_mut()`: sets [`ImageInfo`], returns `true`.
469    ///
470    /// Caller must ensure that pixels are valid for the lifetime of [`Bitmap`] and [`PixelRef`].
471    ///
472    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_installPixels_3>
473    #[allow(clippy::missing_safety_doc)]
474    pub unsafe fn install_pixels(
475        &mut self,
476        info: &ImageInfo,
477        pixels: *mut ffi::c_void,
478        row_bytes: usize,
479    ) -> bool {
480        unsafe {
481            self.native_mut()
482                .installPixels(info.native(), pixels, row_bytes, None, ptr::null_mut())
483        }
484    }
485
486    // TODO: wrap installPixels with SkPixmap&
487
488    // TODO: setPixels()?
489
490    /// Allocates pixel memory with HeapAllocator, and replaces existing [`PixelRef`]. The
491    /// allocation size is determined by [`ImageInfo`] width, height, and [`ColorType`].
492    ///
493    /// Returns `false` if `info().color_type()` is [`ColorType::Unknown`], or allocation fails.
494    #[must_use]
495    pub fn try_alloc_pixels(&mut self) -> bool {
496        unsafe { sb::C_SkBitmap_tryAllocPixels(self.native_mut()) }
497    }
498
499    /// Allocates pixel memory with HeapAllocator, and replaces existing [`PixelRef`]. The
500    /// allocation size is determined by [`ImageInfo`] width, height, and [`ColorType`].
501    ///
502    /// Aborts if `info().color_type()` is [`ColorType::Unknown`], or allocation fails.
503    ///
504    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_allocPixels_3>
505    pub fn alloc_pixels(&mut self) {
506        if !self.try_alloc_pixels() {
507            panic!("Bitmap::alloc_pixels failed");
508        }
509    }
510
511    // TODO: allocPixels(Allocator*)
512
513    // TODO: find a way to return pixel ref without increasing the ref count here?
514
515    /// Returns [`PixelRef`], which contains: pixel base address; its dimensions; and `row_bytes()`,
516    /// the interval from one row to the next. Does not change [`PixelRef`] reference count.
517    /// [`PixelRef`] may be shared by multiple bitmaps.
518    ///
519    /// If [`PixelRef`] has not been set, returns `None`.
520    pub fn pixel_ref(&self) -> Option<PixelRef> {
521        PixelRef::from_unshared_ptr(self.native().fPixelRef.fPtr)
522    }
523
524    /// Returns origin of pixels within [`PixelRef`]. [`Bitmap`] bounds is always contained
525    /// by [`PixelRef`] bounds, which may be the same size or larger. Multiple [`Bitmap`]
526    /// can share the same [`PixelRef`], where each [`Bitmap`] has different bounds.
527    ///
528    /// The returned origin added to [`Bitmap`] dimensions equals or is smaller than the
529    /// [`PixelRef`] dimensions.
530    ///
531    /// Returns `(0, 0)` if [`PixelRef`] is `None`.
532    ///
533    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_pixelRefOrigin>
534    pub fn pixel_ref_origin(&self) -> IPoint {
535        IPoint::from_native_c(unsafe { sb::C_SkBitmap_pixelRefOrigin(self.native()) })
536    }
537
538    /// Replaces `pixel_ref` and origin in [`Bitmap`]. `offset` specifies the offset within the
539    /// [`PixelRef`] pixels for the top-left corner of the bitmap.
540    ///
541    /// Asserts in debug builds if offset is out of range. Pins offset to legal range in release
542    /// builds.
543    ///
544    /// The caller is responsible for ensuring that the pixels match the [`ColorType`] and
545    /// [`AlphaType`] in [`ImageInfo`].
546    ///
547    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_setPixelRef>
548    pub fn set_pixel_ref(
549        &mut self,
550        pixel_ref: impl Into<Option<PixelRef>>,
551        offset: impl Into<IPoint>,
552    ) {
553        let offset = offset.into();
554        unsafe {
555            sb::C_SkBitmap_setPixelRef(
556                self.native_mut(),
557                pixel_ref.into().into_ptr_or_null(),
558                offset.x,
559                offset.y,
560            )
561        }
562    }
563
564    /// Returns `true` if [`Bitmap`] can be drawn.
565    pub fn is_ready_to_draw(&self) -> bool {
566        unsafe { sb::C_SkBitmap_readyToDraw(self.native()) }
567    }
568
569    /// Returns a unique value corresponding to the pixels in [`PixelRef`].  
570    /// Returns a different value after `notify_pixels_changed()` has been called.  
571    /// Returns zero if [`PixelRef`] is `None`.
572    ///
573    /// Determines if pixels have changed since last examined.
574    ///
575    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_getGenerationID>
576    pub fn generation_id(&self) -> u32 {
577        unsafe { self.native().getGenerationID() }
578    }
579
580    /// Marks that pixels in [`PixelRef`] have changed. Subsequent calls to `generation_id()` return
581    /// a different value.
582    ///
583    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_notifyPixelsChanged>
584    pub fn notify_pixels_changed(&self) {
585        unsafe { self.native().notifyPixelsChanged() }
586    }
587
588    /// Replaces pixel values with `c`, interpreted as being in the sRGB [`ColorSpace`]. All pixels
589    /// contained by [`Self::bounds()`] are affected. If the [`Self::color_type()`] is
590    /// [`ColorType::Gray8`] or [`ColorType::RGB565`], then alpha is ignored; RGB is treated as
591    /// opaque. If [`Self::color_type()`] is [`ColorType::Alpha8`], then RGB is ignored.
592    ///
593    /// Input color is ultimately converted to an [`Color4f`], so [`Self::erase_color_4f`] will have
594    /// higher color resolution.
595    ///
596    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_eraseColor>
597    pub fn erase_color(&self, c: impl Into<Color>) {
598        unsafe { self.native().eraseColor1(c.into().into_native()) }
599    }
600
601    /// Replaces pixel values with `c`, interpreted as being in the sRGB [`ColorSpace`]. All pixels
602    /// contained by [`Self::bounds()`] are affected. If the [`Self::color_type()`] is
603    /// [`ColorType::Gray8`] or [`ColorType::RGB565`], then alpha is ignored; RGB is treated as
604    /// opaque. If [`Self::color_type()`] is [`ColorType::Alpha8`], then RGB is ignored.
605    ///
606    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_eraseColor>
607    pub fn erase_color_4f(&self, c: impl AsRef<Color4f>) {
608        unsafe { self.native().eraseColor(c.as_ref().into_native()) }
609    }
610
611    /// Replaces pixel values with unpremultiplied color built from `a`, `r`, `g`, and `b`,
612    /// interpreted as being in the sRGB [`ColorSpace`]. All pixels contained by [`Self::bounds()`]
613    /// are affected. If the [`Self::color_type()`] is [`ColorType::Gray8`] or [`ColorType::RGB565`],
614    /// then `a` is ignored; `r`, `g`, and `b` are treated as opaque. If [`Self::color_type()`] is
615    /// [`ColorType::Alpha8`], then `r`, `g`, and `b` are ignored.
616    pub fn erase_argb(&self, a: u8, r: u8, g: u8, b: u8) {
617        unsafe { sb::C_SkBitmap_eraseARGB(self.native(), a.into(), r.into(), g.into(), b.into()) }
618    }
619
620    /// Replaces pixel values inside area with c. interpreted as being in the sRGB [`ColorSpace`].
621    /// If area does not intersect `bounds()`, call has no effect.
622    ///
623    /// If the `color_type()` is [`ColorType::Gray8`] [`ColorType::RGB565`], then alpha is ignored;
624    /// RGB is treated as opaque. If `color_type()` is [`ColorType::Alpha8`], then RGB is ignored.
625    ///
626    /// Input color is ultimately converted to an [`Color4f`], so [`Self::erase_4f`] will have
627    /// higher color resolution.
628    ///
629    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_erase>
630    pub fn erase(&self, c: impl Into<Color>, area: impl AsRef<IRect>) {
631        unsafe {
632            self.native()
633                .erase1(c.into().into_native(), area.as_ref().native())
634        }
635    }
636
637    /// Replaces pixel values inside area with c. interpreted as being in the sRGB [`ColorSpace`].
638    /// If area does not intersect `bounds()`, call has no effect.
639    ///
640    /// If the `color_type()` is [`ColorType::Gray8`] [`ColorType::RGB565`], then alpha is ignored;
641    /// RGB is treated as opaque. If `color_type()` is [`ColorType::Alpha8`], then RGB is ignored.
642    ///
643    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_erase>
644    pub fn erase_4f(&self, c: impl AsRef<Color4f>, area: impl AsRef<IRect>) {
645        unsafe {
646            self.native()
647                .erase(c.as_ref().into_native(), area.as_ref().native())
648        }
649    }
650
651    /// Returns pixel at `(x, y)` as unpremultiplied color.  
652    /// Returns black with alpha if [`ColorType`] is [`ColorType::Alpha8`]
653    ///
654    /// Input is not validated: out of bounds values of `x` or `y` trigger an `assert()`.
655    ///
656    /// Fails if [`ColorType`] is [`ColorType::Unknown`] or pixel address is `None`.
657    ///
658    /// [`ColorSpace`] in [`ImageInfo`] is ignored. Some color precision may be lost in the
659    /// conversion to unpremultiplied color; original pixel data may have additional precision.
660    pub fn get_color(&self, p: impl Into<IPoint>) -> Color {
661        self.pixmap().get_color(p)
662    }
663
664    /// Returns pixel at `(x, y)` as unpremultiplied color.
665    /// Returns black with alpha if [`ColorType`] is [`ColorType::Alpha8`]
666    ///
667    /// Input is not validated: out of bounds values of x or y trigger an `assert()`.
668    ///
669    /// Fails if [`ColorType`] is [`ColorType::Unknown`] or pixel address is `None`.
670    ///
671    /// [`ColorSpace`] in [`ImageInfo`] is ignored. Some color precision may be lost in the
672    /// conversion to unpremultiplied color.
673    pub fn get_color_4f(&self, p: impl Into<IPoint>) -> Color4f {
674        self.pixmap().get_color_4f(p)
675    }
676
677    /// Look up the pixel at `(x,y)` and return its alpha component, normalized to `[0..1]`. This is
678    /// roughly equivalent to `get_color().a()`, but can be more efficient (and more precise if the
679    /// pixels store more than 8 bits per component).
680    pub fn get_alpha_f(&self, p: impl Into<IPoint>) -> f32 {
681        self.pixmap().get_alpha_f(p)
682    }
683
684    /// Returns pixel address at `(x, y)`.
685    ///
686    /// Input is not validated: out of bounds values of `x` or `y`, or [`ColorType::Unknown`],
687    /// trigger an `assert()`. Returns `None` if [`ColorType`] is [`ColorType::Unknown`], or
688    /// [`PixelRef`] is `None`.
689    ///
690    /// Performs a lookup of pixel size; for better performance, call one of: `get_addr8()`,
691    /// `get_addr16()`, or `get_addr32()`.
692    ///
693    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_getAddr>
694    pub fn get_addr(&self, p: impl Into<IPoint>) -> *const ffi::c_void {
695        let p = p.into();
696        unsafe { self.native().getAddr(p.x, p.y) }
697    }
698
699    // TODO: get_addr_32(), get_addr_16(), get_addr_8()
700
701    /// Shares [`PixelRef`] with `dst`. Pixels are not copied; [`Bitmap`] and dst point to the same
702    /// pixels; dst [`Self::bounds()`] are set to the intersection of subset and the original
703    /// [`Self::bounds()`].
704    ///
705    /// Subset may be larger than [`Self::bounds()`]. Any area outside of [`Self::bounds()`] is
706    /// ignored.
707    ///
708    /// Any contents of dst are discarded.
709    ///
710    /// Return `false` if:
711    /// - dst is `None`
712    /// - [`PixelRef`] is `None`
713    /// - subset does not intersect [`Self::bounds()`]
714    ///
715    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_extractSubset>
716    pub fn extract_subset(&self, dst: &mut Self, subset: impl AsRef<IRect>) -> bool {
717        unsafe {
718            self.native()
719                .extractSubset(dst.native_mut(), subset.as_ref().native())
720        }
721    }
722
723    /// Copies a [`crate::Rect`] of pixels from [`Bitmap`] to `dst_pixels`. Copy starts at `(src_x,
724    /// src_y)`, and does not exceed [`Bitmap`] `(width(), height())`.
725    ///
726    /// `dst_info` specifies width, height, [`ColorType`], [`AlphaType`], and [`ColorSpace`] of
727    /// destination.  
728    /// `dst_row_bytes` specifics the gap from one destination row to the next. Returns `true` if
729    /// pixels are copied. Returns `false` if:
730    /// - `dst_info` has no address
731    /// - `dst_row_bytes` is less than `dst_info.min_row_bytes()`
732    /// - [`PixelRef`] is `None`
733    ///
734    /// Pixels are copied only if pixel conversion is possible. If [`Self::color_type()`] is
735    /// [`ColorType::Gray8`], or [`ColorType::Alpha8`]; `dst_info.color_type()` must match. If
736    /// [`Self::color_type()`] is [`ColorType::Gray8`], `dst_info.color_space()` must match. If
737    /// [`Self::alpha_type()`] is [`AlphaType::Opaque`], `dst_info.alpha_type()` must match. If
738    /// [`Self::color_space()`] is `None`, `dst_info.color_space()` must match. Returns `false`
739    /// if pixel conversion is not possible.
740    ///
741    /// `src_x` and `src_y` may be negative to copy only top or left of source. Returns `false` if
742    /// [`Self::width()`] or [`Self::height()`] is zero or negative. Returns `false` if `abs(src_x)`
743    /// `>=` [`Self::width()`], or if `abs(src_y) >=` [`Self::height()`].
744    ///
745    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_readPixels_2>
746    #[allow(clippy::missing_safety_doc)]
747    pub unsafe fn read_pixels(
748        &self,
749        dst_info: &ImageInfo,
750        dst_pixels: *mut ffi::c_void,
751        dst_row_bytes: usize,
752        src_x: i32,
753        src_y: i32,
754    ) -> bool {
755        unsafe {
756            self.native()
757                .readPixels(dst_info.native(), dst_pixels, dst_row_bytes, src_x, src_y)
758        }
759    }
760
761    // TODO: read_pixels(Pixmap)
762    // TODO: write_pixels(Pixmap)
763
764    /// Sets dst to alpha described by pixels. Returns `false` if `dst` cannot be written to or
765    /// `dst` pixels cannot be allocated.
766    ///
767    /// If `paint` is not `None` and contains [`crate::MaskFilter`], [`crate::MaskFilter`] generates
768    /// mask alpha from [`Bitmap`]. Uses `HeapAllocator` to reserve memory for `dst` [`PixelRef`].
769    /// Returns offset to top-left position for `dst` for alignment with [`Bitmap`]; `(0, 0)` unless
770    /// [`crate::MaskFilter`] generates mask.
771    pub fn extract_alpha(&self, dst: &mut Self, paint: Option<&Paint>) -> Option<IPoint> {
772        let mut offset = IPoint::default();
773        unsafe {
774            sb::C_SkBitmap_extractAlpha(
775                self.native(),
776                dst.native_mut(),
777                paint.native_ptr_or_null(),
778                offset.native_mut(),
779            )
780        }
781        .then_some(offset)
782    }
783
784    /// Copies [`Bitmap`] pixel address, row bytes, and [`ImageInfo`] to pixmap, if address is
785    /// available, and returns `Some(Pixmap)`. If pixel address is not available, return `None`
786    /// and leave pixmap unchanged.
787    ///
788    /// Example (C++): <https://fiddle.skia.org/c/@Bitmap_peekPixels>
789    pub fn peek_pixels(&self) -> Option<Pixmap> {
790        let mut pixmap = Pixmap::default();
791        unsafe { self.native().peekPixels(pixmap.native_mut()) }.then_some(pixmap)
792    }
793
794    /// Make a shader with the specified tiling, matrix and sampling.  
795    /// Defaults to clamp in both X and Y.
796    pub fn to_shader<'a>(
797        &self,
798        tile_modes: impl Into<Option<(TileMode, TileMode)>>,
799        sampling: impl Into<SamplingOptions>,
800        local_matrix: impl Into<Option<&'a Matrix>>,
801    ) -> Option<Shader> {
802        let tile_modes = tile_modes.into();
803        let sampling = sampling.into();
804        let local_matrix = local_matrix.into();
805        Shader::from_ptr(unsafe {
806            let tmx = tile_modes.map(|tm| tm.0).unwrap_or_default();
807            let tmy = tile_modes.map(|tm| tm.1).unwrap_or_default();
808            sb::C_SkBitmap_makeShader(
809                self.native(),
810                tmx,
811                tmy,
812                sampling.native(),
813                local_matrix.native_ptr_or_null(),
814            )
815        })
816    }
817
818    /// Returns a new image from the bitmap. If the bitmap is marked immutable, this will
819    /// share the pixel buffer. If not, it will make a copy of the pixels for the image.
820    pub fn as_image(&self) -> Image {
821        Image::from_ptr(unsafe { sb::C_SkBitmap_asImage(self.native()) }).unwrap()
822    }
823}
824
825#[cfg(test)]
826mod tests {
827    use super::TileMode;
828    use crate::{AlphaType, Bitmap, Canvas, ColorSpace, ColorType, ImageInfo, SamplingOptions};
829
830    #[test]
831    fn create_clone_and_drop() {
832        let bm = Bitmap::new();
833        #[allow(clippy::redundant_clone)]
834        let _bm2 = bm.clone();
835    }
836
837    #[test]
838    fn get_info() {
839        let bm = Bitmap::new();
840        let _info = bm.info();
841    }
842
843    #[test]
844    fn empty_bitmap_shader() {
845        let bm = Bitmap::new();
846        let _shader = bm.to_shader(None, SamplingOptions::default(), None);
847    }
848
849    #[test]
850    fn shader_with_tile_mode() {
851        let bm = Bitmap::new();
852        let _shader = bm.to_shader(
853            (TileMode::Decal, TileMode::Mirror),
854            SamplingOptions::default(),
855            None,
856        );
857    }
858
859    #[test]
860    fn test_get_subset() {
861        let bm = Bitmap::new();
862        let _ = bm.get_subset();
863    }
864
865    #[test]
866    fn test_pixel_ref_origin() {
867        let bm = Bitmap::new();
868        let _ = bm.pixel_ref_origin();
869    }
870
871    /// Test for: <https://github.com/rust-skia/rust-skia/issues/669>
872    #[test]
873    fn cant_get_a_canvas_for_a_non_drawable_bitmap() {
874        let info = ImageInfo::new(
875            (400, 400),
876            ColorType::BGRA8888,
877            AlphaType::Premul,
878            ColorSpace::new_srgb(),
879        );
880        let mut bitmap = Bitmap::new();
881        if !bitmap.set_info(&info, None) {
882            panic!("set_info failed");
883        }
884
885        let canvas = Canvas::from_bitmap(&bitmap, None);
886        assert!(canvas.is_none());
887    }
888}