skia_safe/core/
path.rs

1use std::{fmt, marker::PhantomData, mem::forget, ptr};
2
3use skia_bindings::{self as sb, SkPath, SkPath_Iter, SkPath_RawIter};
4
5use crate::{
6    interop::DynamicMemoryWStream, matrix::ApplyPerspectiveClip, path_types, prelude::*, scalar,
7    Data, Matrix, PathDirection, PathFillType, Point, RRect, Rect, Vector,
8};
9
10#[deprecated(since = "0.25.0", note = "use PathDirection")]
11pub use path_types::PathDirection as Direction;
12
13#[deprecated(since = "0.25.0", note = "use PathFillType")]
14pub use path_types::PathFillType as FillType;
15
16/// Four oval parts with radii (rx, ry) start at last [`Path`] [`Point`] and ends at (x, y).
17/// ArcSize and Direction select one of the four oval parts.
18pub use sb::SkPath_ArcSize as ArcSize;
19variant_name!(ArcSize::Small);
20
21/// AddPathMode chooses how `add_path()` appends. Adding one [`Path`] to another can extend
22/// the last contour or start a new contour.
23pub use sb::SkPath_AddPathMode as AddPathMode;
24variant_name!(AddPathMode::Append);
25
26/// SegmentMask constants correspond to each drawing Verb type in [`crate::Path`]; for instance, if
27/// [`crate::Path`] only contains lines, only the [`crate::path::SegmentMask::LINE`] bit is set.
28pub use path_types::PathSegmentMask as SegmentMask;
29
30/// Verb instructs [`Path`] how to interpret one or more [`Point`] and optional conic weight;
31/// manage contour, and terminate [`Path`].
32pub use sb::SkPath_Verb as Verb;
33
34use super::Arc;
35variant_name!(Verb::Line);
36
37/// Iterates through verb array, and associated [`Point`] array and conic weight.
38/// Provides options to treat open contours as closed, and to ignore
39/// degenerate data.
40#[repr(C)]
41pub struct Iter<'a>(SkPath_Iter, PhantomData<&'a Handle<SkPath>>);
42
43impl NativeAccess for Iter<'_> {
44    type Native = SkPath_Iter;
45
46    fn native(&self) -> &SkPath_Iter {
47        &self.0
48    }
49    fn native_mut(&mut self) -> &mut SkPath_Iter {
50        &mut self.0
51    }
52}
53
54impl Drop for Iter<'_> {
55    fn drop(&mut self) {
56        unsafe { sb::C_SkPath_Iter_destruct(&mut self.0) }
57    }
58}
59
60impl Default for Iter<'_> {
61    /// Initializes [`Iter`] with an empty [`Path`]. `next()` on [`Iter`] returns
62    /// [`Verb::Done`].
63    /// Call `set_path` to initialize [`Iter`] at a later time.
64    ///
65    /// Returns: [`Iter`] of empty [`Path`]
66    ///
67    /// example: <https://fiddle.skia.org/c/@Path_Iter_Iter>
68    fn default() -> Self {
69        Iter(unsafe { SkPath_Iter::new() }, PhantomData)
70    }
71}
72
73impl fmt::Debug for Iter<'_> {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("Iter")
76            .field("conic_weight", &self.conic_weight())
77            .field("is_close_line", &self.is_close_line())
78            .field("is_closed_contour", &self.is_closed_contour())
79            .finish()
80    }
81}
82
83impl Iter<'_> {
84    /// Sets [`Iter`] to return elements of verb array, [`Point`] array, and conic weight in
85    /// path. If `force_close` is `true`, [`Iter`] will add [`Verb::Line`] and [`Verb::Close`] after each
86    /// open contour. path is not altered.
87    ///
88    /// * `path` - [`Path`] to iterate
89    /// * `force_close` - `true` if open contours generate [`Verb::Close`]
90    ///
91    /// Returns: [`Iter`] of path
92    ///
93    /// example: <https://fiddle.skia.org/c/@Path_Iter_const_SkPath>
94    pub fn new(path: &Path, force_close: bool) -> Iter {
95        Iter(
96            unsafe { SkPath_Iter::new1(path.native(), force_close) },
97            PhantomData,
98        )
99    }
100
101    /// Sets [`Iter`] to return elements of verb array, [`Point`] array, and conic weight in
102    /// path. If `force_close` is `true`, [`Iter`] will add [`Verb::Line`] and [`Verb::Close`] after each
103    /// open contour. path is not altered.
104    ///
105    /// * `path` - [`Path`] to iterate
106    /// * `force_close` - `true` if open contours generate [`Verb::Close`]
107    ///
108    /// example: <https://fiddle.skia.org/c/@Path_Iter_setPath>
109    pub fn set_path(mut self, path: &Path, force_close: bool) -> Iter {
110        unsafe {
111            self.0.setPath(path.native(), force_close);
112        }
113        let r = Iter(self.0, PhantomData);
114        forget(self);
115        r
116    }
117
118    /// Returns conic weight if `next()` returned [`Verb::Conic`].
119    ///
120    /// If `next()` has not been called, or `next()` did not return [`Verb::Conic`],
121    /// result is `None`.
122    ///
123    /// Returns: conic weight for conic [`Point`] returned by `next()`
124    pub fn conic_weight(&self) -> Option<scalar> {
125        #[allow(clippy::map_clone)]
126        self.native()
127            .fConicWeights
128            .into_option()
129            .map(|p| unsafe { *p })
130    }
131
132    /// Returns `true` if last [`Verb::Line`] returned by `next()` was generated
133    /// by [`Verb::Close`]. When `true`, the end point returned by `next()` is
134    /// also the start point of contour.
135    ///
136    /// If `next()` has not been called, or `next()` did not return [`Verb::Line`],
137    /// result is undefined.
138    ///
139    /// Returns: `true` if last [`Verb::Line`] was generated by [`Verb::Close`]
140    pub fn is_close_line(&self) -> bool {
141        unsafe { sb::C_SkPath_Iter_isCloseLine(self.native()) }
142    }
143
144    /// Returns `true` if subsequent calls to `next()` return [`Verb::Close`] before returning
145    /// [`Verb::Move`]. if `true`, contour [`Iter`] is processing may end with [`Verb::Close`], or
146    /// [`Iter`] may have been initialized with force close set to `true`.
147    ///
148    /// Returns: `true` if contour is closed
149    ///
150    /// example: <https://fiddle.skia.org/c/@Path_Iter_isClosedContour>
151    pub fn is_closed_contour(&self) -> bool {
152        unsafe { self.native().isClosedContour() }
153    }
154}
155
156impl Iterator for Iter<'_> {
157    type Item = (Verb, Vec<Point>);
158
159    /// Returns next [`Verb`] in verb array, and advances [`Iter`].
160    /// When verb array is exhausted, returns [`Verb::Done`].
161    ///
162    /// Zero to four [`Point`] are stored in pts, depending on the returned [`Verb`].
163    ///
164    /// * `pts` - storage for [`Point`] data describing returned [`Verb`]
165    ///
166    /// Returns: next [`Verb`] from verb array
167    ///
168    /// example: <https://fiddle.skia.org/c/@Path_RawIter_next>
169    fn next(&mut self) -> Option<Self::Item> {
170        let mut points = [Point::default(); Verb::MAX_POINTS];
171        let verb = unsafe { self.native_mut().next(points.native_mut().as_mut_ptr()) };
172        if verb != Verb::Done {
173            Some((verb, points[0..verb.points()].into()))
174        } else {
175            None
176        }
177    }
178}
179
180#[repr(C)]
181#[deprecated(
182    since = "0.30.0",
183    note = "User Iter instead, RawIter will soon be removed."
184)]
185pub struct RawIter<'a>(SkPath_RawIter, PhantomData<&'a Handle<SkPath>>);
186
187#[allow(deprecated)]
188impl NativeAccess for RawIter<'_> {
189    type Native = SkPath_RawIter;
190
191    fn native(&self) -> &SkPath_RawIter {
192        &self.0
193    }
194    fn native_mut(&mut self) -> &mut SkPath_RawIter {
195        &mut self.0
196    }
197}
198
199#[allow(deprecated)]
200impl Drop for RawIter<'_> {
201    fn drop(&mut self) {
202        unsafe { sb::C_SkPath_RawIter_destruct(&mut self.0) }
203    }
204}
205
206#[allow(deprecated)]
207impl Default for RawIter<'_> {
208    fn default() -> Self {
209        RawIter(
210            construct(|ri| unsafe { sb::C_SkPath_RawIter_Construct(ri) }),
211            PhantomData,
212        )
213    }
214}
215
216#[allow(deprecated)]
217impl RawIter<'_> {
218    pub fn new(path: &Path) -> RawIter {
219        RawIter::default().set_path(path)
220    }
221
222    pub fn set_path(mut self, path: &Path) -> RawIter {
223        unsafe { self.native_mut().setPath(path.native()) }
224        let r = RawIter(self.0, PhantomData);
225        forget(self);
226        r
227    }
228
229    pub fn peek(&self) -> Verb {
230        unsafe { sb::C_SkPath_RawIter_peek(self.native()) }
231    }
232
233    pub fn conic_weight(&self) -> scalar {
234        self.native().fConicWeight
235    }
236}
237
238#[allow(deprecated)]
239impl Iterator for RawIter<'_> {
240    type Item = (Verb, Vec<Point>);
241
242    fn next(&mut self) -> Option<Self::Item> {
243        let mut points = [Point::default(); Verb::MAX_POINTS];
244
245        let verb = unsafe { self.native_mut().next(points.native_mut().as_mut_ptr()) };
246        (verb != Verb::Done).if_true_some((verb, points[0..verb.points()].into()))
247    }
248}
249
250pub type Path = Handle<SkPath>;
251unsafe_send_sync!(Path);
252
253impl NativeDrop for SkPath {
254    /// Releases ownership of any shared data and deletes data if [`Path`] is sole owner.
255    ///
256    /// example: <https://fiddle.skia.org/c/@Path_destructor>
257    fn drop(&mut self) {
258        unsafe { sb::C_SkPath_destruct(self) }
259    }
260}
261
262impl NativeClone for SkPath {
263    /// Constructs a copy of an existing path.
264    /// Copy constructor makes two paths identical by value. Internally, path and
265    /// the returned result share pointer values. The underlying verb array, [`Point`] array
266    /// and weights are copied when modified.
267    ///
268    /// Creating a [`Path`] copy is very efficient and never allocates memory.
269    /// [`Path`] are always copied by value from the interface; the underlying shared
270    /// pointers are not exposed.
271    ///
272    /// * `path` - [`Path`] to copy by value
273    ///
274    /// Returns: copy of [`Path`]
275    ///
276    /// example: <https://fiddle.skia.org/c/@Path_copy_const_SkPath>
277    fn clone(&self) -> Self {
278        unsafe { SkPath::new1(self) }
279    }
280}
281
282impl NativePartialEq for SkPath {
283    /// Compares a and b; returns `true` if [`path::FillType`], verb array, [`Point`] array, and weights
284    /// are equivalent.
285    ///
286    /// * `a` - [`Path`] to compare
287    /// * `b` - [`Path`] to compare
288    ///
289    /// Returns: `true` if [`Path`] pair are equivalent
290    fn eq(&self, rhs: &Self) -> bool {
291        unsafe { sb::C_SkPath_Equals(self, rhs) }
292    }
293}
294
295impl Default for Handle<SkPath> {
296    /// See [`Self::new()`]
297    fn default() -> Self {
298        Self::new()
299    }
300}
301
302impl fmt::Debug for Path {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        f.debug_struct("Path")
305            .field("fill_type", &self.fill_type())
306            .field("is_convex", &self.is_convex())
307            .field("is_oval", &self.is_oval())
308            .field("is_rrect", &self.is_rrect())
309            .field("is_arc", &self.is_arc())
310            .field("is_empty", &self.is_empty())
311            .field("is_last_contour_closed", &self.is_last_contour_closed())
312            .field("is_finite", &self.is_finite())
313            .field("is_volatile", &self.is_volatile())
314            .field("is_line", &self.is_line())
315            .field("count_points", &self.count_points())
316            .field("count_verbs", &self.count_verbs())
317            .field("approximate_bytes_used", &self.approximate_bytes_used())
318            .field("bounds", &self.bounds())
319            .field("is_rect", &self.is_rect())
320            .field("segment_masks", &self.segment_masks())
321            .field("generation_id", &self.generation_id())
322            .field("is_valid", &self.is_valid())
323            .finish()
324    }
325}
326
327/// [`Path`] contain geometry. [`Path`] may be empty, or contain one or more verbs that
328/// outline a figure. [`Path`] always starts with a move verb to a Cartesian coordinate,
329/// and may be followed by additional verbs that add lines or curves.
330/// Adding a close verb makes the geometry into a continuous loop, a closed contour.
331/// [`Path`] may contain any number of contours, each beginning with a move verb.
332///
333/// [`Path`] contours may contain only a move verb, or may also contain lines,
334/// quadratic beziers, conics, and cubic beziers. [`Path`] contours may be open or
335/// closed.
336///
337/// When used to draw a filled area, [`Path`] describes whether the fill is inside or
338/// outside the geometry. [`Path`] also describes the winding rule used to fill
339/// overlapping contours.
340///
341/// Internally, [`Path`] lazily computes metrics likes bounds and convexity. Call
342/// [`Path::update_bounds_cache`] to make [`Path`] thread safe.
343impl Path {
344    /// Create a new path with the specified segments.
345    ///
346    /// The points and weights arrays are read in order, based on the sequence of verbs.
347    ///
348    /// Move    1 point
349    /// Line    1 point
350    /// Quad    2 points
351    /// Conic   2 points and 1 weight
352    /// Cubic   3 points
353    /// Close   0 points
354    ///
355    /// If an illegal sequence of verbs is encountered, or the specified number of points
356    /// or weights is not sufficient given the verbs, an empty Path is returned.
357    ///
358    /// A legal sequence of verbs consists of any number of Contours. A contour always begins
359    /// with a Move verb, followed by 0 or more segments: Line, Quad, Conic, Cubic, followed
360    /// by an optional Close.
361    pub fn new_from(
362        points: &[Point],
363        verbs: &[u8],
364        conic_weights: &[scalar],
365        fill_type: FillType,
366        is_volatile: impl Into<Option<bool>>,
367    ) -> Self {
368        Self::construct(|path| unsafe {
369            sb::C_SkPath_Make(
370                path,
371                points.native().as_ptr(),
372                points.len().try_into().unwrap(),
373                verbs.as_ptr(),
374                verbs.len().try_into().unwrap(),
375                conic_weights.as_ptr(),
376                conic_weights.len().try_into().unwrap(),
377                fill_type,
378                is_volatile.into().unwrap_or(false),
379            )
380        })
381    }
382
383    pub fn rect(rect: impl AsRef<Rect>, dir: impl Into<Option<PathDirection>>) -> Self {
384        Self::construct(|path| unsafe {
385            sb::C_SkPath_Rect(
386                path,
387                rect.as_ref().native(),
388                dir.into().unwrap_or(PathDirection::CW),
389            )
390        })
391    }
392
393    pub fn oval(oval: impl AsRef<Rect>, dir: impl Into<Option<PathDirection>>) -> Self {
394        Self::construct(|path| unsafe {
395            sb::C_SkPath_Oval(
396                path,
397                oval.as_ref().native(),
398                dir.into().unwrap_or(PathDirection::CW),
399            )
400        })
401    }
402
403    pub fn oval_with_start_index(
404        oval: impl AsRef<Rect>,
405        dir: PathDirection,
406        start_index: usize,
407    ) -> Self {
408        Self::construct(|path| unsafe {
409            sb::C_SkPath_OvalWithStartIndex(
410                path,
411                oval.as_ref().native(),
412                dir,
413                start_index.try_into().unwrap(),
414            )
415        })
416    }
417
418    pub fn circle(
419        center: impl Into<Point>,
420        radius: scalar,
421        dir: impl Into<Option<PathDirection>>,
422    ) -> Self {
423        let center = center.into();
424        Self::construct(|path| unsafe {
425            sb::C_SkPath_Circle(
426                path,
427                center.x,
428                center.y,
429                radius,
430                dir.into().unwrap_or(PathDirection::CW),
431            )
432        })
433    }
434
435    pub fn rrect(rect: impl AsRef<RRect>, dir: impl Into<Option<PathDirection>>) -> Self {
436        Self::construct(|path| unsafe {
437            sb::C_SkPath_RRect(
438                path,
439                rect.as_ref().native(),
440                dir.into().unwrap_or(PathDirection::CW),
441            )
442        })
443    }
444
445    pub fn rrect_with_start_index(
446        rect: impl AsRef<RRect>,
447        dir: PathDirection,
448        start_index: usize,
449    ) -> Self {
450        Self::construct(|path| unsafe {
451            sb::C_SkPath_RRectWithStartIndex(
452                path,
453                rect.as_ref().native(),
454                dir,
455                start_index.try_into().unwrap(),
456            )
457        })
458    }
459
460    pub fn polygon(
461        pts: &[Point],
462        is_closed: bool,
463        fill_type: impl Into<Option<FillType>>,
464        is_volatile: impl Into<Option<bool>>,
465    ) -> Self {
466        Self::construct(|path| unsafe {
467            sb::C_SkPath_Polygon(
468                path,
469                pts.native().as_ptr(),
470                pts.len().try_into().unwrap(),
471                is_closed,
472                fill_type.into().unwrap_or(FillType::Winding),
473                is_volatile.into().unwrap_or(false),
474            )
475        })
476    }
477
478    pub fn line(a: impl Into<Point>, b: impl Into<Point>) -> Self {
479        Self::polygon(&[a.into(), b.into()], false, None, None)
480    }
481
482    /// Constructs an empty [`Path`]. By default, [`Path`] has no verbs, no [`Point`], and no weights.
483    /// FillType is set to `Winding`.
484    ///
485    /// Returns: empty [`Path`]
486    ///
487    /// example: <https://fiddle.skia.org/c/@Path_empty_constructor>
488    pub fn new() -> Self {
489        Self::construct(|path| unsafe { sb::C_SkPath_Construct(path) })
490    }
491
492    /// Returns a copy of this path in the current state.
493    pub fn snapshot(&self) -> Self {
494        self.clone()
495    }
496
497    /// Returns a copy of this path in the current state, and resets the path to empty.
498    pub fn detach(&mut self) -> Self {
499        let result = self.clone();
500        self.reset();
501        result
502    }
503
504    /// Returns `true` if [`Path`] contain equal verbs and equal weights.
505    /// If [`Path`] contain one or more conics, the weights must match.
506    ///
507    /// `conic_to()` may add different verbs depending on conic weight, so it is not
508    /// trivial to interpolate a pair of [`Path`] containing conics with different
509    /// conic weight values.
510    ///
511    /// * `compare` - [`Path`] to compare
512    ///
513    /// Returns: `true` if [`Path`] verb array and weights are equivalent
514    ///
515    /// example: <https://fiddle.skia.org/c/@Path_isInterpolatable>
516    pub fn is_interpolatable(&self, compare: &Path) -> bool {
517        unsafe { self.native().isInterpolatable(compare.native()) }
518    }
519
520    /// Interpolates between [`Path`] with [`Point`] array of equal size.
521    /// Copy verb array and weights to out, and set out [`Point`] array to a weighted
522    /// average of this [`Point`] array and ending [`Point`] array, using the formula:
523    /// (Path Point * weight) + ending Point * (1 - weight).
524    ///
525    /// weight is most useful when between zero (ending [`Point`] array) and
526    /// one (this Point_Array); will work with values outside of this
527    /// range.
528    ///
529    /// `interpolate()` returns `false` and leaves out unchanged if [`Point`] array is not
530    /// the same size as ending [`Point`] array. Call `is_interpolatable()` to check [`Path`]
531    /// compatibility prior to calling interpolate().
532    ///
533    /// * `ending` - [`Point`] array averaged with this [`Point`] array
534    /// * `weight` - contribution of this [`Point`] array, and
535    ///                one minus contribution of ending [`Point`] array
536    /// * `out` - [`Path`] replaced by interpolated averages
537    ///
538    /// Returns: `true` if [`Path`] contain same number of [`Point`]
539    ///
540    /// example: <https://fiddle.skia.org/c/@Path_interpolate>
541    pub fn interpolate(&self, ending: &Path, weight: scalar) -> Option<Path> {
542        let mut out = Path::default();
543        unsafe {
544            self.native()
545                .interpolate(ending.native(), weight, out.native_mut())
546        }
547        .if_true_some(out)
548    }
549
550    /// Returns [`PathFillType`], the rule used to fill [`Path`].
551    ///
552    /// Returns: current [`PathFillType`] setting
553    pub fn fill_type(&self) -> PathFillType {
554        unsafe { sb::C_SkPath_getFillType(self.native()) }
555    }
556
557    /// Sets FillType, the rule used to fill [`Path`]. While there is no check
558    /// that ft is legal, values outside of FillType are not supported.
559    pub fn set_fill_type(&mut self, ft: PathFillType) -> &mut Self {
560        self.native_mut().set_fFillType(ft as _);
561        self
562    }
563
564    /// Returns if FillType describes area outside [`Path`] geometry. The inverse fill area
565    /// extends indefinitely.
566    ///
567    /// Returns: `true` if FillType is `InverseWinding` or `InverseEvenOdd`
568    pub fn is_inverse_fill_type(&self) -> bool {
569        self.fill_type().is_inverse()
570    }
571
572    /// Replaces FillType with its inverse. The inverse of FillType describes the area
573    /// unmodified by the original FillType.
574    pub fn toggle_inverse_fill_type(&mut self) -> &mut Self {
575        let inverse = self.native().fFillType() ^ 2;
576        self.native_mut().set_fFillType(inverse);
577        self
578    }
579
580    #[deprecated(since = "0.36.0", note = "Removed, use is_convex()")]
581    pub fn convexity_type(&self) -> ! {
582        panic!("Removed")
583    }
584
585    #[deprecated(since = "0.36.0", note = "Removed, use is_convex()")]
586    pub fn convexity_type_or_unknown(&self) -> ! {
587        panic!("Removed")
588    }
589
590    /// Returns `true` if the path is convex. If necessary, it will first compute the convexity.
591    pub fn is_convex(&self) -> bool {
592        unsafe { self.native().isConvex() }
593    }
594
595    /// Returns `true` if this path is recognized as an oval or circle.
596    ///
597    /// bounds receives bounds of oval.
598    ///
599    /// bounds is unmodified if oval is not found.
600    ///
601    /// * `bounds` - storage for bounding [`Rect`] of oval; may be `None`
602    ///
603    /// Returns: `true` if [`Path`] is recognized as an oval or circle
604    ///
605    /// example: <https://fiddle.skia.org/c/@Path_isOval>
606    pub fn is_oval(&self) -> Option<Rect> {
607        let mut bounds = Rect::default();
608        unsafe { self.native().isOval(bounds.native_mut()) }.if_true_some(bounds)
609    }
610
611    /// Returns [`RRect`] if path is representable as [`RRect`].
612    /// Returns `None` if path is representable as oval, circle, or [`Rect`].
613    ///
614    /// Returns: [`RRect`] if [`Path`] contains only [`RRect`]
615    ///
616    /// example: <https://fiddle.skia.org/c/@Path_isRRect>
617    pub fn is_rrect(&self) -> Option<RRect> {
618        let mut rrect = RRect::default();
619        unsafe { self.native().isRRect(rrect.native_mut()) }.if_true_some(rrect)
620    }
621
622    /// Returns [`Arc`] if path is representable as an oval arc. In other words, could this
623    /// path be drawn using `Canvas::draw_arc()`.
624    ///
625    /// Returns: [`Arc`] if [`Path`] contains only a single arc from an oval
626    pub fn is_arc(&self) -> Option<Arc> {
627        let mut arc = Arc::default();
628        unsafe { self.native().isArc(arc.native_mut()) }.if_true_some(arc)
629    }
630
631    /// Sets [`Path`] to its initial state.
632    /// Removes verb array, [`Point`] array, and weights, and sets FillType to `Winding`.
633    /// Internal storage associated with [`Path`] is released.
634    ///
635    /// Returns: reference to [`Path`]
636    ///
637    /// example: <https://fiddle.skia.org/c/@Path_reset>
638    pub fn reset(&mut self) -> &mut Self {
639        unsafe { self.native_mut().reset() };
640        self
641    }
642
643    /// Sets [`Path`] to its initial state, preserving internal storage.
644    /// Removes verb array, [`Point`] array, and weights, and sets FillType to `Winding`.
645    /// Internal storage associated with [`Path`] is retained.
646    ///
647    /// Use `rewind()` instead of `reset()` if [`Path`] storage will be reused and performance
648    /// is critical.
649    ///
650    /// Returns: reference to [`Path`]
651    ///
652    /// example: <https://fiddle.skia.org/c/@Path_rewind>
653    ///
654    pub fn rewind(&mut self) -> &mut Self {
655        unsafe { self.native_mut().rewind() };
656        self
657    }
658
659    /// Returns if [`Path`] is empty.
660    /// Empty [`Path`] may have FillType but has no [`Point`], [`Verb`], or conic weight.
661    /// [`Path::default()`] constructs empty [`Path`]; `reset()` and `rewind()` make [`Path`] empty.
662    ///
663    /// Returns: `true` if the path contains no [`Verb`] array
664    pub fn is_empty(&self) -> bool {
665        unsafe { self.native().isEmpty() }
666    }
667
668    /// Returns if contour is closed.
669    /// Contour is closed if [`Path`] [`Verb`] array was last modified by `close()`. When stroked,
670    /// closed contour draws [`crate::paint::Join`] instead of [`crate::paint::Cap`] at first and last [`Point`].
671    ///
672    /// Returns: `true` if the last contour ends with a [`Verb::Close`]
673    ///
674    /// example: <https://fiddle.skia.org/c/@Path_isLastContourClosed>
675    pub fn is_last_contour_closed(&self) -> bool {
676        unsafe { self.native().isLastContourClosed() }
677    }
678
679    /// Returns `true` for finite [`Point`] array values between negative SK_ScalarMax and
680    /// positive SK_ScalarMax. Returns `false` for any [`Point`] array value of
681    /// SK_ScalarInfinity, SK_ScalarNegativeInfinity, or SK_ScalarNaN.
682    ///
683    /// Returns: `true` if all [`Point`] values are finite
684    pub fn is_finite(&self) -> bool {
685        unsafe { self.native().isFinite() }
686    }
687
688    /// Returns `true` if the path is volatile; it will not be altered or discarded
689    /// by the caller after it is drawn. [`Path`] by default have volatile set `false`, allowing
690    /// [`crate::Surface`] to attach a cache of data which speeds repeated drawing. If `true`, [`crate::Surface`]
691    /// may not speed repeated drawing.
692    ///
693    /// Returns: `true` if caller will alter [`Path`] after drawing
694    pub fn is_volatile(&self) -> bool {
695        self.native().fIsVolatile() != 0
696    }
697
698    /// Specifies whether [`Path`] is volatile; whether it will be altered or discarded
699    /// by the caller after it is drawn. [`Path`] by default have volatile set `false`, allowing
700    /// `Device` to attach a cache of data which speeds repeated drawing.
701    ///
702    /// Mark temporary paths, discarded or modified after use, as volatile
703    /// to inform `Device` that the path need not be cached.
704    ///
705    /// Mark animating [`Path`] volatile to improve performance.
706    /// Mark unchanging [`Path`] non-volatile to improve repeated rendering.
707    ///
708    /// raster surface [`Path`] draws are affected by volatile for some shadows.
709    /// GPU surface [`Path`] draws are affected by volatile for some shadows and concave geometries.
710    ///
711    /// * `is_volatile` - `true` if caller will alter [`Path`] after drawing
712    ///
713    /// Returns: reference to [`Path`]
714    pub fn set_is_volatile(&mut self, is_volatile: bool) -> &mut Self {
715        self.native_mut().set_fIsVolatile(is_volatile as _);
716        self
717    }
718
719    /// Tests if line between [`Point`] pair is degenerate.
720    /// Line with no length or that moves a very short distance is degenerate; it is
721    /// treated as a point.
722    ///
723    /// exact changes the equality test. If `true`, returns `true` only if p1 equals p2.
724    /// If `false`, returns `true` if p1 equals or nearly equals p2.
725    ///
726    /// * `p1` - line start point
727    /// * `p2` - line end point
728    /// * `exact` - if `false`, allow nearly equals
729    ///
730    /// Returns: `true` if line is degenerate; its length is effectively zero
731    ///
732    /// example: <https://fiddle.skia.org/c/@Path_IsLineDegenerate>
733    pub fn is_line_degenerate(p1: impl Into<Point>, p2: impl Into<Point>, exact: bool) -> bool {
734        unsafe { SkPath::IsLineDegenerate(p1.into().native(), p2.into().native(), exact) }
735    }
736
737    /// Tests if quad is degenerate.
738    /// Quad with no length or that moves a very short distance is degenerate; it is
739    /// treated as a point.
740    ///
741    /// * `p1` - quad start point
742    /// * `p2` - quad control point
743    /// * `p3` - quad end point
744    /// * `exact` - if `true`, returns `true` only if p1, p2, and p3 are equal;
745    ///               if `false`, returns `true` if p1, p2, and p3 are equal or nearly equal
746    ///
747    /// Returns: `true` if quad is degenerate; its length is effectively zero
748    pub fn is_quad_degenerate(
749        p1: impl Into<Point>,
750        p2: impl Into<Point>,
751        p3: impl Into<Point>,
752        exact: bool,
753    ) -> bool {
754        unsafe {
755            SkPath::IsQuadDegenerate(
756                p1.into().native(),
757                p2.into().native(),
758                p3.into().native(),
759                exact,
760            )
761        }
762    }
763
764    /// Tests if cubic is degenerate.
765    /// Cubic with no length or that moves a very short distance is degenerate; it is
766    /// treated as a point.
767    ///
768    /// * `p1` - cubic start point
769    /// * `p2` - cubic control point 1
770    /// * `p3` - cubic control point 2
771    /// * `p4` - cubic end point
772    /// * `exact` - if `true`, returns `true` only if p1, p2, p3, and p4 are equal;
773    ///               if `false`, returns `true` if p1, p2, p3, and p4 are equal or nearly equal
774    ///
775    /// Returns: `true` if cubic is degenerate; its length is effectively zero
776    pub fn is_cubic_degenerate(
777        p1: impl Into<Point>,
778        p2: impl Into<Point>,
779        p3: impl Into<Point>,
780        p4: impl Into<Point>,
781        exact: bool,
782    ) -> bool {
783        unsafe {
784            SkPath::IsCubicDegenerate(
785                p1.into().native(),
786                p2.into().native(),
787                p3.into().native(),
788                p4.into().native(),
789                exact,
790            )
791        }
792    }
793
794    /// Returns `true` if [`Path`] contains only one line;
795    /// [`Verb`] array has two entries: [`Verb::Move`], [`Verb::Line`].
796    /// If [`Path`] contains one line and line is not `None`, line is set to
797    /// line start point and line end point.
798    /// Returns `false` if [`Path`] is not one line; line is unaltered.
799    ///
800    /// * `line` - storage for line. May be `None`
801    ///
802    /// Returns: `true` if [`Path`] contains exactly one line
803    ///
804    /// example: <https://fiddle.skia.org/c/@Path_isLine>
805    pub fn is_line(&self) -> Option<(Point, Point)> {
806        let mut line = [Point::default(); 2];
807        #[allow(clippy::tuple_array_conversions)]
808        unsafe { self.native().isLine(line.native_mut().as_mut_ptr()) }
809            .if_true_some((line[0], line[1]))
810    }
811
812    /// Returns the number of points in [`Path`].
813    /// [`Point`] count is initially zero.
814    ///
815    /// Returns: [`Path`] [`Point`] array length
816    ///
817    /// example: <https://fiddle.skia.org/c/@Path_countPoints>
818    pub fn count_points(&self) -> usize {
819        unsafe { self.native().countPoints().try_into().unwrap() }
820    }
821
822    /// Returns [`Point`] at index in [`Point`] array. Valid range for index is
823    /// 0 to `count_points()` - 1.
824    /// Returns (0, 0) if index is out of range.
825    ///
826    /// * `index` - [`Point`] array element selector
827    ///
828    /// Returns: [`Point`] array value or (0, 0)
829    ///
830    /// example: <https://fiddle.skia.org/c/@Path_getPoint>
831    pub fn get_point(&self, index: usize) -> Option<Point> {
832        let p = Point::from_native_c(unsafe {
833            sb::C_SkPath_getPoint(self.native(), index.try_into().unwrap())
834        });
835        // assuming that count_points() is somewhat slow, we
836        // check the index when a Point(0,0) is returned.
837        if p != Point::default() || index < self.count_points() {
838            Some(p)
839        } else {
840            None
841        }
842    }
843
844    /// Returns number of points in [`Path`]. Up to max points are copied.
845    /// points may be `None`; then, max must be zero.
846    /// If max is greater than number of points, excess points storage is unaltered.
847    ///
848    /// * `points` - storage for [`Path`] [`Point`] array. May be `None`
849    /// * `max` - maximum to copy; must be greater than or equal to zero
850    ///
851    /// Returns: [`Path`] [`Point`] array length
852    ///
853    /// example: <https://fiddle.skia.org/c/@Path_getPoints>
854    pub fn get_points(&self, points: &mut [Point]) -> usize {
855        unsafe {
856            self.native().getPoints(
857                points.native_mut().as_mut_ptr(),
858                points.len().try_into().unwrap(),
859            )
860        }
861        .try_into()
862        .unwrap()
863    }
864
865    /// Returns the number of verbs: [`Verb::Move`], [`Verb::Line`], [`Verb::Quad`], [`Verb::Conic`],
866    /// [`Verb::Cubic`], and [`Verb::Close`]; added to [`Path`].
867    ///
868    /// Returns: length of verb array
869    ///
870    /// example: <https://fiddle.skia.org/c/@Path_countVerbs>
871    pub fn count_verbs(&self) -> usize {
872        unsafe { self.native().countVerbs() }.try_into().unwrap()
873    }
874
875    /// Returns the number of verbs in the path. Up to max verbs are copied. The
876    /// verbs are copied as one byte per verb.
877    ///
878    /// * `verbs` - storage for verbs, may be `None`
879    /// * `max` - maximum number to copy into verbs
880    ///
881    /// Returns: the actual number of verbs in the path
882    ///
883    /// example: <https://fiddle.skia.org/c/@Path_getVerbs>
884    pub fn get_verbs(&self, verbs: &mut [u8]) -> usize {
885        unsafe {
886            self.native()
887                .getVerbs(verbs.as_mut_ptr(), verbs.len().try_into().unwrap())
888        }
889        .try_into()
890        .unwrap()
891    }
892
893    /// Returns the approximate byte size of the [`Path`] in memory.
894    ///
895    /// Returns: approximate size
896    pub fn approximate_bytes_used(&self) -> usize {
897        unsafe { self.native().approximateBytesUsed() }
898    }
899
900    /// Exchanges the verb array, [`Point`] array, weights, and [`FillType`] with other.
901    /// Cached state is also exchanged. `swap()` internally exchanges pointers, so
902    /// it is lightweight and does not allocate memory.
903    ///
904    /// `swap()` usage has largely been replaced by PartialEq.
905    /// [`Path`] do not copy their content on assignment until they are written to,
906    /// making assignment as efficient as swap().
907    ///
908    /// * `other` - [`Path`] exchanged by value
909    ///
910    /// example: <https://fiddle.skia.org/c/@Path_swap>
911    pub fn swap(&mut self, other: &mut Path) -> &mut Self {
912        unsafe { self.native_mut().swap(other.native_mut()) }
913        self
914    }
915
916    /// Returns minimum and maximum axes values of [`Point`] array.
917    /// Returns (0, 0, 0, 0) if [`Path`] contains no points. Returned bounds width and height may
918    /// be larger or smaller than area affected when [`Path`] is drawn.
919    ///
920    /// [`Rect`] returned includes all [`Point`] added to [`Path`], including [`Point`] associated with
921    /// [`Verb::Move`] that define empty contours.
922    ///
923    /// Returns: bounds of all [`Point`] in [`Point`] array
924    pub fn bounds(&self) -> &Rect {
925        Rect::from_native_ref(unsafe { &*sb::C_SkPath_getBounds(self.native()) })
926    }
927
928    /// Updates internal bounds so that subsequent calls to `bounds()` are instantaneous.
929    /// Unaltered copies of [`Path`] may also access cached bounds through `bounds()`.
930    ///
931    /// For now, identical to calling `bounds()` and ignoring the returned value.
932    ///
933    /// Call to prepare [`Path`] subsequently drawn from multiple threads,
934    /// to avoid a race condition where each draw separately computes the bounds.
935    pub fn update_bounds_cache(&mut self) -> &mut Self {
936        self.bounds();
937        self
938    }
939
940    /// Returns minimum and maximum axes values of the lines and curves in [`Path`].
941    /// Returns (0, 0, 0, 0) if [`Path`] contains no points.
942    /// Returned bounds width and height may be larger or smaller than area affected
943    /// when [`Path`] is drawn.
944    ///
945    /// Includes [`Point`] associated with [`Verb::Move`] that define empty
946    /// contours.
947    ///
948    /// Behaves identically to `bounds()` when [`Path`] contains
949    /// only lines. If [`Path`] contains curves, computed bounds includes
950    /// the maximum extent of the quad, conic, or cubic; is slower than `bounds()`;
951    /// and unlike `bounds()`, does not cache the result.
952    ///
953    /// Returns: tight bounds of curves in [`Path`]
954    ///
955    /// example: <https://fiddle.skia.org/c/@Path_computeTightBounds>
956    pub fn compute_tight_bounds(&self) -> Rect {
957        Rect::construct(|r| unsafe { sb::C_SkPath_computeTightBounds(self.native(), r) })
958    }
959
960    /// Returns `true` if rect is contained by [`Path`].
961    /// May return `false` when rect is contained by [`Path`].
962    ///
963    /// For now, only returns `true` if [`Path`] has one contour and is convex.
964    /// rect may share points and edges with [`Path`] and be contained.
965    /// Returns `true` if rect is empty, that is, it has zero width or height; and
966    /// the [`Point`] or line described by rect is contained by [`Path`].
967    ///
968    /// * `rect` - [`Rect`], line, or [`Point`] checked for containment
969    ///
970    /// Returns: `true` if rect is contained
971    ///
972    /// example: <https://fiddle.skia.org/c/@Path_conservativelyContainsRect>
973    pub fn conservatively_contains_rect(&self, rect: impl AsRef<Rect>) -> bool {
974        unsafe {
975            self.native()
976                .conservativelyContainsRect(rect.as_ref().native())
977        }
978    }
979
980    /// Grows [`Path`] verb array and [`Point`] array to contain `extra_pt_count` additional [`Point`].
981    /// May improve performance and use less memory by
982    /// reducing the number and size of allocations when creating [`Path`].
983    ///
984    /// * `extra_pt_count` - number of additional [`Point`] to allocate
985    ///
986    /// example: <https://fiddle.skia.org/c/@Path_incReserve>
987    pub fn inc_reserve(&mut self, extra_pt_count: usize) -> &mut Self {
988        self.inc_reserve_with_verb_and_conic(extra_pt_count, None, None);
989        self
990    }
991
992    /// Grows [`Path`] verb array and [`Point`] array to contain `extra_pt_count` additional [`Point`].
993    /// May improve performance and use less memory by
994    /// reducing the number and size of allocations when creating [`Path`].
995    ///
996    /// * `extra_pt_count` - number of additional [`Point`] to allocate
997    /// * `extra_verb_count` - number of additional verbs
998    /// * `extra_conic_count` - number of additional conics
999    ///
1000    /// example: <https://fiddle.skia.org/c/@Path_incReserve>
1001    pub fn inc_reserve_with_verb_and_conic(
1002        &mut self,
1003        extra_pt_count: usize,
1004        extra_verb_count: impl Into<Option<usize>>,
1005        extract_conic_count: impl Into<Option<usize>>,
1006    ) -> &mut Self {
1007        let extra_verb_count = extra_verb_count.into().unwrap_or_default();
1008        let extra_conic_count = extract_conic_count.into().unwrap_or_default();
1009
1010        unsafe {
1011            self.native_mut().incReserve(
1012                extra_pt_count.try_into().unwrap(),
1013                extra_verb_count.try_into().unwrap(),
1014                extra_conic_count.try_into().unwrap(),
1015            )
1016        }
1017
1018        self
1019    }
1020
1021    #[deprecated(since = "0.37.0", note = "Removed without replacement")]
1022    pub fn shrink_to_fit(&mut self) -> ! {
1023        panic!("Removed without replacement");
1024    }
1025
1026    /// Adds beginning of contour at [`Point`] (x, y).
1027    ///
1028    /// * `x` - x-axis value of contour start
1029    /// * `y` - y-axis value of contour start
1030    ///
1031    /// Returns: reference to [`Path`]
1032    ///
1033    /// example: <https://fiddle.skia.org/c/@Path_moveTo>
1034    pub fn move_to(&mut self, p: impl Into<Point>) -> &mut Self {
1035        let p = p.into();
1036        unsafe {
1037            self.native_mut().moveTo(p.x, p.y);
1038        }
1039        self
1040    }
1041
1042    /// Adds beginning of contour relative to last point.
1043    /// If [`Path`] is empty, starts contour at (dx, dy).
1044    /// Otherwise, start contour at last point offset by (dx, dy).
1045    /// Function name stands for "relative move to".
1046    ///
1047    /// * `dx` - offset from last point to contour start on x-axis
1048    /// * `dy` - offset from last point to contour start on y-axis
1049    ///
1050    /// Returns: reference to [`Path`]
1051    ///
1052    /// example: <https://fiddle.skia.org/c/@Path_rMoveTo>
1053    pub fn r_move_to(&mut self, d: impl Into<Vector>) -> &mut Self {
1054        let d = d.into();
1055        unsafe {
1056            self.native_mut().rMoveTo(d.x, d.y);
1057        }
1058        self
1059    }
1060
1061    /// Adds line from last point to (x, y). If [`Path`] is empty, or last [`Verb`] is
1062    /// [`Verb::Close`], last point is set to (0, 0) before adding line.
1063    ///
1064    /// `line_to()` appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array, if needed.
1065    /// `line_to()` then appends [`Verb::Line`] to verb array and (x, y) to [`Point`] array.
1066    ///
1067    /// * `x` - end of added line on x-axis
1068    /// * `y` - end of added line on y-axis
1069    ///
1070    /// Returns: reference to [`Path`]
1071    ///
1072    /// example: <https://fiddle.skia.org/c/@Path_lineTo>
1073    pub fn line_to(&mut self, p: impl Into<Point>) -> &mut Self {
1074        let p = p.into();
1075        unsafe {
1076            self.native_mut().lineTo(p.x, p.y);
1077        }
1078        self
1079    }
1080
1081    /// Adds line from last point to vector (dx, dy). If [`Path`] is empty, or last [`Verb`] is
1082    /// [`Verb::Close`], last point is set to (0, 0) before adding line.
1083    ///
1084    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array, if needed;
1085    /// then appends [`Verb::Line`] to verb array and line end to [`Point`] array.
1086    /// Line end is last point plus vector (dx, dy).
1087    /// Function name stands for "relative line to".
1088    ///
1089    /// * `dx` - offset from last point to line end on x-axis
1090    /// * `dy` - offset from last point to line end on y-axis
1091    ///
1092    /// Returns: reference to [`Path`]
1093    ///
1094    /// example: <https://fiddle.skia.org/c/@Path_rLineTo>
1095    /// example: <https://fiddle.skia.org/c/@Quad_a>
1096    /// example: <https://fiddle.skia.org/c/@Quad_b>
1097    pub fn r_line_to(&mut self, d: impl Into<Vector>) -> &mut Self {
1098        let d = d.into();
1099        unsafe {
1100            self.native_mut().rLineTo(d.x, d.y);
1101        }
1102        self
1103    }
1104
1105    /// Adds quad from last point towards (x1, y1), to (x2, y2).
1106    /// If [`Path`] is empty, or last [`Verb`] is [`Verb::Close`], last point is set to (0, 0)
1107    /// before adding quad.
1108    ///
1109    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array, if needed;
1110    /// then appends [`Verb::Quad`] to verb array; and (x1, y1), (x2, y2)
1111    /// to [`Point`] array.
1112    ///
1113    /// * `x1` - control [`Point`] of quad on x-axis
1114    /// * `y1` - control [`Point`] of quad on y-axis
1115    /// * `x2` - end [`Point`] of quad on x-axis
1116    /// * `y2` - end [`Point`] of quad on y-axis
1117    ///
1118    /// Returns: reference to [`Path`]
1119    ///
1120    /// example: <https://fiddle.skia.org/c/@Path_quadTo>
1121    pub fn quad_to(&mut self, p1: impl Into<Point>, p2: impl Into<Point>) -> &mut Self {
1122        let p1 = p1.into();
1123        let p2 = p2.into();
1124        unsafe {
1125            self.native_mut().quadTo(p1.x, p1.y, p2.x, p2.y);
1126        }
1127        self
1128    }
1129
1130    /// Adds quad from last point towards vector (dx1, dy1), to vector (dx2, dy2).
1131    /// If [`Path`] is empty, or last [`Verb`]
1132    /// is [`Verb::Close`], last point is set to (0, 0) before adding quad.
1133    ///
1134    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array,
1135    /// if needed; then appends [`Verb::Quad`] to verb array; and appends quad
1136    /// control and quad end to [`Point`] array.
1137    /// Quad control is last point plus vector (dx1, dy1).
1138    /// Quad end is last point plus vector (dx2, dy2).
1139    /// Function name stands for "relative quad to".
1140    ///
1141    /// * `dx1` - offset from last point to quad control on x-axis
1142    /// * `dy1` - offset from last point to quad control on y-axis
1143    /// * `dx2` - offset from last point to quad end on x-axis
1144    /// * `dy2` - offset from last point to quad end on y-axis
1145    ///
1146    /// Returns: reference to [`Path`]
1147    ///
1148    /// example: <https://fiddle.skia.org/c/@Conic_Weight_a>
1149    /// example: <https://fiddle.skia.org/c/@Conic_Weight_b>
1150    /// example: <https://fiddle.skia.org/c/@Conic_Weight_c>
1151    /// example: <https://fiddle.skia.org/c/@Path_rQuadTo>
1152    pub fn r_quad_to(&mut self, dx1: impl Into<Vector>, dx2: impl Into<Vector>) -> &mut Self {
1153        let (dx1, dx2) = (dx1.into(), dx2.into());
1154        unsafe {
1155            self.native_mut().rQuadTo(dx1.x, dx1.y, dx2.x, dx2.y);
1156        }
1157        self
1158    }
1159
1160    /// Adds conic from last point towards (x1, y1), to (x2, y2), weighted by w.
1161    /// If [`Path`] is empty, or last [`Verb`] is [`Verb::Close`], last point is set to (0, 0)
1162    /// before adding conic.
1163    ///
1164    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array, if needed.
1165    ///
1166    /// If w is finite and not one, appends [`Verb::Conic`] to verb array;
1167    /// and (x1, y1), (x2, y2) to [`Point`] array; and w to conic weights.
1168    ///
1169    /// If w is one, appends [`Verb::Quad`] to verb array, and
1170    /// (x1, y1), (x2, y2) to [`Point`] array.
1171    ///
1172    /// If w is not finite, appends [`Verb::Line`] twice to verb array, and
1173    /// (x1, y1), (x2, y2) to [`Point`] array.
1174    ///
1175    /// * `x1` - control [`Point`] of conic on x-axis
1176    /// * `y1` - control [`Point`] of conic on y-axis
1177    /// * `x2` - end [`Point`] of conic on x-axis
1178    /// * `y2` - end [`Point`] of conic on y-axis
1179    /// * `w` - weight of added conic
1180    ///
1181    /// Returns: reference to [`Path`]
1182    pub fn conic_to(&mut self, p1: impl Into<Point>, p2: impl Into<Point>, w: scalar) -> &mut Self {
1183        let p1 = p1.into();
1184        let p2 = p2.into();
1185        unsafe {
1186            self.native_mut().conicTo(p1.x, p1.y, p2.x, p2.y, w);
1187        }
1188        self
1189    }
1190
1191    /// Adds conic from last point towards vector (dx1, dy1), to vector (dx2, dy2),
1192    /// weighted by w. If [`Path`] is empty, or last [`Verb`]
1193    /// is [`Verb::Close`], last point is set to (0, 0) before adding conic.
1194    ///
1195    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array,
1196    /// if needed.
1197    ///
1198    /// If w is finite and not one, next appends [`Verb::Conic`] to verb array,
1199    /// and w is recorded as conic weight; otherwise, if w is one, appends
1200    /// [`Verb::Quad`] to verb array; or if w is not finite, appends [`Verb::Line`]
1201    /// twice to verb array.
1202    ///
1203    /// In all cases appends [`Point`] control and end to [`Point`] array.
1204    /// control is last point plus vector (dx1, dy1).
1205    /// end is last point plus vector (dx2, dy2).
1206    ///
1207    /// Function name stands for "relative conic to".
1208    ///
1209    /// * `dx1` - offset from last point to conic control on x-axis
1210    /// * `dy1` - offset from last point to conic control on y-axis
1211    /// * `dx2` - offset from last point to conic end on x-axis
1212    /// * `dy2` - offset from last point to conic end on y-axis
1213    /// * `w` - weight of added conic
1214    ///
1215    /// Returns: reference to [`Path`]
1216    pub fn r_conic_to(
1217        &mut self,
1218        d1: impl Into<Vector>,
1219        d2: impl Into<Vector>,
1220        w: scalar,
1221    ) -> &mut Self {
1222        let (d1, d2) = (d1.into(), d2.into());
1223        unsafe {
1224            self.native_mut().rConicTo(d1.x, d1.y, d2.x, d2.y, w);
1225        }
1226        self
1227    }
1228
1229    /// Adds cubic from last point towards (x1, y1), then towards (x2, y2), ending at
1230    /// (x3, y3). If [`Path`] is empty, or last [`Verb`] is [`Verb::Close`], last point is set to
1231    /// (0, 0) before adding cubic.
1232    ///
1233    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array, if needed;
1234    /// then appends [`Verb::Cubic`] to verb array; and (x1, y1), (x2, y2), (x3, y3)
1235    /// to [`Point`] array.
1236    ///
1237    /// * `x1` - first control [`Point`] of cubic on x-axis
1238    /// * `y1` - first control [`Point`] of cubic on y-axis
1239    /// * `x2` - second control [`Point`] of cubic on x-axis
1240    /// * `y2` - second control [`Point`] of cubic on y-axis
1241    /// * `x3` - end [`Point`] of cubic on x-axis
1242    /// * `y3` - end [`Point`] of cubic on y-axis
1243    ///
1244    /// Returns: reference to [`Path`]
1245    pub fn cubic_to(
1246        &mut self,
1247        p1: impl Into<Point>,
1248        p2: impl Into<Point>,
1249        p3: impl Into<Point>,
1250    ) -> &mut Self {
1251        let (p1, p2, p3) = (p1.into(), p2.into(), p3.into());
1252        unsafe {
1253            self.native_mut()
1254                .cubicTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
1255        }
1256        self
1257    }
1258
1259    /// Adds cubic from last point towards vector (dx1, dy1), then towards
1260    /// vector (dx2, dy2), to vector (dx3, dy3).
1261    /// If [`Path`] is empty, or last [`Verb`]
1262    /// is [`Verb::Close`], last point is set to (0, 0) before adding cubic.
1263    ///
1264    /// Appends [`Verb::Move`] to verb array and (0, 0) to [`Point`] array,
1265    /// if needed; then appends [`Verb::Cubic`] to verb array; and appends cubic
1266    /// control and cubic end to [`Point`] array.
1267    /// Cubic control is last point plus vector (dx1, dy1).
1268    /// Cubic end is last point plus vector (dx2, dy2).
1269    /// Function name stands for "relative cubic to".
1270    ///
1271    /// * `dx1` - offset from last point to first cubic control on x-axis
1272    /// * `dy1` - offset from last point to first cubic control on y-axis
1273    /// * `dx2` - offset from last point to second cubic control on x-axis
1274    /// * `dy2` - offset from last point to second cubic control on y-axis
1275    /// * `dx3` - offset from last point to cubic end on x-axis
1276    /// * `dy3` - offset from last point to cubic end on y-axis
1277    ///
1278    /// Returns: reference to [`Path`]
1279    pub fn r_cubic_to(
1280        &mut self,
1281        d1: impl Into<Vector>,
1282        d2: impl Into<Vector>,
1283        d3: impl Into<Vector>,
1284    ) -> &mut Self {
1285        let (d1, d2, d3) = (d1.into(), d2.into(), d3.into());
1286        unsafe {
1287            self.native_mut()
1288                .rCubicTo(d1.x, d1.y, d2.x, d2.y, d3.x, d3.y);
1289        }
1290        self
1291    }
1292
1293    /// Appends arc to [`Path`]. Arc added is part of ellipse
1294    /// bounded by oval, from `start_angle` through `sweep_angle`. Both `start_angle` and
1295    /// `sweep_angle` are measured in degrees, where zero degrees is aligned with the
1296    /// positive x-axis, and positive sweeps extends arc clockwise.
1297    ///
1298    /// `arc_to()` adds line connecting [`Path`] last [`Point`] to initial arc [`Point`] if `force_move_to`
1299    /// is `false` and [`Path`] is not empty. Otherwise, added contour begins with first point
1300    /// of arc. Angles greater than -360 and less than 360 are treated modulo 360.
1301    ///
1302    /// * `oval` - bounds of ellipse containing arc
1303    /// * `start_angle` - starting angle of arc in degrees
1304    /// * `sweep_angle` - sweep, in degrees. Positive is clockwise; treated modulo 360
1305    /// * `force_move_to` - `true` to start a new contour with arc
1306    ///
1307    /// Returns: reference to [`Path`]
1308    ///
1309    /// example: <https://fiddle.skia.org/c/@Path_arcTo>
1310    pub fn arc_to(
1311        &mut self,
1312        oval: impl AsRef<Rect>,
1313        start_angle: scalar,
1314        sweep_angle: scalar,
1315        force_move_to: bool,
1316    ) -> &mut Self {
1317        unsafe {
1318            self.native_mut().arcTo(
1319                oval.as_ref().native(),
1320                start_angle,
1321                sweep_angle,
1322                force_move_to,
1323            );
1324        }
1325        self
1326    }
1327
1328    /// Appends arc to [`Path`], after appending line if needed. Arc is implemented by conic
1329    /// weighted to describe part of circle. Arc is contained by tangent from
1330    /// last [`Path`] point to (x1, y1), and tangent from (x1, y1) to (x2, y2). Arc
1331    /// is part of circle sized to radius, positioned so it touches both tangent lines.
1332    ///
1333    /// If last Path Point does not start Arc, `arc_to` appends connecting Line to Path.
1334    /// The length of Vector from (x1, y1) to (x2, y2) does not affect Arc.
1335    ///
1336    /// Arc sweep is always less than 180 degrees. If radius is zero, or if
1337    /// tangents are nearly parallel, `arc_to` appends Line from last Path Point to (x1, y1).
1338    ///
1339    /// `arc_to_tangent` appends at most one Line and one conic.
1340    /// `arc_to_tangent` implements the functionality of PostScript arct and HTML Canvas `arc_to`.
1341    ///
1342    /// * `p1.x` - x-axis value common to pair of tangents
1343    /// * `p1.y` - y-axis value common to pair of tangents
1344    /// * `p2.x` - x-axis value end of second tangent
1345    /// * `p2.y` - y-axis value end of second tangent
1346    /// * `radius` - distance from arc to circle center
1347    ///
1348    /// Returns: reference to [`Path`]
1349    ///
1350    /// example: <https://fiddle.skia.org/c/@Path_arcTo_2_a>
1351    /// example: <https://fiddle.skia.org/c/@Path_arcTo_2_b>
1352    /// example: <https://fiddle.skia.org/c/@Path_arcTo_2_c>
1353    pub fn arc_to_tangent(
1354        &mut self,
1355        p1: impl Into<Point>,
1356        p2: impl Into<Point>,
1357        radius: scalar,
1358    ) -> &mut Self {
1359        let (p1, p2) = (p1.into(), p2.into());
1360        unsafe {
1361            self.native_mut().arcTo1(p1.x, p1.y, p2.x, p2.y, radius);
1362        }
1363        self
1364    }
1365
1366    /// Appends arc to [`Path`]. Arc is implemented by one or more conics weighted to
1367    /// describe part of oval with radii (rx, ry) rotated by `x_axis_rotate` degrees. Arc
1368    /// curves from last [`Path`] [`Point`] to (x, y), choosing one of four possible routes:
1369    /// clockwise or counterclockwise, and smaller or larger.
1370    ///
1371    /// Arc sweep is always less than 360 degrees. `arc_to_rotated()` appends line to (x, y) if
1372    /// either radii are zero, or if last [`Path`] [`Point`] equals (x, y). `arc_to_rotated()` scales radii
1373    /// (rx, ry) to fit last [`Path`] [`Point`] and (x, y) if both are greater than zero but
1374    /// too small.
1375    ///
1376    /// `arc_to_rotated()` appends up to four conic curves.
1377    /// `arc_to_rotated()` implements the functionality of SVG arc, although SVG sweep-flag value
1378    /// is opposite the integer value of sweep; SVG sweep-flag uses 1 for clockwise,
1379    /// while [`Direction::CW`] cast to int is zero.
1380    ///
1381    /// * `r.x` - radius on x-axis before x-axis rotation
1382    /// * `r.y` - radius on y-axis before x-axis rotation
1383    /// * `x_axis_rotate` - x-axis rotation in degrees; positive values are clockwise
1384    /// * `large_arc` - chooses smaller or larger arc
1385    /// * `sweep` - chooses clockwise or counterclockwise arc
1386    /// * `end.x` - end of arc
1387    /// * `end.y` - end of arc
1388    ///
1389    /// Returns: reference to [`Path`]
1390    pub fn arc_to_rotated(
1391        &mut self,
1392        r: impl Into<Point>,
1393        x_axis_rotate: scalar,
1394        large_arc: ArcSize,
1395        sweep: PathDirection,
1396        end: impl Into<Point>,
1397    ) -> &mut Self {
1398        let (r, end) = (r.into(), end.into());
1399        unsafe {
1400            self.native_mut()
1401                .arcTo2(r.x, r.y, x_axis_rotate, large_arc, sweep, end.x, end.y);
1402        }
1403        self
1404    }
1405
1406    /// Appends arc to [`Path`], relative to last [`Path`] [`Point`]. Arc is implemented by one or
1407    /// more conic, weighted to describe part of oval with radii (r.x, r.y) rotated by
1408    /// `x_axis_rotate` degrees. Arc curves from last [`Path`] [`Point`] to relative end [`Point`]:
1409    /// (dx, dy), choosing one of four possible routes: clockwise or
1410    /// counterclockwise, and smaller or larger. If [`Path`] is empty, the start arc [`Point`]
1411    /// is (0, 0).
1412    ///
1413    /// Arc sweep is always less than 360 degrees. `arc_to()` appends line to end [`Point`]
1414    /// if either radii are zero, or if last [`Path`] [`Point`] equals end [`Point`].
1415    /// `arc_to()` scales radii (rx, ry) to fit last [`Path`] [`Point`] and end [`Point`] if both are
1416    /// greater than zero but too small to describe an arc.
1417    ///
1418    /// `arc_to()` appends up to four conic curves.
1419    /// `arc_to()` implements the functionality of svg arc, although SVG "sweep-flag" value is
1420    /// opposite the integer value of sweep; SVG "sweep-flag" uses 1 for clockwise, while
1421    /// [`Direction::CW`] cast to int is zero.
1422    ///
1423    /// * `r.x` - radius before x-axis rotation
1424    /// * `r.y` - radius before x-axis rotation
1425    /// * `x_axis_rotate` - x-axis rotation in degrees; positive values are clockwise
1426    /// * `large_arc` - chooses smaller or larger arc
1427    /// * `sweep` - chooses clockwise or counterclockwise arc
1428    /// * `d.x` - x-axis offset end of arc from last [`Path`] [`Point`]
1429    /// * `d.y` - y-axis offset end of arc from last [`Path`] [`Point`]
1430    ///
1431    /// Returns: reference to [`Path`]
1432    pub fn r_arc_to_rotated(
1433        &mut self,
1434        r: impl Into<Point>,
1435        x_axis_rotate: scalar,
1436        large_arc: ArcSize,
1437        sweep: PathDirection,
1438        d: impl Into<Point>,
1439    ) -> &mut Self {
1440        let (r, d) = (r.into(), d.into());
1441        unsafe {
1442            self.native_mut()
1443                .rArcTo(r.x, r.y, x_axis_rotate, large_arc, sweep, d.x, d.y);
1444        }
1445        self
1446    }
1447
1448    /// Appends [`Verb::Close`] to [`Path`]. A closed contour connects the first and last [`Point`]
1449    /// with line, forming a continuous loop. Open and closed contour draw the same
1450    /// with fill style. With stroke style, open contour draws
1451    /// [`crate::paint::Cap`] at contour start and end; closed contour draws
1452    /// [`crate::paint::Join`] at contour start and end.
1453    ///
1454    /// `close()` has no effect if [`Path`] is empty or last [`Path`] [`Verb`] is [`Verb::Close`].
1455    ///
1456    /// Returns: reference to [`Path`]
1457    ///
1458    /// example: <https://fiddle.skia.org/c/@Path_close>
1459    pub fn close(&mut self) -> &mut Self {
1460        unsafe {
1461            self.native_mut().close();
1462        }
1463        self
1464    }
1465
1466    /// Approximates conic with quad array. Conic is constructed from start [`Point`] p0,
1467    /// control [`Point`] p1, end [`Point`] p2, and weight w.
1468    /// Quad array is stored in pts; this storage is supplied by caller.
1469    /// Maximum quad count is 2 to the pow2.
1470    /// Every third point in array shares last [`Point`] of previous quad and first [`Point`] of
1471    /// next quad. Maximum pts storage size is given by:
1472    /// (1 + 2 * (1 << pow2)) * sizeof([`Point`]).
1473    ///
1474    /// Returns quad count used the approximation, which may be smaller
1475    /// than the number requested.
1476    ///
1477    /// conic weight determines the amount of influence conic control point has on the curve.
1478    /// w less than one represents an elliptical section. w greater than one represents
1479    /// a hyperbolic section. w equal to one represents a parabolic section.
1480    ///
1481    /// Two quad curves are sufficient to approximate an elliptical conic with a sweep
1482    /// of up to 90 degrees; in this case, set pow2 to one.
1483    ///
1484    /// * `p0` - conic start [`Point`]
1485    /// * `p1` - conic control [`Point`]
1486    /// * `p2` - conic end [`Point`]
1487    /// * `w` - conic weight
1488    /// * `pts` - storage for quad array
1489    /// * `pow2` - quad count, as power of two, normally 0 to 5 (1 to 32 quad curves)
1490    ///
1491    /// Returns: number of quad curves written to pts
1492    pub fn convert_conic_to_quads(
1493        p0: impl Into<Point>,
1494        p1: impl Into<Point>,
1495        p2: impl Into<Point>,
1496        w: scalar,
1497        pts: &mut [Point],
1498        pow2: usize,
1499    ) -> Option<usize> {
1500        let (p0, p1, p2) = (p0.into(), p1.into(), p2.into());
1501        let max_pts_count = 1 + 2 * (1 << pow2);
1502        if pts.len() >= max_pts_count {
1503            Some(unsafe {
1504                SkPath::ConvertConicToQuads(
1505                    p0.native(),
1506                    p1.native(),
1507                    p2.native(),
1508                    w,
1509                    pts.native_mut().as_mut_ptr(),
1510                    pow2.try_into().unwrap(),
1511                )
1512                .try_into()
1513                .unwrap()
1514            })
1515        } else {
1516            None
1517        }
1518    }
1519
1520    // TODO: return type is probably worth a struct.
1521
1522    /// Returns `Some(Rect, bool, PathDirection)` if [`Path`] is equivalent to [`Rect`] when filled.
1523    /// If `false`: rect, `is_closed`, and direction are unchanged.
1524    /// If `true`: rect, `is_closed`, and direction are written to.
1525    ///
1526    /// rect may be smaller than the [`Path`] bounds. [`Path`] bounds may include [`Verb::Move`] points
1527    /// that do not alter the area drawn by the returned rect.
1528    ///
1529    /// Returns: `Some(rect, is_closed, direction)` if [`Path`] contains [`Rect`]
1530    /// * `rect` - bounds of [`Rect`]
1531    /// * `is_closed` - set to `true` if [`Path`] is closed
1532    /// * `direction` - to [`Rect`] direction
1533    ///
1534    /// example: <https://fiddle.skia.org/c/@Path_isRect>
1535    pub fn is_rect(&self) -> Option<(Rect, bool, PathDirection)> {
1536        let mut rect = Rect::default();
1537        let mut is_closed = Default::default();
1538        let mut direction = PathDirection::default();
1539        unsafe {
1540            self.native()
1541                .isRect(rect.native_mut(), &mut is_closed, &mut direction)
1542        }
1543        .if_true_some((rect, is_closed, direction))
1544    }
1545
1546    /// Adds a new contour to the path, defined by the rect, and wound in the
1547    /// specified direction. The verbs added to the path will be:
1548    ///
1549    /// `Move`, `Line`, `Line`, `Line`, `Close`
1550    ///
1551    /// start specifies which corner to begin the contour:
1552    ///     0: upper-left  corner
1553    ///     1: upper-right corner
1554    ///     2: lower-right corner
1555    ///     3: lower-left  corner
1556    ///
1557    /// This start point also acts as the implied beginning of the subsequent,
1558    /// contour, if it does not have an explicit `move_to`(). e.g.
1559    ///
1560    /// `path.add_rect(...)`
1561    /// // if we don't say `move_to()` here, we will use the rect's start point
1562    /// `path.line_to`(...)`
1563    ///
1564    /// * `rect` - [`Rect`] to add as a closed contour
1565    /// * `dir` - [`Direction`] to orient the new contour
1566    /// * `start` - initial corner of [`Rect`] to add
1567    ///
1568    /// Returns: reference to [`Path`]
1569    ///
1570    /// example: <https://fiddle.skia.org/c/@Path_addRect_2>
1571    pub fn add_rect(
1572        &mut self,
1573        rect: impl AsRef<Rect>,
1574        dir_start: Option<(PathDirection, usize)>,
1575    ) -> &mut Self {
1576        let dir = dir_start.map(|ds| ds.0).unwrap_or_default();
1577        let start = dir_start.map(|ds| ds.1).unwrap_or_default();
1578        unsafe {
1579            self.native_mut()
1580                .addRect(rect.as_ref().native(), dir, start.try_into().unwrap())
1581        };
1582        self
1583    }
1584
1585    /// Adds oval to [`Path`], appending [`Verb::Move`], four [`Verb::Conic`], and [`Verb::Close`].
1586    /// Oval is upright ellipse bounded by [`Rect`] oval with radii equal to half oval width
1587    /// and half oval height. Oval begins at start and continues
1588    /// clockwise if dir is [`Direction::CW`], counterclockwise if dir is [`Direction::CCW`].
1589    ///
1590    /// * `oval` - bounds of ellipse added
1591    /// * `dir` - [`Direction`] to wind ellipse
1592    /// * `start` - index of initial point of ellipse
1593    ///
1594    /// Returns: reference to [`Path`]
1595    ///
1596    /// example: <https://fiddle.skia.org/c/@Path_addOval_2>
1597    pub fn add_oval(
1598        &mut self,
1599        oval: impl AsRef<Rect>,
1600        dir_start: Option<(PathDirection, usize)>,
1601    ) -> &mut Self {
1602        let dir = dir_start.map(|ds| ds.0).unwrap_or_default();
1603        let start = dir_start.map(|ds| ds.1).unwrap_or_default();
1604        unsafe {
1605            self.native_mut()
1606                .addOval1(oval.as_ref().native(), dir, start.try_into().unwrap())
1607        };
1608        self
1609    }
1610
1611    /// Adds circle centered at (x, y) of size radius to [`Path`], appending [`Verb::Move`],
1612    /// four [`Verb::Conic`], and [`Verb::Close`]. Circle begins at: (x + radius, y), continuing
1613    /// clockwise if dir is [`Direction::CW`], and counterclockwise if dir is [`Direction::CCW`].
1614    ///
1615    /// Has no effect if radius is zero or negative.
1616    ///
1617    /// * `p` - center of circle
1618    /// * `radius` - distance from center to edge
1619    /// * `dir` - [`Direction`] to wind circle
1620    ///
1621    /// Returns: reference to [`Path`]
1622    pub fn add_circle(
1623        &mut self,
1624        p: impl Into<Point>,
1625        radius: scalar,
1626        dir: impl Into<Option<PathDirection>>,
1627    ) -> &mut Self {
1628        let p = p.into();
1629        let dir = dir.into().unwrap_or_default();
1630        unsafe { self.native_mut().addCircle(p.x, p.y, radius, dir) };
1631        self
1632    }
1633
1634    /// Appends arc to [`Path`], as the start of new contour. Arc added is part of ellipse
1635    /// bounded by oval, from `start_angle` through `sweep_angle`. Both `start_angle` and
1636    /// `sweep_angle` are measured in degrees, where zero degrees is aligned with the
1637    /// positive x-axis, and positive sweeps extends arc clockwise.
1638    ///
1639    /// If `sweep_angle` <= -360, or `sweep_angle` >= 360; and `start_angle` modulo 90 is nearly
1640    /// zero, append oval instead of arc. Otherwise, `sweep_angle` values are treated
1641    /// modulo 360, and arc may or may not draw depending on numeric rounding.
1642    ///
1643    /// * `oval` - bounds of ellipse containing arc
1644    /// * `start_angle` - starting angle of arc in degrees
1645    /// * `sweep_angle` - sweep, in degrees. Positive is clockwise; treated modulo 360
1646    ///
1647    /// Returns: reference to [`Path`]
1648    ///
1649    /// example: <https://fiddle.skia.org/c/@Path_addArc>
1650    pub fn add_arc(
1651        &mut self,
1652        oval: impl AsRef<Rect>,
1653        start_angle: scalar,
1654        sweep_angle: scalar,
1655    ) -> &mut Self {
1656        unsafe {
1657            self.native_mut()
1658                .addArc(oval.as_ref().native(), start_angle, sweep_angle)
1659        };
1660        self
1661    }
1662
1663    // Decided to only provide the simpler variant of the two, if radii needs to be specified,
1664    // add_rrect can be used.
1665
1666    /// Appends [`RRect`] to [`Path`], creating a new closed contour. [`RRect`] has bounds
1667    /// equal to rect; each corner is 90 degrees of an ellipse with radii (rx, ry). If
1668    /// dir is [`Direction::CW`], [`RRect`] starts at top-left of the lower-left corner and
1669    /// winds clockwise. If dir is [`Direction::CCW`], [`RRect`] starts at the bottom-left
1670    /// of the upper-left corner and winds counterclockwise.
1671    ///
1672    /// If either rx or ry is too large, rx and ry are scaled uniformly until the
1673    /// corners fit. If rx or ry is less than or equal to zero, `add_round_rect()` appends
1674    /// [`Rect`] rect to [`Path`].
1675    ///
1676    /// After appending, [`Path`] may be empty, or may contain: [`Rect`], oval, or [`RRect`].
1677    ///
1678    /// * `rect` - bounds of [`RRect`]
1679    /// * `rx` - x-axis radius of rounded corners on the [`RRect`]
1680    /// * `ry` - y-axis radius of rounded corners on the [`RRect`]
1681    /// * `dir` - [`Direction`] to wind [`RRect`]
1682    ///
1683    /// Returns: reference to [`Path`]
1684    pub fn add_round_rect(
1685        &mut self,
1686        rect: impl AsRef<Rect>,
1687        (rx, ry): (scalar, scalar),
1688        dir: impl Into<Option<PathDirection>>,
1689    ) -> &mut Self {
1690        let dir = dir.into().unwrap_or_default();
1691        unsafe {
1692            self.native_mut()
1693                .addRoundRect(rect.as_ref().native(), rx, ry, dir)
1694        };
1695        self
1696    }
1697
1698    /// Adds rrect to [`Path`], creating a new closed contour. If dir is [`Direction::CW`], rrect
1699    /// winds clockwise; if dir is [`Direction::CCW`], rrect winds counterclockwise.
1700    /// start determines the first point of rrect to add.
1701    ///
1702    /// * `rrect` - bounds and radii of rounded rectangle
1703    /// * `dir` - [`PathDirection`] to wind [`RRect`]
1704    /// * `start` - index of initial point of [`RRect`]
1705    ///
1706    /// Returns: reference to [`Path`]
1707    ///
1708    /// example: <https://fiddle.skia.org/c/@Path_addRRect_2>
1709    pub fn add_rrect(
1710        &mut self,
1711        rrect: impl AsRef<RRect>,
1712        dir_start: Option<(PathDirection, usize)>,
1713    ) -> &mut Self {
1714        let dir = dir_start.map(|ds| ds.0).unwrap_or_default();
1715        let start = dir_start.map(|ds| ds.1).unwrap_or_default();
1716        unsafe {
1717            self.native_mut()
1718                .addRRect1(rrect.as_ref().native(), dir, start.try_into().unwrap())
1719        };
1720        self
1721    }
1722
1723    /// Adds contour created from line array, adding `pts.len() - 1` line segments.
1724    /// Contour added starts at `pts[0]`, then adds a line for every additional [`Point`]
1725    /// in pts slice. If close is `true`, appends [`Verb::Close`] to [`Path`], connecting
1726    /// `pts[pts.len() - 1]` and `pts[0]`.
1727    ///
1728    /// If count is zero, append [`Verb::Move`] to path.
1729    /// Has no effect if ps.len() is less than one.
1730    ///
1731    /// * `pts` - slice of line sharing end and start [`Point`]
1732    /// * `close` - `true` to add line connecting contour end and start
1733    ///
1734    /// Returns: reference to [`Path`]
1735    ///
1736    /// example: <https://fiddle.skia.org/c/@Path_addPoly>
1737    pub fn add_poly(&mut self, pts: &[Point], close: bool) -> &mut Self {
1738        unsafe {
1739            self.native_mut()
1740                .addPoly(pts.native().as_ptr(), pts.len().try_into().unwrap(), close)
1741        };
1742        self
1743    }
1744
1745    // TODO: addPoly(initializer_list)
1746
1747    /// Appends src to [`Path`], offset by `(d.x, d.y)`.
1748    ///
1749    /// If mode is [`AddPathMode::Append`], src verb array, [`Point`] array, and conic weights are
1750    /// added unaltered. If mode is [`AddPathMode::Extend`], add line before appending
1751    /// verbs, [`Point`], and conic weights.
1752    ///
1753    /// * `src` - [`Path`] verbs, [`Point`], and conic weights to add
1754    /// * `d.x` - offset added to src [`Point`] array x-axis coordinates
1755    /// * `d.y` - offset added to src [`Point`] array y-axis coordinates
1756    /// * `mode` - [`AddPathMode::Append`] or [`AddPathMode::Extend`]
1757    ///
1758    /// Returns: reference to [`Path`]
1759    pub fn add_path(
1760        &mut self,
1761        src: &Path,
1762        d: impl Into<Vector>,
1763        mode: impl Into<Option<AddPathMode>>,
1764    ) -> &mut Self {
1765        let d = d.into();
1766        let mode = mode.into().unwrap_or(AddPathMode::Append);
1767        unsafe { self.native_mut().addPath(src.native(), d.x, d.y, mode) };
1768        self
1769    }
1770
1771    // TODO: rename to add_path_with_matrix() ?
1772
1773    /// Appends src to [`Path`], transformed by matrix. Transformed curves may have different
1774    /// verbs, [`Point`], and conic weights.
1775    ///
1776    /// If mode is [`AddPathMode::Append`], src verb array, [`Point`] array, and conic weights are
1777    /// added unaltered. If mode is [`AddPathMode::Extend`], add line before appending
1778    /// verbs, [`Point`], and conic weights.
1779    ///
1780    /// * `src` - [`Path`] verbs, [`Point`], and conic weights to add
1781    /// * `matrix` - transform applied to src
1782    /// * `mode` - [`AddPathMode::Append`] or [`AddPathMode::Extend`]
1783    ///
1784    /// Returns: reference to [`Path`]
1785    pub fn add_path_matrix(
1786        &mut self,
1787        src: &Path,
1788        matrix: &Matrix,
1789        mode: impl Into<Option<AddPathMode>>,
1790    ) -> &mut Self {
1791        let mode = mode.into().unwrap_or(AddPathMode::Append);
1792        unsafe {
1793            self.native_mut()
1794                .addPath1(src.native(), matrix.native(), mode)
1795        };
1796        self
1797    }
1798
1799    /// Appends src to [`Path`], from back to front.
1800    /// Reversed src always appends a new contour to [`Path`].
1801    ///
1802    /// * `src` - [`Path`] verbs, [`Point`], and conic weights to add
1803    ///
1804    /// Returns: reference to [`Path`]
1805    ///
1806    /// example: <https://fiddle.skia.org/c/@Path_reverseAddPath>
1807    pub fn reverse_add_path(&mut self, src: &Path) -> &mut Self {
1808        unsafe { self.native_mut().reverseAddPath(src.native()) };
1809        self
1810    }
1811
1812    /// Offsets [`Point`] array by `(d.x, d.y)`.
1813    ///
1814    /// * `dx` - offset added to [`Point`] array x-axis coordinates
1815    /// * `dy` - offset added to [`Point`] array y-axis coordinates
1816    ///
1817    /// Returns: overwritten, translated copy of [`Path`]; may be `None`
1818    ///
1819    /// example: <https://fiddle.skia.org/c/@Path_offset>
1820    #[must_use]
1821    pub fn with_offset(&self, d: impl Into<Vector>) -> Path {
1822        let d = d.into();
1823        let mut path = Path::default();
1824        unsafe { self.native().offset(d.x, d.y, path.native_mut()) };
1825        path
1826    }
1827
1828    /// Offsets [`Point`] array by `(d.x, d.y)`. [`Path`] is replaced by offset data.
1829    ///
1830    /// * `d.x` - offset added to [`Point`] array x-axis coordinates
1831    /// * `d.y` - offset added to [`Point`] array y-axis coordinates
1832    pub fn offset(&mut self, d: impl Into<Vector>) -> &mut Self {
1833        let d = d.into();
1834        unsafe {
1835            let self_ptr = self.native_mut() as *mut _;
1836            self.native().offset(d.x, d.y, self_ptr)
1837        };
1838        self
1839    }
1840
1841    /// Transforms verb array, [`Point`] array, and weight by matrix.
1842    /// transform may change verbs and increase their number.
1843    ///
1844    /// * `matrix` - [`Matrix`] to apply to [`Path`]
1845    ///
1846    /// example: <https://fiddle.skia.org/c/@Path_transform>
1847    #[must_use]
1848    pub fn with_transform(&self, matrix: &Matrix) -> Path {
1849        self.with_transform_with_perspective_clip(matrix, ApplyPerspectiveClip::Yes)
1850    }
1851
1852    /// Transforms verb array, [`Point`] array, and weight by matrix.
1853    /// transform may change verbs and increase their number.
1854    ///
1855    /// * `matrix` - [`Matrix`] to apply to [`Path`]
1856    /// * `pc` - whether to apply perspective clipping
1857    ///
1858    /// example: <https://fiddle.skia.org/c/@Path_transform>
1859    #[must_use]
1860    pub fn with_transform_with_perspective_clip(
1861        &self,
1862        matrix: &Matrix,
1863        perspective_clip: ApplyPerspectiveClip,
1864    ) -> Path {
1865        let mut path = Path::default();
1866        unsafe {
1867            self.native()
1868                .transform(matrix.native(), path.native_mut(), perspective_clip)
1869        };
1870        path
1871    }
1872
1873    /// Transforms verb array, [`Point`] array, and weight by matrix.
1874    /// transform may change verbs and increase their number.
1875    ///
1876    /// * `matrix` - [`Matrix`] to apply to [`Path`]
1877    pub fn transform(&mut self, matrix: &Matrix) -> &mut Self {
1878        self.transform_with_perspective_clip(matrix, ApplyPerspectiveClip::Yes)
1879    }
1880
1881    /// Transforms verb array, [`Point`] array, and weight by matrix.
1882    /// transform may change verbs and increase their number.
1883    ///
1884    /// * `matrix` - [`Matrix`] to apply to [`Path`]
1885    /// * `pc` - whether to apply perspective clipping
1886    pub fn transform_with_perspective_clip(
1887        &mut self,
1888        matrix: &Matrix,
1889        pc: ApplyPerspectiveClip,
1890    ) -> &mut Self {
1891        let self_ptr = self.native_mut() as *mut _;
1892        unsafe { self.native().transform(matrix.native(), self_ptr, pc) };
1893        self
1894    }
1895
1896    #[must_use]
1897    pub fn make_transform(
1898        &mut self,
1899        m: &Matrix,
1900        pc: impl Into<Option<ApplyPerspectiveClip>>,
1901    ) -> Path {
1902        self.with_transform_with_perspective_clip(m, pc.into().unwrap_or(ApplyPerspectiveClip::Yes))
1903    }
1904
1905    #[must_use]
1906    pub fn make_scale(&mut self, (sx, sy): (scalar, scalar)) -> Path {
1907        self.make_transform(&Matrix::scale((sx, sy)), ApplyPerspectiveClip::No)
1908    }
1909
1910    /// Returns last point on [`Path`]. Returns `None` if [`Point`] array is empty,
1911    /// storing `(0, 0)` if `last_pt` is not `None`.
1912    ///
1913    /// Returns final [`Point`] in [`Point`] array; may be `None`
1914    /// Returns: `Some` if [`Point`] array contains one or more [`Point`]
1915    ///
1916    /// example: <https://fiddle.skia.org/c/@Path_getLastPt>
1917    pub fn last_pt(&self) -> Option<Point> {
1918        let mut last_pt = Point::default();
1919        unsafe { self.native().getLastPt(last_pt.native_mut()) }.if_true_some(last_pt)
1920    }
1921
1922    /// Sets the last point on the path. If [`Point`] array is empty, append [`Verb::Move`] to
1923    /// verb array and append p to [`Point`] array.
1924    ///
1925    /// * `p` - set value of last point
1926    pub fn set_last_pt(&mut self, p: impl Into<Point>) -> &mut Self {
1927        let p = p.into();
1928        unsafe { self.native_mut().setLastPt(p.x, p.y) };
1929        self
1930    }
1931
1932    /// Returns a mask, where each set bit corresponds to a [`SegmentMask`] constant
1933    /// if [`Path`] contains one or more verbs of that type.
1934    /// Returns zero if [`Path`] contains no lines, or curves: quads, conics, or cubics.
1935    ///
1936    /// `segment_masks()` returns a cached result; it is very fast.
1937    ///
1938    /// Returns: [`SegmentMask`] bits or zero
1939    pub fn segment_masks(&self) -> SegmentMask {
1940        SegmentMask::from_bits_truncate(unsafe { self.native().getSegmentMasks() })
1941    }
1942
1943    /// Returns `true` if the point `(p.x, p.y)` is contained by [`Path`], taking into
1944    /// account [`FillType`].
1945    ///
1946    /// * `p.x` - x-axis value of containment test
1947    /// * `p.y` - y-axis value of containment test
1948    ///
1949    /// Returns: `true` if [`Point`] is in [`Path`]
1950    ///
1951    /// example: <https://fiddle.skia.org/c/@Path_contains>
1952    pub fn contains(&self, p: impl Into<Point>) -> bool {
1953        let p = p.into();
1954        unsafe { self.native().contains(p.x, p.y) }
1955    }
1956
1957    /// Writes text representation of [`Path`] to [`Data`].
1958    /// Set `dump_as_hex` `true` to generate exact binary representations
1959    /// of floating point numbers used in [`Point`] array and conic weights.
1960    ///
1961    /// * `dump_as_hex` - `true` if scalar values are written as hexadecimal
1962    ///
1963    /// example: <https://fiddle.skia.org/c/@Path_dump>
1964    pub fn dump_as_data(&self, dump_as_hex: bool) -> Data {
1965        let mut stream = DynamicMemoryWStream::new();
1966        unsafe {
1967            self.native()
1968                .dump(stream.native_mut().base_mut(), dump_as_hex);
1969        }
1970        stream.detach_as_data()
1971    }
1972
1973    /// See [`Path::dump_as_data()`]
1974    pub fn dump(&self) {
1975        unsafe { self.native().dump(ptr::null_mut(), false) }
1976    }
1977
1978    /// See [`Path::dump_as_data()`]
1979    pub fn dump_hex(&self) {
1980        unsafe { self.native().dump(ptr::null_mut(), true) }
1981    }
1982
1983    // Like [`Path::dump()`], but outputs for the [`Path::make()`] factory
1984    pub fn dump_arrays_as_data(&self, dump_as_hex: bool) -> Data {
1985        let mut stream = DynamicMemoryWStream::new();
1986        unsafe {
1987            self.native()
1988                .dumpArrays(stream.native_mut().base_mut(), dump_as_hex);
1989        }
1990        stream.detach_as_data()
1991    }
1992
1993    // Like [`Path::dump()`], but outputs for the [`Path::make()`] factory
1994    pub fn dump_arrays(&self) {
1995        unsafe { self.native().dumpArrays(ptr::null_mut(), false) }
1996    }
1997
1998    // TODO: writeToMemory()?
1999
2000    /// Writes [`Path`] to buffer, returning the buffer written to, wrapped in [`Data`].
2001    ///
2002    /// `serialize()` writes [`FillType`], verb array, [`Point`] array, conic weight, and
2003    /// additionally writes computed information like convexity and bounds.
2004    ///
2005    /// `serialize()` should only be used in concert with `read_from_memory`().
2006    /// The format used for [`Path`] in memory is not guaranteed.
2007    ///
2008    /// Returns: [`Path`] data wrapped in [`Data`] buffer
2009    ///
2010    /// example: <https://fiddle.skia.org/c/@Path_serialize>
2011    pub fn serialize(&self) -> Data {
2012        Data::from_ptr(unsafe { sb::C_SkPath_serialize(self.native()) }).unwrap()
2013    }
2014
2015    // TODO: readFromMemory()?
2016
2017    pub fn deserialize(data: &Data) -> Option<Path> {
2018        let mut path = Path::default();
2019        let bytes = data.as_bytes();
2020        unsafe {
2021            path.native_mut()
2022                .readFromMemory(bytes.as_ptr() as _, bytes.len())
2023                > 0
2024        }
2025        .if_true_some(path)
2026    }
2027    /// (See Skia bug 1762.)
2028    /// Returns a non-zero, globally unique value. A different value is returned
2029    /// if verb array, [`Point`] array, or conic weight changes.
2030    ///
2031    /// Setting [`FillType`] does not change generation identifier.
2032    ///
2033    /// Each time the path is modified, a different generation identifier will be returned.
2034    /// [`FillType`] does affect generation identifier on Android framework.
2035    ///
2036    /// Returns: non-zero, globally unique value
2037    ///
2038    /// example: <https://fiddle.skia.org/c/@Path_getGenerationID>
2039    pub fn generation_id(&self) -> u32 {
2040        unsafe { self.native().getGenerationID() }
2041    }
2042
2043    /// Returns if [`Path`] data is consistent. Corrupt [`Path`] data is detected if
2044    /// internal values are out of range or internal storage does not match
2045    /// array dimensions.
2046    ///
2047    /// Returns: `true` if [`Path`] data is consistent
2048    pub fn is_valid(&self) -> bool {
2049        unsafe { self.native().isValid() }
2050    }
2051}
2052
2053#[cfg(test)]
2054mod tests {
2055    use super::*;
2056
2057    #[test]
2058    fn test_get_points() {
2059        let mut p = Path::new();
2060        p.add_rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
2061        let points_count = p.count_points();
2062        let mut points = vec![Point::default(); points_count];
2063        let count_returned = p.get_points(&mut points);
2064        assert_eq!(count_returned, points.len());
2065        assert_eq!(count_returned, 4);
2066    }
2067
2068    #[test]
2069    fn test_fill_type() {
2070        let mut p = Path::default();
2071        assert_eq!(p.fill_type(), PathFillType::Winding);
2072        p.set_fill_type(PathFillType::EvenOdd);
2073        assert_eq!(p.fill_type(), PathFillType::EvenOdd);
2074        assert!(!p.is_inverse_fill_type());
2075        p.toggle_inverse_fill_type();
2076        assert_eq!(p.fill_type(), PathFillType::InverseEvenOdd);
2077        assert!(p.is_inverse_fill_type());
2078    }
2079
2080    #[test]
2081    fn test_is_volatile() {
2082        let mut p = Path::default();
2083        assert!(!p.is_volatile());
2084        p.set_is_volatile(true);
2085        assert!(p.is_volatile());
2086    }
2087
2088    #[test]
2089    fn test_path_rect() {
2090        let r = Rect::new(0.0, 0.0, 100.0, 100.0);
2091        let path = Path::rect(r, None);
2092        assert_eq!(*path.bounds(), r);
2093    }
2094}