Skip to main content

gpui_base/plot/
grid.rs

1use gpui::{Background, Bounds, Pixels, Point, Window, point, px, size};
2
3use super::origin_point;
4
5/// Axis-aligned grid lines across a plot, at the given x and y positions.
6#[derive(Default)]
7pub struct Grid {
8    x: Vec<Pixels>,
9    y: Vec<Pixels>,
10    stroke: Background,
11    dash_array: Option<Vec<Pixels>>,
12}
13
14impl Grid {
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    /// Set the positions of the vertical lines, from the left of the plot.
20    pub fn x(mut self, x: impl IntoIterator<Item = impl Into<Pixels>>) -> Self {
21        self.x = x.into_iter().map(Into::into).collect();
22        self
23    }
24
25    /// Set the positions of the horizontal lines, from the top of the plot.
26    pub fn y(mut self, y: impl IntoIterator<Item = impl Into<Pixels>>) -> Self {
27        self.y = y.into_iter().map(Into::into).collect();
28        self
29    }
30
31    /// Set the stroke of the grid lines.
32    pub fn stroke(mut self, stroke: impl Into<Background>) -> Self {
33        self.stroke = stroke.into();
34        self
35    }
36
37    /// Set the dash array of the grid lines.
38    pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
39        self.dash_array = Some(dash_array.to_vec());
40        self
41    }
42
43    fn points(&self, bounds: &Bounds<Pixels>) -> Vec<(Point<Pixels>, Point<Pixels>)> {
44        let size = bounds.size;
45        let origin = bounds.origin;
46
47        let mut x = self
48            .x
49            .iter()
50            .map(|x| {
51                (
52                    origin_point(*x, px(0.), origin),
53                    origin_point(*x, size.height, origin),
54                )
55            })
56            .collect::<Vec<_>>();
57
58        let y = self
59            .y
60            .iter()
61            .map(|y| {
62                (
63                    origin_point(px(0.), *y, origin),
64                    origin_point(size.width, *y, origin),
65                )
66            })
67            .collect::<Vec<_>>();
68
69        x.extend(y);
70        x
71    }
72
73    /// Paint the Grid.
74    ///
75    /// Grid lines are axis-aligned, so each one (or each dash of one) is a
76    /// 1px quad rather than a stroked path: a chart repaints its grid on
77    /// every frame while it scrolls, and tessellating each line — measuring
78    /// and sampling it first when dashed — was the largest cost of painting a
79    /// chart card.
80    pub fn paint(&self, bounds: &Bounds<Pixels>, window: &mut Window) {
81        for (start, end) in self.points(bounds) {
82            for (start, end) in dash_segments(start, end, self.dash_array.as_deref()) {
83                window.paint_quad(
84                    gpui::PaintQuad::new(line_bounds(start, end)).background(self.stroke),
85                );
86            }
87        }
88    }
89}
90
91/// The box a 1px stroke of the axis-aligned line `start`–`end` covers:
92/// centred on the coordinate, as `PathBuilder::stroke(px(1.))` draws it.
93fn line_bounds(start: Point<Pixels>, end: Point<Pixels>) -> Bounds<Pixels> {
94    let half = px(0.5);
95    if start.x == end.x {
96        let top = start.y.min(end.y);
97        Bounds::new(
98            point(start.x - half, top),
99            size(px(1.), start.y.max(end.y) - top),
100        )
101    } else {
102        let left = start.x.min(end.x);
103        Bounds::new(
104            point(left, start.y - half),
105            size(start.x.max(end.x) - left, px(1.)),
106        )
107    }
108}
109
110/// Splits the line `start`–`end` into the dashes of `dash_array`, walked from
111/// `start` with the SVG `stroke-dasharray` rules `PathBuilder` follows: values
112/// alternate dash and gap, and an odd-length array repeats to an even one.
113/// Without a dash array the whole line is one segment.
114fn dash_segments(
115    start: Point<Pixels>,
116    end: Point<Pixels>,
117    dash_array: Option<&[Pixels]>,
118) -> Vec<(Point<Pixels>, Point<Pixels>)> {
119    let Some(dash_array) = dash_array.filter(|dashes| !dashes.is_empty()) else {
120        return vec![(start, end)];
121    };
122    let length = ((end.x - start.x).as_f32().powi(2) + (end.y - start.y).as_f32().powi(2)).sqrt();
123    if length <= 0. || dash_array.iter().all(|dash| dash.as_f32() <= 0.) {
124        return vec![(start, end)];
125    }
126    let at = |distance: f32| {
127        let t = distance / length;
128        point(
129            start.x + (end.x - start.x) * t,
130            start.y + (end.y - start.y) * t,
131        )
132    };
133    let pattern_len = if dash_array.len() % 2 == 1 {
134        dash_array.len() * 2
135    } else {
136        dash_array.len()
137    };
138    let mut segments = Vec::new();
139    let mut position = 0.;
140    let mut index = 0;
141    while position < length {
142        let dash = dash_array[index % dash_array.len()].as_f32().max(0.);
143        let next = (position + dash).min(length);
144        if index % 2 == 0 && next > position {
145            segments.push((at(position), at(next)));
146        }
147        position = next;
148        index = (index + 1) % pattern_len;
149    }
150    segments
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    fn xs(segments: &[(Point<Pixels>, Point<Pixels>)]) -> Vec<(f32, f32)> {
158        segments
159            .iter()
160            .map(|(start, end)| (start.x.as_f32(), end.x.as_f32()))
161            .collect()
162    }
163
164    #[test]
165    fn solid_line_is_one_segment() {
166        let segments = dash_segments(point(px(0.), px(5.)), point(px(10.), px(5.)), None);
167        assert_eq!(xs(&segments), vec![(0., 10.)]);
168        let segments = dash_segments(point(px(0.), px(5.)), point(px(10.), px(5.)), Some(&[]));
169        assert_eq!(xs(&segments), vec![(0., 10.)]);
170    }
171
172    #[test]
173    fn dashes_alternate_and_clip_at_the_end() {
174        let segments = dash_segments(
175            point(px(0.), px(5.)),
176            point(px(11.), px(5.)),
177            Some(&[px(4.), px(2.)]),
178        );
179        assert_eq!(xs(&segments), vec![(0., 4.), (6., 10.)]);
180    }
181
182    #[test]
183    fn odd_dash_array_repeats_like_svg() {
184        // 5,3,2 is 5 on, 3 off, 2 on, 5 off, 3 on, 2 off.
185        let segments = dash_segments(
186            point(px(0.), px(0.)),
187            point(px(0.), px(20.)),
188            Some(&[px(5.), px(3.), px(2.)]),
189        );
190        let ys: Vec<_> = segments
191            .iter()
192            .map(|(start, end)| (start.y.as_f32(), end.y.as_f32()))
193            .collect();
194        assert_eq!(ys, vec![(0., 5.), (8., 10.), (15., 18.)]);
195    }
196
197    #[test]
198    fn line_box_is_one_pixel_centred_on_the_coordinate() {
199        let vertical = line_bounds(point(px(10.), px(0.)), point(px(10.), px(40.)));
200        assert_eq!(vertical.origin, point(px(9.5), px(0.)));
201        assert_eq!(vertical.size, size(px(1.), px(40.)));
202        let horizontal = line_bounds(point(px(40.), px(7.)), point(px(0.), px(7.)));
203        assert_eq!(horizontal.origin, point(px(0.), px(6.5)));
204        assert_eq!(horizontal.size, size(px(40.), px(1.)));
205    }
206}