Skip to main content

gpui/
path_builder.rs

1// Modified by Longbridge for gpui-fast.
2use anyhow::{Error, bail};
3use etagere::euclid::{Point2D, Vector2D};
4use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment};
5use lyon_path::math::{Vector, vector};
6use lyon_path::traits::SvgPathBuilder;
7use lyon_path::{ArcFlags, Event, Polygon};
8
9pub use lyon_path::math::Transform;
10pub use lyon_path::{FillRule, LineCap, LineJoin};
11
12use crate::{PathCurve, PathTiles, Pixels, Point, point, px};
13use std::sync::Arc;
14
15/// Style of the PathBuilder
16pub enum PathStyle {
17    /// Stroke style
18    Stroke(StrokeOptions),
19    /// Fill style
20    Fill(FillOptions),
21}
22
23/// How to stroke a path.
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct StrokeOptions {
26    /// Width of the stroke.
27    pub line_width: f32,
28    /// Shape of the ends of open subpaths and dashes.
29    pub line_cap: LineCap,
30    /// Shape of corners.
31    pub line_join: LineJoin,
32    /// How long a miter join may get, as a multiple of the line width,
33    /// before it is beveled instead.
34    pub miter_limit: f32,
35}
36
37impl Default for StrokeOptions {
38    fn default() -> Self {
39        Self {
40            line_width: 1.0,
41            line_cap: LineCap::Butt,
42            line_join: LineJoin::Miter,
43            miter_limit: 4.0,
44        }
45    }
46}
47
48/// How to fill a path.
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct FillOptions {
51    /// How overlapping contours combine into the filled region.
52    pub fill_rule: FillRule,
53}
54
55impl Default for FillOptions {
56    fn default() -> Self {
57        Self {
58            fill_rule: FillRule::EvenOdd,
59        }
60    }
61}
62
63/// A [`Path`] builder.
64pub struct PathBuilder {
65    raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
66    transform: Option<lyon_path::math::Transform>,
67    /// PathStyle of the PathBuilder
68    pub style: PathStyle,
69    dash_array: Option<Vec<Pixels>>,
70}
71
72impl From<lyon_path::Builder> for PathBuilder {
73    fn from(builder: lyon_path::Builder) -> Self {
74        Self {
75            raw: builder.with_svg(),
76            ..Default::default()
77        }
78    }
79}
80
81impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
82    fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
83        Self {
84            raw,
85            ..Default::default()
86        }
87    }
88}
89
90impl From<lyon_path::math::Point> for Point<Pixels> {
91    fn from(p: lyon_path::math::Point) -> Self {
92        point(px(p.x), px(p.y))
93    }
94}
95
96impl From<Point<Pixels>> for lyon_path::math::Point {
97    fn from(p: Point<Pixels>) -> Self {
98        lyon_path::math::point(p.x.0, p.y.0)
99    }
100}
101
102impl From<Point<Pixels>> for Vector {
103    fn from(p: Point<Pixels>) -> Self {
104        vector(p.x.0, p.y.0)
105    }
106}
107
108impl From<Point<Pixels>> for Point2D<f32, Pixels> {
109    fn from(p: Point<Pixels>) -> Self {
110        Point2D::new(p.x.0, p.y.0)
111    }
112}
113
114impl Default for PathBuilder {
115    fn default() -> Self {
116        Self {
117            raw: lyon_path::Path::builder().with_svg(),
118            style: PathStyle::Fill(FillOptions::default()),
119            transform: None,
120            dash_array: None,
121        }
122    }
123}
124
125impl PathBuilder {
126    /// Creates a new [`PathBuilder`] to build a Stroke path.
127    pub fn stroke(width: Pixels) -> Self {
128        Self {
129            style: PathStyle::Stroke(StrokeOptions {
130                line_width: width.0,
131                ..Default::default()
132            }),
133            ..Self::default()
134        }
135    }
136
137    /// Creates a new [`PathBuilder`] to build a Fill path.
138    pub fn fill() -> Self {
139        Self::default()
140    }
141
142    /// Sets the style of the [`PathBuilder`].
143    pub fn with_style(self, style: PathStyle) -> Self {
144        Self { style, ..self }
145    }
146
147    /// Sets the dash array of the [`PathBuilder`]. Fills ignore it.
148    ///
149    /// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray)
150    pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
151        // If an odd number of values is provided, then the list of values is repeated to yield an even number of values.
152        // Thus, 5,3,2 is equivalent to 5,3,2,5,3,2.
153        let array = if dash_array.len() % 2 == 1 {
154            let mut new_dash_array = dash_array.to_vec();
155            new_dash_array.extend_from_slice(dash_array);
156            new_dash_array
157        } else {
158            dash_array.to_vec()
159        };
160
161        self.dash_array = Some(array);
162        self
163    }
164
165    /// Move the current point to the given point.
166    #[inline]
167    pub fn move_to(&mut self, to: Point<Pixels>) {
168        self.raw.move_to(to.into());
169    }
170
171    /// Draw a straight line from the current point to the given point.
172    #[inline]
173    pub fn line_to(&mut self, to: Point<Pixels>) {
174        self.raw.line_to(to.into());
175    }
176
177    /// Draw a curve from the current point to the given point, using the given control point.
178    #[inline]
179    pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
180        self.raw.quadratic_bezier_to(ctrl.into(), to.into());
181    }
182
183    /// Adds a cubic Bézier to the [`Path`] given its two control points
184    /// and its end point.
185    #[inline]
186    pub fn cubic_bezier_to(
187        &mut self,
188        to: Point<Pixels>,
189        control_a: Point<Pixels>,
190        control_b: Point<Pixels>,
191    ) {
192        self.raw
193            .cubic_bezier_to(control_a.into(), control_b.into(), to.into());
194    }
195
196    /// Adds an elliptical arc.
197    pub fn arc_to(
198        &mut self,
199        radii: Point<Pixels>,
200        x_rotation: Pixels,
201        large_arc: bool,
202        sweep: bool,
203        to: Point<Pixels>,
204    ) {
205        self.raw.arc_to(
206            radii.into(),
207            Angle::degrees(x_rotation.into()),
208            ArcFlags { large_arc, sweep },
209            to.into(),
210        );
211    }
212
213    /// Equivalent to `arc_to` in relative coordinates.
214    pub fn relative_arc_to(
215        &mut self,
216        radii: Point<Pixels>,
217        x_rotation: Pixels,
218        large_arc: bool,
219        sweep: bool,
220        to: Point<Pixels>,
221    ) {
222        self.raw.relative_arc_to(
223            radii.into(),
224            Angle::degrees(x_rotation.into()),
225            ArcFlags { large_arc, sweep },
226            to.into(),
227        );
228    }
229
230    /// Adds a polygon.
231    pub fn add_polygon(&mut self, points: &[Point<Pixels>], closed: bool) {
232        let points = points.iter().copied().map(|p| p.into()).collect::<Vec<_>>();
233        self.raw.add_polygon(Polygon {
234            points: points.as_ref(),
235            closed,
236        });
237    }
238
239    /// Close the current sub-path.
240    #[inline]
241    pub fn close(&mut self) {
242        self.raw.close();
243    }
244
245    /// Applies a transform to the path.
246    #[inline]
247    pub fn transform(&mut self, transform: Transform) {
248        self.transform = Some(transform);
249    }
250
251    /// Applies a translation to the path.
252    #[inline]
253    pub fn translate(&mut self, to: Point<Pixels>) {
254        if let Some(transform) = self.transform {
255            self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
256        } else {
257            self.transform = Some(Transform::translation(to.x.0, to.y.0))
258        }
259    }
260
261    /// Applies a scale to the path.
262    #[inline]
263    pub fn scale(&mut self, scale: f32) {
264        if let Some(transform) = self.transform {
265            self.transform = Some(transform.then_scale(scale, scale));
266        } else {
267            self.transform = Some(Transform::scale(scale, scale));
268        }
269    }
270
271    /// Applies a rotation to the path.
272    ///
273    /// The `angle` is in degrees value in the range 0.0 to 360.0.
274    #[inline]
275    pub fn rotate(&mut self, angle: f32) {
276        let radians = angle.to_radians();
277        if let Some(transform) = self.transform {
278            self.transform = Some(transform.then_rotate(Angle::radians(radians)));
279        } else {
280            self.transform = Some(Transform::rotation(Angle::radians(radians)));
281        }
282    }
283
284    /// Builds into a [`Path`].
285    pub fn build(self) -> Result<Path, Error> {
286        crate::fast::path_cache::build(self)
287    }
288
289    /// The transformed path, its style and dash array, for
290    /// crate::fast::path_cache's key, and back.
291    pub(crate) fn fast_into_parts(self) -> (lyon_path::Path, PathStyle, Option<Vec<Pixels>>) {
292        let path = match self.transform {
293            Some(transform) => self.raw.build().transformed(&transform),
294            None => self.raw.build(),
295        };
296        (path, self.style, self.dash_array)
297    }
298
299    pub(crate) fn fast_from_parts(
300        path: &lyon_path::Path,
301        style: PathStyle,
302        dash_array: Option<Vec<Pixels>>,
303    ) -> Self {
304        let mut raw = lyon_path::Path::builder();
305        for event in path.iter() {
306            raw.path_event(event);
307        }
308        Self {
309            raw: raw.with_svg(),
310            transform: None,
311            style,
312            dash_array,
313        }
314    }
315
316    /// The curves a path shares with others of its shape (crate::fast::path_cache).
317    pub(crate) fn fast_curves(path: &Path) -> &Arc<[PathCurve]> {
318        &path.curves
319    }
320
321    /// The closed contours to fill, and the rule to fill them by.
322    pub(crate) fn outline(self) -> Result<(Vec<PathCurve>, FillRule), Error> {
323        let path = if let Some(transform) = self.transform {
324            self.raw.build().transformed(&transform)
325        } else {
326            self.raw.build()
327        };
328
329        Ok(match self.style {
330            PathStyle::Stroke(options) => (
331                Self::stroke_outline(&path, &options, self.dash_array.as_deref())?,
332                FillRule::NonZero,
333            ),
334            PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule),
335        })
336    }
337
338    fn stroke_outline(
339        path: &lyon_path::Path,
340        options: &StrokeOptions,
341        dash_array: Option<&[Pixels]>,
342    ) -> Result<Vec<PathCurve>, Error> {
343        let outline = skia_path(path)
344            .map(|skia_path| match dash_array {
345                Some(dash_array) => {
346                    let array = dash_array.iter().map(|length| length.0).collect();
347                    match tiny_skia_path::StrokeDash::new(array, 0.0) {
348                        Some(dash) => skia_path
349                            .dash(&dash, STROKE_RESOLUTION_SCALE)
350                            .unwrap_or(skia_path),
351                        // An invalid dash array strokes undashed, as in SVG.
352                        None => skia_path,
353                    }
354                }
355                None => skia_path,
356            })
357            .and_then(|skia_path| {
358                skia_path.stroke(
359                    &tiny_skia_path::Stroke {
360                        width: options.line_width,
361                        miter_limit: options.miter_limit,
362                        line_cap: match options.line_cap {
363                            LineCap::Butt => tiny_skia_path::LineCap::Butt,
364                            LineCap::Square => tiny_skia_path::LineCap::Square,
365                            LineCap::Round => tiny_skia_path::LineCap::Round,
366                        },
367                        line_join: match options.line_join {
368                            LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
369                            LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
370                            LineJoin::Round => tiny_skia_path::LineJoin::Round,
371                            LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
372                        },
373                        dash: None,
374                    },
375                    STROKE_RESOLUTION_SCALE,
376                )
377            });
378        let Some(outline) = outline else {
379            return Ok(Vec::new());
380        };
381
382        let mut output = Outline::default();
383        let at = |p: tiny_skia_path::Point| point(p.x, p.y);
384        for segment in outline.segments() {
385            match segment {
386                tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)),
387                tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)),
388                tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)),
389                tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => {
390                    output.cubic_to(at(p), at(ctrl1), at(ctrl2))
391                }
392                tiny_skia_path::PathSegment::Close => output.close(),
393            }
394        }
395        output.into_curves()
396    }
397
398    /// Convert a lyon path into a fill, closing every subpath.
399    fn fill_outline(path: &lyon_path::Path) -> Result<Vec<PathCurve>, Error> {
400        let mut output = Outline::default();
401        let at = |p: lyon_path::math::Point| point(p.x, p.y);
402        for event in path.iter() {
403            match event {
404                Event::Begin { at: p } => output.move_to(at(p)),
405                Event::Line { to, .. } => output.line_to(at(to)),
406                Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)),
407                Event::Cubic {
408                    ctrl1, ctrl2, to, ..
409                } => output.cubic_to(at(to), at(ctrl1), at(ctrl2)),
410                Event::End { .. } => output.close(),
411            }
412        }
413        output.into_curves()
414    }
415}
416
417/// A filled path, ready to paint. Build one with [`PathBuilder`].
418#[derive(Clone, Debug)]
419pub struct Path {
420    /// Closed contours of monotone curves, in logical pixels.
421    curves: Arc<[PathCurve]>,
422    even_odd: bool,
423}
424
425impl Path {
426    pub(crate) fn from_curves(curves: Vec<PathCurve>, fill_rule: FillRule) -> Self {
427        Self {
428            curves: curves.into(),
429            even_odd: matches!(fill_rule, FillRule::EvenOdd),
430        }
431    }
432
433    pub(crate) fn even_odd(&self) -> bool {
434        self.even_odd
435    }
436
437    /// Bin the curves into tiles in device pixels, for painting at the given
438    /// display scale.
439    pub(crate) fn bin(&self, scale: f32) -> PathTiles {
440        crate::path_winding::bin(&self.curves, self.even_odd, scale)
441    }
442}
443
444/// A path's contours as monotone curves, collected by [`PathBuilder`].
445#[derive(Default)]
446pub(crate) struct Outline {
447    curves: Vec<PathCurve>,
448    start: Point<f32>,
449    current: Point<f32>,
450    non_finite: bool,
451}
452
453impl Outline {
454    /// Whether segments through these points can be added.
455    fn accepts(&mut self, points: &[Point<f32>]) -> bool {
456        self.non_finite |= !points
457            .iter()
458            .all(|point| point.x.is_finite() && point.y.is_finite());
459        !self.non_finite
460    }
461
462    /// Close the current contour and start a new one at the given point.
463    pub(crate) fn move_to(&mut self, to: Point<f32>) {
464        if !self.accepts(&[to]) {
465            return;
466        }
467        self.close();
468        self.start = to;
469        self.current = to;
470    }
471
472    pub(crate) fn line_to(&mut self, to: Point<f32>) {
473        if self.accepts(&[to]) && to != self.current {
474            self.curves.push(PathCurve::line(self.current, to));
475            self.current = to;
476        }
477    }
478
479    pub(crate) fn curve_to(&mut self, to: Point<f32>, ctrl: Point<f32>) {
480        if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) {
481            return;
482        }
483        PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to);
484        self.current = to;
485    }
486
487    pub(crate) fn cubic_to(&mut self, to: Point<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
488        /// Maximum error, in logical pixels.
489        const TOLERANCE: f32 = 0.25;
490        if !self.accepts(&[to, ctrl1, ctrl2]) {
491            return;
492        }
493        let lyon_point = |p: Point<f32>| lyon_path::math::point(p.x, p.y);
494        let cubic = CubicBezierSegment {
495            from: lyon_point(self.current),
496            ctrl1: lyon_point(ctrl1),
497            ctrl2: lyon_point(ctrl2),
498            to: lyon_point(to),
499        };
500        cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| {
501            self.curve_to(
502                point(quadratic.to.x, quadratic.to.y),
503                point(quadratic.ctrl.x, quadratic.ctrl.y),
504            );
505        });
506    }
507
508    /// Close the current contour with a straight line back to its start.
509    pub(crate) fn close(&mut self) {
510        let start = self.start;
511        self.line_to(start);
512    }
513
514    /// The curves, with every contour closed.
515    pub(crate) fn into_curves(mut self) -> Result<Vec<PathCurve>, Error> {
516        if self.non_finite {
517            bail!("path has a non-finite point");
518        }
519        self.close();
520        Ok(self.curves)
521    }
522}
523
524impl PathCurve {
525    fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, sign: f32) -> Self {
526        Self {
527            p0,
528            p1,
529            a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y),
530            b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)),
531            sign,
532            pad: 0,
533        }
534    }
535
536    /// A line, with exactly zero quadratic terms.
537    fn line(from: Point<f32>, to: Point<f32>) -> Self {
538        let (p0, p1, sign) = downward(from, to);
539        Self {
540            p0,
541            p1,
542            a: point(0.0, 0.0),
543            b: point(p1.x - p0.x, p1.y - p0.y),
544            sign,
545            pad: 0,
546        }
547    }
548
549    /// Split a quadratic segment at its extrema into xy-monotone curves.
550    fn push_monotone(curves: &mut Vec<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
551        let curve = QuadraticBezierSegment {
552            from: lyon_path::math::point(p0.x, p0.y),
553            ctrl: lyon_path::math::point(ctrl.x, ctrl.y),
554            to: lyon_path::math::point(p1.x, p1.y),
555        };
556        // Unlike `split_range`, this also clamps each piece's control point
557        // back into its endpoint box when rounding pushes it out.
558        curve.for_each_monotonic(&mut |monotone| {
559            let from = point(monotone.from.x, monotone.from.y);
560            let to = point(monotone.to.x, monotone.to.y);
561            if from == to {
562                return;
563            }
564            // Horizontal curves are kept: upward rays cross them.
565            let (p0, p1, sign) = downward(from, to);
566            let ctrl = point(
567                monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)),
568                monotone.ctrl.y.clamp(p0.y, p1.y),
569            );
570            curves.push(Self::new(p0, ctrl, p1, sign));
571        });
572    }
573}
574
575fn downward(from: Point<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, f32) {
576    if from.y > to.y {
577        (to, from, -1.0)
578    } else {
579        (from, to, 1.0)
580    }
581}
582
583/// Strokes are expanded in logical pixels. tiny-skia keeps offset curves
584/// within `0.25 / STROKE_RESOLUTION_SCALE` of exact, a quarter device pixel at
585/// 2x, and flattens curves to within `0.5 / STROKE_RESOLUTION_SCALE` to measure
586/// dashes. Round joins and caps ignore it: their arcs are approximated to 0.25
587/// logical pixels.
588const STROKE_RESOLUTION_SCALE: f32 = 2.0;
589
590/// Returns [`None`] for empty geometry.
591fn skia_path(path: &lyon_path::Path) -> Option<tiny_skia_path::Path> {
592    let mut builder = tiny_skia_path::PathBuilder::new();
593    for event in path.iter() {
594        match event {
595            Event::Begin { at } => builder.move_to(at.x, at.y),
596            Event::Line { to, .. } => builder.line_to(to.x, to.y),
597            Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y),
598            Event::Cubic {
599                ctrl1, ctrl2, to, ..
600            } => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y),
601            Event::End { close, .. } => {
602                if close {
603                    builder.close();
604                }
605            }
606        }
607    }
608    builder.finish()
609}