Skip to main content

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