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