Skip to main content

gpui_base/plot/shape/
bar.rs

1use gpui::{App, Background, Bounds, Corners, PaintQuad, Pixels, Point, Size, Window, point, px};
2
3use crate::plot::{
4    label::{PlotLabel, TEXT_GAP, TEXT_HEIGHT, TEXT_SIZE, Text},
5    origin_point,
6};
7
8/// Alignment of bars within a [`Bar`] shape, controlling both the orientation
9/// (vertical vs horizontal) and the side where the baseline lives.
10#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
11pub enum BarAlignment {
12    /// Vertical bars with the baseline at the bottom; bars grow upward.
13    #[default]
14    Bottom,
15    /// Vertical bars with the baseline at the top; bars grow downward.
16    Top,
17    /// Horizontal bars with the baseline at the left; bars grow rightward.
18    Left,
19    /// Horizontal bars with the baseline at the right; bars grow leftward.
20    Right,
21}
22
23impl BarAlignment {
24    pub fn is_horizontal(self) -> bool {
25        matches!(self, Self::Left | Self::Right)
26    }
27
28    pub fn is_vertical(self) -> bool {
29        !self.is_horizontal()
30    }
31
32    /// Linear-gradient angle (in degrees) that runs from the bar's base to its
33    /// tip for this alignment.
34    ///
35    /// gpui convention: `0°` points upward (stop-0 at bottom, stop-1 at top);
36    /// angles increase clockwise.
37    pub fn gradient_angle(self) -> f32 {
38        match self {
39            Self::Bottom => 0.,
40            Self::Top => 180.,
41            Self::Left => 90.,
42            Self::Right => 270.,
43        }
44    }
45}
46
47#[allow(clippy::type_complexity)]
48pub struct Bar<T> {
49    data: Vec<T>,
50    alignment: BarAlignment,
51    cross: Box<dyn Fn(&T) -> Option<f32>>,
52    band_width: f32,
53    base: Box<dyn Fn(&T) -> f32>,
54    value: Box<dyn Fn(&T) -> Option<f32>>,
55    fill: Box<dyn Fn(&T, Bounds<f32>, BarAlignment) -> Background>,
56    label: Option<Box<dyn Fn(&T, Point<Pixels>) -> Vec<Text>>>,
57    corner_radii: Corners<Pixels>,
58}
59
60impl<T> Default for Bar<T> {
61    fn default() -> Self {
62        Self {
63            data: Vec::new(),
64            alignment: BarAlignment::default(),
65            cross: Box::new(|_| None),
66            band_width: 0.,
67            base: Box::new(|_| 0.),
68            value: Box::new(|_| None),
69            fill: Box::new(|_, _, _| gpui::black().into()),
70            label: None,
71            corner_radii: Corners::all(px(0.)),
72        }
73    }
74}
75
76impl<T> Bar<T> {
77    pub fn new() -> Self {
78        Self::default()
79    }
80
81    /// Set the data of the Bar.
82    pub fn data<I>(mut self, data: I) -> Self
83    where
84        I: IntoIterator<Item = T>,
85    {
86        self.data = data.into_iter().collect();
87        self
88    }
89
90    /// Set the alignment of the Bar.
91    ///
92    /// Default is [`BarAlignment::Bottom`].
93    pub fn alignment(mut self, alignment: BarAlignment) -> Self {
94        self.alignment = alignment;
95        self
96    }
97
98    /// Set the cross-axis position of each bar (in pixels).
99    ///
100    /// For vertical alignments this is the X coordinate; for horizontal
101    /// alignments this is the Y coordinate.
102    pub fn cross<F>(mut self, cross: F) -> Self
103    where
104        F: Fn(&T) -> Option<f32> + 'static,
105    {
106        self.cross = Box::new(cross);
107        self
108    }
109
110    /// Set the band width of the Bar (the bar thickness along the cross axis).
111    pub fn band_width(mut self, band_width: f32) -> Self {
112        self.band_width = band_width;
113        self
114    }
115
116    /// Set the baseline position of each bar (in pixels along the value axis).
117    pub fn base<F>(mut self, base: F) -> Self
118    where
119        F: Fn(&T) -> f32 + 'static,
120    {
121        self.base = Box::new(base);
122        self
123    }
124
125    /// Set the value-end position of each bar (in pixels along the value axis).
126    pub fn value<F>(mut self, value: F) -> Self
127    where
128        F: Fn(&T) -> Option<f32> + 'static,
129    {
130        self.value = Box::new(value);
131        self
132    }
133
134    /// Set the fill of each bar.
135    ///
136    /// The closure receives the datum, the bar's painted frame (`Bounds<f32>`)
137    /// in raw pixel coordinates relative to the plot bounds origin, and the
138    /// bar's [`BarAlignment`] (so callers can branch on orientation, e.g. flip
139    /// a gradient angle). Callers wishing to derive normalized or chart-relative
140    /// coordinates from this frame should do so themselves.
141    ///
142    /// Accepts any type convertible to [`Background`], including solid colors and
143    /// fully-specified [`gpui::linear_gradient`] values. The background is used
144    /// verbatim — the gradient angle is not adjusted for bar orientation.
145    pub fn fill<F, B>(mut self, fill: F) -> Self
146    where
147        F: Fn(&T, Bounds<f32>, BarAlignment) -> B + 'static,
148        B: Into<Background>,
149    {
150        self.fill = Box::new(move |v, frame, alignment| fill(v, frame, alignment).into());
151        self
152    }
153
154    /// Set the label of the Bar.
155    pub fn label<F>(mut self, label: F) -> Self
156    where
157        F: Fn(&T, Point<Pixels>) -> Vec<Text> + 'static,
158    {
159        self.label = Some(Box::new(label));
160        self
161    }
162
163    /// Set the corner radii applied to every bar rectangle.
164    ///
165    /// Use [`Corners::all`] for uniform rounding, or construct `Corners` manually to
166    /// round only specific corners (e.g. just the tip end of each bar).
167    pub fn corner_radii(mut self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
168        self.corner_radii = corner_radii.into();
169        self
170    }
171
172    fn path(&self, bounds: &Bounds<Pixels>) -> (Vec<PaintQuad>, PlotLabel) {
173        let origin = bounds.origin;
174        let mut graph = vec![];
175        let mut labels = vec![];
176
177        for v in &self.data {
178            let Some(cross) = (self.cross)(v) else {
179                continue;
180            };
181            let Some(value) = (self.value)(v) else {
182                continue;
183            };
184            let base = (self.base)(v);
185
186            let bw = self.band_width;
187            let (frame, p1, p2) = if self.alignment.is_vertical() {
188                let x0 = cross;
189                let x1 = cross + bw;
190                let y_min = value.min(base);
191                let y_max = value.max(base);
192                let frame = Bounds {
193                    origin: Point::new(x0, y_min),
194                    size: Size::new(x1 - x0, y_max - y_min),
195                };
196                (
197                    frame,
198                    origin_point(px(x0), px(y_min), origin),
199                    origin_point(px(x1), px(y_max), origin),
200                )
201            } else {
202                let y0 = cross;
203                let y1 = cross + bw;
204                let x_min = value.min(base);
205                let x_max = value.max(base);
206                let frame = Bounds {
207                    origin: Point::new(x_min, y0),
208                    size: Size::new(x_max - x_min, y1 - y0),
209                };
210                (
211                    frame,
212                    origin_point(px(x_min), px(y0), origin),
213                    origin_point(px(x_max), px(y1), origin),
214                )
215            };
216
217            let bg = (self.fill)(v, frame, self.alignment);
218            graph.push(
219                gpui::PaintQuad::new(Bounds::from_corners(p1, p2))
220                    .background(bg)
221                    .corner_radii(self.corner_radii),
222            );
223
224            if let Some(label) = &self.label {
225                let label_origin = label_origin(self.alignment, cross, base, value, bw);
226                labels.extend(label(v, label_origin));
227            }
228        }
229
230        (graph, PlotLabel::new(labels))
231    }
232
233    /// Paint the Bar.
234    pub fn paint(&self, bounds: &Bounds<Pixels>, window: &mut Window, cx: &mut App) {
235        let (graph, labels) = self.path(bounds);
236        for quad in graph {
237            window.paint_quad(quad);
238        }
239        labels.paint(bounds, window, cx);
240    }
241}
242
243/// Origin point for a bar label, positioned outside the bar at the value end.
244///
245/// The caller chooses the [`gpui::TextAlign`] (typically `Center` for vertical
246/// bars, `Left` for `BarAlignment::Left`, `Right` for `BarAlignment::Right`).
247fn label_origin(
248    alignment: BarAlignment,
249    cross: f32,
250    base: f32,
251    value: f32,
252    band_width: f32,
253) -> Point<Pixels> {
254    match alignment {
255        BarAlignment::Bottom => {
256            let cx = cross + band_width / 2.;
257            // Normal: value < base (bar grows up). Label above bar end.
258            if value <= base {
259                point(px(cx), px(value - TEXT_HEIGHT))
260            } else {
261                point(px(cx), px(value + TEXT_GAP))
262            }
263        }
264        BarAlignment::Top => {
265            let cx = cross + band_width / 2.;
266            // Normal: value > base (bar grows down). Label below bar end.
267            if value >= base {
268                point(px(cx), px(value + TEXT_GAP))
269            } else {
270                point(px(cx), px(value - TEXT_HEIGHT))
271            }
272        }
273        BarAlignment::Left => {
274            // Vertical centering: text origin is the top of the glyph cell.
275            let cy = cross + band_width / 2. - TEXT_SIZE / 2.;
276            // Normal: value > base (bar grows right). Label to the right of bar end.
277            if value >= base {
278                point(px(value + TEXT_GAP), px(cy))
279            } else {
280                point(px(value - TEXT_GAP), px(cy))
281            }
282        }
283        BarAlignment::Right => {
284            let cy = cross + band_width / 2. - TEXT_SIZE / 2.;
285            // Normal: value < base (bar grows left). Label to the left of bar end.
286            if value <= base {
287                point(px(value - TEXT_GAP), px(cy))
288            } else {
289                point(px(value + TEXT_GAP), px(cy))
290            }
291        }
292    }
293}