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, hsla, 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 shape_label(
24    text: &SharedString,
25    font_size: Pixels,
26    color: Hsla,
27    window: &mut Window,
28) -> ShapedLine {
29    let text_run = TextRun {
30        len: text.len(),
31        font: window.text_style().font(),
32        color,
33        background_color: None,
34        underline: None,
35        strikethrough: None,
36        letter_spacing: None,
37    };
38    window
39        .text_system()
40        .shape_line(text.clone(), font_size, &[text_run])
41}
42
43/// Returns the rendered width of `text` at `font_size` using the window's
44/// current text style.  Used for layout calculations that need to reserve
45/// space for labels before the scale ranges are fixed.
46pub fn measure_text_width(text: &SharedString, font_size: Pixels, window: &mut Window) -> f32 {
47    if text.is_empty() {
48        return 0.;
49    }
50    shape_label(text, font_size, hsla(0., 0., 0., 1.), window)
51        .width()
52        .as_f32()
53}
54
55/// Truncate `text` with a trailing ellipsis so it fits within `max_width` at
56/// `font_size`. Returns `text` unchanged when it already fits; returns just
57/// the ellipsis when not even one character fits. `max_width <= 0` is treated
58/// as "no budget" and returns `text` unchanged (the caller has no room to
59/// reason about).
60pub fn truncate_text_to_width(
61    text: &SharedString,
62    font_size: Pixels,
63    max_width: f32,
64    window: &mut Window,
65) -> SharedString {
66    if max_width <= 0. || measure_text_width(text, font_size, window) <= max_width {
67        return text.clone();
68    }
69
70    const ELLIPSIS: &str = "…";
71    // Byte offsets of every char boundary after the first char; cutting at
72    // `cuts[k]` keeps the first `k + 1` chars.
73    let cuts: Vec<usize> = text.char_indices().skip(1).map(|(i, _)| i).collect();
74
75    // Binary search the largest prefix whose text + ellipsis still fits.
76    let mut best: Option<usize> = None;
77    let (mut lo, mut hi) = (0usize, cuts.len());
78    while lo < hi {
79        let mid = (lo + hi) / 2;
80        let candidate = SharedString::from(format!("{}{ELLIPSIS}", &text[..cuts[mid]]));
81        if measure_text_width(&candidate, font_size, window) <= max_width {
82            best = Some(mid);
83            lo = mid + 1;
84        } else {
85            hi = mid;
86        }
87    }
88
89    match best {
90        Some(mid) => SharedString::from(format!("{}{ELLIPSIS}", &text[..cuts[mid]])),
91        None => SharedString::from(ELLIPSIS),
92    }
93}
94
95/// A label [`PlotLabel`] draws: its text, where it sits relative to the plot
96/// origin and how it is drawn. `font_size` defaults to [`TEXT_SIZE`].
97#[non_exhaustive]
98pub struct Text {
99    pub text: SharedString,
100    pub origin: Point<Pixels>,
101    pub color: Hsla,
102    pub font_size: Pixels,
103    pub font_weight: FontWeight,
104    pub align: TextAlign,
105}
106
107impl Text {
108    pub fn new<T>(text: impl Into<SharedString>, origin: Point<T>, color: Hsla) -> Self
109    where
110        T: Default + Clone + Copy + Debug + PartialEq + Into<Pixels>,
111    {
112        let origin = point(origin.x.into(), origin.y.into());
113
114        Self {
115            text: text.into(),
116            origin,
117            color,
118            font_size: TEXT_SIZE.into(),
119            font_weight: FontWeight::NORMAL,
120            align: TextAlign::Left,
121        }
122    }
123
124    /// Set the font size of the Text.
125    pub fn font_size(mut self, font_size: impl Into<Pixels>) -> Self {
126        self.font_size = font_size.into();
127        self
128    }
129
130    /// Set the font weight of the Text.
131    pub fn font_weight(mut self, font_weight: FontWeight) -> Self {
132        self.font_weight = font_weight;
133        self
134    }
135
136    /// Set the alignment of the Text.
137    pub fn align(mut self, align: TextAlign) -> Self {
138        self.align = align;
139        self
140    }
141}
142
143impl<I> From<I> for PlotLabel
144where
145    I: Iterator<Item = Text>,
146{
147    fn from(items: I) -> Self {
148        Self::new(items.collect())
149    }
150}
151
152#[derive(Default)]
153pub struct PlotLabel(Vec<Text>);
154
155impl PlotLabel {
156    pub fn new(items: Vec<Text>) -> Self {
157        Self(items)
158    }
159
160    /// Paint the Label.
161    pub fn paint(&self, bounds: &Bounds<Pixels>, window: &mut Window, cx: &mut App) {
162        for Text {
163            text,
164            origin,
165            color,
166            font_size,
167            font_weight: _,
168            align,
169        } in self.0.iter()
170        {
171            let origin = origin_point(origin.x, origin.y, bounds.origin);
172
173            let line = shape_label(text, *font_size, *color, window);
174            let origin = match align {
175                TextAlign::Left => origin,
176                TextAlign::Right => origin - point(line.width(), px(0.)),
177                _ => origin - point(line.width() / 2., px(0.)),
178            };
179            let _ = line.paint(origin, *font_size, *align, None, window, cx);
180        }
181    }
182}