skia_safe/core/
canvas.rs

1use std::{cell::UnsafeCell, ffi::CString, fmt, marker::PhantomData, mem, ops::Deref, ptr, slice};
2
3use sb::SkCanvas_FilterSpan;
4use skia_bindings::{
5    self as sb, SkAutoCanvasRestore, SkCanvas, SkCanvas_SaveLayerRec, SkColorSpace, SkImageFilter,
6    SkPaint, SkRect, U8CPU,
7};
8
9#[cfg(feature = "gpu")]
10use crate::gpu;
11use crate::{
12    prelude::*, scalar, Bitmap, BlendMode, ClipOp, Color, Color4f, Data, Drawable, FilterMode,
13    Font, GlyphId, IPoint, IRect, ISize, Image, ImageFilter, ImageInfo, Matrix, Paint, Path,
14    Picture, Pixmap, Point, QuickReject, RRect, RSXform, Rect, Region, SamplingOptions, Shader,
15    Surface, SurfaceProps, TextBlob, TextEncoding, TileMode, Vector, Vertices, M44,
16};
17use crate::{Arc, ColorSpace};
18
19pub use lattice::Lattice;
20
21bitflags! {
22    /// [`SaveLayerFlags`] provides options that may be used in any combination in [`SaveLayerRec`],
23    /// defining how layer allocated by [`Canvas::save_layer()`] operates. It may be set to zero,
24    /// [`PRESERVE_LCD_TEXT`], [`INIT_WITH_PREVIOUS`], or both flags.
25    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
26    pub struct SaveLayerFlags: u32 {
27        const PRESERVE_LCD_TEXT = sb::SkCanvas_SaveLayerFlagsSet_kPreserveLCDText_SaveLayerFlag as _;
28        /// initializes with previous contents
29        const INIT_WITH_PREVIOUS = sb::SkCanvas_SaveLayerFlagsSet_kInitWithPrevious_SaveLayerFlag as _;
30        const F16_COLOR_TYPE = sb::SkCanvas_SaveLayerFlagsSet_kF16ColorType as _;
31    }
32}
33
34/// [`SaveLayerRec`] contains the state used to create the layer.
35#[repr(C)]
36pub struct SaveLayerRec<'a> {
37    // We _must_ store _references_ to the native types here, because not all of them are native
38    // transmutable, like ImageFilter or Image, which are represented as ref counted pointers and so
39    // we would store a reference to a pointer only.
40    bounds: Option<&'a SkRect>,
41    paint: Option<&'a SkPaint>,
42    filters: SkCanvas_FilterSpan,
43    backdrop: Option<&'a SkImageFilter>,
44    backdrop_tile_mode: sb::SkTileMode,
45    color_space: Option<&'a SkColorSpace>,
46    flags: SaveLayerFlags,
47    experimental_backdrop_scale: scalar,
48}
49
50native_transmutable!(SkCanvas_SaveLayerRec, SaveLayerRec<'_>);
51
52impl Default for SaveLayerRec<'_> {
53    /// Sets [`Self::bounds`], [`Self::paint`], and [`Self::backdrop`] to `None`. Clears
54    /// [`Self::flags`].
55    ///
56    /// Returns empty [`SaveLayerRec`]
57    fn default() -> Self {
58        SaveLayerRec::construct(|slr| unsafe { sb::C_SkCanvas_SaveLayerRec_Construct(slr) })
59    }
60}
61
62impl Drop for SaveLayerRec<'_> {
63    fn drop(&mut self) {
64        unsafe { sb::C_SkCanvas_SaveLayerRec_destruct(self.native_mut()) }
65    }
66}
67
68impl fmt::Debug for SaveLayerRec<'_> {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_struct("SaveLayerRec")
71            .field("bounds", &self.bounds.map(Rect::from_native_ref))
72            .field("paint", &self.paint.map(Paint::from_native_ref))
73            .field(
74                "backdrop",
75                &ImageFilter::from_unshared_ptr_ref(&(self.backdrop.as_ptr_or_null() as *mut _)),
76            )
77            .field("backdrop_tile_mode", &self.backdrop_tile_mode)
78            .field(
79                "color_space",
80                &ColorSpace::from_unshared_ptr_ref(&(self.color_space.as_ptr_or_null() as *mut _)),
81            )
82            .field("flags", &self.flags)
83            .field(
84                "experimental_backdrop_scale",
85                &self.experimental_backdrop_scale,
86            )
87            .finish()
88    }
89}
90
91impl<'a> SaveLayerRec<'a> {
92    /// Hints at layer size limit
93    #[must_use]
94    pub fn bounds(mut self, bounds: &'a Rect) -> Self {
95        self.bounds = Some(bounds.native());
96        self
97    }
98
99    /// Modifies overlay
100    #[must_use]
101    pub fn paint(mut self, paint: &'a Paint) -> Self {
102        self.paint = Some(paint.native());
103        self
104    }
105
106    /// If not `None`, this triggers the same initialization behavior as setting
107    /// [`SaveLayerFlags::INIT_WITH_PREVIOUS`] on [`Self::flags`]: the current layer is copied into
108    /// the new layer, rather than initializing the new layer with transparent-black. This is then
109    /// filtered by [`Self::backdrop`] (respecting the current clip).
110    #[must_use]
111    pub fn backdrop(mut self, backdrop: &'a ImageFilter) -> Self {
112        self.backdrop = Some(backdrop.native());
113        self
114    }
115
116    /// If the layer is initialized with prior content (and/or with a backdrop filter) and this
117    /// would require sampling outside of the available backdrop, this is the tilemode applied
118    /// to the boundary of the prior layer's image.
119    #[must_use]
120    pub fn backdrop_tile_mode(mut self, backdrop_tile_mode: TileMode) -> Self {
121        self.backdrop_tile_mode = backdrop_tile_mode;
122        self
123    }
124
125    /// If not `None`, this triggers a color space conversion when the layer is restored. It
126    /// will be as if the layer's contents are drawn in this color space. Filters from
127    /// `backdrop` and `paint` will be applied in this color space.
128    pub fn color_space(mut self, color_space: &'a ColorSpace) -> Self {
129        self.color_space = Some(color_space.native());
130        self
131    }
132
133    /// Preserves LCD text, creates with prior layer contents
134    #[must_use]
135    pub fn flags(mut self, flags: SaveLayerFlags) -> Self {
136        self.flags = flags;
137        self
138    }
139}
140
141/// Selects if an array of points are drawn as discrete points, as lines, or as an open polygon.
142pub use sb::SkCanvas_PointMode as PointMode;
143variant_name!(PointMode::Polygon);
144
145/// [`SrcRectConstraint`] controls the behavior at the edge of source [`Rect`], provided to
146/// [`Canvas::draw_image_rect()`] when there is any filtering. If kStrict is set, then extra code is
147/// used to ensure it nevers samples outside of the src-rect.
148///
149/// [`SrcRectConstraint::Strict`] disables the use of mipmaps and anisotropic filtering.
150pub use sb::SkCanvas_SrcRectConstraint as SrcRectConstraint;
151variant_name!(SrcRectConstraint::Fast);
152
153/// Provides access to Canvas's pixels.
154///
155/// Returned by [`Canvas::access_top_layer_pixels()`]
156#[derive(Debug)]
157pub struct TopLayerPixels<'a> {
158    /// Address of pixels
159    pub pixels: &'a mut [u8],
160    /// Writable pixels' [`ImageInfo`]
161    pub info: ImageInfo,
162    /// Writable pixels' row bytes
163    pub row_bytes: usize,
164    /// [`Canvas`] top layer origin, its top-left corner
165    pub origin: IPoint,
166}
167
168/// Used to pass either a slice of [`Point`] or [`RSXform`] to [`Canvas::draw_glyphs_at`].
169#[derive(Clone, Debug)]
170pub enum GlyphPositions<'a> {
171    Points(&'a [Point]),
172    RSXforms(&'a [RSXform]),
173}
174
175impl<'a> From<&'a [Point]> for GlyphPositions<'a> {
176    fn from(points: &'a [Point]) -> Self {
177        Self::Points(points)
178    }
179}
180
181impl<'a> From<&'a [RSXform]> for GlyphPositions<'a> {
182    fn from(rs_xforms: &'a [RSXform]) -> Self {
183        Self::RSXforms(rs_xforms)
184    }
185}
186
187///  [`Canvas`] provides an interface for drawing, and how the drawing is clipped and transformed.
188///  [`Canvas`] contains a stack of [`Matrix`] and clip values.
189///
190///  [`Canvas`] and [`Paint`] together provide the state to draw into [`Surface`] or `Device`.
191///  Each [`Canvas`] draw call transforms the geometry of the object by the concatenation of all
192///  [`Matrix`] values in the stack. The transformed geometry is clipped by the intersection
193///  of all of clip values in the stack. The [`Canvas`] draw calls use [`Paint`] to supply drawing
194///  state such as color, [`crate::Typeface`], text size, stroke width, [`Shader`] and so on.
195///
196///  To draw to a pixel-based destination, create raster surface or GPU surface.
197///  Request [`Canvas`] from [`Surface`] to obtain the interface to draw.
198///  [`Canvas`] generated by raster surface draws to memory visible to the CPU.
199///  [`Canvas`] generated by GPU surface uses Vulkan or OpenGL to draw to the GPU.
200///
201///  To draw to a document, obtain [`Canvas`] from SVG canvas, document PDF, or
202///  [`crate::PictureRecorder`]. [`crate::Document`] based [`Canvas`] and other [`Canvas`]
203///  subclasses reference Device describing the destination.
204///
205///  [`Canvas`] can be constructed to draw to [`Bitmap`] without first creating raster surface.
206///  This approach may be deprecated in the future.
207#[repr(transparent)]
208pub struct Canvas(UnsafeCell<SkCanvas>);
209
210impl Canvas {
211    pub(self) fn native(&self) -> &SkCanvas {
212        unsafe { &*self.0.get() }
213    }
214
215    #[allow(clippy::mut_from_ref)]
216    pub(crate) fn native_mut(&self) -> &mut SkCanvas {
217        unsafe { &mut (*self.0.get()) }
218    }
219}
220
221impl fmt::Debug for Canvas {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        f.debug_struct("Canvas")
224            .field("image_info", &self.image_info())
225            .field("props", &self.props())
226            .field("base_layer_size", &self.base_layer_size())
227            .field("save_count", &self.save_count())
228            .field("local_clip_bounds", &self.local_clip_bounds())
229            .field("device_clip_bounds", &self.device_clip_bounds())
230            .field("local_to_device", &self.local_to_device())
231            .finish()
232    }
233}
234
235/// Represents a [`Canvas`] that is owned and dropped when it goes out of scope _and_ is bound to
236/// the lifetime of some other value (an array of pixels for example).
237///
238/// Access to the [`Canvas`] functions are resolved with the [`Deref`] trait.
239#[repr(transparent)]
240pub struct OwnedCanvas<'lt>(ptr::NonNull<Canvas>, PhantomData<&'lt ()>);
241
242impl Deref for OwnedCanvas<'_> {
243    type Target = Canvas;
244
245    fn deref(&self) -> &Self::Target {
246        unsafe { self.0.as_ref() }
247    }
248}
249
250impl Drop for OwnedCanvas<'_> {
251    /// Draws saved layers, if any.
252    /// Frees up resources used by [`Canvas`].
253    ///
254    /// example: <https://fiddle.skia.org/c/@Canvas_destructor>
255    fn drop(&mut self) {
256        unsafe { sb::C_SkCanvas_delete(self.native()) }
257    }
258}
259
260impl Default for OwnedCanvas<'_> {
261    /// Creates an empty [`Canvas`] with no backing device or pixels, with
262    /// a width and height of zero.
263    ///
264    /// Returns empty [`Canvas`]
265    ///
266    /// example: <https://fiddle.skia.org/c/@Canvas_empty_constructor>
267    fn default() -> Self {
268        let ptr = unsafe { sb::C_SkCanvas_newEmpty() };
269        Canvas::own_from_native_ptr(ptr).unwrap()
270    }
271}
272
273impl fmt::Debug for OwnedCanvas<'_> {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        f.debug_tuple("OwnedCanvas").field(self as &Canvas).finish()
276    }
277}
278
279impl Canvas {
280    /// Allocates raster [`Canvas`] that will draw directly into pixels.
281    ///
282    /// [`Canvas`] is returned if all parameters are valid.
283    /// Valid parameters include:
284    /// - `info` dimensions are zero or positive
285    /// - `info` contains [`crate::ColorType`] and [`crate::AlphaType`] supported by raster surface
286    /// - `row_bytes` is `None` or large enough to contain info width pixels of [`crate::ColorType`]
287    ///
288    /// Pass `None` for `row_bytes` to compute `row_bytes` from info width and size of pixel.
289    /// If `row_bytes` is not `None`, it must be equal to or greater than `info` width times
290    /// bytes required for [`crate::ColorType`].
291    ///
292    /// Pixel buffer size should be info height times computed `row_bytes`.
293    /// Pixels are not initialized.
294    /// To access pixels after drawing, call `flush()` or [`Self::peek_pixels()`].
295    ///
296    /// - `info` width, height, [`crate::ColorType`], [`crate::AlphaType`], [`crate::ColorSpace`],
297    ///   of raster surface; width, or height, or both, may be zero
298    /// - `pixels` pointer to destination pixels buffer
299    /// - `row_bytes` interval from one [`Surface`] row to the next, or zero
300    /// - `props` LCD striping orientation and setting for device independent fonts;
301    ///   may be `None`
302    ///
303    /// Returns [`OwnedCanvas`] if all parameters are valid; otherwise, `None`.
304    pub fn from_raster_direct<'pixels>(
305        info: &ImageInfo,
306        pixels: &'pixels mut [u8],
307        row_bytes: impl Into<Option<usize>>,
308        props: Option<&SurfaceProps>,
309    ) -> Option<OwnedCanvas<'pixels>> {
310        let row_bytes = row_bytes.into().unwrap_or_else(|| info.min_row_bytes());
311        if info.valid_pixels(row_bytes, pixels) {
312            let ptr = unsafe {
313                sb::C_SkCanvas_MakeRasterDirect(
314                    info.native(),
315                    pixels.as_mut_ptr() as _,
316                    row_bytes,
317                    props.native_ptr_or_null(),
318                )
319            };
320            Self::own_from_native_ptr(ptr)
321        } else {
322            None
323        }
324    }
325
326    /// Allocates raster [`Canvas`] specified by inline image specification. Subsequent [`Canvas`]
327    /// calls draw into pixels.
328    /// [`crate::ColorType`] is set to [`crate::ColorType::n32()`].
329    /// [`crate::AlphaType`] is set to [`crate::AlphaType::Premul`].
330    /// To access pixels after drawing, call `flush()` or [`Self::peek_pixels()`].
331    ///
332    /// [`OwnedCanvas`] is returned if all parameters are valid.
333    /// Valid parameters include:
334    /// - width and height are zero or positive
335    /// - `row_bytes` is zero or large enough to contain width pixels of [`crate::ColorType::n32()`]
336    ///
337    /// Pass `None` for `row_bytes` to compute `row_bytes` from width and size of pixel.
338    /// If `row_bytes` is greater than zero, it must be equal to or greater than width times bytes
339    /// required for [`crate::ColorType`].
340    ///
341    /// Pixel buffer size should be height times `row_bytes`.
342    ///
343    /// - `size` pixel column and row count on raster surface created; must both be zero or greater
344    /// - `pixels` pointer to destination pixels buffer; buffer size should be height times
345    ///   `row_bytes`
346    /// - `row_bytes` interval from one [`Surface`] row to the next, or zero
347    ///
348    /// Returns [`OwnedCanvas`] if all parameters are valid; otherwise, `None`
349    pub fn from_raster_direct_n32<'pixels>(
350        size: impl Into<ISize>,
351        pixels: &'pixels mut [u32],
352        row_bytes: impl Into<Option<usize>>,
353    ) -> Option<OwnedCanvas<'pixels>> {
354        let info = ImageInfo::new_n32_premul(size, None);
355        let pixels_ptr: *mut u8 = pixels.as_mut_ptr() as _;
356        let pixels_u8: &'pixels mut [u8] =
357            unsafe { slice::from_raw_parts_mut(pixels_ptr, mem::size_of_val(pixels)) };
358        Self::from_raster_direct(&info, pixels_u8, row_bytes, None)
359    }
360
361    /// Creates [`Canvas`] of the specified dimensions without a [`Surface`].
362    /// Used by subclasses with custom implementations for draw member functions.
363    ///
364    /// If props equals `None`, [`SurfaceProps`] are created with `SurfaceProps::InitType` settings,
365    /// which choose the pixel striping direction and order. Since a platform may dynamically change
366    /// its direction when the device is rotated, and since a platform may have multiple monitors
367    /// with different characteristics, it is best not to rely on this legacy behavior.
368    ///
369    /// - `size` with and height zero or greater
370    /// - `props` LCD striping orientation and setting for device independent fonts;
371    ///   may be `None`
372    ///
373    /// Returns [`Canvas`] placeholder with dimensions
374    ///
375    /// example: <https://fiddle.skia.org/c/@Canvas_int_int_const_SkSurfaceProps_star>
376    #[allow(clippy::new_ret_no_self)]
377    pub fn new<'lt>(
378        size: impl Into<ISize>,
379        props: Option<&SurfaceProps>,
380    ) -> Option<OwnedCanvas<'lt>> {
381        let size = size.into();
382        if size.width >= 0 && size.height >= 0 {
383            let ptr = unsafe {
384                sb::C_SkCanvas_newWidthHeightAndProps(
385                    size.width,
386                    size.height,
387                    props.native_ptr_or_null(),
388                )
389            };
390            Canvas::own_from_native_ptr(ptr)
391        } else {
392            None
393        }
394    }
395
396    /// Constructs a canvas that draws into bitmap.
397    /// Use props to match the device characteristics, like LCD striping.
398    ///
399    /// bitmap is copied so that subsequently editing bitmap will not affect constructed [`Canvas`].
400    ///
401    /// - `bitmap` width, height, [`crate::ColorType`], [`crate::AlphaType`], and pixel storage of
402    ///   raster surface
403    /// - `props` order and orientation of RGB striping; and whether to use device independent fonts
404    ///
405    /// Returns [`Canvas`] that can be used to draw into bitmap
406    ///
407    /// example: <https://fiddle.skia.org/c/@Canvas_const_SkBitmap_const_SkSurfaceProps>
408    pub fn from_bitmap<'lt>(
409        bitmap: &Bitmap,
410        props: Option<&SurfaceProps>,
411    ) -> Option<OwnedCanvas<'lt>> {
412        // <https://github.com/rust-skia/rust-skia/issues/669>
413        if !bitmap.is_ready_to_draw() {
414            return None;
415        }
416        let props_ptr = props.native_ptr_or_null();
417        let ptr = if props_ptr.is_null() {
418            unsafe { sb::C_SkCanvas_newFromBitmap(bitmap.native()) }
419        } else {
420            unsafe { sb::C_SkCanvas_newFromBitmapAndProps(bitmap.native(), props_ptr) }
421        };
422        Canvas::own_from_native_ptr(ptr)
423    }
424
425    /// Returns [`ImageInfo`] for [`Canvas`]. If [`Canvas`] is not associated with raster surface or
426    /// GPU surface, returned [`crate::ColorType`] is set to [`crate::ColorType::Unknown`]
427    ///
428    /// Returns dimensions and [`crate::ColorType`] of [`Canvas`]
429    ///
430    /// example: <https://fiddle.skia.org/c/@Canvas_imageInfo>
431    pub fn image_info(&self) -> ImageInfo {
432        let mut ii = ImageInfo::default();
433        unsafe { sb::C_SkCanvas_imageInfo(self.native(), ii.native_mut()) };
434        ii
435    }
436
437    /// Copies [`SurfaceProps`], if [`Canvas`] is associated with raster surface or GPU surface, and
438    /// returns `true`. Otherwise, returns `false` and leave props unchanged.
439    ///
440    /// - `props` storage for writable [`SurfaceProps`]
441    ///
442    /// Returns `true` if [`SurfaceProps`] was copied
443    ///
444    /// example: <https://fiddle.skia.org/c/@Canvas_getProps>
445    pub fn props(&self) -> Option<SurfaceProps> {
446        let mut sp = SurfaceProps::default();
447        unsafe { self.native().getProps(sp.native_mut()) }.then_some(sp)
448    }
449
450    /// Returns the [`SurfaceProps`] associated with the canvas (i.e., at the base of the layer
451    /// stack).
452    pub fn base_props(&self) -> SurfaceProps {
453        SurfaceProps::from_native_c(unsafe { self.native().getBaseProps() })
454    }
455
456    /// Returns the [`SurfaceProps`] associated with the canvas that are currently active (i.e., at
457    /// the top of the layer stack). This can differ from [`Self::base_props`] depending on the flags
458    /// passed to saveLayer (see [`SaveLayerFlags`]).
459    pub fn top_props(&self) -> SurfaceProps {
460        SurfaceProps::from_native_c(unsafe { self.native().getTopProps() })
461    }
462
463    /// Gets the size of the base or root layer in global canvas coordinates. The
464    /// origin of the base layer is always (0,0). The area available for drawing may be
465    /// smaller (due to clipping or saveLayer).
466    ///
467    /// Returns integral size of base layer
468    ///
469    /// example: <https://fiddle.skia.org/c/@Canvas_getBaseLayerSize>
470    pub fn base_layer_size(&self) -> ISize {
471        let mut size = ISize::default();
472        unsafe { sb::C_SkCanvas_getBaseLayerSize(self.native(), size.native_mut()) }
473        size
474    }
475
476    /// Creates [`Surface`] matching info and props, and associates it with [`Canvas`].
477    /// Returns `None` if no match found.
478    ///
479    /// If props is `None`, matches [`SurfaceProps`] in [`Canvas`]. If props is `None` and
480    /// [`Canvas`] does not have [`SurfaceProps`], creates [`Surface`] with default
481    /// [`SurfaceProps`].
482    ///
483    /// - `info` width, height, [`crate::ColorType`], [`crate::AlphaType`], and
484    ///   [`crate::ColorSpace`]
485    /// - `props` [`SurfaceProps`] to match; may be `None` to match [`Canvas`]
486    ///
487    /// Returns [`Surface`] matching info and props, or `None` if no match is available
488    ///
489    /// example: <https://fiddle.skia.org/c/@Canvas_makeSurface>
490    pub fn new_surface(&self, info: &ImageInfo, props: Option<&SurfaceProps>) -> Option<Surface> {
491        Surface::from_ptr(unsafe {
492            sb::C_SkCanvas_makeSurface(self.native_mut(), info.native(), props.native_ptr_or_null())
493        })
494    }
495
496    /// Returns Ganesh context of the GPU surface associated with [`Canvas`].
497    ///
498    /// Returns GPU context, if available; `None` otherwise
499    ///
500    /// example: <https://fiddle.skia.org/c/@Canvas_recordingContext>
501    #[cfg(feature = "gpu")]
502    pub fn recording_context(&self) -> Option<gpu::RecordingContext> {
503        gpu::RecordingContext::from_unshared_ptr(unsafe {
504            sb::C_SkCanvas_recordingContext(self.native())
505        })
506    }
507
508    /// Returns the [`gpu::DirectContext`].
509    /// This is a rust-skia helper for that makes it simpler to call [`Image::encode`].
510    #[cfg(feature = "gpu")]
511    pub fn direct_context(&self) -> Option<gpu::DirectContext> {
512        self.recording_context()
513            .and_then(|mut c| c.as_direct_context())
514    }
515
516    /// Sometimes a canvas is owned by a surface. If it is, [`Self::surface()`] will return a bare
517    /// pointer to that surface, else this will return `None`.
518    ///
519    /// # Safety
520    /// This function is unsafe because it is not clear how exactly the lifetime of the canvas
521    /// relates to surface returned.
522    /// See also [`OwnedCanvas`], [`RCHandle<SkSurface>::canvas()`].
523    pub unsafe fn surface(&self) -> Option<Surface> {
524        // TODO: It might be possible to make this safe by returning a _kind of_ reference to the
525        //       Surface that can not be cloned and stays bound to the lifetime of canvas.
526        //       But even then, the Surface might exist twice then, which is confusing, but
527        //       probably safe, because the first instance is borrowed by the canvas.
528        Surface::from_unshared_ptr(self.native().getSurface())
529    }
530
531    /// Returns the pixel base address, [`ImageInfo`], `row_bytes`, and origin if the pixels
532    /// can be read directly.
533    ///
534    /// - `info` storage for writable pixels' [`ImageInfo`]
535    /// - `row_bytes` storage for writable pixels' row bytes
536    /// - `origin` storage for [`Canvas`] top layer origin, its top-left corner
537    ///
538    /// Returns address of pixels, or `None` if inaccessible
539    ///
540    /// example: <https://fiddle.skia.org/c/@Canvas_accessTopLayerPixels_a>
541    /// example: <https://fiddle.skia.org/c/@Canvas_accessTopLayerPixels_b>
542    pub fn access_top_layer_pixels(&self) -> Option<TopLayerPixels> {
543        let mut info = ImageInfo::default();
544        let mut row_bytes = 0;
545        let mut origin = IPoint::default();
546        let ptr = unsafe {
547            self.native_mut().accessTopLayerPixels(
548                info.native_mut(),
549                &mut row_bytes,
550                origin.native_mut(),
551            )
552        };
553        if !ptr.is_null() {
554            let size = info.compute_byte_size(row_bytes);
555            let pixels = unsafe { slice::from_raw_parts_mut(ptr as _, size) };
556            Some(TopLayerPixels {
557                pixels,
558                info,
559                row_bytes,
560                origin,
561            })
562        } else {
563            None
564        }
565    }
566
567    // TODO: accessTopRasterHandle()
568
569    /// Returns `true` if [`Canvas`] has direct access to its pixels.
570    ///
571    /// Pixels are readable when `Device` is raster. Pixels are not readable when [`Canvas`] is
572    /// returned from GPU surface, returned by [`crate::Document::begin_page()`], returned by
573    /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
574    /// class like `DebugCanvas`.
575    ///
576    /// pixmap is valid only while [`Canvas`] is in scope and unchanged. Any [`Canvas`] or
577    /// [`Surface`] call may invalidate the pixmap values.
578    ///
579    /// Returns [`Pixmap`] if [`Canvas`] has direct access to pixels
580    ///
581    /// example: <https://fiddle.skia.org/c/@Canvas_peekPixels>
582    pub fn peek_pixels(&self) -> Option<Pixmap> {
583        let mut pixmap = Pixmap::default();
584        unsafe { self.native_mut().peekPixels(pixmap.native_mut()) }.then_some(pixmap)
585    }
586
587    /// Copies [`Rect`] of pixels from [`Canvas`] into `dst_pixels`. [`Matrix`] and clip are
588    /// ignored.
589    ///
590    /// Source [`Rect`] corners are `src_point` and `(image_info().width(), image_info().height())`.
591    /// Destination [`Rect`] corners are `(0, 0)` and `(dst_Info.width(), dst_info.height())`.
592    /// Copies each readable pixel intersecting both rectangles, without scaling,
593    /// converting to `dst_info.color_type()` and `dst_info.alpha_type()` if required.
594    ///
595    /// Pixels are readable when `Device` is raster, or backed by a GPU.
596    /// Pixels are not readable when [`Canvas`] is returned by [`crate::Document::begin_page()`],
597    /// returned by [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a
598    /// utility class like `DebugCanvas`.
599    ///
600    /// The destination pixel storage must be allocated by the caller.
601    ///
602    /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
603    /// do not match. Only pixels within both source and destination rectangles
604    /// are copied. `dst_pixels` contents outside [`Rect`] intersection are unchanged.
605    ///
606    /// Pass negative values for `src_point.x` or `src_point.y` to offset pixels across or down
607    /// destination.
608    ///
609    /// Does not copy, and returns `false` if:
610    /// - Source and destination rectangles do not intersect.
611    /// - [`Canvas`] pixels could not be converted to `dst_info.color_type()` or
612    ///   `dst_info.alpha_type()`.
613    /// - [`Canvas`] pixels are not readable; for instance, [`Canvas`] is document-based.
614    /// - `dst_row_bytes` is too small to contain one row of pixels.
615    ///
616    /// - `dst_info` width, height, [`crate::ColorType`], and [`crate::AlphaType`] of dstPixels
617    /// - `dst_pixels` storage for pixels; `dst_info.height()` times `dst_row_bytes`, or larger
618    /// - `dst_row_bytes` size of one destination row; `dst_info.width()` times pixel size, or
619    ///   larger
620    /// - `src_point` offset into readable pixels; may be negative
621    ///
622    /// Returns `true` if pixels were copied
623    #[must_use]
624    pub fn read_pixels(
625        &self,
626        dst_info: &ImageInfo,
627        dst_pixels: &mut [u8],
628        dst_row_bytes: usize,
629        src_point: impl Into<IPoint>,
630    ) -> bool {
631        let src_point = src_point.into();
632        let required_size = dst_info.compute_byte_size(dst_row_bytes);
633        (dst_pixels.len() >= required_size)
634            && unsafe {
635                self.native_mut().readPixels(
636                    dst_info.native(),
637                    dst_pixels.as_mut_ptr() as _,
638                    dst_row_bytes,
639                    src_point.x,
640                    src_point.y,
641                )
642            }
643    }
644
645    /// Copies [`Rect`] of pixels from [`Canvas`] into pixmap. [`Matrix`] and clip are
646    /// ignored.
647    ///
648    /// Source [`Rect`] corners are `(src.x, src.y)` and `(image_info().width(),
649    /// image_info().height())`.
650    /// Destination [`Rect`] corners are `(0, 0)` and `(pixmap.width(), pixmap.height())`.
651    /// Copies each readable pixel intersecting both rectangles, without scaling,
652    /// converting to `pixmap.color_type()` and `pixmap.alpha_type()` if required.
653    ///
654    /// Pixels are readable when `Device` is raster, or backed by a GPU. Pixels are not readable
655    /// when [`Canvas`] is returned by [`crate::Document::begin_page()`], returned by
656    /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
657    /// class like `DebugCanvas`.
658    ///
659    /// Caller must allocate pixel storage in pixmap if needed.
660    ///
661    /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`] do not
662    /// match. Only pixels within both source and destination [`Rect`] are copied. pixmap pixels
663    /// contents outside [`Rect`] intersection are unchanged.
664    ///
665    /// Pass negative values for `src.x` or `src.y` to offset pixels across or down pixmap.
666    ///
667    /// Does not copy, and returns `false` if:
668    /// - Source and destination rectangles do not intersect.
669    /// - [`Canvas`] pixels could not be converted to `pixmap.color_type()` or
670    ///   `pixmap.alpha_type()`.
671    /// - [`Canvas`] pixels are not readable; for instance, [`Canvas`] is document-based.
672    /// - [`Pixmap`] pixels could not be allocated.
673    /// - `pixmap.row_bytes()` is too small to contain one row of pixels.
674    ///
675    /// - `pixmap` storage for pixels copied from [`Canvas`]
676    /// - `src` offset into readable pixels ; may be negative
677    ///
678    /// Returns `true` if pixels were copied
679    ///
680    /// example: <https://fiddle.skia.org/c/@Canvas_readPixels_2>
681    #[must_use]
682    pub fn read_pixels_to_pixmap(&self, pixmap: &mut Pixmap, src: impl Into<IPoint>) -> bool {
683        let src = src.into();
684        unsafe { self.native_mut().readPixels1(pixmap.native(), src.x, src.y) }
685    }
686
687    /// Copies [`Rect`] of pixels from [`Canvas`] into bitmap. [`Matrix`] and clip are
688    /// ignored.
689    ///
690    /// Source [`Rect`] corners are `(src.x, src.y)` and `(image_info().width(),
691    /// image_info().height())`.
692    /// Destination [`Rect`] corners are `(0, 0)` and `(bitmap.width(), bitmap.height())`.
693    /// Copies each readable pixel intersecting both rectangles, without scaling,
694    /// converting to `bitmap.color_type()` and `bitmap.alpha_type()` if required.
695    ///
696    /// Pixels are readable when `Device` is raster, or backed by a GPU. Pixels are not readable
697    /// when [`Canvas`] is returned by [`crate::Document::begin_page()`], returned by
698    /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
699    /// class like DebugCanvas.
700    ///
701    /// Caller must allocate pixel storage in bitmap if needed.
702    ///
703    /// [`Bitmap`] values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
704    /// do not match. Only pixels within both source and destination rectangles
705    /// are copied. [`Bitmap`] pixels outside [`Rect`] intersection are unchanged.
706    ///
707    /// Pass negative values for srcX or srcY to offset pixels across or down bitmap.
708    ///
709    /// Does not copy, and returns `false` if:
710    /// - Source and destination rectangles do not intersect.
711    /// - [`Canvas`] pixels could not be converted to `bitmap.color_type()` or
712    ///   `bitmap.alpha_type()`.
713    /// - [`Canvas`] pixels are not readable; for instance, [`Canvas`] is document-based.
714    /// - bitmap pixels could not be allocated.
715    /// - `bitmap.row_bytes()` is too small to contain one row of pixels.
716    ///
717    /// - `bitmap` storage for pixels copied from [`Canvas`]
718    /// - `src` offset into readable pixels; may be negative
719    ///
720    /// Returns `true` if pixels were copied
721    ///
722    /// example: <https://fiddle.skia.org/c/@Canvas_readPixels_3>
723    #[must_use]
724    pub fn read_pixels_to_bitmap(&self, bitmap: &mut Bitmap, src: impl Into<IPoint>) -> bool {
725        let src = src.into();
726        unsafe {
727            self.native_mut()
728                .readPixels2(bitmap.native_mut(), src.x, src.y)
729        }
730    }
731
732    /// Copies [`Rect`] from pixels to [`Canvas`]. [`Matrix`] and clip are ignored.
733    /// Source [`Rect`] corners are `(0, 0)` and `(info.width(), info.height())`.
734    /// Destination [`Rect`] corners are `(offset.x, offset.y)` and
735    /// `(image_info().width(), image_info().height())`.
736    ///
737    /// Copies each readable pixel intersecting both rectangles, without scaling,
738    /// converting to `image_info().color_type()` and `image_info().alpha_type()` if required.
739    ///
740    /// Pixels are writable when `Device` is raster, or backed by a GPU.
741    /// Pixels are not writable when [`Canvas`] is returned by [`crate::Document::begin_page()`],
742    /// returned by [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a
743    /// utility class like `DebugCanvas`.
744    ///
745    /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
746    /// do not match. Only pixels within both source and destination rectangles
747    /// are copied. [`Canvas`] pixels outside [`Rect`] intersection are unchanged.
748    ///
749    /// Pass negative values for `offset.x` or `offset.y` to offset pixels to the left or
750    /// above [`Canvas`] pixels.
751    ///
752    /// Does not copy, and returns `false` if:
753    /// - Source and destination rectangles do not intersect.
754    /// - pixels could not be converted to [`Canvas`] `image_info().color_type()` or
755    ///   `image_info().alpha_type()`.
756    /// - [`Canvas`] pixels are not writable; for instance, [`Canvas`] is document-based.
757    /// - `row_bytes` is too small to contain one row of pixels.
758    ///
759    /// - `info` width, height, [`crate::ColorType`], and [`crate::AlphaType`] of pixels
760    /// - `pixels` pixels to copy, of size `info.height()` times `row_bytes`, or larger
761    /// - `row_bytes` size of one row of pixels; info.width() times pixel size, or larger
762    /// - `offset` offset into [`Canvas`] writable pixels; may be negative
763    ///
764    /// Returns `true` if pixels were written to [`Canvas`]
765    ///
766    /// example: <https://fiddle.skia.org/c/@Canvas_writePixels>
767    #[must_use]
768    pub fn write_pixels(
769        &self,
770        info: &ImageInfo,
771        pixels: &[u8],
772        row_bytes: usize,
773        offset: impl Into<IPoint>,
774    ) -> bool {
775        let offset = offset.into();
776        let required_size = info.compute_byte_size(row_bytes);
777        (pixels.len() >= required_size)
778            && unsafe {
779                self.native_mut().writePixels(
780                    info.native(),
781                    pixels.as_ptr() as _,
782                    row_bytes,
783                    offset.x,
784                    offset.y,
785                )
786            }
787    }
788
789    /// Copies [`Rect`] from pixels to [`Canvas`]. [`Matrix`] and clip are ignored.
790    /// Source [`Rect`] corners are `(0, 0)` and `(bitmap.width(), bitmap.height())`.
791    ///
792    /// Destination [`Rect`] corners are `(offset.x, offset.y)` and
793    /// `(image_info().width(), image_info().height())`.
794    ///
795    /// Copies each readable pixel intersecting both rectangles, without scaling,
796    /// converting to `image_info().color_type()` and `image_info().alpha_type()` if required.
797    ///
798    /// Pixels are writable when `Device` is raster, or backed by a GPU. Pixels are not writable
799    /// when [`Canvas`] is returned by [`crate::Document::begin_page()`], returned by
800    /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
801    /// class like `DebugCanvas`.
802    ///
803    /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
804    /// do not match. Only pixels within both source and destination rectangles
805    /// are copied. [`Canvas`] pixels outside [`Rect`] intersection are unchanged.
806    ///
807    /// Pass negative values for `offset` to offset pixels to the left or
808    /// above [`Canvas`] pixels.
809    ///
810    /// Does not copy, and returns `false` if:
811    /// - Source and destination rectangles do not intersect.
812    /// - bitmap does not have allocated pixels.
813    /// - bitmap pixels could not be converted to [`Canvas`] `image_info().color_type()` or
814    ///   `image_info().alpha_type()`.
815    /// - [`Canvas`] pixels are not writable; for instance, [`Canvas`] is document based.
816    /// - bitmap pixels are inaccessible; for instance, bitmap wraps a texture.
817    ///
818    /// - `bitmap` contains pixels copied to [`Canvas`]
819    /// - `offset` offset into [`Canvas`] writable pixels; may be negative
820    ///
821    /// Returns `true` if pixels were written to [`Canvas`]
822    ///
823    /// example: <https://fiddle.skia.org/c/@Canvas_writePixels_2>
824    /// example: <https://fiddle.skia.org/c/@State_Stack_a>
825    /// example: <https://fiddle.skia.org/c/@State_Stack_b>
826    #[must_use]
827    pub fn write_pixels_from_bitmap(&self, bitmap: &Bitmap, offset: impl Into<IPoint>) -> bool {
828        let offset = offset.into();
829        unsafe {
830            self.native_mut()
831                .writePixels1(bitmap.native(), offset.x, offset.y)
832        }
833    }
834
835    /// Saves [`Matrix`] and clip.
836    /// Calling [`Self::restore()`] discards changes to [`Matrix`] and clip,
837    /// restoring the [`Matrix`] and clip to their state when [`Self::save()`] was called.
838    ///
839    /// [`Matrix`] may be changed by [`Self::translate()`], [`Self::scale()`], [`Self::rotate()`],
840    /// [`Self::skew()`], [`Self::concat()`], [`Self::set_matrix()`], and [`Self::reset_matrix()`].
841    /// Clip may be changed by [`Self::clip_rect()`], [`Self::clip_rrect()`], [`Self::clip_path()`],
842    /// [`Self::clip_region()`].
843    ///
844    /// Saved [`Canvas`] state is put on a stack; multiple calls to [`Self::save()`] should be
845    /// balance by an equal number of calls to [`Self::restore()`].
846    ///
847    /// Call [`Self::restore_to_count()`] with result to restore this and subsequent saves.
848    ///
849    /// Returns depth of saved stack
850    ///
851    /// example: <https://fiddle.skia.org/c/@Canvas_save>
852    pub fn save(&self) -> usize {
853        unsafe { self.native_mut().save().try_into().unwrap() }
854    }
855
856    // The save_layer(bounds, paint) variants have been replaced by SaveLayerRec.
857
858    /// Saves [`Matrix`] and clip, and allocates [`Surface`] for subsequent drawing.
859    ///
860    /// Calling [`Self::restore()`] discards changes to [`Matrix`] and clip, and blends layer with
861    /// alpha opacity onto prior layer.
862    ///
863    /// [`Matrix`] may be changed by [`Self::translate()`], [`Self::scale()`], [`Self::rotate()`],
864    /// [`Self::skew()`], [`Self::concat()`], [`Self::set_matrix()`], and [`Self::reset_matrix()`].
865    /// Clip may be changed by [`Self::clip_rect()`], [`Self::clip_rrect()`], [`Self::clip_path()`],
866    /// [`Self::clip_region()`].
867    ///
868    /// [`Rect`] bounds suggests but does not define layer size. To clip drawing to a specific
869    /// rectangle, use [`Self::clip_rect()`].
870    ///
871    /// alpha of zero is fully transparent, 1.0 is fully opaque.
872    ///
873    /// Call [`Self::restore_to_count()`] with result to restore this and subsequent saves.
874    ///
875    /// - `bounds` hint to limit the size of layer; may be `None`
876    /// - `alpha` opacity of layer
877    ///
878    /// Returns depth of saved stack
879    ///
880    /// example: <https://fiddle.skia.org/c/@Canvas_saveLayerAlpha>
881    pub fn save_layer_alpha_f(&self, bounds: impl Into<Option<Rect>>, alpha: f32) -> usize {
882        unsafe {
883            self.native_mut()
884                .saveLayerAlphaf(bounds.into().native().as_ptr_or_null(), alpha)
885        }
886        .try_into()
887        .unwrap()
888    }
889
890    /// Helper that accepts an int between 0 and 255, and divides it by 255.0
891    pub fn save_layer_alpha(&self, bounds: impl Into<Option<Rect>>, alpha: U8CPU) -> usize {
892        self.save_layer_alpha_f(bounds, alpha as f32 * (1.0 / 255.0))
893    }
894
895    /// Saves [`Matrix`] and clip, and allocates [`Surface`] for subsequent drawing.
896    ///
897    /// Calling [`Self::restore()`] discards changes to [`Matrix`] and clip,
898    /// and blends [`Surface`] with alpha opacity onto the prior layer.
899    ///
900    /// [`Matrix`] may be changed by [`Self::translate()`], [`Self::scale()`], [`Self::rotate()`],
901    /// [`Self::skew()`], [`Self::concat()`], [`Self::set_matrix()`], and [`Self::reset_matrix()`].
902    /// Clip may be changed by [`Self::clip_rect()`], [`Self::clip_rrect()`], [`Self::clip_path()`],
903    /// [`Self::clip_region()`].
904    ///
905    /// [`SaveLayerRec`] contains the state used to create the layer.
906    ///
907    /// Call [`Self::restore_to_count()`] with result to restore this and subsequent saves.
908    ///
909    /// - `layer_rec` layer state
910    ///
911    /// Returns depth of save state stack before this call was made.
912    ///
913    /// example: <https://fiddle.skia.org/c/@Canvas_saveLayer_3>
914    pub fn save_layer(&self, layer_rec: &SaveLayerRec) -> usize {
915        unsafe { self.native_mut().saveLayer1(layer_rec.native()) }
916            .try_into()
917            .unwrap()
918    }
919
920    /// Removes changes to [`Matrix`] and clip since [`Canvas`] state was
921    /// last saved. The state is removed from the stack.
922    ///
923    /// Does nothing if the stack is empty.
924    ///
925    /// example: <https://fiddle.skia.org/c/@AutoCanvasRestore_restore>
926    ///
927    /// example: <https://fiddle.skia.org/c/@Canvas_restore>
928    pub fn restore(&self) -> &Self {
929        unsafe { self.native_mut().restore() };
930        self
931    }
932
933    /// Returns the number of saved states, each containing: [`Matrix`] and clip.
934    /// Equals the number of [`Self::save()`] calls less the number of [`Self::restore()`] calls
935    /// plus one.
936    /// The save count of a new canvas is one.
937    ///
938    /// Returns depth of save state stack
939    ///
940    /// example: <https://fiddle.skia.org/c/@Canvas_getSaveCount>
941    pub fn save_count(&self) -> usize {
942        unsafe { self.native().getSaveCount() }.try_into().unwrap()
943    }
944
945    /// Restores state to [`Matrix`] and clip values when [`Self::save()`], [`Self::save_layer()`],
946    /// or [`Self::save_layer_alpha()`] returned `save_count`.
947    ///
948    /// Does nothing if `save_count` is greater than state stack count.
949    /// Restores state to initial values if `save_count` is less than or equal to one.
950    ///
951    /// - `saveCount` depth of state stack to restore
952    ///
953    /// example: <https://fiddle.skia.org/c/@Canvas_restoreToCount>
954    pub fn restore_to_count(&self, save_count: usize) -> &Self {
955        unsafe {
956            self.native_mut()
957                .restoreToCount(save_count.try_into().unwrap())
958        }
959        self
960    }
961
962    /// Translates [`Matrix`] by `d`.
963    ///
964    /// Mathematically, replaces [`Matrix`] with a translation matrix premultiplied with [`Matrix`].
965    ///
966    /// This has the effect of moving the drawing by `(d.x, d.y)` before transforming the result
967    /// with [`Matrix`].
968    ///
969    /// - `d` distance to translate
970    ///
971    /// example: <https://fiddle.skia.org/c/@Canvas_translate>
972    pub fn translate(&self, d: impl Into<Vector>) -> &Self {
973        let d = d.into();
974        unsafe { self.native_mut().translate(d.x, d.y) }
975        self
976    }
977
978    /// Scales [`Matrix`] by `sx` on the x-axis and `sy` on the y-axis.
979    ///
980    /// Mathematically, replaces [`Matrix`] with a scale matrix premultiplied with [`Matrix`].
981    ///
982    /// This has the effect of scaling the drawing by `(sx, sy)` before transforming the result with
983    /// [`Matrix`].
984    ///
985    /// - `sx` amount to scale on x-axis
986    /// - `sy` amount to scale on y-axis
987    ///
988    /// example: <https://fiddle.skia.org/c/@Canvas_scale>
989    pub fn scale(&self, (sx, sy): (scalar, scalar)) -> &Self {
990        unsafe { self.native_mut().scale(sx, sy) }
991        self
992    }
993
994    /// Rotates [`Matrix`] by degrees about a point at `(p.x, p.y)`. Positive degrees rotates
995    /// clockwise.
996    ///
997    /// Mathematically, constructs a rotation matrix; premultiplies the rotation matrix by a
998    /// translation matrix; then replaces [`Matrix`] with the resulting matrix premultiplied with
999    /// [`Matrix`].
1000    ///
1001    /// This has the effect of rotating the drawing about a given point before transforming the
1002    /// result with [`Matrix`].
1003    ///
1004    /// - `degrees` amount to rotate, in degrees
1005    /// - `p` the point to rotate about
1006    ///
1007    /// example: <https://fiddle.skia.org/c/@Canvas_rotate_2>
1008    pub fn rotate(&self, degrees: scalar, p: Option<Point>) -> &Self {
1009        unsafe {
1010            match p {
1011                Some(point) => self.native_mut().rotate1(degrees, point.x, point.y),
1012                None => self.native_mut().rotate(degrees),
1013            }
1014        }
1015        self
1016    }
1017
1018    /// Skews [`Matrix`] by `sx` on the x-axis and `sy` on the y-axis. A positive value of `sx`
1019    /// skews the drawing right as y-axis values increase; a positive value of `sy` skews the
1020    /// drawing down as x-axis values increase.
1021    ///
1022    /// Mathematically, replaces [`Matrix`] with a skew matrix premultiplied with [`Matrix`].
1023    ///
1024    /// This has the effect of skewing the drawing by `(sx, sy)` before transforming the result with
1025    /// [`Matrix`].
1026    ///
1027    /// - `sx` amount to skew on x-axis
1028    /// - `sy` amount to skew on y-axis
1029    ///
1030    /// example: <https://fiddle.skia.org/c/@Canvas_skew>
1031    pub fn skew(&self, (sx, sy): (scalar, scalar)) -> &Self {
1032        unsafe { self.native_mut().skew(sx, sy) }
1033        self
1034    }
1035
1036    /// Replaces [`Matrix`] with matrix premultiplied with existing [`Matrix`].
1037    ///
1038    /// This has the effect of transforming the drawn geometry by matrix, before transforming the
1039    /// result with existing [`Matrix`].
1040    ///
1041    /// - `matrix` matrix to premultiply with existing [`Matrix`]
1042    ///
1043    /// example: <https://fiddle.skia.org/c/@Canvas_concat>
1044    pub fn concat(&self, matrix: &Matrix) -> &Self {
1045        unsafe { self.native_mut().concat(matrix.native()) }
1046        self
1047    }
1048
1049    pub fn concat_44(&self, m: &M44) -> &Self {
1050        unsafe { self.native_mut().concat1(m.native()) }
1051        self
1052    }
1053
1054    /// Replaces [`Matrix`] with `matrix`.
1055    /// Unlike [`Self::concat()`], any prior matrix state is overwritten.
1056    ///
1057    /// - `matrix` matrix to copy, replacing existing [`Matrix`]
1058    ///
1059    /// example: <https://fiddle.skia.org/c/@Canvas_setMatrix>
1060    pub fn set_matrix(&self, matrix: &M44) -> &Self {
1061        unsafe { self.native_mut().setMatrix(matrix.native()) }
1062        self
1063    }
1064
1065    /// Sets [`Matrix`] to the identity matrix.
1066    /// Any prior matrix state is overwritten.
1067    ///
1068    /// example: <https://fiddle.skia.org/c/@Canvas_resetMatrix>
1069    pub fn reset_matrix(&self) -> &Self {
1070        unsafe { self.native_mut().resetMatrix() }
1071        self
1072    }
1073
1074    /// Replaces clip with the intersection or difference of clip and `rect`,
1075    /// with an aliased or anti-aliased clip edge. `rect` is transformed by [`Matrix`]
1076    /// before it is combined with clip.
1077    ///
1078    /// - `rect` [`Rect`] to combine with clip
1079    /// - `op` [`ClipOp`] to apply to clip
1080    /// - `do_anti_alias` `true` if clip is to be anti-aliased
1081    ///
1082    /// example: <https://fiddle.skia.org/c/@Canvas_clipRect>
1083    pub fn clip_rect(
1084        &self,
1085        rect: impl AsRef<Rect>,
1086        op: impl Into<Option<ClipOp>>,
1087        do_anti_alias: impl Into<Option<bool>>,
1088    ) -> &Self {
1089        unsafe {
1090            self.native_mut().clipRect(
1091                rect.as_ref().native(),
1092                op.into().unwrap_or_default(),
1093                do_anti_alias.into().unwrap_or_default(),
1094            )
1095        }
1096        self
1097    }
1098
1099    pub fn clip_irect(&self, irect: impl AsRef<IRect>, op: impl Into<Option<ClipOp>>) -> &Self {
1100        let r = Rect::from(*irect.as_ref());
1101        self.clip_rect(r, op, false)
1102    }
1103
1104    /// Replaces clip with the intersection or difference of clip and `rrect`,
1105    /// with an aliased or anti-aliased clip edge.
1106    /// `rrect` is transformed by [`Matrix`]
1107    /// before it is combined with clip.
1108    ///
1109    /// - `rrect` [`RRect`] to combine with clip
1110    /// - `op` [`ClipOp`] to apply to clip
1111    /// - `do_anti_alias` `true` if clip is to be anti-aliased
1112    ///
1113    /// example: <https://fiddle.skia.org/c/@Canvas_clipRRect>
1114    pub fn clip_rrect(
1115        &self,
1116        rrect: impl AsRef<RRect>,
1117        op: impl Into<Option<ClipOp>>,
1118        do_anti_alias: impl Into<Option<bool>>,
1119    ) -> &Self {
1120        unsafe {
1121            self.native_mut().clipRRect(
1122                rrect.as_ref().native(),
1123                op.into().unwrap_or_default(),
1124                do_anti_alias.into().unwrap_or_default(),
1125            )
1126        }
1127        self
1128    }
1129
1130    /// Replaces clip with the intersection or difference of clip and `path`,
1131    /// with an aliased or anti-aliased clip edge. [`crate::PathFillType`] determines if `path`
1132    /// describes the area inside or outside its contours; and if path contour overlaps
1133    /// itself or another path contour, whether the overlaps form part of the area.
1134    /// `path` is transformed by [`Matrix`] before it is combined with clip.
1135    ///
1136    /// - `path` [`Path`] to combine with clip
1137    /// - `op` [`ClipOp`] to apply to clip
1138    /// - `do_anti_alias` `true` if clip is to be anti-aliased
1139    ///
1140    /// example: <https://fiddle.skia.org/c/@Canvas_clipPath>
1141    pub fn clip_path(
1142        &self,
1143        path: &Path,
1144        op: impl Into<Option<ClipOp>>,
1145        do_anti_alias: impl Into<Option<bool>>,
1146    ) -> &Self {
1147        unsafe {
1148            self.native_mut().clipPath(
1149                path.native(),
1150                op.into().unwrap_or_default(),
1151                do_anti_alias.into().unwrap_or_default(),
1152            )
1153        }
1154        self
1155    }
1156
1157    pub fn clip_shader(&self, shader: impl Into<Shader>, op: impl Into<Option<ClipOp>>) -> &Self {
1158        unsafe {
1159            sb::C_SkCanvas_clipShader(
1160                self.native_mut(),
1161                shader.into().into_ptr(),
1162                op.into().unwrap_or(ClipOp::Intersect),
1163            )
1164        }
1165        self
1166    }
1167
1168    /// Replaces clip with the intersection or difference of clip and [`Region`] `device_rgn`.
1169    /// Resulting clip is aliased; pixels are fully contained by the clip.
1170    /// `device_rgn` is unaffected by [`Matrix`].
1171    ///
1172    /// - `device_rgn` [`Region`] to combine with clip
1173    /// - `op` [`ClipOp`] to apply to clip
1174    ///
1175    /// example: <https://fiddle.skia.org/c/@Canvas_clipRegion>
1176    pub fn clip_region(&self, device_rgn: &Region, op: impl Into<Option<ClipOp>>) -> &Self {
1177        unsafe {
1178            self.native_mut()
1179                .clipRegion(device_rgn.native(), op.into().unwrap_or_default())
1180        }
1181        self
1182    }
1183
1184    // quickReject() functions are implemented as a trait.
1185
1186    /// Returns bounds of clip, transformed by inverse of [`Matrix`]. If clip is empty,
1187    /// return [`Rect::new_empty()`], where all [`Rect`] sides equal zero.
1188    ///
1189    /// [`Rect`] returned is outset by one to account for partial pixel coverage if clip
1190    /// is anti-aliased.
1191    ///
1192    /// Returns bounds of clip in local coordinates
1193    ///
1194    /// example: <https://fiddle.skia.org/c/@Canvas_getLocalClipBounds>
1195    pub fn local_clip_bounds(&self) -> Option<Rect> {
1196        let r = Rect::construct(|r| unsafe { sb::C_SkCanvas_getLocalClipBounds(self.native(), r) });
1197        (!r.is_empty()).then_some(r)
1198    }
1199
1200    /// Returns [`IRect`] bounds of clip, unaffected by [`Matrix`]. If clip is empty,
1201    /// return [`Rect::new_empty()`], where all [`Rect`] sides equal zero.
1202    ///
1203    /// Unlike [`Self::local_clip_bounds()`], returned [`IRect`] is not outset.
1204    ///
1205    /// Returns bounds of clip in `Device` coordinates
1206    ///
1207    /// example: <https://fiddle.skia.org/c/@Canvas_getDeviceClipBounds>
1208    pub fn device_clip_bounds(&self) -> Option<IRect> {
1209        let r =
1210            IRect::construct(|r| unsafe { sb::C_SkCanvas_getDeviceClipBounds(self.native(), r) });
1211        (!r.is_empty()).then_some(r)
1212    }
1213
1214    /// Fills clip with color `color`.
1215    /// `mode` determines how ARGB is combined with destination.
1216    ///
1217    /// - `color` [`Color4f`] representing unpremultiplied color.
1218    /// - `mode` [`BlendMode`] used to combine source color and destination
1219    pub fn draw_color(
1220        &self,
1221        color: impl Into<Color4f>,
1222        mode: impl Into<Option<BlendMode>>,
1223    ) -> &Self {
1224        unsafe {
1225            self.native_mut()
1226                .drawColor(&color.into().into_native(), mode.into().unwrap_or_default())
1227        }
1228        self
1229    }
1230
1231    /// Fills clip with color `color` using [`BlendMode::Src`].
1232    /// This has the effect of replacing all pixels contained by clip with `color`.
1233    ///
1234    /// - `color` [`Color4f`] representing unpremultiplied color.
1235    pub fn clear(&self, color: impl Into<Color4f>) -> &Self {
1236        self.draw_color(color, BlendMode::Src)
1237    }
1238
1239    /// Makes [`Canvas`] contents undefined. Subsequent calls that read [`Canvas`] pixels,
1240    /// such as drawing with [`BlendMode`], return undefined results. `discard()` does
1241    /// not change clip or [`Matrix`].
1242    ///
1243    /// `discard()` may do nothing, depending on the implementation of [`Surface`] or `Device`
1244    /// that created [`Canvas`].
1245    ///
1246    /// `discard()` allows optimized performance on subsequent draws by removing
1247    /// cached data associated with [`Surface`] or `Device`.
1248    /// It is not necessary to call `discard()` once done with [`Canvas`];
1249    /// any cached data is deleted when owning [`Surface`] or `Device` is deleted.
1250    pub fn discard(&self) -> &Self {
1251        unsafe { sb::C_SkCanvas_discard(self.native_mut()) }
1252        self
1253    }
1254
1255    /// Fills clip with [`Paint`] `paint`. [`Paint`] components, [`Shader`],
1256    /// [`crate::ColorFilter`], [`ImageFilter`], and [`BlendMode`] affect drawing;
1257    /// [`crate::MaskFilter`] and [`crate::PathEffect`] in `paint` are ignored.
1258    ///
1259    /// - `paint` graphics state used to fill [`Canvas`]
1260    ///
1261    /// example: <https://fiddle.skia.org/c/@Canvas_drawPaint>
1262    pub fn draw_paint(&self, paint: &Paint) -> &Self {
1263        unsafe { self.native_mut().drawPaint(paint.native()) }
1264        self
1265    }
1266
1267    /// Draws `pts` using clip, [`Matrix`] and [`Paint`] `pain`.
1268    /// if the number of points is less than one, has no effect.
1269    /// `mode` may be one of: [`PointMode::Points`], [`PointMode::Lines`], or [`PointMode::Polygon`]
1270    ///
1271    /// If `mode` is [`PointMode::Points`], the shape of point drawn depends on `paint`
1272    /// [`crate::paint::Cap`]. If `paint` is set to [`crate::paint::Cap::Round`], each point draws a
1273    /// circle of diameter [`Paint`] stroke width. If `paint` is set to [`crate::paint::Cap::Square`]
1274    /// or [`crate::paint::Cap::Butt`], each point draws a square of width and height
1275    /// [`Paint`] stroke width.
1276    ///
1277    /// If `mode` is [`PointMode::Lines`], each pair of points draws a line segment.
1278    /// One line is drawn for every two points; each point is used once. If count is odd,
1279    /// the final point is ignored.
1280    ///
1281    /// If mode is [`PointMode::Polygon`], each adjacent pair of points draws a line segment.
1282    /// count minus one lines are drawn; the first and last point are used once.
1283    ///
1284    /// Each line segment respects `paint` [`crate::paint::Cap`] and [`Paint`] stroke width.
1285    /// [`crate::paint::Style`] is ignored, as if were set to [`crate::paint::Style::Stroke`].
1286    ///
1287    /// Always draws each element one at a time; is not affected by
1288    /// [`crate::paint::Join`], and unlike [`Self::draw_path()`], does not create a mask from all points
1289    /// and lines before drawing.
1290    ///
1291    /// - `mode` whether pts draws points or lines
1292    /// - `pts` array of points to draw
1293    /// - `paint` stroke, blend, color, and so on, used to draw
1294    ///
1295    /// example: <https://fiddle.skia.org/c/@Canvas_drawPoints>
1296    pub fn draw_points(&self, mode: PointMode, pts: &[Point], paint: &Paint) -> &Self {
1297        unsafe {
1298            sb::C_SkCanvas_drawPoints(
1299                self.native_mut(),
1300                mode,
1301                pts.native().as_ptr(),
1302                pts.len(),
1303                paint.native(),
1304            )
1305        }
1306        self
1307    }
1308
1309    /// Draws point `p` using clip, [`Matrix`] and [`Paint`] paint.
1310    ///
1311    /// The shape of point drawn depends on `paint` [`crate::paint::Cap`].
1312    /// If `paint` is set to [`crate::paint::Cap::Round`], draw a circle of diameter [`Paint`]
1313    /// stroke width. If `paint` is set to [`crate::paint::Cap::Square`] or
1314    /// [`crate::paint::Cap::Butt`], draw a square of width and height [`Paint`] stroke width.
1315    /// [`crate::paint::Style`] is ignored, as if were set to [`crate::paint::Style::Stroke`].
1316    ///
1317    /// - `p` top-left edge of circle or square
1318    /// - `paint` stroke, blend, color, and so on, used to draw
1319    pub fn draw_point(&self, p: impl Into<Point>, paint: &Paint) -> &Self {
1320        let p = p.into();
1321        unsafe { self.native_mut().drawPoint(p.x, p.y, paint.native()) }
1322        self
1323    }
1324
1325    /// Draws line segment from `p1` to `p2` using clip, [`Matrix`], and [`Paint`] paint.
1326    /// In paint: [`Paint`] stroke width describes the line thickness;
1327    /// [`crate::paint::Cap`] draws the end rounded or square;
1328    /// [`crate::paint::Style`] is ignored, as if were set to [`crate::paint::Style::Stroke`].
1329    ///
1330    /// - `p1` start of line segment
1331    /// - `p2` end of line segment
1332    /// - `paint` stroke, blend, color, and so on, used to draw
1333    pub fn draw_line(&self, p1: impl Into<Point>, p2: impl Into<Point>, paint: &Paint) -> &Self {
1334        let (p1, p2) = (p1.into(), p2.into());
1335        unsafe {
1336            self.native_mut()
1337                .drawLine(p1.x, p1.y, p2.x, p2.y, paint.native())
1338        }
1339        self
1340    }
1341
1342    /// Draws [`Rect`] rect using clip, [`Matrix`], and [`Paint`] `paint`.
1343    /// In paint: [`crate::paint::Style`] determines if rectangle is stroked or filled;
1344    /// if stroked, [`Paint`] stroke width describes the line thickness, and
1345    /// [`crate::paint::Join`] draws the corners rounded or square.
1346    ///
1347    /// - `rect` rectangle to draw
1348    /// - `paint` stroke or fill, blend, color, and so on, used to draw
1349    ///
1350    /// example: <https://fiddle.skia.org/c/@Canvas_drawRect>
1351    pub fn draw_rect(&self, rect: impl AsRef<Rect>, paint: &Paint) -> &Self {
1352        unsafe {
1353            self.native_mut()
1354                .drawRect(rect.as_ref().native(), paint.native())
1355        }
1356        self
1357    }
1358
1359    /// Draws [`IRect`] rect using clip, [`Matrix`], and [`Paint`] `paint`.
1360    /// In `paint`: [`crate::paint::Style`] determines if rectangle is stroked or filled;
1361    /// if stroked, [`Paint`] stroke width describes the line thickness, and
1362    /// [`crate::paint::Join`] draws the corners rounded or square.
1363    ///
1364    /// - `rect` rectangle to draw
1365    /// - `paint` stroke or fill, blend, color, and so on, used to draw
1366    pub fn draw_irect(&self, rect: impl AsRef<IRect>, paint: &Paint) -> &Self {
1367        self.draw_rect(Rect::from(*rect.as_ref()), paint)
1368    }
1369
1370    /// Draws [`Region`] region using clip, [`Matrix`], and [`Paint`] `paint`.
1371    /// In `paint`: [`crate::paint::Style`] determines if rectangle is stroked or filled;
1372    /// if stroked, [`Paint`] stroke width describes the line thickness, and
1373    /// [`crate::paint::Join`] draws the corners rounded or square.
1374    ///
1375    /// - `region` region to draw
1376    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1377    ///
1378    /// example: <https://fiddle.skia.org/c/@Canvas_drawRegion>
1379    pub fn draw_region(&self, region: &Region, paint: &Paint) -> &Self {
1380        unsafe {
1381            self.native_mut()
1382                .drawRegion(region.native(), paint.native())
1383        }
1384        self
1385    }
1386
1387    /// Draws oval oval using clip, [`Matrix`], and [`Paint`].
1388    /// In `paint`: [`crate::paint::Style`] determines if oval is stroked or filled;
1389    /// if stroked, [`Paint`] stroke width describes the line thickness.
1390    ///
1391    /// - `oval` [`Rect`] bounds of oval
1392    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1393    ///
1394    /// example: <https://fiddle.skia.org/c/@Canvas_drawOval>
1395    pub fn draw_oval(&self, oval: impl AsRef<Rect>, paint: &Paint) -> &Self {
1396        unsafe {
1397            self.native_mut()
1398                .drawOval(oval.as_ref().native(), paint.native())
1399        }
1400        self
1401    }
1402
1403    /// Draws [`RRect`] rrect using clip, [`Matrix`], and [`Paint`] `paint`.
1404    /// In `paint`: [`crate::paint::Style`] determines if rrect is stroked or filled;
1405    /// if stroked, [`Paint`] stroke width describes the line thickness.
1406    ///
1407    /// `rrect` may represent a rectangle, circle, oval, uniformly rounded rectangle, or
1408    /// may have any combination of positive non-square radii for the four corners.
1409    ///
1410    /// - `rrect` [`RRect`] with up to eight corner radii to draw
1411    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1412    ///
1413    /// example: <https://fiddle.skia.org/c/@Canvas_drawRRect>
1414    pub fn draw_rrect(&self, rrect: impl AsRef<RRect>, paint: &Paint) -> &Self {
1415        unsafe {
1416            self.native_mut()
1417                .drawRRect(rrect.as_ref().native(), paint.native())
1418        }
1419        self
1420    }
1421
1422    /// Draws [`RRect`] outer and inner
1423    /// using clip, [`Matrix`], and [`Paint`] `paint`.
1424    /// outer must contain inner or the drawing is undefined.
1425    /// In paint: [`crate::paint::Style`] determines if [`RRect`] is stroked or filled;
1426    /// if stroked, [`Paint`] stroke width describes the line thickness.
1427    /// If stroked and [`RRect`] corner has zero length radii, [`crate::paint::Join`] can
1428    /// draw corners rounded or square.
1429    ///
1430    /// GPU-backed platforms optimize drawing when both outer and inner are
1431    /// concave and outer contains inner. These platforms may not be able to draw
1432    /// [`Path`] built with identical data as fast.
1433    ///
1434    /// - `outer` [`RRect`] outer bounds to draw
1435    /// - `inner` [`RRect`] inner bounds to draw
1436    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1437    ///
1438    /// example: <https://fiddle.skia.org/c/@Canvas_drawDRRect_a>
1439    /// example: <https://fiddle.skia.org/c/@Canvas_drawDRRect_b>
1440    pub fn draw_drrect(
1441        &self,
1442        outer: impl AsRef<RRect>,
1443        inner: impl AsRef<RRect>,
1444        paint: &Paint,
1445    ) -> &Self {
1446        unsafe {
1447            self.native_mut().drawDRRect(
1448                outer.as_ref().native(),
1449                inner.as_ref().native(),
1450                paint.native(),
1451            )
1452        }
1453        self
1454    }
1455
1456    /// Draws circle at center with radius using clip, [`Matrix`], and [`Paint`] `paint`.
1457    /// If radius is zero or less, nothing is drawn.
1458    /// In `paint`: [`crate::paint::Style`] determines if circle is stroked or filled;
1459    /// if stroked, [`Paint`] stroke width describes the line thickness.
1460    ///
1461    /// - `center` circle center
1462    /// - `radius` half the diameter of circle
1463    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1464    pub fn draw_circle(&self, center: impl Into<Point>, radius: scalar, paint: &Paint) -> &Self {
1465        let center = center.into();
1466        unsafe {
1467            self.native_mut()
1468                .drawCircle(center.x, center.y, radius, paint.native())
1469        }
1470        self
1471    }
1472
1473    /// Draws arc using clip, [`Matrix`], and [`Paint`] paint.
1474    ///
1475    /// Arc is part of oval bounded by oval, sweeping from `start_angle` to `start_angle` plus
1476    /// `sweep_angle`. `start_angle` and `sweep_angle` are in degrees.
1477    ///
1478    /// `start_angle` of zero places start point at the right middle edge of oval.
1479    /// A positive `sweep_angle` places arc end point clockwise from start point;
1480    /// a negative `sweep_angle` places arc end point counterclockwise from start point.
1481    /// `sweep_angle` may exceed 360 degrees, a full circle.
1482    /// If `use_center` is `true`, draw a wedge that includes lines from oval
1483    /// center to arc end points. If `use_center` is `false`, draw arc between end points.
1484    ///
1485    /// If [`Rect`] oval is empty or `sweep_angle` is zero, nothing is drawn.
1486    ///
1487    /// - `oval` [`Rect`] bounds of oval containing arc to draw
1488    /// - `start_angle` angle in degrees where arc begins
1489    /// - `sweep_angle` sweep angle in degrees; positive is clockwise
1490    /// - `use_center` if `true`, include the center of the oval
1491    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1492    pub fn draw_arc(
1493        &self,
1494        oval: impl AsRef<Rect>,
1495        start_angle: scalar,
1496        sweep_angle: scalar,
1497        use_center: bool,
1498        paint: &Paint,
1499    ) -> &Self {
1500        unsafe {
1501            self.native_mut().drawArc(
1502                oval.as_ref().native(),
1503                start_angle,
1504                sweep_angle,
1505                use_center,
1506                paint.native(),
1507            )
1508        }
1509        self
1510    }
1511
1512    /// Draws arc using clip, [`Matrix`], and [`Paint`] paint.
1513    ///
1514    /// Arc is part of oval bounded by oval, sweeping from `start_angle` to `start_angle` plus
1515    /// `sweep_angle`. `start_angle` and `sweep_angle` are in degrees.
1516    ///
1517    /// `start_angle` of zero places start point at the right middle edge of oval.
1518    /// A positive `sweep_angle` places arc end point clockwise from start point;
1519    /// a negative `sweep_angle` places arc end point counterclockwise from start point.
1520    /// `sweep_angle` may exceed 360 degrees, a full circle.
1521    /// If `use_center` is `true`, draw a wedge that includes lines from oval
1522    /// center to arc end points. If `use_center` is `false`, draw arc between end points.
1523    ///
1524    /// If [`Rect`] oval is empty or `sweep_angle` is zero, nothing is drawn.
1525    ///
1526    /// - `arc` [`Arc`] SkArc specifying oval, startAngle, sweepAngle, and arc-vs-wedge
1527    /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1528    pub fn draw_arc_2(&self, arc: &Arc, paint: &Paint) -> &Self {
1529        self.draw_arc(
1530            arc.oval,
1531            arc.start_angle,
1532            arc.sweep_angle,
1533            arc.is_wedge(),
1534            paint,
1535        );
1536        self
1537    }
1538
1539    /// Draws [`RRect`] bounded by [`Rect`] rect, with corner radii `(rx, ry)` using clip,
1540    /// [`Matrix`], and [`Paint`] `paint`.
1541    ///
1542    /// In `paint`: [`crate::paint::Style`] determines if [`RRect`] is stroked or filled;
1543    /// if stroked, [`Paint`] stroke width describes the line thickness.
1544    /// If `rx` or `ry` are less than zero, they are treated as if they are zero.
1545    /// If `rx` plus `ry` exceeds rect width or rect height, radii are scaled down to fit.
1546    /// If `rx` and `ry` are zero, [`RRect`] is drawn as [`Rect`] and if stroked is affected by
1547    /// [`crate::paint::Join`].
1548    ///
1549    /// - `rect` [`Rect`] bounds of [`RRect`] to draw
1550    /// - `rx` axis length on x-axis of oval describing rounded corners
1551    /// - `ry` axis length on y-axis of oval describing rounded corners
1552    /// - `paint` stroke, blend, color, and so on, used to draw
1553    ///
1554    /// example: <https://fiddle.skia.org/c/@Canvas_drawRoundRect>
1555    pub fn draw_round_rect(
1556        &self,
1557        rect: impl AsRef<Rect>,
1558        rx: scalar,
1559        ry: scalar,
1560        paint: &Paint,
1561    ) -> &Self {
1562        unsafe {
1563            self.native_mut()
1564                .drawRoundRect(rect.as_ref().native(), rx, ry, paint.native())
1565        }
1566        self
1567    }
1568
1569    /// Draws [`Path`] path using clip, [`Matrix`], and [`Paint`] `paint`.
1570    /// [`Path`] contains an array of path contour, each of which may be open or closed.
1571    ///
1572    /// In `paint`: [`crate::paint::Style`] determines if [`RRect`] is stroked or filled:
1573    /// if filled, [`crate::PathFillType`] determines whether path contour describes inside or
1574    /// outside of fill; if stroked, [`Paint`] stroke width describes the line thickness,
1575    /// [`crate::paint::Cap`] describes line ends, and [`crate::paint::Join`] describes how
1576    /// corners are drawn.
1577    ///
1578    /// - `path` [`Path`] to draw
1579    /// - `paint` stroke, blend, color, and so on, used to draw
1580    ///
1581    /// example: <https://fiddle.skia.org/c/@Canvas_drawPath>
1582    pub fn draw_path(&self, path: &Path, paint: &Paint) -> &Self {
1583        unsafe { self.native_mut().drawPath(path.native(), paint.native()) }
1584        self
1585    }
1586
1587    pub fn draw_image(
1588        &self,
1589        image: impl AsRef<Image>,
1590        left_top: impl Into<Point>,
1591        paint: Option<&Paint>,
1592    ) -> &Self {
1593        let left_top = left_top.into();
1594        self.draw_image_with_sampling_options(image, left_top, SamplingOptions::default(), paint)
1595    }
1596
1597    pub fn draw_image_rect(
1598        &self,
1599        image: impl AsRef<Image>,
1600        src: Option<(&Rect, SrcRectConstraint)>,
1601        dst: impl AsRef<Rect>,
1602        paint: &Paint,
1603    ) -> &Self {
1604        self.draw_image_rect_with_sampling_options(
1605            image,
1606            src,
1607            dst,
1608            SamplingOptions::default(),
1609            paint,
1610        )
1611    }
1612
1613    pub fn draw_image_with_sampling_options(
1614        &self,
1615        image: impl AsRef<Image>,
1616        left_top: impl Into<Point>,
1617        sampling: impl Into<SamplingOptions>,
1618        paint: Option<&Paint>,
1619    ) -> &Self {
1620        let left_top = left_top.into();
1621        unsafe {
1622            self.native_mut().drawImage(
1623                image.as_ref().native(),
1624                left_top.x,
1625                left_top.y,
1626                sampling.into().native(),
1627                paint.native_ptr_or_null(),
1628            )
1629        }
1630        self
1631    }
1632
1633    pub fn draw_image_rect_with_sampling_options(
1634        &self,
1635        image: impl AsRef<Image>,
1636        src: Option<(&Rect, SrcRectConstraint)>,
1637        dst: impl AsRef<Rect>,
1638        sampling: impl Into<SamplingOptions>,
1639        paint: &Paint,
1640    ) -> &Self {
1641        let sampling = sampling.into();
1642        match src {
1643            Some((src, constraint)) => unsafe {
1644                self.native_mut().drawImageRect(
1645                    image.as_ref().native(),
1646                    src.native(),
1647                    dst.as_ref().native(),
1648                    sampling.native(),
1649                    paint.native(),
1650                    constraint,
1651                )
1652            },
1653            None => unsafe {
1654                self.native_mut().drawImageRect1(
1655                    image.as_ref().native(),
1656                    dst.as_ref().native(),
1657                    sampling.native(),
1658                    paint.native(),
1659                )
1660            },
1661        }
1662        self
1663    }
1664
1665    /// Draws [`Image`] `image` stretched proportionally to fit into [`Rect`] `dst`.
1666    /// [`IRect`] `center` divides the image into nine sections: four sides, four corners, and
1667    /// the center. Corners are unmodified or scaled down proportionately if their sides
1668    /// are larger than `dst`; center and four sides are scaled to fit remaining space, if any.
1669    ///
1670    /// Additionally transform draw using clip, [`Matrix`], and optional [`Paint`] `paint`.
1671    ///
1672    /// If [`Paint`] `paint` is supplied, apply [`crate::ColorFilter`], alpha, [`ImageFilter`], and
1673    /// [`BlendMode`]. If `image` is [`crate::ColorType::Alpha8`], apply [`Shader`].
1674    /// If `paint` contains [`crate::MaskFilter`], generate mask from `image` bounds.
1675    /// Any [`crate::MaskFilter`] on `paint` is ignored as is paint anti-aliasing state.
1676    ///
1677    /// If generated mask extends beyond image bounds, replicate image edge colors, just
1678    /// as [`Shader`] made from [`RCHandle<Image>::to_shader()`] with [`crate::TileMode::Clamp`] set
1679    /// replicates the image edge color when it samples outside of its bounds.
1680    ///
1681    /// - `image` [`Image`] containing pixels, dimensions, and format
1682    /// - `center` [`IRect`] edge of image corners and sides
1683    /// - `dst` destination [`Rect`] of image to draw to
1684    /// - `filter` what technique to use when sampling the image
1685    /// - `paint` [`Paint`] containing [`BlendMode`], [`crate::ColorFilter`], [`ImageFilter`],
1686    ///    and so on; or `None`
1687    pub fn draw_image_nine(
1688        &self,
1689        image: impl AsRef<Image>,
1690        center: impl AsRef<IRect>,
1691        dst: impl AsRef<Rect>,
1692        filter_mode: FilterMode,
1693        paint: Option<&Paint>,
1694    ) -> &Self {
1695        unsafe {
1696            self.native_mut().drawImageNine(
1697                image.as_ref().native(),
1698                center.as_ref().native(),
1699                dst.as_ref().native(),
1700                filter_mode,
1701                paint.native_ptr_or_null(),
1702            )
1703        }
1704        self
1705    }
1706
1707    /// Draws [`Image`] `image` stretched proportionally to fit into [`Rect`] `dst`.
1708    ///
1709    /// [`lattice::Lattice`] lattice divides image into a rectangular grid.
1710    /// Each intersection of an even-numbered row and column is fixed;
1711    /// fixed lattice elements never scale larger than their initial
1712    /// size and shrink proportionately when all fixed elements exceed the bitmap
1713    /// dimension. All other grid elements scale to fill the available space, if any.
1714    ///
1715    /// Additionally transform draw using clip, [`Matrix`], and optional [`Paint`] `paint`.
1716    ///
1717    /// If [`Paint`] `paint` is supplied, apply [`crate::ColorFilter`], alpha, [`ImageFilter`], and
1718    /// [`BlendMode`]. If image is [`crate::ColorType::Alpha8`], apply [`Shader`].
1719    /// If `paint` contains [`crate::MaskFilter`], generate mask from image bounds.
1720    /// Any [`crate::MaskFilter`] on `paint` is ignored as is `paint` anti-aliasing state.
1721    ///
1722    /// If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1723    /// just as [`Shader`] made from `SkShader::MakeBitmapShader` with
1724    /// [`crate::TileMode::Clamp`] set replicates the bitmap edge color when it samples
1725    /// outside of its bounds.
1726    ///
1727    /// - `image` [`Image`] containing pixels, dimensions, and format
1728    /// - `lattice` division of bitmap into fixed and variable rectangles
1729    /// - `dst` destination [`Rect`] of image to draw to
1730    /// - `filter` what technique to use when sampling the image
1731    /// - `paint` [`Paint`] containing [`BlendMode`], [`crate::ColorFilter`], [`ImageFilter`],
1732    ///   and so on; or `None`
1733    pub fn draw_image_lattice(
1734        &self,
1735        image: impl AsRef<Image>,
1736        lattice: &Lattice,
1737        dst: impl AsRef<Rect>,
1738        filter: FilterMode,
1739        paint: Option<&Paint>,
1740    ) -> &Self {
1741        unsafe {
1742            self.native_mut().drawImageLattice(
1743                image.as_ref().native(),
1744                &lattice.native().native,
1745                dst.as_ref().native(),
1746                filter,
1747                paint.native_ptr_or_null(),
1748            )
1749        }
1750        self
1751    }
1752
1753    // TODO: drawSimpleText?
1754
1755    /// Draws [`String`], with origin at `(origin.x, origin.y)`, using clip, [`Matrix`], [`Font`]
1756    /// `font`, and [`Paint`] `paint`.
1757    ///
1758    /// This function uses the default character-to-glyph mapping from the [`crate::Typeface`] in
1759    /// font.  It does not perform typeface fallback for characters not found in the
1760    /// [`crate::Typeface`].  It does not perform kerning; glyphs are positioned based on their
1761    /// default advances.
1762    ///
1763    /// Text size is affected by [`Matrix`] and [`Font`] text size. Default text size is 12 point.
1764    ///
1765    /// All elements of `paint`: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1766    /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to text. By default, draws filled black
1767    /// glyphs.
1768    ///
1769    /// - `str` character code points drawn,
1770    ///    ending with a char value of zero
1771    /// - `origin` start of string on x,y-axis
1772    /// - `font` typeface, text size and so, used to describe the text
1773    /// - `paint` blend, color, and so on, used to draw
1774    pub fn draw_str(
1775        &self,
1776        str: impl AsRef<str>,
1777        origin: impl Into<Point>,
1778        font: &Font,
1779        paint: &Paint,
1780    ) -> &Self {
1781        // rust specific, based on drawSimpleText with fixed UTF8 encoding,
1782        // implementation is similar to Font's *_str methods.
1783        let origin = origin.into();
1784        let bytes = str.as_ref().as_bytes();
1785        unsafe {
1786            self.native_mut().drawSimpleText(
1787                bytes.as_ptr() as _,
1788                bytes.len(),
1789                TextEncoding::UTF8.into_native(),
1790                origin.x,
1791                origin.y,
1792                font.native(),
1793                paint.native(),
1794            )
1795        }
1796        self
1797    }
1798
1799    /// Draws glyphs at positions relative to `origin` styled with `font` and `paint` with
1800    /// supporting utf8 and cluster information.
1801    ///
1802    /// This function draw glyphs at the given positions relative to the given origin. It does not
1803    /// perform typeface fallback for glyphs not found in the [`crate::Typeface`] in font.
1804    ///
1805    /// The drawing obeys the current transform matrix and clipping.
1806    ///
1807    /// All elements of paint: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1808    /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to text. By default, draws filled black
1809    /// glyphs.
1810    ///
1811    /// - `count`           number of glyphs to draw
1812    /// - `glyphs`          the array of glyphIDs to draw
1813    /// - `positions`       where to draw each glyph relative to origin
1814    /// - `clusters`        array of size count of cluster information
1815    /// - `utf8_text`       utf8text supporting information for the glyphs
1816    /// - `origin`          the origin of all the positions
1817    /// - `font`            typeface, text size and so, used to describe the text
1818    /// - `paint`           blend, color, and so on, used to draw
1819    #[allow(clippy::too_many_arguments)]
1820    pub fn draw_glyphs_utf8(
1821        &self,
1822        glyphs: &[GlyphId],
1823        positions: &[Point],
1824        clusters: &[u32],
1825        utf8_text: impl AsRef<str>,
1826        origin: impl Into<Point>,
1827        font: &Font,
1828        paint: &Paint,
1829    ) {
1830        let count = glyphs.len();
1831        if count == 0 {
1832            return;
1833        }
1834        assert_eq!(positions.len(), count);
1835        assert_eq!(clusters.len(), count);
1836        let utf8_text = utf8_text.as_ref().as_bytes();
1837        let origin = origin.into();
1838        unsafe {
1839            sb::C_SkCanvas_drawGlyphs2(
1840                self.native_mut(),
1841                glyphs.as_ptr(),
1842                count,
1843                positions.native().as_ptr(),
1844                clusters.as_ptr(),
1845                utf8_text.as_ptr() as _,
1846                utf8_text.len(),
1847                origin.into_native(),
1848                font.native(),
1849                paint.native(),
1850            )
1851        }
1852    }
1853
1854    /// Draws `count` glyphs, at positions relative to `origin` styled with `font` and `paint`.
1855    ///
1856    /// This function draw glyphs at the given positions relative to the given origin.
1857    /// It does not perform typeface fallback for glyphs not found in the [`crate::Typeface`]] in
1858    /// font.
1859    ///
1860    /// The drawing obeys the current transform matrix and clipping.
1861    ///
1862    /// All elements of paint: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1863    /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to text. By default, draws filled black
1864    /// glyphs.
1865    ///
1866    /// - `count`       number of glyphs to draw
1867    /// - `glyphs`      the array of glyphIDs to draw
1868    /// - `positions`   where to draw each glyph relative to origin, either a `&[Point]` or
1869    ///                `&[RSXform]` slice
1870    /// - `origin`      the origin of all the positions
1871    /// - `font`        typeface, text size and so, used to describe the text
1872    /// - `paint`       blend, color, and so on, used to draw
1873    pub fn draw_glyphs_at<'a>(
1874        &self,
1875        glyphs: &[GlyphId],
1876        positions: impl Into<GlyphPositions<'a>>,
1877        origin: impl Into<Point>,
1878        font: &Font,
1879        paint: &Paint,
1880    ) {
1881        let count = glyphs.len();
1882        if count == 0 {
1883            return;
1884        }
1885        let positions: GlyphPositions = positions.into();
1886        let origin = origin.into();
1887
1888        let glyphs = glyphs.as_ptr();
1889        let origin = origin.into_native();
1890        let font = font.native();
1891        let paint = paint.native();
1892
1893        match positions {
1894            GlyphPositions::Points(points) => {
1895                assert_eq!(points.len(), count);
1896                unsafe {
1897                    sb::C_SkCanvas_drawGlyphs(
1898                        self.native_mut(),
1899                        glyphs,
1900                        count,
1901                        points.native().as_ptr(),
1902                        origin,
1903                        font,
1904                        paint,
1905                    )
1906                }
1907            }
1908            GlyphPositions::RSXforms(xforms) => {
1909                assert_eq!(xforms.len(), count);
1910                unsafe {
1911                    sb::C_SkCanvas_drawGlyphsRSXform(
1912                        self.native_mut(),
1913                        glyphs,
1914                        count,
1915                        xforms.native().as_ptr(),
1916                        origin,
1917                        font,
1918                        paint,
1919                    )
1920                }
1921            }
1922        }
1923    }
1924
1925    /// Draws [`TextBlob`] blob at `(origin.x, origin.y)`, using clip, [`Matrix`], and [`Paint`]
1926    /// paint.
1927    ///
1928    /// `blob` contains glyphs, their positions, and paint attributes specific to text:
1929    /// [`crate::Typeface`], [`Paint`] text size, [`Paint`] text scale x, [`Paint`] text skew x,
1930    /// [`Paint`] align, [`Paint`] hinting, anti-alias, [`Paint`] fake bold, [`Paint`] font embedded
1931    /// bitmaps, [`Paint`] full hinting spacing, LCD text, [`Paint`] linear text, and [`Paint`]
1932    /// subpixel text.
1933    ///
1934    /// [`TextEncoding`] must be set to [`TextEncoding::GlyphId`].
1935    ///
1936    /// Elements of `paint`: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1937    /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to blob.
1938    ///
1939    /// - `blob` glyphs, positions, and their paints' text size, typeface, and so on
1940    /// - `origin` horizontal and vertical offset applied to blob
1941    /// - `paint` blend, color, stroking, and so on, used to draw
1942    pub fn draw_text_blob(
1943        &self,
1944        blob: impl AsRef<TextBlob>,
1945        origin: impl Into<Point>,
1946        paint: &Paint,
1947    ) -> &Self {
1948        let origin = origin.into();
1949        #[cfg(all(feature = "textlayout", feature = "embed-icudtl"))]
1950        crate::icu::init();
1951        unsafe {
1952            self.native_mut().drawTextBlob(
1953                blob.as_ref().native(),
1954                origin.x,
1955                origin.y,
1956                paint.native(),
1957            )
1958        }
1959        self
1960    }
1961
1962    /// Draws [`Picture`] picture, using clip and [`Matrix`]; transforming picture with
1963    /// [`Matrix`] matrix, if provided; and use [`Paint`] `paint` alpha, [`crate::ColorFilter`],
1964    /// [`ImageFilter`], and [`BlendMode`], if provided.
1965    ///
1966    /// If paint is not `None`, then the picture is always drawn into a temporary layer before
1967    /// actually landing on the canvas. Note that drawing into a layer can also change its
1968    /// appearance if there are any non-associative blend modes inside any of the pictures elements.
1969    ///
1970    /// - `picture` recorded drawing commands to play
1971    /// - `matrix` [`Matrix`] to rotate, scale, translate, and so on; may be `None`
1972    /// - `paint` [`Paint`] to apply transparency, filtering, and so on; may be `None`
1973    pub fn draw_picture(
1974        &self,
1975        picture: impl AsRef<Picture>,
1976        matrix: Option<&Matrix>,
1977        paint: Option<&Paint>,
1978    ) -> &Self {
1979        unsafe {
1980            self.native_mut().drawPicture(
1981                picture.as_ref().native(),
1982                matrix.native_ptr_or_null(),
1983                paint.native_ptr_or_null(),
1984            )
1985        }
1986        self
1987    }
1988
1989    /// Draws [`Vertices`] vertices, a triangle mesh, using clip and [`Matrix`].
1990    /// If `paint` contains an [`Shader`] and vertices does not contain tex coords, the shader is
1991    /// mapped using the vertices' positions.
1992    ///
1993    /// [`BlendMode`] is ignored if [`Vertices`] does not have colors. Otherwise, it combines
1994    ///   - the [`Shader`] if [`Paint`] contains [`Shader`
1995    ///   - or the opaque [`Paint`] color if [`Paint`] does not contain [`Shader`]
1996    ///
1997    /// as the src of the blend and the interpolated vertex colors as the dst.
1998    ///
1999    /// [`crate::MaskFilter`], [`crate::PathEffect`], and antialiasing on [`Paint`] are ignored.
2000    //
2001    /// - `vertices` triangle mesh to draw
2002    /// - `mode` combines vertices' colors with [`Shader`] if present or [`Paint`] opaque color if
2003    ///   not. Ignored if the vertices do not contain color.
2004    /// - `paint` specifies the [`Shader`], used as [`Vertices`] texture, and
2005    ///   [`crate::ColorFilter`].
2006    ///
2007    /// example: <https://fiddle.skia.org/c/@Canvas_drawVertices>
2008    /// example: <https://fiddle.skia.org/c/@Canvas_drawVertices_2>
2009    pub fn draw_vertices(&self, vertices: &Vertices, mode: BlendMode, paint: &Paint) -> &Self {
2010        unsafe {
2011            self.native_mut()
2012                .drawVertices(vertices.native(), mode, paint.native())
2013        }
2014        self
2015    }
2016
2017    /// Draws a Coons patch: the interpolation of four cubics with shared corners,
2018    /// associating a color, and optionally a texture [`Point`], with each corner.
2019    ///
2020    /// [`Point`] array cubics specifies four [`Path`] cubic starting at the top-left corner,
2021    /// in clockwise order, sharing every fourth point. The last [`Path`] cubic ends at the
2022    /// first point.
2023    ///
2024    /// Color array color associates colors with corners in top-left, top-right,
2025    /// bottom-right, bottom-left order.
2026    ///
2027    /// If paint contains [`Shader`], [`Point`] array `tex_coords` maps [`Shader`] as texture to
2028    /// corners in top-left, top-right, bottom-right, bottom-left order. If `tex_coords` is
2029    /// `None`, [`Shader`] is mapped using positions (derived from cubics).
2030    ///
2031    /// [`BlendMode`] is ignored if colors is `None`. Otherwise, it combines
2032    ///   - the [`Shader`] if [`Paint`] contains [`Shader`]
2033    ///   - or the opaque [`Paint`] color if [`Paint`] does not contain [`Shader`]
2034    ///
2035    /// as the src of the blend and the interpolated patch colors as the dst.
2036    ///
2037    /// [`crate::MaskFilter`], [`crate::PathEffect`], and antialiasing on [`Paint`] are ignored.
2038    ///
2039    /// - `cubics` [`Path`] cubic array, sharing common points
2040    /// - `colors` color array, one for each corner
2041    /// - `tex_coords` [`Point`] array of texture coordinates, mapping [`Shader`] to corners;
2042    ///   may be `None`
2043    /// - `mode` combines patch's colors with [`Shader`] if present or [`Paint`] opaque color if
2044    ///    not. Ignored if colors is `None`.
2045    /// - `paint` [`Shader`], [`crate::ColorFilter`], [`BlendMode`], used to draw
2046    pub fn draw_patch<'a>(
2047        &self,
2048        cubics: &[Point; 12],
2049        colors: impl Into<Option<&'a [Color; 4]>>,
2050        tex_coords: Option<&[Point; 4]>,
2051        mode: BlendMode,
2052        paint: &Paint,
2053    ) -> &Self {
2054        let colors = colors
2055            .into()
2056            .map(|c| c.native().as_ptr())
2057            .unwrap_or(ptr::null());
2058        unsafe {
2059            self.native_mut().drawPatch(
2060                cubics.native().as_ptr(),
2061                colors,
2062                tex_coords
2063                    .map(|tc| tc.native().as_ptr())
2064                    .unwrap_or(ptr::null()),
2065                mode,
2066                paint.native(),
2067            )
2068        }
2069        self
2070    }
2071
2072    /// Draws a set of sprites from atlas, using clip, [`Matrix`], and optional [`Paint`] paint.
2073    /// paint uses anti-alias, alpha, [`crate::ColorFilter`], [`ImageFilter`], and [`BlendMode`]
2074    /// to draw, if present. For each entry in the array, [`Rect`] tex locates sprite in
2075    /// atlas, and [`RSXform`] xform transforms it into destination space.
2076    ///
2077    /// [`crate::MaskFilter`] and [`crate::PathEffect`] on paint are ignored.
2078    ///
2079    /// xform, tex, and colors if present, must contain the same number of entries.
2080    /// Optional colors are applied for each sprite using [`BlendMode`] mode, treating
2081    /// sprite as source and colors as destination.
2082    /// Optional `cull_rect` is a conservative bounds of all transformed sprites.
2083    /// If `cull_rect` is outside of clip, canvas can skip drawing.
2084    ///
2085    /// * `atlas` - [`Image`] containing sprites
2086    /// * `xform` - [`RSXform`] mappings for sprites in atlas
2087    /// * `tex` - [`Rect`] locations of sprites in atlas
2088    /// * `colors` - one per sprite, blended with sprite using [`BlendMode`]; may be `None`
2089    /// * `count` - number of sprites to draw
2090    /// * `mode` - [`BlendMode`] combining colors and sprites
2091    /// * `sampling` - [`SamplingOptions`] used when sampling from the atlas image
2092    /// * `cull_rect` - bounds of transformed sprites for efficient clipping; may be `None`
2093    /// * `paint` - [`crate::ColorFilter`], [`ImageFilter`], [`BlendMode`], and so on; may be `None`
2094    #[allow(clippy::too_many_arguments)]
2095    pub fn draw_atlas<'a>(
2096        &self,
2097        atlas: &Image,
2098        xform: &[RSXform],
2099        tex: &[Rect],
2100        colors: impl Into<Option<&'a [Color]>>,
2101        mode: BlendMode,
2102        sampling: impl Into<SamplingOptions>,
2103        cull_rect: impl Into<Option<Rect>>,
2104        paint: impl Into<Option<&'a Paint>>,
2105    ) {
2106        let count = xform.len();
2107        assert_eq!(tex.len(), count);
2108        let colors = colors.into();
2109        if let Some(color_slice) = colors {
2110            assert_eq!(color_slice.len(), count);
2111        }
2112        unsafe {
2113            sb::C_SkCanvas_drawAtlas(
2114                self.native_mut(),
2115                atlas.native(),
2116                xform.native().as_ptr(),
2117                count,
2118                tex.native().as_ptr(),
2119                colors.native().as_ptr_or_null(),
2120                mode,
2121                sampling.into().native(),
2122                cull_rect.into().native().as_ptr_or_null(),
2123                paint.into().native_ptr_or_null(),
2124            )
2125        }
2126    }
2127
2128    /// Draws [`Drawable`] drawable using clip and [`Matrix`], concatenated with
2129    /// optional matrix.
2130    ///
2131    /// If [`Canvas`] has an asynchronous implementation, as is the case when it is recording into
2132    /// [`Picture`], then drawable will be referenced, so that [`RCHandle<Drawable>::draw()`] can be
2133    /// called when the operation is finalized. To force immediate drawing, call
2134    /// [`RCHandle<Drawable>::draw()`] instead.
2135    ///
2136    /// - `drawable` custom struct encapsulating drawing commands
2137    /// - `matrix` transformation applied to drawing; may be `None`
2138    ///
2139    /// example: <https://fiddle.skia.org/c/@Canvas_drawDrawable>
2140    pub fn draw_drawable(&self, drawable: &mut Drawable, matrix: Option<&Matrix>) {
2141        unsafe {
2142            self.native_mut()
2143                .drawDrawable(drawable.native_mut(), matrix.native_ptr_or_null())
2144        }
2145    }
2146
2147    /// Draws [`Drawable`] drawable using clip and [`Matrix`], offset by `(offset.x, offset.y)`.
2148    ///
2149    /// If [`Canvas`] has an asynchronous implementation, as is the case when it is recording into
2150    /// [`Picture`], then drawable will be referenced, so that [`RCHandle<Drawable>::draw()`] can be
2151    /// called when the operation is finalized. To force immediate drawing, call
2152    /// [`RCHandle<Drawable>::draw()`] instead.
2153    ///
2154    /// - `drawable` custom struct encapsulating drawing commands
2155    /// - `offset` offset into [`Canvas`] writable pixels on x,y-axis
2156    ///
2157    /// example: <https://fiddle.skia.org/c/@Canvas_drawDrawable_2>
2158    pub fn draw_drawable_at(&self, drawable: &mut Drawable, offset: impl Into<Point>) {
2159        let offset = offset.into();
2160        unsafe {
2161            self.native_mut()
2162                .drawDrawable1(drawable.native_mut(), offset.x, offset.y)
2163        }
2164    }
2165
2166    /// Associates [`Rect`] on [`Canvas`] when an annotation; a key-value pair, where the key is
2167    /// a UTF-8 string, and optional value is stored as [`Data`].
2168    ///
2169    /// Only some canvas implementations, such as recording to [`Picture`], or drawing to
2170    /// document PDF, use annotations.
2171    ///
2172    /// - `rect` [`Rect`] extent of canvas to annotate
2173    /// - `key` string used for lookup
2174    /// - `value` data holding value stored in annotation
2175    pub fn draw_annotation(&self, rect: impl AsRef<Rect>, key: &str, value: &Data) -> &Self {
2176        let key = CString::new(key).unwrap();
2177        unsafe {
2178            self.native_mut().drawAnnotation(
2179                rect.as_ref().native(),
2180                key.as_ptr(),
2181                value.native_mut_force(),
2182            )
2183        }
2184        self
2185    }
2186
2187    /// Returns `true` if clip is empty; that is, nothing will draw.
2188    ///
2189    /// May do work when called; it should not be called more often than needed. However, once
2190    /// called, subsequent calls perform no work until clip changes.
2191    ///
2192    /// Returns `true` if clip is empty
2193    ///
2194    /// example: <https://fiddle.skia.org/c/@Canvas_isClipEmpty>
2195    pub fn is_clip_empty(&self) -> bool {
2196        unsafe { sb::C_SkCanvas_isClipEmpty(self.native()) }
2197    }
2198
2199    /// Returns `true` if clip is [`Rect`] and not empty.
2200    /// Returns `false` if the clip is empty, or if it is not [`Rect`].
2201    ///
2202    /// Returns `true` if clip is [`Rect`] and not empty
2203    ///
2204    /// example: <https://fiddle.skia.org/c/@Canvas_isClipRect>
2205    pub fn is_clip_rect(&self) -> bool {
2206        unsafe { sb::C_SkCanvas_isClipRect(self.native()) }
2207    }
2208
2209    /// Returns the current transform from local coordinates to the 'device', which for most
2210    /// purposes means pixels.
2211    ///
2212    /// Returns transformation from local coordinates to device / pixels.
2213    pub fn local_to_device(&self) -> M44 {
2214        M44::construct(|m| unsafe { sb::C_SkCanvas_getLocalToDevice(self.native(), m) })
2215    }
2216
2217    /// Throws away the 3rd row and column in the matrix, so be warned.
2218    pub fn local_to_device_as_3x3(&self) -> Matrix {
2219        self.local_to_device().to_m33()
2220    }
2221
2222    /// DEPRECATED
2223    /// Legacy version of [`Self::local_to_device()`], which strips away any Z information, and just
2224    /// returns a 3x3 version.
2225    ///
2226    /// Returns 3x3 version of [`Self::local_to_device()`]
2227    ///
2228    /// example: <https://fiddle.skia.org/c/@Canvas_getTotalMatrix>
2229    /// example: <https://fiddle.skia.org/c/@Clip>
2230    #[deprecated(
2231        since = "0.38.0",
2232        note = "use local_to_device() or local_to_device_as_3x3() instead"
2233    )]
2234    pub fn total_matrix(&self) -> Matrix {
2235        let mut matrix = Matrix::default();
2236        unsafe { sb::C_SkCanvas_getTotalMatrix(self.native(), matrix.native_mut()) };
2237        matrix
2238    }
2239
2240    //
2241    // internal helper
2242    //
2243
2244    pub(crate) fn own_from_native_ptr<'lt>(native: *mut SkCanvas) -> Option<OwnedCanvas<'lt>> {
2245        if !native.is_null() {
2246            Some(OwnedCanvas::<'lt>(
2247                ptr::NonNull::new(
2248                    Self::borrow_from_native(unsafe { &*native }) as *const _ as *mut _
2249                )
2250                .unwrap(),
2251                PhantomData,
2252            ))
2253        } else {
2254            None
2255        }
2256    }
2257
2258    pub(crate) fn borrow_from_native(native: &SkCanvas) -> &Self {
2259        unsafe { transmute_ref(native) }
2260    }
2261}
2262
2263impl QuickReject<Rect> for Canvas {
2264    /// Returns `true` if [`Rect`] `rect`, transformed by [`Matrix`], can be quickly determined to
2265    /// be outside of clip. May return `false` even though rect is outside of clip.
2266    ///
2267    /// Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
2268    ///
2269    /// - `rect` [`Rect`] to compare with clip
2270    ///
2271    /// Returns `true` if `rect`, transformed by [`Matrix`], does not intersect clip
2272    ///
2273    /// example: <https://fiddle.skia.org/c/@Canvas_quickReject>
2274    fn quick_reject(&self, rect: &Rect) -> bool {
2275        unsafe { self.native().quickReject(rect.native()) }
2276    }
2277}
2278
2279impl QuickReject<Path> for Canvas {
2280    /// Returns `true` if `path`, transformed by [`Matrix`], can be quickly determined to be
2281    /// outside of clip. May return `false` even though `path` is outside of clip.
2282    ///
2283    /// Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
2284    ///
2285    /// - `path` [`Path`] to compare with clip
2286    ///
2287    /// Returns `true` if `path`, transformed by [`Matrix`], does not intersect clip
2288    ///
2289    /// example: <https://fiddle.skia.org/c/@Canvas_quickReject_2>
2290    fn quick_reject(&self, path: &Path) -> bool {
2291        unsafe { self.native().quickReject1(path.native()) }
2292    }
2293}
2294
2295pub trait SetMatrix {
2296    /// DEPRECATED -- use [`M44`] version
2297    #[deprecated(since = "0.38.0", note = "Use M44 version")]
2298    fn set_matrix(&self, matrix: &Matrix) -> &Self;
2299}
2300
2301impl SetMatrix for Canvas {
2302    /// DEPRECATED -- use [`M44`] version
2303    fn set_matrix(&self, matrix: &Matrix) -> &Self {
2304        unsafe { self.native_mut().setMatrix1(matrix.native()) }
2305        self
2306    }
2307}
2308
2309//
2310// Lattice
2311//
2312
2313pub mod lattice {
2314    use crate::{prelude::*, Color, IRect};
2315    use skia_bindings::{self as sb, SkCanvas_Lattice};
2316    use std::marker::PhantomData;
2317
2318    /// [`Lattice`] divides [`crate::Bitmap`] or [`crate::Image`] into a rectangular grid.
2319    /// Grid entries on even columns and even rows are fixed; these entries are
2320    /// always drawn at their original size if the destination is large enough.
2321    /// If the destination side is too small to hold the fixed entries, all fixed
2322    /// entries are proportionately scaled down to fit.
2323    /// The grid entries not on even columns and rows are scaled to fit the
2324    /// remaining space, if any.
2325    #[derive(Debug)]
2326    pub struct Lattice<'a> {
2327        /// x-axis values dividing bitmap
2328        pub x_divs: &'a [i32],
2329        /// y-axis values dividing bitmap
2330        pub y_divs: &'a [i32],
2331        /// array of fill types
2332        pub rect_types: Option<&'a [RectType]>,
2333        /// source bounds to draw from
2334        pub bounds: Option<IRect>,
2335        /// array of colors
2336        pub colors: Option<&'a [Color]>,
2337    }
2338
2339    #[derive(Debug)]
2340    pub(crate) struct Ref<'a> {
2341        pub native: SkCanvas_Lattice,
2342        pd: PhantomData<&'a Lattice<'a>>,
2343    }
2344
2345    impl Lattice<'_> {
2346        pub(crate) fn native(&self) -> Ref {
2347            if let Some(rect_types) = self.rect_types {
2348                let rect_count = (self.x_divs.len() + 1) * (self.y_divs.len() + 1);
2349                assert_eq!(rect_count, rect_types.len());
2350                // even though rect types may not include any FixedColor refs,
2351                // we expect the colors slice with a proper size here, this
2352                // saves us for going over the types array and looking for FixedColor
2353                // entries.
2354                assert_eq!(rect_count, self.colors.unwrap().len());
2355            }
2356
2357            let native = SkCanvas_Lattice {
2358                fXDivs: self.x_divs.as_ptr(),
2359                fYDivs: self.y_divs.as_ptr(),
2360                fRectTypes: self.rect_types.as_ptr_or_null(),
2361                fXCount: self.x_divs.len().try_into().unwrap(),
2362                fYCount: self.y_divs.len().try_into().unwrap(),
2363                fBounds: self.bounds.native().as_ptr_or_null(),
2364                fColors: self.colors.native().as_ptr_or_null(),
2365            };
2366            Ref {
2367                native,
2368                pd: PhantomData,
2369            }
2370        }
2371    }
2372
2373    /// Optional setting per rectangular grid entry to make it transparent,
2374    /// or to fill the grid entry with a color.
2375    pub use sb::SkCanvas_Lattice_RectType as RectType;
2376    variant_name!(RectType::FixedColor);
2377}
2378
2379#[derive(Debug)]
2380/// Stack helper class calls [`Canvas::restore_to_count()`] when [`AutoCanvasRestore`]
2381/// goes out of scope. Use this to guarantee that the canvas is restored to a known
2382/// state.
2383pub struct AutoRestoredCanvas<'a> {
2384    canvas: &'a Canvas,
2385    restore: SkAutoCanvasRestore,
2386}
2387
2388impl Deref for AutoRestoredCanvas<'_> {
2389    type Target = Canvas;
2390    fn deref(&self) -> &Self::Target {
2391        self.canvas
2392    }
2393}
2394
2395impl NativeAccess for AutoRestoredCanvas<'_> {
2396    type Native = SkAutoCanvasRestore;
2397
2398    fn native(&self) -> &SkAutoCanvasRestore {
2399        &self.restore
2400    }
2401
2402    fn native_mut(&mut self) -> &mut SkAutoCanvasRestore {
2403        &mut self.restore
2404    }
2405}
2406
2407impl Drop for AutoRestoredCanvas<'_> {
2408    /// Restores [`Canvas`] to saved state. Drop is called when container goes out of scope.
2409    fn drop(&mut self) {
2410        unsafe { sb::C_SkAutoCanvasRestore_destruct(self.native_mut()) }
2411    }
2412}
2413
2414impl AutoRestoredCanvas<'_> {
2415    /// Restores [`Canvas`] to saved state immediately. Subsequent calls and [`Self::drop()`] have
2416    /// no effect.
2417    pub fn restore(&mut self) {
2418        unsafe { sb::C_SkAutoCanvasRestore_restore(self.native_mut()) }
2419    }
2420}
2421
2422pub enum AutoCanvasRestore {}
2423
2424impl AutoCanvasRestore {
2425    // TODO: rename to save(), add a method to Canvas, perhaps named auto_restored()?
2426    /// Preserves [`Canvas::save()`] count. Optionally saves [`Canvas`] clip and [`Canvas`] matrix.
2427    ///
2428    /// - `canvas` [`Canvas`] to guard
2429    /// - `do_save` call [`Canvas::save()`]
2430    ///
2431    /// Returns utility to restore [`Canvas`] state on destructor
2432    pub fn guard(canvas: &Canvas, do_save: bool) -> AutoRestoredCanvas {
2433        let restore = construct(|acr| unsafe {
2434            sb::C_SkAutoCanvasRestore_Construct(acr, canvas.native_mut(), do_save)
2435        });
2436
2437        AutoRestoredCanvas { canvas, restore }
2438    }
2439}
2440
2441#[cfg(test)]
2442mod tests {
2443    use crate::{
2444        canvas::SaveLayerFlags, canvas::SaveLayerRec, surfaces, AlphaType, Canvas, ClipOp, Color,
2445        ColorType, ImageInfo, OwnedCanvas, Rect,
2446    };
2447
2448    #[test]
2449    fn test_raster_direct_creation_and_clear_in_memory() {
2450        let info = ImageInfo::new((2, 2), ColorType::RGBA8888, AlphaType::Unpremul, None);
2451        assert_eq!(8, info.min_row_bytes());
2452        let mut bytes: [u8; 8 * 2] = Default::default();
2453        {
2454            let canvas = Canvas::from_raster_direct(&info, bytes.as_mut(), None, None).unwrap();
2455            canvas.clear(Color::RED);
2456        }
2457
2458        assert_eq!(0xff, bytes[0]);
2459        assert_eq!(0x00, bytes[1]);
2460        assert_eq!(0x00, bytes[2]);
2461        assert_eq!(0xff, bytes[3]);
2462    }
2463
2464    #[test]
2465    fn test_raster_direct_n32_creation_and_clear_in_memory() {
2466        let mut pixels: [u32; 4] = Default::default();
2467        {
2468            let canvas = Canvas::from_raster_direct_n32((2, 2), pixels.as_mut(), None).unwrap();
2469            canvas.clear(Color::RED);
2470        }
2471
2472        // TODO: equals to 0xff0000ff on macOS, but why? Endianness should be the same.
2473        // assert_eq!(0xffff0000, pixels[0]);
2474    }
2475
2476    #[test]
2477    fn test_empty_canvas_creation() {
2478        let canvas = OwnedCanvas::default();
2479        drop(canvas)
2480    }
2481
2482    #[test]
2483    fn test_save_layer_rec_lifetimes() {
2484        let rect = Rect::default();
2485        {
2486            let _rec = SaveLayerRec::default()
2487                .flags(SaveLayerFlags::PRESERVE_LCD_TEXT)
2488                .bounds(&rect);
2489        }
2490    }
2491
2492    #[test]
2493    fn test_make_surface() {
2494        let mut pixels: [u32; 4] = Default::default();
2495        let canvas = Canvas::from_raster_direct_n32((2, 2), pixels.as_mut(), None).unwrap();
2496        let ii = canvas.image_info();
2497        let mut surface = canvas.new_surface(&ii, None).unwrap();
2498        dbg!(&canvas as *const _);
2499        drop(canvas);
2500
2501        let canvas = surface.canvas();
2502        dbg!(canvas as *const _);
2503        canvas.clear(Color::RED);
2504    }
2505
2506    #[test]
2507    fn clip_options_overloads() {
2508        let c = OwnedCanvas::default();
2509        // do_anti_alias
2510        c.clip_rect(Rect::default(), None, true);
2511        // clip_op
2512        c.clip_rect(Rect::default(), ClipOp::Difference, None);
2513        // both
2514        c.clip_rect(Rect::default(), ClipOp::Difference, true);
2515    }
2516
2517    /// Regression test for: <https://github.com/rust-skia/rust-skia/issues/427>
2518    #[test]
2519    fn test_local_and_device_clip_bounds() {
2520        let mut surface =
2521            surfaces::raster(&ImageInfo::new_n32_premul((100, 100), None), 0, None).unwrap();
2522        let _ = surface.canvas().device_clip_bounds();
2523        let _ = surface.canvas().local_clip_bounds();
2524        let _ = surface.canvas().local_to_device();
2525    }
2526}