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