Skip to main content

tui_chart/
gauge.rs

1//! Gauge: linear / bullet / arc gauge with threshold bands and target marker.
2
3use crate::canvas::{Canvas, Marker};
4use crate::theme::{self, Theme};
5use ratatui::{
6    buffer::Buffer,
7    layout::Rect,
8    style::{Color, Style},
9    widgets::Block,
10};
11
12/// Direction of a linear gauge.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub enum GaugeOrientation {
16    /// Fills left to right.
17    #[default]
18    Horizontal,
19    /// Fills bottom to top.
20    Vertical,
21}
22
23/// Visual form of a [`Gauge`].
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub enum GaugeStyle {
27    /// Full-thickness bar over a dim band track.
28    #[default]
29    Linear,
30    /// Bullet chart: bands as background, thin value bar in the middle.
31    Bullet,
32    /// Semicircular dial drawn with braille dots.
33    Arc,
34}
35
36/// Gauge showing a value inside `[min, max]`.
37#[derive(Debug, Clone)]
38pub struct Gauge<'a> {
39    value: f64,
40    min: f64,
41    max: f64,
42    bands: Vec<(f64, Color)>,
43    target: Option<f64>,
44    label: Option<String>,
45    orientation: GaugeOrientation,
46    style: GaugeStyle,
47    color: Option<Color>,
48    theme: Option<Theme>,
49    base: Option<Style>,
50    marker: Marker,
51    block: Option<Block<'a>>,
52}
53
54impl<'a> Gauge<'a> {
55    /// Create a gauge for `value` on the scale 0..=100.
56    pub fn new(value: f64) -> Self {
57        Self {
58            value,
59            min: 0.0,
60            max: 100.0,
61            bands: Vec::new(),
62            target: None,
63            label: None,
64            orientation: GaugeOrientation::Horizontal,
65            style: GaugeStyle::Linear,
66            color: None,
67            theme: None,
68            base: None,
69            marker: Marker::Braille,
70            block: None,
71        }
72    }
73    /// Scale range.
74    pub fn range(mut self, min: f64, max: f64) -> Self {
75        self.min = min;
76        self.max = max;
77        self
78    }
79    /// Threshold bands: each `(upper_bound, color)` covers up to that value.
80    pub fn bands(mut self, bands: impl IntoIterator<Item = (f64, Color)>) -> Self {
81        self.bands = bands.into_iter().collect();
82        self.bands.sort_by(|a, b| a.0.total_cmp(&b.0));
83        self
84    }
85    opt_setter!(
86        /// Target marker value.
87        target: f64
88    );
89    /// Centered label text.
90    pub fn label(mut self, l: impl Into<String>) -> Self {
91        self.label = Some(l.into());
92        self
93    }
94    setter!(
95        /// Horizontal or vertical.
96        orientation: GaugeOrientation
97    );
98    setter!(
99        /// Gauge form.
100        style: GaugeStyle
101    );
102    opt_setter!(
103        /// Bar color when no bands are set.
104        color: Color
105    );
106    theme_setter!(
107        /// Apply a [`Theme`]: bar color (bull color), track/needle colors and
108        /// background fill. Explicit [`Gauge::color`] and band colors win.
109        theme
110    );
111    base_style_setter!(base);
112    fn fg(&self) -> Color {
113        self.theme.as_ref().map_or(Color::White, |t| t.foreground)
114    }
115    fn track(&self) -> Color {
116        self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid)
117    }
118    fn bar_color(&self) -> Color {
119        self.color
120            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
121    }
122    setter!(
123        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
124        marker: Marker
125    );
126
127    block_setter!(block, 'a);
128
129    fn frac(&self, v: f64) -> f64 {
130        let span = self.max - self.min;
131        if !v.is_finite() || !span.is_finite() || span <= 0.0 {
132            return 0.0;
133        }
134        ((v - self.min) / span).clamp(0.0, 1.0)
135    }
136
137    fn band_color(&self, f: f64) -> Color {
138        let v = self.min + f * (self.max - self.min);
139        self.bands
140            .iter()
141            .find(|b| v <= b.0)
142            .or(self.bands.last())
143            .map_or(self.bar_color(), |b| b.1)
144    }
145
146    fn draw_label(&self, area: Rect, buf: &mut Buffer) {
147        let Some(l) = &self.label else { return };
148        let n = l.chars().count().min(area.width as usize);
149        let x0 = area.x + (area.width as usize - n) as u16 / 2;
150        let y = area.y + area.height / 2;
151        for (i, ch) in l.chars().take(n).enumerate() {
152            if let Some(c) = buf.cell_mut((x0 + i as u16, y)) {
153                c.set_char(ch).set_fg(self.fg());
154            }
155        }
156    }
157
158    fn draw_linear(&self, area: Rect, buf: &mut Buffer) {
159        let horiz = self.orientation == GaugeOrientation::Horizontal;
160        let (len, cross) = if horiz {
161            (area.width, area.height)
162        } else {
163            (area.height, area.width)
164        };
165        let bullet = self.style == GaugeStyle::Bullet;
166        let eighths = (self.frac(self.value) * len as f64 * 8.0).round() as i64;
167        let (c0, c1) = if bullet && cross >= 3 {
168            (cross / 3, cross - cross / 3)
169        } else if bullet {
170            (cross / 2, cross / 2 + 1)
171        } else {
172            (0, cross)
173        };
174        let tpos = self
175            .target
176            .map(|t| ((self.frac(t) * len as f64).floor() as u16).min(len.saturating_sub(1)));
177        for i in 0..len {
178            let f = (i as f64 + 0.5) / len as f64;
179            let bc = self.band_color(f);
180            let rem = eighths - i as i64 * 8;
181            for c in 0..cross {
182                let (x, y) = if horiz {
183                    (area.x + i, area.y + c)
184                } else {
185                    (area.x + c, area.y + area.height - 1 - i)
186                };
187                let Some(cell) = buf.cell_mut((x, y)) else {
188                    continue;
189                };
190                let in_bar = c >= c0 && c < c1;
191                if tpos == Some(i) {
192                    cell.set_char(if horiz { '┃' } else { '━' })
193                        .set_fg(self.fg());
194                } else if in_bar && rem >= 8 {
195                    cell.set_char('█').set_fg(bc);
196                } else if in_bar && rem > 0 {
197                    let k = (rem - 1) as usize;
198                    let ch = if horiz {
199                        ['▏', '▎', '▍', '▌', '▋', '▊', '▉'][k]
200                    } else {
201                        ['▁', '▂', '▃', '▄', '▅', '▆', '▇'][k]
202                    };
203                    cell.set_char(ch).set_fg(bc);
204                } else if !self.bands.is_empty() || bullet {
205                    cell.set_char(if bullet { '▒' } else { '░' }).set_fg(bc);
206                } else {
207                    cell.set_char('░').set_fg(self.track());
208                }
209            }
210        }
211        self.draw_label(area, buf);
212    }
213
214    fn draw_arc(&self, area: Rect, buf: &mut Buffer) {
215        let mut cv = Canvas::new(area.width, area.height, self.marker);
216        let (pw, ph) = (cv.px_w(), cv.px_h());
217        let r = ((pw / 2).min(ph - 1)).max(1) as f64;
218        let (cx, cy) = (pw as f64 / 2.0 - 0.5, ph as f64 - 1.0);
219        let at = |f: f64, rad: f64| {
220            let a = std::f64::consts::PI * (1.0 - f);
221            (
222                (cx + rad * a.cos()).round() as i32,
223                (cy - rad * a.sin()).round() as i32,
224            )
225        };
226        let vf = self.frac(self.value);
227        let steps = (std::f64::consts::PI * r * 2.0).ceil() as usize + 1;
228        for s in 0..=steps {
229            let f = s as f64 / steps as f64;
230            let col = if f <= vf || !self.bands.is_empty() {
231                self.band_color(f)
232            } else {
233                self.track()
234            };
235            let col = if f > vf { self.track() } else { col };
236            for t in 0..(r as i32 / 4).max(1) {
237                let p = at(f, r - t as f64);
238                cv.set(p.0, p.1, col);
239            }
240        }
241        if let Some(t) = self.target {
242            let tf = self.frac(t);
243            let (a, b) = (at(tf, r * 0.5), at(tf, r));
244            cv.line(a.0, a.1, b.0, b.1, self.fg());
245        }
246        let tip = at(vf, r * 0.85);
247        cv.line(cx.round() as i32, cy as i32, tip.0, tip.1, self.fg());
248        cv.render(buf, area);
249        self.draw_label(area, buf);
250    }
251}
252
253impl Gauge<'_> {
254    fn render_into(&self, area: Rect, buf: &mut Buffer) {
255        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
256        if inner.width == 0 || inner.height == 0 {
257            return;
258        }
259        match self.style {
260            GaugeStyle::Arc => self.draw_arc(inner, buf),
261            _ => self.draw_linear(inner, buf),
262        }
263    }
264}
265
266widget_impls!(Gauge<'_>);
267
268#[cfg(feature = "theme")]
269impl<'a> tui_nuances::Themed for Gauge<'a> {
270    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
271        self.theme(theme)
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use ratatui::widgets::Widget;
279
280    fn run(g: Gauge, w: u16, h: u16) -> Buffer {
281        let a = Rect::new(0, 0, w, h);
282        let mut b = Buffer::empty(a);
283        g.render(a, &mut b);
284        b
285    }
286
287    #[test]
288    fn half_filled() {
289        let b = run(Gauge::new(50.0), 10, 1);
290        assert_eq!(b[(0, 0)].symbol(), "█");
291        assert_eq!(b[(4, 0)].symbol(), "█");
292        assert_eq!(b[(5, 0)].symbol(), "░");
293    }
294
295    #[test]
296    fn bands_target_label() {
297        let g = Gauge::new(80.0)
298            .bands([(50.0, Color::Green), (100.0, Color::Red)])
299            .target(25.0)
300            .label("ab");
301        let b = run(g, 20, 3);
302        assert_eq!(b[(5, 0)].symbol(), "┃");
303        assert_eq!(b[(0, 0)].fg, Color::Green);
304        assert_eq!(b[(15, 0)].fg, Color::Red);
305        assert_eq!(b[(9, 1)].symbol(), "a");
306    }
307
308    #[test]
309    fn vertical_fills_from_bottom() {
310        let b = run(
311            Gauge::new(100.0).orientation(GaugeOrientation::Vertical),
312            2,
313            4,
314        );
315        assert_eq!(b[(0, 3)].symbol(), "█");
316        assert_eq!(b[(0, 0)].symbol(), "█");
317        let b = run(
318            Gauge::new(0.0).orientation(GaugeOrientation::Vertical),
319            2,
320            4,
321        );
322        assert_eq!(b[(0, 3)].symbol(), "░");
323    }
324
325    #[test]
326    fn bullet_and_arc_and_degenerate() {
327        let b = run(Gauge::new(60.0).style(GaugeStyle::Bullet), 10, 3);
328        assert_eq!(b[(0, 1)].symbol(), "█");
329        assert_eq!(b[(0, 0)].symbol(), "▒");
330        let b = run(Gauge::new(60.0).style(GaugeStyle::Arc).target(30.0), 20, 6);
331        assert!(b.content().iter().any(|c| c.symbol() != " "));
332        for s in [GaugeStyle::Linear, GaugeStyle::Bullet, GaugeStyle::Arc] {
333            run(
334                Gauge::new(f64::NAN)
335                    .style(s)
336                    .range(1.0, 1.0)
337                    .target(f64::NAN),
338                1,
339                1,
340            );
341            run(Gauge::new(5.0).style(s).label("long label"), 3, 2);
342            run(Gauge::new(5.0).style(s), 0, 0);
343        }
344    }
345}