Skip to main content

gpui/
path_builder.rs

1// Modified by Longbridge for gpui-fast.
2use anyhow::Error;
3use etagere::euclid::{Point2D, Vector2D};
4use lyon::geom::Angle;
5use lyon::math::{Vector, vector};
6use lyon::path::traits::SvgPathBuilder;
7use lyon::path::{ArcFlags, Polygon};
8use lyon::tessellation::{
9    BuffersBuilder, FillTessellator, FillVertex, StrokeTessellator, StrokeVertex, VertexBuffers,
10};
11
12pub use lyon::math::Transform;
13pub use lyon::tessellation::{FillOptions, FillRule, StrokeOptions};
14
15use crate::{Path, Pixels, Point, point, px};
16
17/// Style of the PathBuilder
18pub enum PathStyle {
19    /// Stroke style
20    Stroke(StrokeOptions),
21    /// Fill style
22    Fill(FillOptions),
23}
24
25/// A [`Path`] builder.
26pub struct PathBuilder {
27    pub(crate) raw: lyon::path::builder::WithSvg<lyon::path::BuilderImpl>,
28    pub(crate) transform: Option<lyon::math::Transform>,
29    /// PathStyle of the PathBuilder
30    pub style: PathStyle,
31    pub(crate) dash_array: Option<Vec<Pixels>>,
32}
33
34impl From<lyon::path::Builder> for PathBuilder {
35    fn from(builder: lyon::path::Builder) -> Self {
36        Self {
37            raw: builder.with_svg(),
38            ..Default::default()
39        }
40    }
41}
42
43impl From<lyon::path::builder::WithSvg<lyon::path::BuilderImpl>> for PathBuilder {
44    fn from(raw: lyon::path::builder::WithSvg<lyon::path::BuilderImpl>) -> Self {
45        Self {
46            raw,
47            ..Default::default()
48        }
49    }
50}
51
52impl From<lyon::math::Point> for Point<Pixels> {
53    fn from(p: lyon::math::Point) -> Self {
54        point(px(p.x), px(p.y))
55    }
56}
57
58impl From<Point<Pixels>> for lyon::math::Point {
59    fn from(p: Point<Pixels>) -> Self {
60        lyon::math::point(p.x.0, p.y.0)
61    }
62}
63
64impl From<Point<Pixels>> for Vector {
65    fn from(p: Point<Pixels>) -> Self {
66        vector(p.x.0, p.y.0)
67    }
68}
69
70impl From<Point<Pixels>> for Point2D<f32, Pixels> {
71    fn from(p: Point<Pixels>) -> Self {
72        Point2D::new(p.x.0, p.y.0)
73    }
74}
75
76impl Default for PathBuilder {
77    fn default() -> Self {
78        Self {
79            raw: lyon::path::Path::builder().with_svg(),
80            style: PathStyle::Fill(FillOptions::default()),
81            transform: None,
82            dash_array: None,
83        }
84    }
85}
86
87impl PathBuilder {
88    /// Creates a new [`PathBuilder`] to build a Stroke path.
89    pub fn stroke(width: Pixels) -> Self {
90        Self {
91            style: PathStyle::Stroke(StrokeOptions::default().with_line_width(width.0)),
92            ..Self::default()
93        }
94    }
95
96    /// Creates a new [`PathBuilder`] to build a Fill path.
97    pub fn fill() -> Self {
98        Self::default()
99    }
100
101    /// Sets the style of the [`PathBuilder`].
102    pub fn with_style(self, style: PathStyle) -> Self {
103        Self { style, ..self }
104    }
105
106    /// Sets the dash array of the [`PathBuilder`].
107    ///
108    /// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray)
109    pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
110        // If an odd number of values is provided, then the list of values is repeated to yield an even number of values.
111        // Thus, 5,3,2 is equivalent to 5,3,2,5,3,2.
112        let array = if dash_array.len() % 2 == 1 {
113            let mut new_dash_array = dash_array.to_vec();
114            new_dash_array.extend_from_slice(dash_array);
115            new_dash_array
116        } else {
117            dash_array.to_vec()
118        };
119
120        self.dash_array = Some(array);
121        self
122    }
123
124    /// Move the current point to the given point.
125    #[inline]
126    pub fn move_to(&mut self, to: Point<Pixels>) {
127        self.raw.move_to(to.into());
128    }
129
130    /// Draw a straight line from the current point to the given point.
131    #[inline]
132    pub fn line_to(&mut self, to: Point<Pixels>) {
133        self.raw.line_to(to.into());
134    }
135
136    /// Draw a curve from the current point to the given point, using the given control point.
137    #[inline]
138    pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
139        self.raw.quadratic_bezier_to(ctrl.into(), to.into());
140    }
141
142    /// Adds a cubic Bézier to the [`Path`] given its two control points
143    /// and its end point.
144    #[inline]
145    pub fn cubic_bezier_to(
146        &mut self,
147        to: Point<Pixels>,
148        control_a: Point<Pixels>,
149        control_b: Point<Pixels>,
150    ) {
151        self.raw
152            .cubic_bezier_to(control_a.into(), control_b.into(), to.into());
153    }
154
155    /// Adds an elliptical arc.
156    pub fn arc_to(
157        &mut self,
158        radii: Point<Pixels>,
159        x_rotation: Pixels,
160        large_arc: bool,
161        sweep: bool,
162        to: Point<Pixels>,
163    ) {
164        self.raw.arc_to(
165            radii.into(),
166            Angle::degrees(x_rotation.into()),
167            ArcFlags { large_arc, sweep },
168            to.into(),
169        );
170    }
171
172    /// Equivalent to `arc_to` in relative coordinates.
173    pub fn relative_arc_to(
174        &mut self,
175        radii: Point<Pixels>,
176        x_rotation: Pixels,
177        large_arc: bool,
178        sweep: bool,
179        to: Point<Pixels>,
180    ) {
181        self.raw.relative_arc_to(
182            radii.into(),
183            Angle::degrees(x_rotation.into()),
184            ArcFlags { large_arc, sweep },
185            to.into(),
186        );
187    }
188
189    /// Adds a polygon.
190    pub fn add_polygon(&mut self, points: &[Point<Pixels>], closed: bool) {
191        let points = points.iter().copied().map(|p| p.into()).collect::<Vec<_>>();
192        self.raw.add_polygon(Polygon {
193            points: points.as_ref(),
194            closed,
195        });
196    }
197
198    /// Close the current sub-path.
199    #[inline]
200    pub fn close(&mut self) {
201        self.raw.close();
202    }
203
204    /// Applies a transform to the path.
205    #[inline]
206    pub fn transform(&mut self, transform: Transform) {
207        self.transform = Some(transform);
208    }
209
210    /// Applies a translation to the path.
211    #[inline]
212    pub fn translate(&mut self, to: Point<Pixels>) {
213        if let Some(transform) = self.transform {
214            self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
215        } else {
216            self.transform = Some(Transform::translation(to.x.0, to.y.0))
217        }
218    }
219
220    /// Applies a scale to the path.
221    #[inline]
222    pub fn scale(&mut self, scale: f32) {
223        if let Some(transform) = self.transform {
224            self.transform = Some(transform.then_scale(scale, scale));
225        } else {
226            self.transform = Some(Transform::scale(scale, scale));
227        }
228    }
229
230    /// Applies a rotation to the path.
231    ///
232    /// The `angle` is in degrees value in the range 0.0 to 360.0.
233    #[inline]
234    pub fn rotate(&mut self, angle: f32) {
235        let radians = angle.to_radians();
236        if let Some(transform) = self.transform {
237            self.transform = Some(transform.then_rotate(Angle::radians(radians)));
238        } else {
239            self.transform = Some(Transform::rotation(Angle::radians(radians)));
240        }
241    }
242
243    /// Builds into a [`Path`].
244    #[inline]
245    pub fn build(self) -> Result<Path<Pixels>, Error> {
246        crate::fast::path_cache::build(self)
247    }
248
249    pub(crate) fn tessellate_fill(
250        path: &lyon::path::Path,
251        options: &FillOptions,
252    ) -> Result<Path<Pixels>, Error> {
253        // Will contain the result of the tessellation.
254        let mut buf: VertexBuffers<lyon::math::Point, u16> = VertexBuffers::new();
255        let mut tessellator = FillTessellator::new();
256
257        // Compute the tessellation.
258        tessellator.tessellate_path(
259            path,
260            options,
261            &mut BuffersBuilder::new(&mut buf, |vertex: FillVertex| vertex.position()),
262        )?;
263
264        Ok(Self::build_path(buf))
265    }
266
267    pub(crate) fn tessellate_stroke(
268        dash_array: Option<Vec<Pixels>>,
269        path: &lyon::path::Path,
270        options: &StrokeOptions,
271    ) -> Result<Path<Pixels>, Error> {
272        let path = if let Some(dash_array) = dash_array {
273            let measurements = lyon::algorithms::measure::PathMeasurements::from_path(path, 0.01);
274            let mut sampler = measurements
275                .create_sampler(path, lyon::algorithms::measure::SampleType::Normalized);
276            let mut builder = lyon::path::Path::builder();
277
278            let total_length = sampler.length();
279            let dash_array_len = dash_array.len();
280            let mut pos = 0.;
281            let mut dash_index = 0;
282            while pos < total_length {
283                let dash_length = dash_array[dash_index % dash_array_len].0;
284                let next_pos = (pos + dash_length).min(total_length);
285                if dash_index % 2 == 0 {
286                    let start = pos / total_length;
287                    let end = next_pos / total_length;
288                    sampler.split_range(start..end, &mut builder);
289                }
290                pos = next_pos;
291                dash_index += 1;
292            }
293
294            &builder.build()
295        } else {
296            path
297        };
298
299        // Will contain the result of the tessellation.
300        let mut buf: VertexBuffers<lyon::math::Point, u16> = VertexBuffers::new();
301        let mut tessellator = StrokeTessellator::new();
302
303        // Compute the tessellation.
304        tessellator.tessellate_path(
305            path,
306            options,
307            &mut BuffersBuilder::new(&mut buf, |vertex: StrokeVertex| vertex.position()),
308        )?;
309
310        Ok(Self::build_path(buf))
311    }
312
313    /// Builds a [`Path`] from a [`lyon::tessellation::VertexBuffers`].
314    pub fn build_path(buf: VertexBuffers<lyon::math::Point, u16>) -> Path<Pixels> {
315        if buf.vertices.is_empty() {
316            return Path::new(Point::default());
317        }
318
319        let first_point = buf.vertices[0];
320
321        let mut path = Path::new(first_point.into());
322        for i in 0..buf.indices.len() / 3 {
323            let i0 = buf.indices[i * 3] as usize;
324            let i1 = buf.indices[i * 3 + 1] as usize;
325            let i2 = buf.indices[i * 3 + 2] as usize;
326
327            let v0 = buf.vertices[i0];
328            let v1 = buf.vertices[i1];
329            let v2 = buf.vertices[i2];
330
331            path.push_triangle(
332                (v0.into(), v1.into(), v2.into()),
333                (point(0., 1.), point(0., 1.), point(0., 1.)),
334            );
335        }
336
337        path
338    }
339}