Skip to main content

gpui_base/plot/
label.rs

1use std::fmt::Debug;
2
3use gpui::{
4    App, Bounds, FontWeight, Hsla, Pixels, Point, ShapedLine, SharedString, TextAlign, TextRun,
5    Window, point, px,
6};
7
8use super::origin_point;
9
10/// The default label font size, in pixels, of [`Text`] and
11/// [`AxisText`](super::AxisText).
12///
13/// A default, not a rule: a styled layer passes its own size through
14/// `font_size`, and reserves axis space with [`axis_gutter`](super::axis_gutter)
15/// for that size.
16pub const TEXT_SIZE: f32 = 10.;
17/// The default gap, in pixels, between a label and what it labels.
18pub const TEXT_GAP: f32 = 2.;
19/// The default height, in pixels, a label line takes: [`TEXT_SIZE`] plus
20/// [`TEXT_GAP`].
21pub const TEXT_HEIGHT: f32 = TEXT_SIZE + TEXT_GAP;
22
23fn label_run(
24    text: &SharedString,
25    color: Hsla,
26    font_weight: FontWeight,
27    window: &Window,
28) -> TextRun {
29    let mut font = window.text_style().font();
30    font.weight = font_weight;
31    TextRun {
32        len: text.len(),
33        font,
34        color,
35        background_color: None,
36        underline: None,
37        strikethrough: None,
38    }
39}
40
41fn shape_label(
42    text: &SharedString,
43    font_size: Pixels,
44    font_weight: FontWeight,
45    color: Hsla,
46    window: &mut Window,
47) -> ShapedLine {
48    let text_run = label_run(text, color, font_weight, window);
49    window
50        .text_system()
51        .shape_line(text.clone(), font_size, &[text_run], None)
52}
53
54/// Returns the rendered width of `text` at `font_size` using the window's
55/// current text style.  Used for layout calculations that need to reserve
56/// space for labels before the scale ranges are fixed.
57pub fn measure_text_width(text: &SharedString, font_size: Pixels, window: &mut Window) -> f32 {
58    if text.is_empty() {
59        return 0.;
60    }
61    let font_weight = window.text_style().font_weight;
62    shape_label(
63        text,
64        font_size,
65        font_weight,
66        Hsla {
67            h: 0.,
68            s: 0.,
69            l: 0.,
70            a: 1.,
71        },
72        window,
73    )
74    .width()
75    .as_f32()
76}
77
78/// Truncate `text` with a trailing ellipsis so it fits within `max_width` at
79/// `font_size`. Returns `text` unchanged when it already fits; returns just
80/// the ellipsis when not even one character fits. `max_width <= 0` is treated
81/// as "no budget" and returns `text` unchanged (the caller has no room to
82/// reason about).
83pub fn truncate_text_to_width(
84    text: &SharedString,
85    font_size: Pixels,
86    max_width: f32,
87    window: &mut Window,
88) -> SharedString {
89    if max_width <= 0. || measure_text_width(text, font_size, window) <= max_width {
90        return text.clone();
91    }
92
93    const ELLIPSIS: &str = "…";
94    // Byte offsets of every char boundary after the first char; cutting at
95    // `cuts[k]` keeps the first `k + 1` chars.
96    let cuts: Vec<usize> = text.char_indices().skip(1).map(|(i, _)| i).collect();
97
98    // Binary search the largest prefix whose text + ellipsis still fits.
99    let mut best: Option<usize> = None;
100    let (mut lo, mut hi) = (0usize, cuts.len());
101    while lo < hi {
102        let mid = (lo + hi) / 2;
103        let candidate = SharedString::from(format!("{}{ELLIPSIS}", &text[..cuts[mid]]));
104        if measure_text_width(&candidate, font_size, window) <= max_width {
105            best = Some(mid);
106            lo = mid + 1;
107        } else {
108            hi = mid;
109        }
110    }
111
112    match best {
113        Some(mid) => SharedString::from(format!("{}{ELLIPSIS}", &text[..cuts[mid]])),
114        None => SharedString::from(ELLIPSIS),
115    }
116}
117
118/// A label [`PlotLabel`] draws: its text, where it sits relative to the plot
119/// origin and how it is drawn. `font_size` defaults to [`TEXT_SIZE`].
120#[non_exhaustive]
121pub struct Text {
122    pub text: SharedString,
123    pub origin: Point<Pixels>,
124    pub color: Hsla,
125    pub font_size: Pixels,
126    pub font_weight: FontWeight,
127    pub align: TextAlign,
128}
129
130impl Text {
131    pub fn new<T>(text: impl Into<SharedString>, origin: Point<T>, color: Hsla) -> Self
132    where
133        T: Default + Clone + Copy + Debug + PartialEq + Into<Pixels>,
134    {
135        let origin = point(origin.x.into(), origin.y.into());
136
137        Self {
138            text: text.into(),
139            origin,
140            color,
141            font_size: TEXT_SIZE.into(),
142            font_weight: FontWeight::NORMAL,
143            align: TextAlign::Left,
144        }
145    }
146
147    /// Set the font size of the Text.
148    pub fn font_size(mut self, font_size: impl Into<Pixels>) -> Self {
149        self.font_size = font_size.into();
150        self
151    }
152
153    /// Set the font weight of the Text.
154    pub fn font_weight(mut self, font_weight: FontWeight) -> Self {
155        self.font_weight = font_weight;
156        self
157    }
158
159    /// Set the alignment of the Text.
160    pub fn align(mut self, align: TextAlign) -> Self {
161        self.align = align;
162        self
163    }
164}
165
166impl<I> From<I> for PlotLabel
167where
168    I: Iterator<Item = Text>,
169{
170    fn from(items: I) -> Self {
171        Self::new(items.collect())
172    }
173}
174
175#[derive(Default)]
176pub struct PlotLabel(Vec<Text>);
177
178impl PlotLabel {
179    pub fn new(items: Vec<Text>) -> Self {
180        Self(items)
181    }
182
183    /// Paint the Label.
184    pub fn paint(&self, bounds: &Bounds<Pixels>, window: &mut Window, cx: &mut App) {
185        for Text {
186            text,
187            origin,
188            color,
189            font_size,
190            font_weight,
191            align,
192        } in self.0.iter()
193        {
194            let origin = origin_point(origin.x, origin.y, bounds.origin);
195
196            let line = shape_label(text, *font_size, *font_weight, *color, window);
197            let origin = match align {
198                TextAlign::Left => origin,
199                TextAlign::Right => origin - point(line.width(), px(0.)),
200                _ => origin - point(line.width() / 2., px(0.)),
201            };
202            let _ = line.paint(origin, *font_size, *align, None, window, cx);
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use gpui::{Context, IntoElement, Render, TestAppContext, div};
211
212    struct Empty;
213
214    impl Render for Empty {
215        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
216            div()
217        }
218    }
219
220    #[gpui::test]
221    fn a_label_is_shaped_at_its_own_weight(cx: &mut TestAppContext) {
222        let window = cx.add_window(|_, _| Empty);
223        window
224            .update(cx, |_, window, _| {
225                let text = SharedString::from("14:30");
226                let color = Hsla::default();
227                assert_eq!(
228                    label_run(&text, color, FontWeight::BOLD, window)
229                        .font
230                        .weight,
231                    FontWeight::BOLD
232                );
233                assert_eq!(
234                    label_run(&text, color, FontWeight::NORMAL, window)
235                        .font
236                        .weight,
237                    FontWeight::NORMAL
238                );
239            })
240            .unwrap();
241    }
242}