skia_safe/core/path.rs
1//! Describes geometry as a set of contours, each beginning with a move verb and followed by lines,
2//! quadratic beziers, conics, and cubic beziers.
3
4use std::{fmt, marker::PhantomData, mem::forget, ptr};
5
6use skia_bindings::{self as sb, SkPath, SkPath_Iter, SkPath_RawIter};
7
8use crate::PathIter;
9use crate::{
10 Data, Matrix, PathDirection, PathFillType, PathVerb, Point, RRect, Rect, Vector,
11 interop::DynamicMemoryWStream, path_types, prelude::*, scalar,
12};
13
14/// [`Path`] contain geometry. [`Path`] may be empty, or contain one or more verbs that
15/// outline a figure. [`Path`] always starts with a move verb to a Cartesian coordinate,
16/// and may be followed by additional verbs that add lines or curves.
17/// Adding a close verb makes the geometry into a continuous loop, a closed contour.
18/// [`Path`] may contain any number of contours, each beginning with a move verb.
19///
20/// [`Path`] contours may contain only a move verb, or may also contain lines,
21/// quadratic beziers, conics, and cubic beziers. [`Path`] contours may be open or
22/// closed.
23///
24/// When used to draw a filled area, [`Path`] describes whether the fill is inside or
25/// outside the geometry. [`Path`] also describes the winding rule used to fill
26/// overlapping contours.
27///
28/// Internally, [`Path`] lazily computes convexity.
29pub type Path = Handle<SkPath>;
30unsafe impl Send for Path {}
31
32impl NativeDrop for SkPath {
33 /// Releases ownership of any shared data and deletes data if [`Path`] is sole owner.
34 ///
35 /// Example (C++): <https://fiddle.skia.org/c/@Path_destructor>
36 fn drop(&mut self) {
37 unsafe { sb::C_SkPath_destruct(self) }
38 }
39}
40
41impl NativeClone for SkPath {
42 /// Constructs a copy of an existing path.
43 /// Copy constructor makes two paths identical by value. Internally, path and
44 /// the returned result share pointer values. The underlying verb array, [`Point`] array
45 /// and weights are copied when modified.
46 ///
47 /// Creating a [`Path`] copy is very efficient and never allocates memory.
48 /// [`Path`] are always copied by value from the interface; the underlying shared
49 /// pointers are not exposed.
50 ///
51 /// * `path` - [`Path`] to copy by value
52 ///
53 /// Returns: copy of [`Path`]
54 ///
55 /// Example (C++): <https://fiddle.skia.org/c/@Path_copy_const_SkPath>
56 /// Example (C++): <https://fiddle.skia.org/c/@Path_copy_operator>
57 fn clone(&self) -> Self {
58 unsafe { SkPath::new1(self) }
59 }
60}
61
62impl NativePartialEq for SkPath {
63 /// Compares a and b; returns `true` if [`path::FillType`], verb array, [`Point`] array, and weights
64 /// are equivalent.
65 ///
66 /// * `a` - [`Path`] to compare
67 /// * `b` - [`Path`] to compare
68 ///
69 /// Returns: `true` if [`Path`] pair are equivalent
70 fn eq(&self, rhs: &Self) -> bool {
71 unsafe { sb::C_SkPath_Equals(self, rhs) }
72 }
73}
74
75impl Default for Handle<SkPath> {
76 /// See [`Self::new()`]
77 fn default() -> Self {
78 Self::new()
79 }
80}
81
82impl fmt::Debug for Path {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.debug_struct("Path")
85 .field("fill_type", &self.fill_type())
86 .field("is_convex", &self.is_convex())
87 .field("is_oval", &self.is_oval())
88 .field("is_rrect", &self.is_rrect())
89 .field("is_empty", &self.is_empty())
90 .field("is_last_contour_closed", &self.is_last_contour_closed())
91 .field("is_finite", &self.is_finite())
92 .field("is_volatile", &self.is_volatile())
93 .field("is_line", &self.is_line())
94 .field("count_points", &self.count_points())
95 .field("count_verbs", &self.count_verbs())
96 .field("approximate_bytes_used", &self.approximate_bytes_used())
97 .field("bounds", &self.bounds())
98 .field("is_rect", &self.is_rect())
99 .field("segment_masks", &self.segment_masks())
100 .field("generation_id", &self.generation_id())
101 .field("is_valid", &self.is_valid())
102 .finish()
103 }
104}
105
106/// [`Path`] contain geometry. [`Path`] may be empty, or contain one or more verbs that
107/// outline a figure. [`Path`] always starts with a move verb to a Cartesian coordinate,
108/// and may be followed by additional verbs that add lines or curves.
109/// Adding a close verb makes the geometry into a continuous loop, a closed contour.
110/// [`Path`] may contain any number of contours, each beginning with a move verb.
111///
112/// [`Path`] contours may contain only a move verb, or may also contain lines,
113/// quadratic beziers, conics, and cubic beziers. [`Path`] contours may be open or
114/// closed.
115///
116/// When used to draw a filled area, [`Path`] describes whether the fill is inside or
117/// outside the geometry. [`Path`] also describes the winding rule used to fill
118/// overlapping contours.
119///
120/// Internally, [`Path`] lazily computes convexity.
121impl Path {
122 /// Create a new path with the specified spans.
123 ///
124 /// The points and weights arrays are read in order, based on the sequence of verbs.
125 ///
126 /// Move 1 point
127 /// Line 1 point
128 /// Quad 2 points
129 /// Conic 2 points and 1 weight
130 /// Cubic 3 points
131 /// Close 0 points
132 ///
133 /// If an illegal sequence of verbs is encountered, or the specified number of points
134 /// or weights is not sufficient given the verbs, an empty Path is returned.
135 ///
136 /// A legal sequence of verbs consists of any number of Contours. A contour always begins
137 /// with a Move verb, followed by 0 or more segments: Line, Quad, Conic, Cubic, followed
138 /// by an optional Close.
139 pub fn raw(
140 points: &[Point],
141 verbs: &[PathVerb],
142 conic_weights: &[scalar],
143 fill_type: PathFillType,
144 is_volatile: impl Into<Option<bool>>,
145 ) -> Self {
146 Self::construct(|path| unsafe {
147 sb::C_SkPath_Raw(
148 path,
149 points.native().as_ptr(),
150 points.len(),
151 verbs.as_ptr(),
152 verbs.len(),
153 conic_weights.as_ptr(),
154 conic_weights.len(),
155 fill_type,
156 is_volatile.into().unwrap_or(false),
157 )
158 })
159 }
160
161 /// Create a new path with the specified spans.
162 ///
163 /// The points and weights arrays are read in order, based on the sequence of verbs.
164 ///
165 /// Move 1 point
166 /// Line 1 point
167 /// Quad 2 points
168 /// Conic 2 points and 1 weight
169 /// Cubic 3 points
170 /// Close 0 points
171 ///
172 /// If an illegal sequence of verbs is encountered, or the specified number of points
173 /// or weights is not sufficient given the verbs, an empty Path is returned.
174 ///
175 /// A legal sequence of verbs consists of any number of Contours. A contour always begins
176 /// with a Move verb, followed by 0 or more segments: Line, Quad, Conic, Cubic, followed
177 /// by an optional Close.
178 #[deprecated(since = "0.88.0", note = "use raw()")]
179 pub fn new_from(
180 points: &[Point],
181 verbs: &[u8],
182 conic_weights: &[scalar],
183 fill_type: PathFillType,
184 is_volatile: impl Into<Option<bool>>,
185 ) -> Self {
186 Self::construct(|path| unsafe {
187 sb::C_SkPath_Make(
188 path,
189 points.native().as_ptr(),
190 points.len(),
191 verbs.as_ptr(),
192 verbs.len(),
193 conic_weights.as_ptr(),
194 conic_weights.len(),
195 fill_type,
196 is_volatile.into().unwrap_or(false),
197 )
198 })
199 }
200
201 pub fn rect_with_fill_type(
202 rect: impl AsRef<Rect>,
203 fill_type: PathFillType,
204 dir: impl Into<Option<PathDirection>>,
205 ) -> Self {
206 Self::construct(|path| unsafe {
207 sb::C_SkPath_Rect(
208 path,
209 rect.as_ref().native(),
210 fill_type,
211 dir.into().unwrap_or_default(),
212 )
213 })
214 }
215
216 pub fn rect(rect: impl AsRef<Rect>, dir: impl Into<Option<PathDirection>>) -> Self {
217 Self::rect_with_fill_type(rect, PathFillType::default(), dir)
218 }
219
220 pub fn oval(oval: impl AsRef<Rect>, dir: impl Into<Option<PathDirection>>) -> Self {
221 Self::construct(|path| unsafe {
222 sb::C_SkPath_Oval(path, oval.as_ref().native(), dir.into().unwrap_or_default())
223 })
224 }
225
226 pub fn oval_with_start_index(
227 oval: impl AsRef<Rect>,
228 dir: PathDirection,
229 start_index: usize,
230 ) -> Self {
231 Self::construct(|path| unsafe {
232 sb::C_SkPath_OvalWithStartIndex(
233 path,
234 oval.as_ref().native(),
235 dir,
236 start_index.try_into().unwrap(),
237 )
238 })
239 }
240
241 pub fn circle(
242 center: impl Into<Point>,
243 radius: scalar,
244 dir: impl Into<Option<PathDirection>>,
245 ) -> Self {
246 let center = center.into();
247 Self::construct(|path| unsafe {
248 sb::C_SkPath_Circle(
249 path,
250 center.x,
251 center.y,
252 radius,
253 dir.into().unwrap_or(PathDirection::CW),
254 )
255 })
256 }
257
258 pub fn rrect(rect: impl AsRef<RRect>, dir: impl Into<Option<PathDirection>>) -> Self {
259 Self::construct(|path| unsafe {
260 sb::C_SkPath_RRect(path, rect.as_ref().native(), dir.into().unwrap_or_default())
261 })
262 }
263
264 pub fn rrect_with_start_index(
265 rect: impl AsRef<RRect>,
266 dir: PathDirection,
267 start_index: usize,
268 ) -> Self {
269 Self::construct(|path| unsafe {
270 sb::C_SkPath_RRectWithStartIndex(
271 path,
272 rect.as_ref().native(),
273 dir,
274 start_index.try_into().unwrap(),
275 )
276 })
277 }
278
279 pub fn polygon(
280 pts: &[Point],
281 is_closed: bool,
282 fill_type: impl Into<Option<PathFillType>>,
283 is_volatile: impl Into<Option<bool>>,
284 ) -> Self {
285 Self::construct(|path| unsafe {
286 sb::C_SkPath_Polygon(
287 path,
288 pts.native().as_ptr(),
289 pts.len(),
290 is_closed,
291 fill_type.into().unwrap_or_default(),
292 is_volatile.into().unwrap_or(false),
293 )
294 })
295 }
296
297 pub fn line(a: impl Into<Point>, b: impl Into<Point>) -> Self {
298 Self::polygon(&[a.into(), b.into()], false, None, None)
299 }
300
301 /// Constructs an empty [`Path`]. By default, [`Path`] has no verbs, no [`Point`], and no weights.
302 ///
303 /// Returns: empty [`Path`]
304 ///
305 pub fn new_with_fill_type(fill_type: PathFillType) -> Self {
306 Self::construct(|path| unsafe { sb::C_SkPath_Construct(path, fill_type) })
307 }
308
309 pub fn new() -> Self {
310 Self::new_with_fill_type(PathFillType::default())
311 }
312
313 /// Returns a copy of this path in the current state.
314 pub fn snapshot(&self) -> Self {
315 self.clone()
316 }
317
318 /// Returns `true` if [`Path`] contain equal verbs and equal weights.
319 /// If [`Path`] contain one or more conics, the weights must match.
320 ///
321 /// `conic_to()` may add different verbs depending on conic weight, so it is not
322 /// trivial to interpolate a pair of [`Path`] containing conics with different
323 /// conic weight values.
324 ///
325 /// * `compare` - [`Path`] to compare
326 ///
327 /// Returns: `true` if [`Path`] verb array and weights are equivalent
328 ///
329 /// Example (C++): <https://fiddle.skia.org/c/@Path_isInterpolatable>
330 pub fn is_interpolatable(&self, compare: &Path) -> bool {
331 unsafe { self.native().isInterpolatable(compare.native()) }
332 }
333
334 /// Interpolates between [`Path`] with [`Point`] array of equal size.
335 /// Copy verb array and weights to out, and set out [`Point`] array to a weighted
336 /// average of this [`Point`] array and ending [`Point`] array, using the formula:
337 /// (Path Point * weight) + ending Point * (1 - weight).
338 ///
339 /// weight is most useful when between zero (ending [`Point`] array) and
340 /// one (this Point_Array); will work with values outside of this
341 /// range.
342 ///
343 /// `interpolate()` returns an empty [`Path`] if [`Point`] array is not the same size
344 /// as ending [`Point`] array. Call `is_interpolatable()` to check [`Path`] compatibility
345 /// prior to calling `make_interpolate`().
346 ///
347 /// * `ending` - [`Point`] array averaged with this [`Point`] array
348 /// * `weight` - contribution of this [`Point`] array, and
349 /// one minus contribution of ending [`Point`] array
350 ///
351 /// Returns: [`Path`] replaced by interpolated averages
352 ///
353 /// Example (C++): <https://fiddle.skia.org/c/@Path_interpolate>
354 pub fn interpolate(&self, ending: &Path, weight: scalar) -> Option<Self> {
355 let mut out = Path::default();
356 self.interpolate_inplace(ending, weight, &mut out)
357 .then_some(out)
358 }
359
360 /// Interpolates between [`Path`] with [`Point`] array of equal size.
361 /// Copy verb array and weights to out, and set out [`Point`] array to a weighted
362 /// average of this [`Point`] array and ending [`Point`] array, using the formula:
363 /// `(Path Point * weight) + ending Point * (1 - weight)`.
364 ///
365 /// `weight` is most useful when between zero (ending [`Point`] array) and
366 /// one (this Point_Array); will work with values outside of this
367 /// range.
368 ///
369 /// `interpolate_inplace()` returns `false` and leaves out unchanged if [`Point`] array is not
370 /// the same size as ending [`Point`] array. Call `is_interpolatable()` to check [`Path`]
371 /// compatibility prior to calling `interpolate_inplace()`.
372 ///
373 /// * `ending` - [`Point`] array averaged with this [`Point`] array
374 /// * `weight` - contribution of this [`Point`] array, and
375 /// one minus contribution of ending [`Point`] array
376 /// * `out` - [`Path`] replaced by interpolated averages
377 ///
378 /// Returns: `true` if [`Path`] contain same number of [`Point`]
379 ///
380 /// Example (C++): <https://fiddle.skia.org/c/@Path_interpolate>
381 pub fn interpolate_inplace(&self, ending: &Path, weight: scalar, out: &mut Path) -> bool {
382 unsafe {
383 self.native()
384 .interpolate(ending.native(), weight, out.native_mut())
385 }
386 }
387
388 /// Returns [`PathFillType`], the rule used to fill [`Path`].
389 ///
390 /// Returns: current [`PathFillType`] setting
391 pub fn fill_type(&self) -> PathFillType {
392 unsafe { sb::C_SkPath_getFillType(self.native()) }
393 }
394
395 pub fn with_fill_type(&self, new_fill_type: PathFillType) -> Path {
396 Self::construct(|p| unsafe { sb::C_SkPath_makeFillType(self.native(), new_fill_type, p) })
397 }
398
399 /// Returns if FillType describes area outside [`Path`] geometry. The inverse fill area
400 /// extends indefinitely.
401 ///
402 /// Returns: `true` if FillType is `InverseWinding` or `InverseEvenOdd`
403 pub fn is_inverse_fill_type(&self) -> bool {
404 self.fill_type().is_inverse()
405 }
406
407 /// Creates an [`Path`] with the same properties and data, and with [`PathFillType`] replaced
408 /// with its inverse. The inverse of [`PathFillType`] describes the area unmodified by the
409 /// original FillType.
410 pub fn with_toggle_inverse_fill_type(&self) -> Self {
411 Self::construct(|p| unsafe {
412 sb::C_SkPath_makeToggleInverseFillType(self.native(), p);
413 })
414 }
415
416 /// Returns `true` if the path is convex. If necessary, it will first compute the convexity.
417 pub fn is_convex(&self) -> bool {
418 unsafe { self.native().isConvex() }
419 }
420
421 /// Returns `true` if this path is recognized as an oval or circle.
422 ///
423 /// bounds receives bounds of oval.
424 ///
425 /// bounds is unmodified if oval is not found.
426 ///
427 /// * `bounds` - storage for bounding [`Rect`] of oval; may be `None`
428 ///
429 /// Returns: `true` if [`Path`] is recognized as an oval or circle
430 ///
431 /// Example (C++): <https://fiddle.skia.org/c/@Path_isOval>
432 pub fn is_oval(&self) -> Option<Rect> {
433 let mut bounds = Rect::default();
434 unsafe { self.native().isOval(bounds.native_mut()) }.then_some(bounds)
435 }
436
437 /// Returns [`RRect`] if path is representable as [`RRect`].
438 /// Returns `None` if path is representable as oval, circle, or [`Rect`].
439 ///
440 /// Returns: [`RRect`] if [`Path`] contains only [`RRect`]
441 ///
442 /// Example (C++): <https://fiddle.skia.org/c/@Path_isRRect>
443 pub fn is_rrect(&self) -> Option<RRect> {
444 let mut rrect = RRect::default();
445 unsafe { self.native().isRRect(rrect.native_mut()) }.then_some(rrect)
446 }
447
448 /// Returns if [`Path`] is empty.
449 /// Empty [`Path`] may have FillType but has no [`Point`], [`Verb`], or conic weight.
450 /// [`Path::default()`] constructs empty [`Path`]; `reset()` and `rewind()` make [`Path`] empty.
451 ///
452 /// Returns: `true` if the path contains no [`Verb`] array
453 pub fn is_empty(&self) -> bool {
454 unsafe { self.native().isEmpty() }
455 }
456
457 /// Returns if contour is closed.
458 /// Contour is closed if [`Path`] [`Verb`] array was last modified by `close()`. When stroked,
459 /// closed contour draws [`crate::paint::Join`] instead of [`crate::paint::Cap`] at first and last [`Point`].
460 ///
461 /// Returns: `true` if the last contour ends with a [`Verb::Close`]
462 ///
463 /// Example (C++): <https://fiddle.skia.org/c/@Path_isLastContourClosed>
464 pub fn is_last_contour_closed(&self) -> bool {
465 unsafe { self.native().isLastContourClosed() }
466 }
467
468 /// Returns `true` for finite [`Point`] array values between negative SK_ScalarMax and
469 /// positive SK_ScalarMax. Returns `false` for any [`Point`] array value of
470 /// SK_ScalarInfinity, SK_ScalarNegativeInfinity, or SK_ScalarNaN.
471 ///
472 /// Returns: `true` if all [`Point`] values are finite
473 pub fn is_finite(&self) -> bool {
474 unsafe { self.native().isFinite() }
475 }
476
477 /// Returns `true` if the path is volatile; it will not be altered or discarded
478 /// by the caller after it is drawn. [`Path`] by default have volatile set `false`, allowing
479 /// [`crate::Surface`] to attach a cache of data which speeds repeated drawing. If `true`, [`crate::Surface`]
480 /// may not speed repeated drawing.
481 ///
482 /// Returns: `true` if caller will alter [`Path`] after drawing
483 pub fn is_volatile(&self) -> bool {
484 self.native().fIsVolatile
485 }
486
487 /// Return a copy of [`Path`] with `is_volatile` indicating whether it will be altered
488 /// or discarded by the caller after it is drawn. [`Path`] by default have volatile
489 /// set `false`, allowing Skia to attach a cache of data which speeds repeated drawing.
490 ///
491 /// Mark temporary paths, discarded or modified after use, as volatile
492 /// to inform Skia that the path need not be cached.
493 ///
494 /// Mark animating [`Path`] volatile to improve performance.
495 /// Mark unchanging [`Path`] non-volatile to improve repeated rendering.
496 ///
497 /// raster surface [`Path`] draws are affected by volatile for some shadows.
498 /// GPU surface [`Path`] draws are affected by volatile for some shadows and concave geometries.
499 ///
500 /// * `is_volatile` - `true` if caller will alter [`Path`] after drawing
501 ///
502 /// Returns: [`Path`]
503 pub fn with_is_volatile(&self, is_volatile: bool) -> Self {
504 Self::construct(|p| unsafe { sb::C_SkPath_makeIsVolatile(self.native(), is_volatile, p) })
505 }
506
507 /// Tests if line between [`Point`] pair is degenerate.
508 /// Line with no length or that moves a very short distance is degenerate; it is
509 /// treated as a point.
510 ///
511 /// exact changes the equality test. If `true`, returns `true` only if p1 equals p2.
512 /// If `false`, returns `true` if p1 equals or nearly equals p2.
513 ///
514 /// * `p1` - line start point
515 /// * `p2` - line end point
516 /// * `exact` - if `false`, allow nearly equals
517 ///
518 /// Returns: `true` if line is degenerate; its length is effectively zero
519 ///
520 /// Example (C++): <https://fiddle.skia.org/c/@Path_IsLineDegenerate>
521 pub fn is_line_degenerate(p1: impl Into<Point>, p2: impl Into<Point>, exact: bool) -> bool {
522 unsafe { SkPath::IsLineDegenerate(p1.into().native(), p2.into().native(), exact) }
523 }
524
525 /// Tests if quad is degenerate.
526 /// Quad with no length or that moves a very short distance is degenerate; it is
527 /// treated as a point.
528 ///
529 /// * `p1` - quad start point
530 /// * `p2` - quad control point
531 /// * `p3` - quad end point
532 /// * `exact` - if `true`, returns `true` only if p1, p2, and p3 are equal;
533 /// if `false`, returns `true` if p1, p2, and p3 are equal or nearly equal
534 ///
535 /// Returns: `true` if quad is degenerate; its length is effectively zero
536 pub fn is_quad_degenerate(
537 p1: impl Into<Point>,
538 p2: impl Into<Point>,
539 p3: impl Into<Point>,
540 exact: bool,
541 ) -> bool {
542 unsafe {
543 SkPath::IsQuadDegenerate(
544 p1.into().native(),
545 p2.into().native(),
546 p3.into().native(),
547 exact,
548 )
549 }
550 }
551
552 /// Tests if cubic is degenerate.
553 /// Cubic with no length or that moves a very short distance is degenerate; it is
554 /// treated as a point.
555 ///
556 /// * `p1` - cubic start point
557 /// * `p2` - cubic control point 1
558 /// * `p3` - cubic control point 2
559 /// * `p4` - cubic end point
560 /// * `exact` - if `true`, returns `true` only if p1, p2, p3, and p4 are equal;
561 /// if `false`, returns `true` if p1, p2, p3, and p4 are equal or nearly equal
562 ///
563 /// Returns: `true` if cubic is degenerate; its length is effectively zero
564 pub fn is_cubic_degenerate(
565 p1: impl Into<Point>,
566 p2: impl Into<Point>,
567 p3: impl Into<Point>,
568 p4: impl Into<Point>,
569 exact: bool,
570 ) -> bool {
571 unsafe {
572 SkPath::IsCubicDegenerate(
573 p1.into().native(),
574 p2.into().native(),
575 p3.into().native(),
576 p4.into().native(),
577 exact,
578 )
579 }
580 }
581
582 /// Returns `true` if [`Path`] contains only one line;
583 /// [`Verb`] array has two entries: [`Verb::Move`], [`Verb::Line`].
584 /// If [`Path`] contains one line and line is not `None`, line is set to
585 /// line start point and line end point.
586 /// Returns `false` if [`Path`] is not one line; line is unaltered.
587 ///
588 /// * `line` - storage for line. May be `None`
589 ///
590 /// Returns: `true` if [`Path`] contains exactly one line
591 ///
592 /// Example (C++): <https://fiddle.skia.org/c/@Path_isLine>
593 pub fn is_line(&self) -> Option<(Point, Point)> {
594 let mut line = [Point::default(); 2];
595 #[allow(clippy::tuple_array_conversions)]
596 unsafe { self.native().isLine(line.native_mut().as_mut_ptr()) }
597 .then_some((line[0], line[1]))
598 }
599
600 /// Return a read-only view into the path's points.
601 pub fn points(&self) -> &[Point] {
602 unsafe {
603 let mut len = 0;
604 let points = sb::C_SkPath_points(self.native(), &mut len);
605 safer::from_raw_parts(Point::from_native_ptr(points), len)
606 }
607 }
608
609 /// Return a read-only view into the path's verbs.
610 pub fn verbs(&self) -> &[PathVerb] {
611 unsafe {
612 let mut len = 0;
613 let verbs = sb::C_SkPath_verbs(self.native(), &mut len);
614 safer::from_raw_parts(verbs, len)
615 }
616 }
617
618 /// Return a read-only view into the path's conic-weights.
619 pub fn conic_weights(&self) -> &[scalar] {
620 unsafe {
621 let mut len = 0;
622 let weights = sb::C_SkPath_conicWeights(self.native(), &mut len);
623 safer::from_raw_parts(weights, len)
624 }
625 }
626
627 pub fn count_points(&self) -> usize {
628 self.points().len()
629 }
630
631 pub fn count_verbs(&self) -> usize {
632 self.verbs().len()
633 }
634
635 /// Return the last point, or `None`
636 ///
637 /// Returns: The last if the path contains one or more [`Point`], else returns `None`
638 ///
639 /// Example (C++): <https://fiddle.skia.org/c/@Path_getLastPt>
640 pub fn last_pt(&self) -> Option<Point> {
641 let mut p = Point::default();
642 unsafe { sb::C_SkPath_getLastPt(self.native(), p.native_mut()) }.then_some(p)
643 }
644}
645
646impl Path {
647 /// Returns [`Point`] at index in [`Point`] array. Valid range for index is
648 /// 0 to `count_points()` - 1.
649 /// Returns `None` if index is out of range.
650 /// DEPRECATED
651 ///
652 /// * `index` - [`Point`] array element selector
653 ///
654 /// Returns: [`Point`] array value
655 ///
656 #[deprecated(since = "0.91.0", note = "use points()")]
657 pub fn get_point(&self, index: usize) -> Option<Point> {
658 let p = Point::from_native_c(unsafe { self.native().getPoint(index.try_into().ok()?) });
659 // Assuming that count_points() is somewhat slow, we check the index when a Point(0,0) is
660 // returned.
661 if p != Point::default() || index < self.count_points() {
662 Some(p)
663 } else {
664 None
665 }
666 }
667
668 /// Returns number of points in [`Path`].
669 /// Copies N points from the path into the span, where N = min(#points, span capacity)
670 /// DEPRECATED
671 /// * `points` - span to receive the points. may be empty
672 ///
673 /// Returns: the number of points in the path
674 ///
675 #[deprecated(since = "0.91.0", note = "use points()")]
676 pub fn get_points(&self, points: &mut [Point]) -> usize {
677 unsafe {
678 sb::C_SkPath_getPoints(
679 self.native(),
680 points.native_mut().as_mut_ptr(),
681 points.len(),
682 )
683 }
684 }
685
686 /// Returns number of points in [`Path`].
687 /// Copies N points from the path into the span, where N = min(#points, span capacity)
688 /// DEPRECATED
689 ///
690 /// * `verbs` - span to store the verbs. may be empty.
691 ///
692 /// Returns: the number of verbs in the path
693 ///
694 /// Example (C++): <https://fiddle.skia.org/c/@Path_getVerbs>
695 #[deprecated(since = "0.91.0")]
696 pub fn get_verbs(&self, verbs: &mut [u8]) -> usize {
697 unsafe { sb::C_SkPath_getVerbs(self.native(), verbs.as_mut_ptr(), verbs.len()) }
698 }
699}
700
701impl Path {
702 /// Returns the approximate byte size of the [`Path`] in memory.
703 ///
704 /// Returns: approximate size
705 pub fn approximate_bytes_used(&self) -> usize {
706 unsafe { self.native().approximateBytesUsed() }
707 }
708
709 /// Returns the min/max of the path's 'trimmed' points. The trimmed points are all of the
710 /// points in the path, with the exception of the path having more than one contour, and the
711 /// final contour containing only a [`Verb::Move`]. In that case the trailing [`Verb::Move`] point
712 /// is ignored when computing the bounds.
713 ///
714 /// If the path has no verbs, or the path contains non-finite values,
715 /// then `{0, 0, 0, 0}` is returned. (see `is_finite`())
716 ///
717 /// Returns: bounds of the path's points
718 pub fn bounds(&self) -> &Rect {
719 Rect::from_native_ref(unsafe { &*sb::C_SkPath_getBounds(self.native()) })
720 }
721
722 /// Calls [`Self::bounds()`] and ignores the result.
723 #[deprecated(
724 since = "0.100.0",
725 note = "SkPath bounds are no longer computed lazily"
726 )]
727 pub fn update_bounds_cache(&mut self) -> &mut Self {
728 self.bounds();
729 self
730 }
731
732 /// Returns minimum and maximum axes values of the lines and curves in [`Path`].
733 /// Returns (0, 0, 0, 0) if [`Path`] contains no points.
734 /// Returned bounds width and height may be larger or smaller than area affected
735 /// when [`Path`] is drawn.
736 ///
737 /// Includes [`Point`] associated with [`Verb::Move`] that define empty
738 /// contours.
739 ///
740 /// Behaves identically to `bounds()` when [`Path`] contains
741 /// only lines. If [`Path`] contains curves, computed bounds includes
742 /// the maximum extent of the quad, conic, or cubic; is slower than `bounds()`;
743 /// and unlike `bounds()`, does not cache the result.
744 ///
745 /// Returns: tight bounds of curves in [`Path`]
746 ///
747 /// Example (C++): <https://fiddle.skia.org/c/@Path_computeTightBounds>
748 pub fn compute_tight_bounds(&self) -> Rect {
749 Rect::construct(|r| unsafe { sb::C_SkPath_computeTightBounds(self.native(), r) })
750 }
751
752 /// Returns `true` if rect is contained by [`Path`].
753 /// May return `false` when rect is contained by [`Path`].
754 ///
755 /// For now, only returns `true` if [`Path`] has one contour and is convex.
756 /// rect may share points and edges with [`Path`] and be contained.
757 /// Returns `true` if rect is empty, that is, it has zero width or height; and
758 /// the [`Point`] or line described by rect is contained by [`Path`].
759 ///
760 /// * `rect` - [`Rect`], line, or [`Point`] checked for containment
761 ///
762 /// Returns: `true` if rect is contained
763 ///
764 /// Example (C++): <https://fiddle.skia.org/c/@Path_conservativelyContainsRect>
765 pub fn conservatively_contains_rect(&self, rect: impl AsRef<Rect>) -> bool {
766 unsafe {
767 self.native()
768 .conservativelyContainsRect(rect.as_ref().native())
769 }
770 }
771}
772
773impl Path {
774 /// Approximates conic with quad array. Conic is constructed from start [`Point`] p0,
775 /// control [`Point`] p1, end [`Point`] p2, and weight w.
776 /// Quad array is stored in pts; this storage is supplied by caller.
777 /// Maximum quad count is 2 to the pow2.
778 /// Every third point in array shares last [`Point`] of previous quad and first [`Point`] of
779 /// next quad. Maximum pts storage size is given by:
780 /// (1 + 2 * (1 << pow2)) * sizeof([`Point`]).
781 ///
782 /// Returns quad count used the approximation, which may be smaller
783 /// than the number requested.
784 ///
785 /// conic weight determines the amount of influence conic control point has on the curve.
786 /// w less than one represents an elliptical section. w greater than one represents
787 /// a hyperbolic section. w equal to one represents a parabolic section.
788 ///
789 /// Two quad curves are sufficient to approximate an elliptical conic with a sweep
790 /// of up to 90 degrees; in this case, set pow2 to one.
791 ///
792 /// * `p0` - conic start [`Point`]
793 /// * `p1` - conic control [`Point`]
794 /// * `p2` - conic end [`Point`]
795 /// * `w` - conic weight
796 /// * `pts` - storage for quad array
797 /// * `pow2` - quad count, as power of two, normally 0 to 5 (1 to 32 quad curves)
798 ///
799 /// Returns: number of quad curves written to pts
800 pub fn convert_conic_to_quads(
801 p0: impl Into<Point>,
802 p1: impl Into<Point>,
803 p2: impl Into<Point>,
804 w: scalar,
805 pts: &mut [Point],
806 pow2: usize,
807 ) -> Option<usize> {
808 let (p0, p1, p2) = (p0.into(), p1.into(), p2.into());
809 let max_pts_count = 1 + 2 * (1 << pow2);
810 if pts.len() >= max_pts_count {
811 Some(unsafe {
812 SkPath::ConvertConicToQuads(
813 p0.native(),
814 p1.native(),
815 p2.native(),
816 w,
817 pts.native_mut().as_mut_ptr(),
818 pow2.try_into().unwrap(),
819 )
820 .try_into()
821 .unwrap()
822 })
823 } else {
824 None
825 }
826 }
827
828 // TODO: return type is probably worth a struct.
829
830 /// Returns `Some(Rect, bool, PathDirection)` if [`Path`] is equivalent to [`Rect`] when filled.
831 /// If `false`: rect, `is_closed`, and direction are unchanged.
832 /// If `true`: rect, `is_closed`, and direction are written to.
833 ///
834 /// rect may be smaller than the [`Path`] bounds. [`Path`] bounds may include [`Verb::Move`] points
835 /// that do not alter the area drawn by the returned rect.
836 ///
837 /// Returns: `Some(rect, is_closed, direction)` if [`Path`] contains [`Rect`]
838 /// * `rect` - bounds of [`Rect`]
839 /// * `is_closed` - set to `true` if [`Path`] is closed
840 /// * `direction` - to [`Rect`] direction
841 ///
842 /// Example (C++): <https://fiddle.skia.org/c/@Path_isRect>
843 pub fn is_rect(&self) -> Option<(Rect, bool, PathDirection)> {
844 let mut rect = Rect::default();
845 let mut is_closed = Default::default();
846 let mut direction = PathDirection::default();
847 unsafe {
848 self.native()
849 .isRect(rect.native_mut(), &mut is_closed, &mut direction)
850 }
851 .then_some((rect, is_closed, direction))
852 }
853}
854
855/// AddPathMode chooses how `add_path()` appends. Adding one [`Path`] to another can extend
856/// the last contour or start a new contour.
857pub use sb::SkPath_AddPathMode as AddPathMode;
858variant_name!(AddPathMode::Append);
859
860impl Path {
861 /// Return a copy of [`Path`] with verb array, [`Point`] array, and weight transformed
862 /// by matrix. `try_make_transform` may change verbs and increase their number.
863 ///
864 /// If the resulting path has any non-finite values, returns `None`.
865 ///
866 /// * `matrix` - [`Matrix`] to apply to [`Path`]
867 ///
868 /// Returns: [`Path`] if finite, or `None`
869 pub fn try_make_transform(&self, matrix: &Matrix) -> Option<Path> {
870 Path::try_construct(|path| unsafe {
871 sb::C_SkPath_tryMakeTransform(self.native(), matrix.native(), path)
872 })
873 }
874
875 pub fn try_make_offset(&self, d: impl Into<Vector>) -> Option<Path> {
876 let d = d.into();
877 Path::try_construct(|path| unsafe {
878 sb::C_SkPath_tryMakeOffset(self.native(), d.x, d.y, path)
879 })
880 }
881
882 pub fn try_make_scale(&self, (sx, sy): (scalar, scalar)) -> Option<Path> {
883 Path::try_construct(|path| unsafe {
884 sb::C_SkPath_tryMakeScale(self.native(), sx, sy, path)
885 })
886 }
887
888 // TODO: I think we should keep only the make_ variants.
889
890 /// Return a copy of [`Path`] with verb array, [`Point`] array, and weight transformed
891 /// by matrix. `with_transform` may change verbs and increase their number.
892 ///
893 /// If the resulting path has any non-finite values, this will still return a path
894 /// but that path will return `true` for `is_finite()`.
895 ///
896 /// The newer pattern is to call [`try_make_transform`](Self::try_make_transform) which will only return a
897 /// path if the result is finite.
898 ///
899 /// * `matrix` - [`Matrix`] to apply to [`Path`]
900 ///
901 /// Returns: [`Path`]
902 ///
903 #[must_use]
904 pub fn with_transform(&self, matrix: &Matrix) -> Path {
905 Path::construct(|path| unsafe {
906 sb::C_SkPath_makeTransform(self.native(), matrix.native(), path)
907 })
908 }
909
910 #[must_use]
911 pub fn make_transform(&self, m: &Matrix) -> Path {
912 self.with_transform(m)
913 }
914
915 /// Returns [`Path`] with [`Point`] array offset by `(d.x, d.y)`.
916 ///
917 /// * `d` - offset added to [`Point`] array coordinates
918 ///
919 /// Returns: [`Path`]
920 ///
921 #[must_use]
922 pub fn with_offset(&self, d: impl Into<Vector>) -> Path {
923 let d = d.into();
924 Path::construct(|path| unsafe { sb::C_SkPath_makeOffset(self.native(), d.x, d.y, path) })
925 }
926
927 #[must_use]
928 pub fn make_offset(&self, d: impl Into<Vector>) -> Path {
929 self.with_offset(d)
930 }
931
932 #[must_use]
933 pub fn make_scale(&self, (sx, sy): (scalar, scalar)) -> Path {
934 self.make_transform(&Matrix::scale((sx, sy)))
935 }
936}
937
938/// SegmentMask constants correspond to each drawing Verb type in [`crate::Path`]; for instance, if
939/// [`crate::Path`] only contains lines, only the [`crate::path::SegmentMask::LINE`] bit is set.
940pub type SegmentMask = path_types::PathSegmentMask;
941
942impl Path {
943 /// Returns a mask, where each set bit corresponds to a [`SegmentMask`] constant
944 /// if [`Path`] contains one or more verbs of that type.
945 /// Returns zero if [`Path`] contains no lines, or curves: quads, conics, or cubics.
946 ///
947 /// `segment_masks()` returns a cached result; it is very fast.
948 ///
949 /// Returns: [`SegmentMask`] bits or zero
950 pub fn segment_masks(&self) -> SegmentMask {
951 SegmentMask::from_bits_truncate(unsafe { self.native().getSegmentMasks() })
952 }
953}
954
955/// Verb instructs [`Path`] how to interpret one or more [`Point`] and optional conic weight;
956/// manage contour, and terminate [`Path`].
957pub type Verb = sb::SkPath_Verb;
958variant_name!(Verb::Line);
959
960// SK_HIDE_PATH_EDIT_METHODS
961
962impl Path {
963 /// Specifies whether [`Path`] is volatile; whether it will be altered or discarded
964 /// by the caller after it is drawn. [`Path`] by default have volatile set `false`, allowing
965 /// `Device` to attach a cache of data which speeds repeated drawing.
966 ///
967 /// Mark temporary paths, discarded or modified after use, as volatile
968 /// to inform `Device` that the path need not be cached.
969 ///
970 /// Mark animating [`Path`] volatile to improve performance.
971 /// Mark unchanging [`Path`] non-volatile to improve repeated rendering.
972 ///
973 /// raster surface [`Path`] draws are affected by volatile for some shadows.
974 /// GPU surface [`Path`] draws are affected by volatile for some shadows and concave geometries.
975 ///
976 /// * `is_volatile` - `true` if caller will alter [`Path`] after drawing
977 ///
978 /// Returns: reference to [`Path`]
979 pub fn set_is_volatile(&mut self, is_volatile: bool) -> &mut Self {
980 self.native_mut().fIsVolatile = is_volatile;
981 self
982 }
983
984 /// Exchanges the verb array, [`Point`] array, weights, and [`PathFillType`] with other.
985 /// Cached state is also exchanged. `swap()` internally exchanges pointers, so
986 /// it is lightweight and does not allocate memory.
987 ///
988 /// `swap()` usage has largely been replaced by PartialEq.
989 /// [`Path`] do not copy their content on assignment until they are written to,
990 /// making assignment as efficient as swap().
991 ///
992 /// * `other` - [`Path`] exchanged by value
993 ///
994 /// Example (C++): <https://fiddle.skia.org/c/@Path_swap>
995 pub fn swap(&mut self, other: &mut Path) -> &mut Self {
996 unsafe { self.native_mut().swap(other.native_mut()) }
997 self
998 }
999
1000 /// Sets `FillType`, the rule used to fill [`Path`]. While there is no check
1001 /// that `ft` is legal, values outside of `FillType` are not supported.
1002 pub fn set_fill_type(&mut self, ft: PathFillType) -> &mut Self {
1003 self.native_mut().fFillType = ft;
1004 self
1005 }
1006
1007 /// Replaces FillType with its inverse. The inverse of FillType describes the area
1008 /// unmodified by the original FillType.
1009 pub fn toggle_inverse_fill_type(&mut self) -> &mut Self {
1010 let n = self.native_mut();
1011 n.fFillType = n.fFillType.toggle_inverse();
1012 self
1013 }
1014
1015 /// Sets [`Path`] to its initial state.
1016 /// Removes verb array, [`Point`] array, and weights, and sets FillType to `Winding`.
1017 /// Internal storage associated with [`Path`] is released.
1018 ///
1019 /// Returns: reference to [`Path`]
1020 ///
1021 /// Example (C++): <https://fiddle.skia.org/c/@Path_reset>
1022 pub fn reset(&mut self) -> &mut Self {
1023 unsafe { self.native_mut().reset() };
1024 self
1025 }
1026}
1027
1028impl Path {
1029 /// Returns a copy of this path in the current state, and resets the path to empty.
1030 pub fn detach(&mut self) -> Self {
1031 let result = self.clone();
1032 self.reset();
1033 result
1034 }
1035
1036 pub fn iter(&self) -> PathIter {
1037 PathIter::from_native_c(construct(|iter| unsafe {
1038 sb::C_SkPath_iter(self.native(), iter)
1039 }))
1040 }
1041}
1042
1043/// Iterates through verb array, and associated [`Point`] array and conic weight.
1044/// Provides options to treat open contours as closed, and to ignore
1045/// degenerate data.
1046#[repr(transparent)]
1047pub struct Iter<'a>(SkPath_Iter, PhantomData<&'a Handle<SkPath>>);
1048
1049impl NativeAccess for Iter<'_> {
1050 type Native = SkPath_Iter;
1051
1052 fn native(&self) -> &SkPath_Iter {
1053 &self.0
1054 }
1055 fn native_mut(&mut self) -> &mut SkPath_Iter {
1056 &mut self.0
1057 }
1058}
1059
1060impl Drop for Iter<'_> {
1061 fn drop(&mut self) {
1062 unsafe { sb::C_SkPath_Iter_destruct(&mut self.0) }
1063 }
1064}
1065
1066impl Default for Iter<'_> {
1067 /// Initializes [`Iter`] with an empty [`Path`]. `next()` on [`Iter`] returns
1068 /// [`Verb::Done`].
1069 /// Call `set_path` to initialize [`Iter`] at a later time.
1070 ///
1071 /// Returns: [`Iter`] of empty [`Path`]
1072 ///
1073 /// Example (C++): <https://fiddle.skia.org/c/@Path_Iter_Iter>
1074 fn default() -> Self {
1075 Iter(unsafe { SkPath_Iter::new() }, PhantomData)
1076 }
1077}
1078
1079impl fmt::Debug for Iter<'_> {
1080 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081 f.debug_struct("Iter")
1082 .field("conic_weight", &self.conic_weight())
1083 .field("is_close_line", &self.is_close_line())
1084 .field("is_closed_contour", &self.is_closed_contour())
1085 .finish()
1086 }
1087}
1088
1089impl Iter<'_> {
1090 /// Sets [`Iter`] to return elements of verb array, [`Point`] array, and conic weight in
1091 /// path. If `force_close` is `true`, [`Iter`] will add [`Verb::Line`] and [`Verb::Close`] after each
1092 /// open contour. path is not altered.
1093 ///
1094 /// * `path` - [`Path`] to iterate
1095 /// * `force_close` - `true` if open contours generate [`Verb::Close`]
1096 ///
1097 /// Returns: [`Iter`] of path
1098 ///
1099 /// Example (C++): <https://fiddle.skia.org/c/@Path_Iter_const_SkPath>
1100 pub fn new(path: &Path, force_close: bool) -> Self {
1101 Self(
1102 unsafe { SkPath_Iter::new1(path.native(), force_close) },
1103 PhantomData,
1104 )
1105 }
1106
1107 /// Sets [`Iter`] to return elements of verb array, [`Point`] array, and conic weight in
1108 /// path. If `force_close` is `true`, [`Iter`] will add [`Verb::Line`] and [`Verb::Close`] after each
1109 /// open contour. path is not altered.
1110 ///
1111 /// * `path` - [`Path`] to iterate
1112 /// * `force_close` - `true` if open contours generate [`Verb::Close`]
1113 ///
1114 /// Example (C++): <https://fiddle.skia.org/c/@Path_Iter_setPath>
1115 pub fn set_path(&mut self, path: &Path, force_close: bool) {
1116 unsafe {
1117 self.0.setPath(path.native(), force_close);
1118 }
1119 }
1120
1121 /// Returns conic weight if `next()` returned [`Verb::Conic`].
1122 ///
1123 /// If `next()` has not been called, or `next()` did not return [`Verb::Conic`],
1124 /// result is `None`.
1125 ///
1126 /// Returns: conic weight for conic [`Point`] returned by `next()`
1127 pub fn conic_weight(&self) -> Option<scalar> {
1128 #[allow(clippy::map_clone)]
1129 self.native()
1130 .fConicWeights
1131 .into_non_null()
1132 .map(|p| unsafe { *p.as_ref() })
1133 }
1134
1135 /// Returns `true` if last [`Verb::Line`] returned by `next()` was generated
1136 /// by [`Verb::Close`]. When `true`, the end point returned by `next()` is
1137 /// also the start point of contour.
1138 ///
1139 /// If `next()` has not been called, or `next()` did not return [`Verb::Line`],
1140 /// result is undefined.
1141 ///
1142 /// Returns: `true` if last [`Verb::Line`] was generated by [`Verb::Close`]
1143 pub fn is_close_line(&self) -> bool {
1144 unsafe { sb::C_SkPath_Iter_isCloseLine(self.native()) }
1145 }
1146
1147 /// Returns `true` if subsequent calls to `next()` return [`Verb::Close`] before returning
1148 /// [`Verb::Move`]. if `true`, contour [`Iter`] is processing may end with [`Verb::Close`], or
1149 /// [`Iter`] may have been initialized with force close set to `true`.
1150 ///
1151 /// Returns: `true` if contour is closed
1152 ///
1153 /// Example (C++): <https://fiddle.skia.org/c/@Path_Iter_isClosedContour>
1154 pub fn is_closed_contour(&self) -> bool {
1155 unsafe { self.native().isClosedContour() }
1156 }
1157}
1158
1159impl Iterator for Iter<'_> {
1160 type Item = (Verb, Vec<Point>);
1161
1162 /// Returns next [`Verb`] in verb array, and advances [`Iter`].
1163 /// When verb array is exhausted, returns [`Verb::Done`].
1164 ///
1165 /// Zero to four [`Point`] are stored in pts, depending on the returned [`Verb`].
1166 ///
1167 /// * `pts` - storage for [`Point`] data describing returned [`Verb`]
1168 ///
1169 /// Returns: next [`Verb`] from verb array
1170 ///
1171 /// Example (C++): <https://fiddle.skia.org/c/@Path_RawIter_next>
1172 fn next(&mut self) -> Option<Self::Item> {
1173 let mut points = [Point::default(); Verb::MAX_POINTS];
1174 let verb = unsafe { self.native_mut().next(points.native_mut().as_mut_ptr()) };
1175 if verb != Verb::Done {
1176 Some((verb, points[0..verb.points()].into()))
1177 } else {
1178 None
1179 }
1180 }
1181}
1182
1183#[repr(transparent)]
1184#[deprecated(
1185 since = "0.30.0",
1186 note = "User Iter instead, RawIter will soon be removed."
1187)]
1188pub struct RawIter<'a>(SkPath_RawIter, PhantomData<&'a Handle<SkPath>>);
1189
1190#[allow(deprecated)]
1191impl NativeAccess for RawIter<'_> {
1192 type Native = SkPath_RawIter;
1193
1194 fn native(&self) -> &SkPath_RawIter {
1195 &self.0
1196 }
1197 fn native_mut(&mut self) -> &mut SkPath_RawIter {
1198 &mut self.0
1199 }
1200}
1201
1202#[allow(deprecated)]
1203impl Drop for RawIter<'_> {
1204 fn drop(&mut self) {
1205 unsafe { sb::C_SkPath_RawIter_destruct(&mut self.0) }
1206 }
1207}
1208
1209#[allow(deprecated)]
1210impl Default for RawIter<'_> {
1211 fn default() -> Self {
1212 RawIter(
1213 construct(|ri| unsafe { sb::C_SkPath_RawIter_Construct(ri) }),
1214 PhantomData,
1215 )
1216 }
1217}
1218
1219#[allow(deprecated)]
1220impl RawIter<'_> {
1221 pub fn new(path: &Path) -> RawIter {
1222 RawIter::default().set_path(path)
1223 }
1224
1225 pub fn set_path(mut self, path: &Path) -> RawIter {
1226 unsafe { self.native_mut().setPath(path.native()) }
1227 let r = RawIter(self.0, PhantomData);
1228 forget(self);
1229 r
1230 }
1231
1232 pub fn peek(&self) -> Verb {
1233 unsafe { sb::C_SkPath_RawIter_peek(self.native()) }
1234 }
1235
1236 pub fn conic_weight(&self) -> scalar {
1237 self.native().fConicWeight
1238 }
1239}
1240
1241#[allow(deprecated)]
1242impl Iterator for RawIter<'_> {
1243 type Item = (Verb, Vec<Point>);
1244
1245 fn next(&mut self) -> Option<Self::Item> {
1246 let mut points = [Point::default(); Verb::MAX_POINTS];
1247
1248 let verb = unsafe { self.native_mut().next(points.native_mut().as_mut_ptr()) };
1249 (verb != Verb::Done).then(|| (verb, points[0..verb.points()].into()))
1250 }
1251}
1252
1253impl Path {
1254 /// Returns `true` if the point is contained by [`Path`], taking into
1255 /// account [`PathFillType`].
1256 ///
1257 /// * `point` - the point to test
1258 ///
1259 /// Returns: `true` if [`Point`] is in [`Path`]
1260 ///
1261 pub fn contains(&self, point: impl Into<Point>) -> bool {
1262 let point = point.into();
1263 unsafe { self.native().contains(point.into_native()) }
1264 }
1265
1266 /// Writes text representation of [`Path`] to [`Data`].
1267 /// Set `dump_as_hex` `true` to generate exact binary representations
1268 /// of floating point numbers used in [`Point`] array and conic weights.
1269 ///
1270 /// * `dump_as_hex` - `true` if scalar values are written as hexadecimal
1271 ///
1272 /// Example (C++): <https://fiddle.skia.org/c/@Path_dump>
1273 pub fn dump_as_data(&self, dump_as_hex: bool) -> Data {
1274 let mut stream = DynamicMemoryWStream::new();
1275 unsafe {
1276 self.native()
1277 .dump(stream.native_mut().base_mut(), dump_as_hex);
1278 }
1279 stream.detach_as_data()
1280 }
1281
1282 /// See [`Path::dump_as_data()`]
1283 pub fn dump(&self) {
1284 unsafe { self.native().dump(ptr::null_mut(), false) }
1285 }
1286
1287 /// See [`Path::dump_as_data()`]
1288 pub fn dump_hex(&self) {
1289 unsafe { self.native().dump(ptr::null_mut(), true) }
1290 }
1291
1292 // TODO: writeToMemory()?
1293
1294 /// Writes [`Path`] to buffer, returning the buffer written to, wrapped in [`Data`].
1295 ///
1296 /// `serialize()` writes [`PathFillType`], verb array, [`Point`] array, conic weight, and
1297 /// additionally writes computed information like convexity and bounds.
1298 ///
1299 /// `serialize()` should only be used in concert with `read_from_memory`().
1300 /// The format used for [`Path`] in memory is not guaranteed.
1301 ///
1302 /// Returns: [`Path`] data wrapped in [`Data`] buffer
1303 ///
1304 /// Example (C++): <https://fiddle.skia.org/c/@Path_serialize>
1305 pub fn serialize(&self) -> Data {
1306 Data::from_ptr(unsafe { sb::C_SkPath_serialize(self.native()) }).unwrap()
1307 }
1308
1309 // TODO: ReadFromMemory
1310
1311 pub fn deserialize(data: &Data) -> Option<Path> {
1312 let mut path = Path::default();
1313 let bytes = data.as_bytes();
1314 unsafe { sb::C_SkPath_ReadFromMemory(path.native_mut(), bytes.as_ptr() as _, bytes.len()) }
1315 .then_some(path)
1316 }
1317
1318 /// (See skbug.com/40032862)
1319 /// Returns a non-zero, globally unique value. A different value is returned
1320 /// if verb array, [`Point`] array, or conic weight changes.
1321 ///
1322 /// Setting [`PathFillType`] does not change generation identifier.
1323 ///
1324 /// Each time the path is modified, a different generation identifier will be returned.
1325 /// [`PathFillType`] does affect generation identifier on Android framework.
1326 ///
1327 /// Returns: non-zero, globally unique value
1328 ///
1329 /// Example (C++): <https://fiddle.skia.org/c/@Path_getGenerationID>
1330 pub fn generation_id(&self) -> u32 {
1331 unsafe { self.native().getGenerationID() }
1332 }
1333
1334 /// Returns if [`Path`] data is consistent. Corrupt [`Path`] data is detected if
1335 /// internal values are out of range or internal storage does not match
1336 /// array dimensions.
1337 ///
1338 /// Returns: `true` if [`Path`] data is consistent
1339 pub fn is_valid(&self) -> bool {
1340 unsafe { self.native().isValid() }
1341 }
1342}
1343
1344#[cfg(test)]
1345mod tests {
1346 use super::*;
1347
1348 #[test]
1349 fn test_count_points() {
1350 let p = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1351 let points_count = p.count_points();
1352 assert_eq!(points_count, 4);
1353 }
1354
1355 #[test]
1356 fn test_fill_type() {
1357 let mut p = Path::default();
1358 assert_eq!(p.fill_type(), PathFillType::Winding);
1359 p.set_fill_type(PathFillType::EvenOdd);
1360 assert_eq!(p.fill_type(), PathFillType::EvenOdd);
1361 assert!(!p.is_inverse_fill_type());
1362 p.toggle_inverse_fill_type();
1363 assert_eq!(p.fill_type(), PathFillType::InverseEvenOdd);
1364 assert!(p.is_inverse_fill_type());
1365 }
1366
1367 #[test]
1368 fn test_is_volatile() {
1369 let mut p = Path::default();
1370 assert!(!p.is_volatile());
1371 p.set_is_volatile(true);
1372 assert!(p.is_volatile());
1373 }
1374
1375 #[test]
1376 fn test_path_rect() {
1377 let r = Rect::new(0.0, 0.0, 100.0, 100.0);
1378 let path = Path::rect(r, None);
1379 assert_eq!(*path.bounds(), r);
1380 }
1381
1382 #[test]
1383 fn test_points_verbs_conic_weights() {
1384 let path = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1385
1386 // Test points()
1387 let points = path.points();
1388 assert_eq!(points.len(), 4);
1389
1390 // Test verbs()
1391 let verbs = path.verbs();
1392 assert_eq!(verbs.len(), 5); // Move + 4 Lines + Close
1393
1394 // Test conic_weights()
1395 let weights = path.conic_weights();
1396 assert_eq!(weights.len(), 0); // Rectangle has no conics
1397 }
1398
1399 #[test]
1400 fn test_with_offset() {
1401 let path = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1402 let offset_path = path.with_offset((5.0, 5.0));
1403
1404 assert_eq!(*offset_path.bounds(), Rect::new(5.0, 5.0, 15.0, 15.0));
1405 }
1406
1407 #[test]
1408 fn test_with_transform() {
1409 let path = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1410 let matrix = Matrix::scale((2.0, 2.0));
1411 let transformed = path.with_transform(&matrix);
1412
1413 assert_eq!(*transformed.bounds(), Rect::new(0.0, 0.0, 20.0, 20.0));
1414 }
1415
1416 #[test]
1417 fn test_try_make_transform() {
1418 let path = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1419
1420 // Test with finite transform
1421 let matrix = Matrix::scale((2.0, 2.0));
1422 let result = path.try_make_transform(&matrix);
1423 assert!(result.is_some());
1424 let transformed = result.unwrap();
1425 assert_eq!(*transformed.bounds(), Rect::new(0.0, 0.0, 20.0, 20.0));
1426
1427 // Test with extreme scale that might produce non-finite values
1428 let extreme_matrix = Matrix::scale((f32::MAX, f32::MAX));
1429 let result = path.try_make_transform(&extreme_matrix);
1430 // The result depends on whether the transform produces finite values
1431 // This test documents the behavior
1432 if let Some(transformed) = result {
1433 assert!(transformed.is_finite());
1434 }
1435 }
1436
1437 #[test]
1438 fn test_try_make_offset() {
1439 let path = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1440
1441 // Test with finite offset
1442 let result = path.try_make_offset((5.0, 5.0));
1443 assert!(result.is_some());
1444 let offset_path = result.unwrap();
1445 assert_eq!(*offset_path.bounds(), Rect::new(5.0, 5.0, 15.0, 15.0));
1446 }
1447
1448 #[test]
1449 fn test_try_make_scale() {
1450 let path = Path::rect(Rect::new(0.0, 0.0, 10.0, 10.0), None);
1451
1452 // Test with finite scale
1453 let result = path.try_make_scale((3.0, 3.0));
1454 assert!(result.is_some());
1455 let scaled = result.unwrap();
1456 assert_eq!(*scaled.bounds(), Rect::new(0.0, 0.0, 30.0, 30.0));
1457 }
1458
1459 #[test]
1460 fn test_serialize_deserialize() {
1461 let path = Path::rect(Rect::new(10.0, 10.0, 20.0, 20.0), None);
1462
1463 let data = path.serialize();
1464 let deserialized = Path::deserialize(&data).unwrap();
1465
1466 assert_eq!(path, deserialized);
1467 }
1468}