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 crate::util::{darken, format_compact};
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13/// Direction of a linear gauge.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum GaugeOrientation {
17    /// Fills left to right.
18    #[default]
19    Horizontal,
20    /// Fills bottom to top.
21    Vertical,
22}
23
24/// Visual form of a [`Gauge`].
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub enum GaugeStyle {
28    /// Full-thickness bar over a dim band track.
29    #[default]
30    Linear,
31    /// Bullet chart: bands as background, thin value bar in the middle.
32    Bullet,
33    /// Semicircular dial drawn with braille dots: banded ring, ticks, needle,
34    /// target notch, min/max scale labels and the value label underneath.
35    Arc,
36    /// Discrete blocks (htop / battery style); lit blocks take the band color.
37    Segmented,
38}
39
40/// Gauge showing a value inside `[min, max]`.
41///
42/// # Example
43///
44/// ```
45/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
46/// use tui_chart::{Gauge};
47///
48/// let chart = Gauge::new(0.62);
49/// let area = Rect::new(0, 0, 40, 12);
50/// let mut buf = Buffer::empty(area);
51/// chart.render(area, &mut buf);
52/// ```
53#[derive(Debug, Clone)]
54pub struct Gauge<'a> {
55    value: f64,
56    min: f64,
57    max: f64,
58    bands: Vec<(f64, Color)>,
59    target: Option<f64>,
60    label: Option<String>,
61    orientation: GaugeOrientation,
62    style: GaugeStyle,
63    color: Option<Color>,
64    theme: Option<Theme>,
65    base: Option<Style>,
66    marker: Marker,
67    block: Option<Block<'a>>,
68}
69
70impl<'a> Gauge<'a> {
71    /// Create a gauge for `value` on the scale 0..=100.
72    pub fn new(value: f64) -> Self {
73        Self {
74            value,
75            min: 0.0,
76            max: 100.0,
77            bands: Vec::new(),
78            target: None,
79            label: None,
80            orientation: GaugeOrientation::Horizontal,
81            style: GaugeStyle::Linear,
82            color: None,
83            theme: None,
84            base: None,
85            marker: Marker::Braille,
86            block: None,
87        }
88    }
89    /// Scale range.
90    pub fn range(mut self, min: f64, max: f64) -> Self {
91        self.min = min;
92        self.max = max;
93        self
94    }
95    /// Threshold bands: each `(upper_bound, color)` covers up to that value.
96    pub fn bands(mut self, bands: impl IntoIterator<Item = (f64, Color)>) -> Self {
97        self.bands = bands.into_iter().collect();
98        self.bands.sort_by(|a, b| a.0.total_cmp(&b.0));
99        self
100    }
101    opt_setter!(
102        /// Target marker value.
103        target: f64
104    );
105    /// Centered label text.
106    pub fn label(mut self, l: impl Into<String>) -> Self {
107        self.label = Some(l.into());
108        self
109    }
110    setter!(
111        /// Horizontal or vertical.
112        orientation: GaugeOrientation
113    );
114    setter!(
115        /// Gauge form.
116        style: GaugeStyle
117    );
118    opt_setter!(
119        /// Bar color when no bands are set.
120        color: Color
121    );
122    theme_setter!(
123        /// Apply a [`Theme`]: bar color (bull color), track/needle colors and
124        /// background fill. Explicit [`Gauge::color`] and band colors win.
125        theme
126    );
127    base_style_setter!(base);
128    fn fg(&self) -> Color {
129        self.theme.as_ref().map_or(Color::White, |t| t.foreground)
130    }
131    fn track(&self) -> Color {
132        self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid)
133    }
134    fn bar_color(&self) -> Color {
135        self.color
136            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
137    }
138    setter!(
139        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
140        marker: Marker
141    );
142
143    block_setter!(block, 'a);
144
145    fn frac(&self, v: f64) -> f64 {
146        let span = self.max - self.min;
147        if !v.is_finite() || !span.is_finite() || span <= 0.0 {
148            return 0.0;
149        }
150        ((v - self.min) / span).clamp(0.0, 1.0)
151    }
152
153    fn band_color(&self, f: f64) -> Color {
154        let v = self.min + f * (self.max - self.min);
155        self.bands
156            .iter()
157            .find(|b| v <= b.0)
158            .or(self.bands.last())
159            .map_or(self.bar_color(), |b| b.1)
160    }
161
162    /// Color of the unfilled part of the track at fraction `f`: the band color
163    /// (or track color) darkened, so bands stay readable without hatching.
164    fn dim(&self, f: f64) -> Color {
165        let base = if self.bands.is_empty() {
166            self.track()
167        } else {
168            self.band_color(f)
169        };
170        darken(base, if self.bands.is_empty() { 0.35 } else { 0.5 })
171    }
172
173    fn draw_label_at(&self, text: &str, cx: u16, y: u16, clip: Rect, buf: &mut Buffer) {
174        let n = text.chars().count().min(clip.width as usize) as u16;
175        let x0 = cx
176            .saturating_sub(n / 2)
177            .clamp(clip.x, clip.right().saturating_sub(n));
178        for (i, ch) in text.chars().take(n as usize).enumerate() {
179            if let Some(c) = buf.cell_mut((x0 + i as u16, y)) {
180                c.set_char(ch)
181                    .set_fg(self.fg())
182                    .set_style(Style::default().add_modifier(ratatui::style::Modifier::BOLD));
183            }
184        }
185    }
186
187    fn draw_label(&self, area: Rect, buf: &mut Buffer) {
188        let Some(l) = &self.label else { return };
189        self.draw_label_at(
190            l,
191            area.x + area.width / 2,
192            area.y + area.height / 2,
193            area,
194            buf,
195        );
196    }
197
198    fn draw_linear(&self, area: Rect, buf: &mut Buffer) {
199        let horiz = self.orientation == GaugeOrientation::Horizontal;
200        let (len, cross) = if horiz {
201            (area.width, area.height)
202        } else {
203            (area.height, area.width)
204        };
205        let bullet = self.style == GaugeStyle::Bullet;
206        let segmented = self.style == GaugeStyle::Segmented;
207        let vf = self.frac(self.value);
208        let eighths = (vf * len as f64 * 8.0).round() as i64;
209        let (c0, c1) = if bullet && cross >= 3 {
210            (cross / 3, cross - cross / 3)
211        } else if bullet {
212            (cross / 2, cross / 2 + 1)
213        } else {
214            (0, cross)
215        };
216        let tpos = self
217            .target
218            .map(|t| ((self.frac(t) * len as f64).floor() as u16).min(len.saturating_sub(1)));
219        // segmented: 2-cell blocks (1 vertically) separated by a 1-cell gap
220        let seg = if horiz { 2 } else { 1 };
221        let nseg = ((len as usize + 1) / (seg + 1)).max(1);
222        for i in 0..len {
223            let f = (i as f64 + 0.5) / len as f64;
224            let bc = self.band_color(f);
225            let track = self.dim(f);
226            let rem = eighths - i as i64 * 8;
227            for c in 0..cross {
228                let (x, y) = if horiz {
229                    (area.x + i, area.y + c)
230                } else {
231                    (area.x + c, area.y + area.height - 1 - i)
232                };
233                let Some(cell) = buf.cell_mut((x, y)) else {
234                    continue;
235                };
236                if segmented {
237                    let slot = i as usize % (seg + 1);
238                    if slot == seg {
239                        continue; // gap
240                    }
241                    let idx = i as usize / (seg + 1);
242                    let sf = (idx as f64 + 0.5) / nseg as f64;
243                    let lit = sf <= vf || (idx == 0 && vf > 0.0);
244                    let col = if lit {
245                        self.band_color(sf)
246                    } else {
247                        self.dim(sf)
248                    };
249                    cell.set_char('█').set_fg(col);
250                    continue;
251                }
252                let in_bar = c >= c0 && c < c1;
253                if tpos == Some(i) {
254                    cell.set_char(if horiz { '┃' } else { '━' })
255                        .set_fg(self.fg())
256                        .set_bg(track);
257                } else if in_bar && rem >= 8 {
258                    cell.set_char('█').set_fg(bc).set_bg(bc);
259                } else if in_bar && rem > 0 {
260                    let k = (rem - 1) as usize;
261                    let ch = if horiz {
262                        ['▏', '▎', '▍', '▌', '▋', '▊', '▉'][k]
263                    } else {
264                        ['▁', '▂', '▃', '▄', '▅', '▆', '▇'][k]
265                    };
266                    cell.set_char(ch).set_fg(bc).set_bg(track);
267                } else {
268                    // solid dimmed track (bullet: bands behind the bar)
269                    cell.set_char(' ').set_bg(track);
270                }
271            }
272        }
273        if let (Some(_), true) = (tpos, segmented) {
274            // keep the target visible between blocks
275            if let Some(i) = tpos {
276                for c in 0..cross {
277                    let (x, y) = if horiz {
278                        (area.x + i, area.y + c)
279                    } else {
280                        (area.x + c, area.y + area.height - 1 - i)
281                    };
282                    if let Some(cell) = buf.cell_mut((x, y)) {
283                        cell.set_char(if horiz { '┃' } else { '━' })
284                            .set_fg(self.fg());
285                    }
286                }
287            }
288        }
289        self.draw_label(area, buf);
290    }
291
292    fn draw_arc(&self, area: Rect, buf: &mut Buffer) {
293        // bottom row: min · value label · max (only when there is room)
294        let scale_row = area.height >= 3;
295        let canvas_area = if scale_row {
296            Rect::new(area.x, area.y, area.width, area.height - 1)
297        } else {
298            area
299        };
300        let mut cv = Canvas::new(canvas_area.width, canvas_area.height, self.marker);
301        let (pw, ph) = (cv.px_w(), cv.px_h());
302        // leave room outside the ring for tick marks
303        let tick_len = if ph >= 12 { 3 } else { 0 };
304        let r = (((pw - 1) / 2 - tick_len).min(ph - 1 - tick_len)).max(1) as f64;
305        let thick = (r / 4.0).max(2.0);
306        let (cx, cy) = ((pw - 1) as f64 / 2.0, (ph - 1) as f64);
307        let vf = self.frac(self.value);
308        let mid = r - thick / 2.0;
309        let thumb = 1.6 / (std::f64::consts::PI * mid.max(1.0)); // ~1.6 dots wide, as a fraction
310        for py in 0..ph {
311            for px in 0..pw {
312                let (dx, dy) = (px as f64 - cx, cy - py as f64);
313                if dy < -0.5 {
314                    continue;
315                }
316                let d = (dx * dx + dy * dy).sqrt();
317                if d > r || d < r - thick {
318                    continue;
319                }
320                let f = 1.0 - dy.max(0.0).atan2(dx) / std::f64::consts::PI;
321                let col = if (f - vf).abs() <= thumb && vf > 0.0 && vf < 1.0 {
322                    self.fg()
323                } else if f <= vf {
324                    self.band_color(f)
325                } else {
326                    self.dim(f)
327                };
328                cv.set(px, py, col);
329            }
330        }
331        let at = |f: f64, rad: f64| {
332            let a = std::f64::consts::PI * (1.0 - f);
333            (
334                (cx + rad * a.cos()).round() as i32,
335                (cy - rad * a.sin()).round() as i32,
336            )
337        };
338        if tick_len > 0 {
339            let tick = darken(self.fg(), 0.35);
340            for k in 0..=10 {
341                let f = k as f64 / 10.0;
342                let len = if k % 5 == 0 { tick_len as f64 } else { 1.0 };
343                let (a, b) = (at(f, r + 1.0), at(f, r + 1.0 + len));
344                cv.line(a.0, a.1, b.0, b.1, tick);
345            }
346        }
347        if let Some(t) = self.target {
348            let tf = self.frac(t);
349            let (a, b) = (at(tf, r - thick - 1.0), at(tf, r + 1.0 + tick_len as f64));
350            cv.line(a.0, a.1, b.0, b.1, self.fg());
351        }
352        // needle + hub
353        let tip = at(vf, r - thick - 2.0);
354        cv.line(cx.round() as i32, cy as i32, tip.0, tip.1, self.fg());
355        let hub = 2;
356        for dy in -hub..=hub {
357            for dx in -hub..=hub {
358                if dx * dx + dy * dy <= hub * hub {
359                    cv.set(cx.round() as i32 + dx, cy as i32 + dy, self.fg());
360                }
361            }
362        }
363        cv.render(buf, canvas_area);
364        if scale_row {
365            let y = area.bottom() - 1;
366            let (rx, _) = self.marker.resolution();
367            let cell_of = |dot: f64| canvas_area.x + (dot / rx as f64).floor().max(0.0) as u16;
368            self.draw_label_at(&format_compact(self.min), cell_of(cx - mid), y, area, buf);
369            self.draw_label_at(&format_compact(self.max), cell_of(cx + mid), y, area, buf);
370            let center = self
371                .label
372                .clone()
373                .unwrap_or_else(|| format_compact(self.value));
374            self.draw_label_at(&center, area.x + area.width / 2, y, area, buf);
375        } else {
376            self.draw_label(area, buf);
377        }
378    }
379}
380
381impl Gauge<'_> {
382    fn render_into(&self, area: Rect, buf: &mut Buffer) {
383        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
384        if inner.width == 0 || inner.height == 0 {
385            return;
386        }
387        match self.style {
388            GaugeStyle::Arc => self.draw_arc(inner, buf),
389            _ => self.draw_linear(inner, buf),
390        }
391    }
392}
393
394widget_impls!(Gauge<'_>);
395
396#[cfg(feature = "theme")]
397impl<'a> tui_nuances::Themed for Gauge<'a> {
398    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
399        self.theme(theme)
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406    use ratatui::widgets::Widget;
407
408    fn run(g: Gauge, w: u16, h: u16) -> Buffer {
409        let a = Rect::new(0, 0, w, h);
410        let mut b = Buffer::empty(a);
411        g.render(a, &mut b);
412        b
413    }
414
415    #[test]
416    fn half_filled() {
417        let b = run(Gauge::new(50.0), 10, 1);
418        assert_eq!(b[(0, 0)].symbol(), "█");
419        assert_eq!(b[(4, 0)].symbol(), "█");
420        assert_eq!(b[(5, 0)].symbol(), " ");
421        assert_ne!(b[(5, 0)].bg, Color::Reset);
422    }
423
424    #[test]
425    fn bands_target_label() {
426        let g = Gauge::new(80.0)
427            .bands([(50.0, Color::Green), (100.0, Color::Red)])
428            .target(25.0)
429            .label("ab");
430        let b = run(g, 20, 3);
431        assert_eq!(b[(5, 0)].symbol(), "┃");
432        assert_eq!(b[(0, 0)].fg, Color::Green);
433        assert_eq!(b[(15, 0)].fg, Color::Red);
434        assert_eq!(b[(9, 1)].symbol(), "a");
435    }
436
437    #[test]
438    fn vertical_fills_from_bottom() {
439        let b = run(
440            Gauge::new(100.0).orientation(GaugeOrientation::Vertical),
441            2,
442            4,
443        );
444        assert_eq!(b[(0, 3)].symbol(), "█");
445        assert_eq!(b[(0, 0)].symbol(), "█");
446        let b = run(
447            Gauge::new(0.0).orientation(GaugeOrientation::Vertical),
448            2,
449            4,
450        );
451        assert_eq!(b[(0, 3)].symbol(), " ");
452    }
453
454    #[test]
455    fn segmented_lights_blocks_with_gaps() {
456        let b = run(Gauge::new(50.0).style(GaugeStyle::Segmented), 12, 1);
457        let s: String = (0..12).map(|x| b[(x, 0)].symbol().to_string()).collect();
458        assert_eq!(&s[..], "██ ██ ██ ██ ");
459        assert_ne!(b[(0, 0)].fg, b[(9, 0)].fg); // lit vs dim
460    }
461
462    #[test]
463    fn arc_shows_scale_and_value() {
464        let g = Gauge::new(42.0).style(GaugeStyle::Arc).range(0.0, 100.0);
465        let b = run(g, 40, 12);
466        let last: String = (0..40).map(|x| b[(x, 11)].symbol().to_string()).collect();
467        assert!(
468            last.contains('0') && last.contains("100") && last.contains("42"),
469            "{last:?}"
470        );
471    }
472
473    #[test]
474    fn bullet_and_arc_and_degenerate() {
475        let b = run(Gauge::new(60.0).style(GaugeStyle::Bullet), 10, 3);
476        assert_eq!(b[(0, 1)].symbol(), "█");
477        assert_eq!(b[(0, 0)].symbol(), " ");
478        assert_ne!(b[(0, 0)].bg, Color::Reset);
479        let b = run(Gauge::new(60.0).style(GaugeStyle::Arc).target(30.0), 20, 6);
480        assert!(b.content().iter().any(|c| c.symbol() != " "));
481        for s in [
482            GaugeStyle::Linear,
483            GaugeStyle::Bullet,
484            GaugeStyle::Arc,
485            GaugeStyle::Segmented,
486        ] {
487            run(
488                Gauge::new(f64::NAN)
489                    .style(s)
490                    .range(1.0, 1.0)
491                    .target(f64::NAN),
492                1,
493                1,
494            );
495            run(Gauge::new(5.0).style(s).label("long label"), 3, 2);
496            run(Gauge::new(5.0).style(s), 0, 0);
497        }
498    }
499}