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