skathi-gpui 0.5.2

gpui, Zed's GPU-accelerated UI framework, as Skathi renders with it
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use anyhow::{Error, bail};
use etagere::euclid::{Point2D, Vector2D};
use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment};
use lyon_path::math::{Vector, vector};
use lyon_path::traits::SvgPathBuilder;
use lyon_path::{ArcFlags, Event, Polygon};

pub use lyon_path::math::Transform;
pub use lyon_path::{FillRule, LineCap, LineJoin};

use crate::{PathCurve, PathTiles, Pixels, Point, point, px};
use std::sync::Arc;

/// Style of the PathBuilder
pub enum PathStyle {
    /// Stroke style
    Stroke(StrokeOptions),
    /// Fill style
    Fill(FillOptions),
}

/// How to stroke a path.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StrokeOptions {
    /// Width of the stroke.
    pub line_width: f32,
    /// Shape of the ends of open subpaths and dashes.
    pub line_cap: LineCap,
    /// Shape of corners.
    pub line_join: LineJoin,
    /// How long a miter join may get, as a multiple of the line width,
    /// before it is beveled instead.
    pub miter_limit: f32,
}

impl Default for StrokeOptions {
    fn default() -> Self {
        Self {
            line_width: 1.0,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            miter_limit: 4.0,
        }
    }
}

/// How to fill a path.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FillOptions {
    /// How overlapping contours combine into the filled region.
    pub fill_rule: FillRule,
}

impl Default for FillOptions {
    fn default() -> Self {
        Self {
            fill_rule: FillRule::EvenOdd,
        }
    }
}

/// A [`Path`] builder.
pub struct PathBuilder {
    raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
    transform: Option<lyon_path::math::Transform>,
    /// PathStyle of the PathBuilder
    pub style: PathStyle,
    dash_array: Option<Vec<Pixels>>,
}

impl From<lyon_path::Builder> for PathBuilder {
    fn from(builder: lyon_path::Builder) -> Self {
        Self {
            raw: builder.with_svg(),
            ..Default::default()
        }
    }
}

impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
    fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
        Self {
            raw,
            ..Default::default()
        }
    }
}

impl From<lyon_path::math::Point> for Point<Pixels> {
    fn from(p: lyon_path::math::Point) -> Self {
        point(px(p.x), px(p.y))
    }
}

impl From<Point<Pixels>> for lyon_path::math::Point {
    fn from(p: Point<Pixels>) -> Self {
        lyon_path::math::point(p.x.0, p.y.0)
    }
}

impl From<Point<Pixels>> for Vector {
    fn from(p: Point<Pixels>) -> Self {
        vector(p.x.0, p.y.0)
    }
}

impl From<Point<Pixels>> for Point2D<f32, Pixels> {
    fn from(p: Point<Pixels>) -> Self {
        Point2D::new(p.x.0, p.y.0)
    }
}

impl Default for PathBuilder {
    fn default() -> Self {
        Self {
            raw: lyon_path::Path::builder().with_svg(),
            style: PathStyle::Fill(FillOptions::default()),
            transform: None,
            dash_array: None,
        }
    }
}

impl PathBuilder {
    /// Creates a new [`PathBuilder`] to build a Stroke path.
    pub fn stroke(width: Pixels) -> Self {
        Self {
            style: PathStyle::Stroke(StrokeOptions {
                line_width: width.0,
                ..Default::default()
            }),
            ..Self::default()
        }
    }

    /// Creates a new [`PathBuilder`] to build a Fill path.
    pub fn fill() -> Self {
        Self::default()
    }

    /// Sets the style of the [`PathBuilder`].
    pub fn with_style(self, style: PathStyle) -> Self {
        Self { style, ..self }
    }

    /// Sets the dash array of the [`PathBuilder`]. Fills ignore it.
    ///
    /// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray)
    pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
        // If an odd number of values is provided, then the list of values is repeated to yield an even number of values.
        // Thus, 5,3,2 is equivalent to 5,3,2,5,3,2.
        let array = if dash_array.len() % 2 == 1 {
            let mut new_dash_array = dash_array.to_vec();
            new_dash_array.extend_from_slice(dash_array);
            new_dash_array
        } else {
            dash_array.to_vec()
        };

        self.dash_array = Some(array);
        self
    }

    /// Move the current point to the given point.
    #[inline]
    pub fn move_to(&mut self, to: Point<Pixels>) {
        self.raw.move_to(to.into());
    }

    /// Draw a straight line from the current point to the given point.
    #[inline]
    pub fn line_to(&mut self, to: Point<Pixels>) {
        self.raw.line_to(to.into());
    }

    /// Draw a curve from the current point to the given point, using the given control point.
    #[inline]
    pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
        self.raw.quadratic_bezier_to(ctrl.into(), to.into());
    }

    /// Adds a cubic Bézier to the [`Path`] given its two control points
    /// and its end point.
    #[inline]
    pub fn cubic_bezier_to(
        &mut self,
        to: Point<Pixels>,
        control_a: Point<Pixels>,
        control_b: Point<Pixels>,
    ) {
        self.raw
            .cubic_bezier_to(control_a.into(), control_b.into(), to.into());
    }

    /// Adds an elliptical arc.
    pub fn arc_to(
        &mut self,
        radii: Point<Pixels>,
        x_rotation: Pixels,
        large_arc: bool,
        sweep: bool,
        to: Point<Pixels>,
    ) {
        self.raw.arc_to(
            radii.into(),
            Angle::degrees(x_rotation.into()),
            ArcFlags { large_arc, sweep },
            to.into(),
        );
    }

    /// Equivalent to `arc_to` in relative coordinates.
    pub fn relative_arc_to(
        &mut self,
        radii: Point<Pixels>,
        x_rotation: Pixels,
        large_arc: bool,
        sweep: bool,
        to: Point<Pixels>,
    ) {
        self.raw.relative_arc_to(
            radii.into(),
            Angle::degrees(x_rotation.into()),
            ArcFlags { large_arc, sweep },
            to.into(),
        );
    }

    /// Adds a polygon.
    pub fn add_polygon(&mut self, points: &[Point<Pixels>], closed: bool) {
        let points = points.iter().copied().map(|p| p.into()).collect::<Vec<_>>();
        self.raw.add_polygon(Polygon {
            points: points.as_ref(),
            closed,
        });
    }

    /// Close the current sub-path.
    #[inline]
    pub fn close(&mut self) {
        self.raw.close();
    }

    /// Applies a transform to the path.
    #[inline]
    pub fn transform(&mut self, transform: Transform) {
        self.transform = Some(transform);
    }

    /// Applies a translation to the path.
    #[inline]
    pub fn translate(&mut self, to: Point<Pixels>) {
        if let Some(transform) = self.transform {
            self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
        } else {
            self.transform = Some(Transform::translation(to.x.0, to.y.0))
        }
    }

    /// Applies a scale to the path.
    #[inline]
    pub fn scale(&mut self, scale: f32) {
        if let Some(transform) = self.transform {
            self.transform = Some(transform.then_scale(scale, scale));
        } else {
            self.transform = Some(Transform::scale(scale, scale));
        }
    }

    /// Applies a rotation to the path.
    ///
    /// The `angle` is in degrees value in the range 0.0 to 360.0.
    #[inline]
    pub fn rotate(&mut self, angle: f32) {
        let radians = angle.to_radians();
        if let Some(transform) = self.transform {
            self.transform = Some(transform.then_rotate(Angle::radians(radians)));
        } else {
            self.transform = Some(Transform::rotation(Angle::radians(radians)));
        }
    }

    /// Builds into a [`Path`].
    pub fn build(self) -> Result<Path, Error> {
        let (curves, fill_rule) = self.outline()?;
        Ok(Path::from_curves(curves, fill_rule))
    }

    /// The closed contours to fill, and the rule to fill them by.
    pub(crate) fn outline(self) -> Result<(Vec<PathCurve>, FillRule), Error> {
        let path = if let Some(transform) = self.transform {
            self.raw.build().transformed(&transform)
        } else {
            self.raw.build()
        };

        Ok(match self.style {
            PathStyle::Stroke(options) => (
                Self::stroke_outline(&path, &options, self.dash_array.as_deref())?,
                FillRule::NonZero,
            ),
            PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule),
        })
    }

    fn stroke_outline(
        path: &lyon_path::Path,
        options: &StrokeOptions,
        dash_array: Option<&[Pixels]>,
    ) -> Result<Vec<PathCurve>, Error> {
        let outline = skia_path(path)
            .map(|skia_path| match dash_array {
                Some(dash_array) => {
                    let array = dash_array.iter().map(|length| length.0).collect();
                    match tiny_skia_path::StrokeDash::new(array, 0.0) {
                        Some(dash) => skia_path
                            .dash(&dash, STROKE_RESOLUTION_SCALE)
                            .unwrap_or(skia_path),
                        // An invalid dash array strokes undashed, as in SVG.
                        None => skia_path,
                    }
                }
                None => skia_path,
            })
            .and_then(|skia_path| {
                skia_path.stroke(
                    &tiny_skia_path::Stroke {
                        width: options.line_width,
                        miter_limit: options.miter_limit,
                        line_cap: match options.line_cap {
                            LineCap::Butt => tiny_skia_path::LineCap::Butt,
                            LineCap::Square => tiny_skia_path::LineCap::Square,
                            LineCap::Round => tiny_skia_path::LineCap::Round,
                        },
                        line_join: match options.line_join {
                            LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
                            LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
                            LineJoin::Round => tiny_skia_path::LineJoin::Round,
                            LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
                        },
                        dash: None,
                    },
                    STROKE_RESOLUTION_SCALE,
                )
            });
        let Some(outline) = outline else {
            return Ok(Vec::new());
        };

        let mut output = Outline::default();
        let at = |p: tiny_skia_path::Point| point(p.x, p.y);
        for segment in outline.segments() {
            match segment {
                tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)),
                tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)),
                tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)),
                tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => {
                    output.cubic_to(at(p), at(ctrl1), at(ctrl2))
                }
                tiny_skia_path::PathSegment::Close => output.close(),
            }
        }
        output.into_curves()
    }

    /// Convert a lyon path into a fill, closing every subpath.
    fn fill_outline(path: &lyon_path::Path) -> Result<Vec<PathCurve>, Error> {
        let mut output = Outline::default();
        let at = |p: lyon_path::math::Point| point(p.x, p.y);
        for event in path.iter() {
            match event {
                Event::Begin { at: p } => output.move_to(at(p)),
                Event::Line { to, .. } => output.line_to(at(to)),
                Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)),
                Event::Cubic {
                    ctrl1, ctrl2, to, ..
                } => output.cubic_to(at(to), at(ctrl1), at(ctrl2)),
                Event::End { .. } => output.close(),
            }
        }
        output.into_curves()
    }
}

/// A filled path, ready to paint. Build one with [`PathBuilder`].
#[derive(Clone, Debug)]
pub struct Path {
    /// Closed contours of monotone curves, in logical pixels.
    curves: Arc<[PathCurve]>,
    even_odd: bool,
}

impl Path {
    pub(crate) fn from_curves(curves: Vec<PathCurve>, fill_rule: FillRule) -> Self {
        Self {
            curves: curves.into(),
            even_odd: matches!(fill_rule, FillRule::EvenOdd),
        }
    }

    pub(crate) fn even_odd(&self) -> bool {
        self.even_odd
    }

    /// Bin the curves into tiles in device pixels, for painting at the given
    /// display scale.
    pub(crate) fn bin(&self, scale: f32) -> PathTiles {
        crate::path_winding::bin(&self.curves, self.even_odd, scale)
    }

    /// vue-native fork: the path moved through `matrix`, a device-space
    /// transform, for painting at `scale`. A path has no transformation of its
    /// own to hand the renderer, so its curves move instead; an affine map
    /// keeps a quadratic quadratic, but not monotone, so each is split again.
    pub(crate) fn transformed(&self, matrix: crate::TransformationMatrix, scale: f32) -> Self {
        let map = |p: Point<f32>| {
            let moved = matrix.apply(point(Pixels(p.x * scale), Pixels(p.y * scale)));
            point(moved.x.0 / scale, moved.y.0 / scale)
        };
        let mut curves = Vec::with_capacity(self.curves.len());
        for curve in self.curves.iter() {
            let (from, to) = if curve.sign < 0.0 {
                (curve.p1, curve.p0)
            } else {
                (curve.p0, curve.p1)
            };
            if curve.a == point(0.0, 0.0) {
                let (from, to) = (map(from), map(to));
                if from != to {
                    curves.push(PathCurve::line(from, to));
                }
            } else {
                let ctrl = point(curve.p0.x + curve.b.x / 2.0, curve.p0.y + curve.b.y / 2.0);
                PathCurve::push_monotone(&mut curves, map(from), map(ctrl), map(to));
            }
        }
        Self {
            curves: curves.into(),
            even_odd: self.even_odd,
        }
    }
}

/// A path's contours as monotone curves, collected by [`PathBuilder`].
#[derive(Default)]
pub(crate) struct Outline {
    curves: Vec<PathCurve>,
    start: Point<f32>,
    current: Point<f32>,
    non_finite: bool,
}

impl Outline {
    /// Whether segments through these points can be added.
    fn accepts(&mut self, points: &[Point<f32>]) -> bool {
        self.non_finite |= !points
            .iter()
            .all(|point| point.x.is_finite() && point.y.is_finite());
        !self.non_finite
    }

    /// Close the current contour and start a new one at the given point.
    pub(crate) fn move_to(&mut self, to: Point<f32>) {
        if !self.accepts(&[to]) {
            return;
        }
        self.close();
        self.start = to;
        self.current = to;
    }

    pub(crate) fn line_to(&mut self, to: Point<f32>) {
        if self.accepts(&[to]) && to != self.current {
            self.curves.push(PathCurve::line(self.current, to));
            self.current = to;
        }
    }

    pub(crate) fn curve_to(&mut self, to: Point<f32>, ctrl: Point<f32>) {
        if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) {
            return;
        }
        PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to);
        self.current = to;
    }

    pub(crate) fn cubic_to(&mut self, to: Point<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
        /// Maximum error, in logical pixels.
        const TOLERANCE: f32 = 0.25;
        if !self.accepts(&[to, ctrl1, ctrl2]) {
            return;
        }
        let lyon_point = |p: Point<f32>| lyon_path::math::point(p.x, p.y);
        let cubic = CubicBezierSegment {
            from: lyon_point(self.current),
            ctrl1: lyon_point(ctrl1),
            ctrl2: lyon_point(ctrl2),
            to: lyon_point(to),
        };
        cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| {
            self.curve_to(
                point(quadratic.to.x, quadratic.to.y),
                point(quadratic.ctrl.x, quadratic.ctrl.y),
            );
        });
    }

    /// Close the current contour with a straight line back to its start.
    pub(crate) fn close(&mut self) {
        let start = self.start;
        self.line_to(start);
    }

    /// The curves, with every contour closed.
    pub(crate) fn into_curves(mut self) -> Result<Vec<PathCurve>, Error> {
        if self.non_finite {
            bail!("path has a non-finite point");
        }
        self.close();
        Ok(self.curves)
    }
}

impl PathCurve {
    fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, sign: f32) -> Self {
        Self {
            p0,
            p1,
            a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y),
            b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)),
            sign,
            pad: 0,
        }
    }

    /// A line, with exactly zero quadratic terms.
    fn line(from: Point<f32>, to: Point<f32>) -> Self {
        let (p0, p1, sign) = downward(from, to);
        Self {
            p0,
            p1,
            a: point(0.0, 0.0),
            b: point(p1.x - p0.x, p1.y - p0.y),
            sign,
            pad: 0,
        }
    }

    /// Split a quadratic segment at its extrema into xy-monotone curves.
    fn push_monotone(curves: &mut Vec<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
        let curve = QuadraticBezierSegment {
            from: lyon_path::math::point(p0.x, p0.y),
            ctrl: lyon_path::math::point(ctrl.x, ctrl.y),
            to: lyon_path::math::point(p1.x, p1.y),
        };
        // Unlike `split_range`, this also clamps each piece's control point
        // back into its endpoint box when rounding pushes it out.
        curve.for_each_monotonic(&mut |monotone| {
            let from = point(monotone.from.x, monotone.from.y);
            let to = point(monotone.to.x, monotone.to.y);
            if from == to {
                return;
            }
            // Horizontal curves are kept: upward rays cross them.
            let (p0, p1, sign) = downward(from, to);
            let ctrl = point(
                monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)),
                monotone.ctrl.y.clamp(p0.y, p1.y),
            );
            curves.push(Self::new(p0, ctrl, p1, sign));
        });
    }
}

fn downward(from: Point<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, f32) {
    if from.y > to.y {
        (to, from, -1.0)
    } else {
        (from, to, 1.0)
    }
}

/// Strokes are expanded in logical pixels. tiny-skia keeps offset curves
/// within `0.25 / STROKE_RESOLUTION_SCALE` of exact, a quarter device pixel at
/// 2x, and flattens curves to within `0.5 / STROKE_RESOLUTION_SCALE` to measure
/// dashes. Round joins and caps ignore it: their arcs are approximated to 0.25
/// logical pixels.
const STROKE_RESOLUTION_SCALE: f32 = 2.0;

/// Returns [`None`] for empty geometry.
fn skia_path(path: &lyon_path::Path) -> Option<tiny_skia_path::Path> {
    let mut builder = tiny_skia_path::PathBuilder::new();
    for event in path.iter() {
        match event {
            Event::Begin { at } => builder.move_to(at.x, at.y),
            Event::Line { to, .. } => builder.line_to(to.x, to.y),
            Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y),
            Event::Cubic {
                ctrl1, ctrl2, to, ..
            } => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y),
            Event::End { close, .. } => {
                if close {
                    builder.close();
                }
            }
        }
    }
    builder.finish()
}