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    /// Full-circle-ish dial (270°): banded ring, ticks, needle and value readout.
39    Dial,
40    /// Half-circle meter with a needle and the readout underneath.
41    Meter,
42    /// Sci-fi reticle: ring with tick marks, inner dashed ring and crosshair.
43    Reticle,
44    /// Full ring (360°) filling clockwise, value in the hole.
45    Ring,
46    /// Row of chevron cells (`❯`), lit up to the value.
47    Chevron,
48    /// Smooth sub-cell bar with a rounded end.
49    Smooth,
50    /// Row of round dots, lit up to the value.
51    Dots,
52    /// LED strip: lit segments take the band color, unlit ones are dim.
53    Led,
54    /// Battery outline with a terminal nub and a charge fill.
55    Battery,
56    /// Vertical liquid level in a tank, with a wavy surface.
57    Level,
58    /// Vertical thermometer with a bulb.
59    Thermometer,
60    /// Rising signal bars (like a phone's reception indicator).
61    Signal,
62}
63
64impl GaugeStyle {
65    /// Every gauge style.
66    pub const ALL: [GaugeStyle; 16] = [
67        GaugeStyle::Linear,
68        GaugeStyle::Bullet,
69        GaugeStyle::Arc,
70        GaugeStyle::Segmented,
71        GaugeStyle::Dial,
72        GaugeStyle::Meter,
73        GaugeStyle::Reticle,
74        GaugeStyle::Ring,
75        GaugeStyle::Chevron,
76        GaugeStyle::Smooth,
77        GaugeStyle::Dots,
78        GaugeStyle::Led,
79        GaugeStyle::Battery,
80        GaugeStyle::Level,
81        GaugeStyle::Thermometer,
82        GaugeStyle::Signal,
83    ];
84
85    fn look(self) -> Option<crate::gauge_kit::Look> {
86        use crate::gauge_kit::Look;
87        Some(match self {
88            GaugeStyle::Dial => Look::Dial,
89            GaugeStyle::Meter => Look::Meter,
90            GaugeStyle::Reticle => Look::Reticle,
91            GaugeStyle::Ring => Look::Ring,
92            GaugeStyle::Chevron => Look::Chevron,
93            GaugeStyle::Smooth => Look::Smooth,
94            GaugeStyle::Dots => Look::Dots,
95            GaugeStyle::Led => Look::Led,
96            GaugeStyle::Battery => Look::Battery,
97            GaugeStyle::Level => Look::Level,
98            GaugeStyle::Thermometer => Look::Thermometer,
99            GaugeStyle::Signal => Look::Signal,
100            _ => return None,
101        })
102    }
103
104    /// A good `(width, height)` in cells for this style.
105    pub const fn preferred_size(self) -> (u16, u16) {
106        match self {
107            GaugeStyle::Meter => (22, 7),
108            GaugeStyle::Level => (8, 8),
109            GaugeStyle::Thermometer => (5, 8),
110            GaugeStyle::Signal => (14, 6),
111            GaugeStyle::Arc
112            | GaugeStyle::Dial
113            | GaugeStyle::Reticle
114            | GaugeStyle::Ring
115            | GaugeStyle::Segmented => (20, 10),
116            _ => (36, 1),
117        }
118    }
119}
120
121/// Gauge showing a value inside `[min, max]`.
122///
123/// # Example
124///
125/// ```
126/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
127/// use tui_chart::{Gauge};
128///
129/// let chart = Gauge::new(0.62);
130/// let area = Rect::new(0, 0, 40, 12);
131/// let mut buf = Buffer::empty(area);
132/// chart.render(area, &mut buf);
133/// ```
134#[derive(Debug, Clone)]
135pub struct Gauge<'a> {
136    value: f64,
137    min: f64,
138    max: f64,
139    bands: Vec<(f64, Color)>,
140    target: Option<f64>,
141    label: Option<String>,
142    orientation: GaugeOrientation,
143    style: GaugeStyle,
144    color: Option<Color>,
145    theme: Option<Theme>,
146    base: Option<Style>,
147    marker: Marker,
148    block: Option<Block<'a>>,
149}
150
151impl<'a> Gauge<'a> {
152    /// Create a gauge for `value` on the scale 0..=100.
153    pub fn new(value: f64) -> Self {
154        Self {
155            value,
156            min: 0.0,
157            max: 100.0,
158            bands: Vec::new(),
159            target: None,
160            label: None,
161            orientation: GaugeOrientation::Horizontal,
162            style: GaugeStyle::Linear,
163            color: None,
164            theme: None,
165            base: None,
166            marker: Marker::Braille,
167            block: None,
168        }
169    }
170    /// Scale range.
171    pub fn range(mut self, min: f64, max: f64) -> Self {
172        self.min = min;
173        self.max = max;
174        self
175    }
176    /// Threshold bands: each `(upper_bound, color)` covers up to that value.
177    pub fn bands(mut self, bands: impl IntoIterator<Item = (f64, Color)>) -> Self {
178        self.bands = bands.into_iter().collect();
179        self.bands.sort_by(|a, b| a.0.total_cmp(&b.0));
180        self
181    }
182    opt_setter!(
183        /// Target marker value.
184        target: f64
185    );
186    /// Centered label text.
187    pub fn label(mut self, l: impl Into<String>) -> Self {
188        self.label = Some(l.into());
189        self
190    }
191    setter!(
192        /// Horizontal or vertical.
193        orientation: GaugeOrientation
194    );
195    setter!(
196        /// Gauge form.
197        style: GaugeStyle
198    );
199    opt_setter!(
200        /// Bar color when no bands are set.
201        color: Color
202    );
203    theme_setter!(
204        /// Apply a [`Theme`]: bar color (bull color), track/needle colors and
205        /// background fill. Explicit [`Gauge::color`] and band colors win.
206        theme
207    );
208    base_style_setter!(base);
209    fn fg(&self) -> Color {
210        self.theme.as_ref().map_or(Color::White, |t| t.foreground)
211    }
212    fn track(&self) -> Color {
213        self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid)
214    }
215    fn bar_color(&self) -> Color {
216        self.color
217            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
218    }
219    setter!(
220        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
221        marker: Marker
222    );
223
224    block_setter!(block, 'a);
225
226    fn frac(&self, v: f64) -> f64 {
227        let span = self.max - self.min;
228        if !v.is_finite() || !span.is_finite() || span <= 0.0 {
229            return 0.0;
230        }
231        ((v - self.min) / span).clamp(0.0, 1.0)
232    }
233
234    fn band_color(&self, f: f64) -> Color {
235        let v = self.min + f * (self.max - self.min);
236        self.bands
237            .iter()
238            .find(|b| v <= b.0)
239            .or(self.bands.last())
240            .map_or(self.bar_color(), |b| b.1)
241    }
242
243    /// Color of the unfilled part of the track at fraction `f`: the band color
244    /// (or track color) darkened, so bands stay readable without hatching.
245    fn dim(&self, f: f64) -> Color {
246        let base = if self.bands.is_empty() {
247            self.track()
248        } else {
249            self.band_color(f)
250        };
251        darken(base, if self.bands.is_empty() { 0.35 } else { 0.5 })
252    }
253
254    fn draw_label_at(&self, text: &str, cx: u16, y: u16, clip: Rect, buf: &mut Buffer) {
255        let n = text.chars().count().min(clip.width as usize) as u16;
256        let x0 = cx
257            .saturating_sub(n / 2)
258            .clamp(clip.x, clip.right().saturating_sub(n));
259        for (i, ch) in text.chars().take(n as usize).enumerate() {
260            if let Some(c) = buf.cell_mut((x0 + i as u16, y)) {
261                c.set_char(ch)
262                    .set_fg(self.fg())
263                    .set_style(Style::default().add_modifier(ratatui::style::Modifier::BOLD));
264            }
265        }
266    }
267
268    fn draw_label(&self, area: Rect, buf: &mut Buffer) {
269        let Some(l) = &self.label else { return };
270        self.draw_label_at(
271            l,
272            area.x + area.width / 2,
273            area.y + area.height / 2,
274            area,
275            buf,
276        );
277    }
278
279    fn draw_linear(&self, area: Rect, buf: &mut Buffer) {
280        let horiz = self.orientation == GaugeOrientation::Horizontal;
281        let (len, cross) = if horiz {
282            (area.width, area.height)
283        } else {
284            (area.height, area.width)
285        };
286        let bullet = self.style == GaugeStyle::Bullet;
287        let segmented = self.style == GaugeStyle::Segmented;
288        let vf = self.frac(self.value);
289        let eighths = (vf * len as f64 * 8.0).round() as i64;
290        let (c0, c1) = if bullet && cross >= 3 {
291            (cross / 3, cross - cross / 3)
292        } else if bullet {
293            (cross / 2, cross / 2 + 1)
294        } else {
295            (0, cross)
296        };
297        let tpos = self
298            .target
299            .map(|t| ((self.frac(t) * len as f64).floor() as u16).min(len.saturating_sub(1)));
300        // segmented: 2-cell blocks (1 vertically) separated by a 1-cell gap
301        let seg = if horiz { 2 } else { 1 };
302        let nseg = ((len as usize + 1) / (seg + 1)).max(1);
303        for i in 0..len {
304            let f = (i as f64 + 0.5) / len as f64;
305            let bc = self.band_color(f);
306            let track = self.dim(f);
307            let rem = eighths - i as i64 * 8;
308            for c in 0..cross {
309                let (x, y) = if horiz {
310                    (area.x + i, area.y + c)
311                } else {
312                    (area.x + c, area.y + area.height - 1 - i)
313                };
314                let Some(cell) = buf.cell_mut((x, y)) else {
315                    continue;
316                };
317                if segmented {
318                    let slot = i as usize % (seg + 1);
319                    if slot == seg {
320                        continue; // gap
321                    }
322                    let idx = i as usize / (seg + 1);
323                    let sf = (idx as f64 + 0.5) / nseg as f64;
324                    let lit = sf <= vf || (idx == 0 && vf > 0.0);
325                    let col = if lit {
326                        self.band_color(sf)
327                    } else {
328                        self.dim(sf)
329                    };
330                    cell.set_char('█').set_fg(col);
331                    continue;
332                }
333                let in_bar = c >= c0 && c < c1;
334                if tpos == Some(i) {
335                    cell.set_char(if horiz { '┃' } else { '━' })
336                        .set_fg(self.fg())
337                        .set_bg(track);
338                } else if in_bar && rem >= 8 {
339                    cell.set_char('█').set_fg(bc).set_bg(bc);
340                } else if in_bar && rem > 0 {
341                    let k = (rem - 1) as usize;
342                    let ch = if horiz {
343                        ['▏', '▎', '▍', '▌', '▋', '▊', '▉'][k]
344                    } else {
345                        ['▁', '▂', '▃', '▄', '▅', '▆', '▇'][k]
346                    };
347                    cell.set_char(ch).set_fg(bc).set_bg(track);
348                } else {
349                    // solid dimmed track (bullet: bands behind the bar)
350                    cell.set_char(' ').set_bg(track);
351                }
352            }
353        }
354        if let (Some(_), true) = (tpos, segmented) {
355            // keep the target visible between blocks
356            if let Some(i) = tpos {
357                for c in 0..cross {
358                    let (x, y) = if horiz {
359                        (area.x + i, area.y + c)
360                    } else {
361                        (area.x + c, area.y + area.height - 1 - i)
362                    };
363                    if let Some(cell) = buf.cell_mut((x, y)) {
364                        cell.set_char(if horiz { '┃' } else { '━' })
365                            .set_fg(self.fg());
366                    }
367                }
368            }
369        }
370        self.draw_label(area, buf);
371    }
372
373    fn draw_arc(&self, area: Rect, buf: &mut Buffer) {
374        // bottom row: min · value label · max (only when there is room)
375        let scale_row = area.height >= 3;
376        let canvas_area = if scale_row {
377            Rect::new(area.x, area.y, area.width, area.height - 1)
378        } else {
379            area
380        };
381        let mut cv = Canvas::new(canvas_area.width, canvas_area.height, self.marker);
382        let (pw, ph) = (cv.px_w(), cv.px_h());
383        // leave room outside the ring for tick marks
384        let tick_len = if ph >= 12 { 3 } else { 0 };
385        let r = (((pw - 1) / 2 - tick_len).min(ph - 1 - tick_len)).max(1) as f64;
386        let thick = (r / 4.0).max(2.0);
387        let (cx, cy) = ((pw - 1) as f64 / 2.0, (ph - 1) as f64);
388        let vf = self.frac(self.value);
389        let mid = r - thick / 2.0;
390        let thumb = 1.6 / (std::f64::consts::PI * mid.max(1.0)); // ~1.6 dots wide, as a fraction
391        for py in 0..ph {
392            for px in 0..pw {
393                let (dx, dy) = (px as f64 - cx, cy - py as f64);
394                if dy < -0.5 {
395                    continue;
396                }
397                let d = (dx * dx + dy * dy).sqrt();
398                if d > r || d < r - thick {
399                    continue;
400                }
401                let f = 1.0 - dy.max(0.0).atan2(dx) / std::f64::consts::PI;
402                let col = if (f - vf).abs() <= thumb && vf > 0.0 && vf < 1.0 {
403                    self.fg()
404                } else if f <= vf {
405                    self.band_color(f)
406                } else {
407                    self.dim(f)
408                };
409                cv.set(px, py, col);
410            }
411        }
412        let at = |f: f64, rad: f64| {
413            let a = std::f64::consts::PI * (1.0 - f);
414            (
415                (cx + rad * a.cos()).round() as i32,
416                (cy - rad * a.sin()).round() as i32,
417            )
418        };
419        if tick_len > 0 {
420            let tick = darken(self.fg(), 0.35);
421            for k in 0..=10 {
422                let f = k as f64 / 10.0;
423                let len = if k % 5 == 0 { tick_len as f64 } else { 1.0 };
424                let (a, b) = (at(f, r + 1.0), at(f, r + 1.0 + len));
425                cv.line(a.0, a.1, b.0, b.1, tick);
426            }
427        }
428        if let Some(t) = self.target {
429            let tf = self.frac(t);
430            let (a, b) = (at(tf, r - thick - 1.0), at(tf, r + 1.0 + tick_len as f64));
431            cv.line(a.0, a.1, b.0, b.1, self.fg());
432        }
433        // needle + hub
434        let tip = at(vf, r - thick - 2.0);
435        cv.line(cx.round() as i32, cy as i32, tip.0, tip.1, self.fg());
436        let hub = 2;
437        for dy in -hub..=hub {
438            for dx in -hub..=hub {
439                if dx * dx + dy * dy <= hub * hub {
440                    cv.set(cx.round() as i32 + dx, cy as i32 + dy, self.fg());
441                }
442            }
443        }
444        cv.render(buf, canvas_area);
445        if scale_row {
446            let y = area.bottom() - 1;
447            let (rx, _) = self.marker.resolution();
448            let cell_of = |dot: f64| canvas_area.x + (dot / rx as f64).floor().max(0.0) as u16;
449            self.draw_label_at(&format_compact(self.min), cell_of(cx - mid), y, area, buf);
450            self.draw_label_at(&format_compact(self.max), cell_of(cx + mid), y, area, buf);
451            let center = self
452                .label
453                .clone()
454                .unwrap_or_else(|| format_compact(self.value));
455            self.draw_label_at(&center, area.x + area.width / 2, y, area, buf);
456        } else {
457            self.draw_label(area, buf);
458        }
459    }
460}
461
462impl Gauge<'_> {
463    fn render_into(&self, area: Rect, buf: &mut Buffer) {
464        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
465        if inner.width == 0 || inner.height == 0 {
466            return;
467        }
468        crate::interact::record_point(inner, 0, 0, || {
469            let f = crate::util::format_compact;
470            let frac = self.frac(self.value);
471            (
472                "gauge".to_string(),
473                vec![
474                    format!("{} of {} .. {}", f(self.value), f(self.min), f(self.max)),
475                    format!("{:.0}%", frac * 100.0),
476                ],
477            )
478        });
479        if let Some(look) = self.style.look() {
480            let frac = self.frac(self.value);
481            let span = self.max - self.min;
482            let bands = self
483                .bands
484                .iter()
485                .map(|(v, c)| (self.frac(*v), *c))
486                .filter(|_| span > 0.0)
487                .collect();
488            let readout = self
489                .label
490                .clone()
491                .unwrap_or_else(|| format!("{:.0}%", frac * 100.0));
492            crate::gauge_kit::Painter {
493                look,
494                frac,
495                readout,
496                label: None,
497                bands,
498                color: self.bar_color(),
499                track: self.track(),
500                fg: self.fg(),
501            }
502            .render(inner, buf);
503            return;
504        }
505        match self.style {
506            GaugeStyle::Arc => self.draw_arc(inner, buf),
507            _ => self.draw_linear(inner, buf),
508        }
509    }
510}
511
512widget_impls!(Gauge<'_>);
513
514#[cfg(feature = "theme")]
515impl<'a> tui_nuances::Themed for Gauge<'a> {
516    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
517        self.theme(theme)
518    }
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524    use ratatui::widgets::Widget;
525
526    fn run(g: Gauge, w: u16, h: u16) -> Buffer {
527        let a = Rect::new(0, 0, w, h);
528        let mut b = Buffer::empty(a);
529        g.render(a, &mut b);
530        b
531    }
532
533    #[test]
534    fn half_filled() {
535        let b = run(Gauge::new(50.0), 10, 1);
536        assert_eq!(b[(0, 0)].symbol(), "█");
537        assert_eq!(b[(4, 0)].symbol(), "█");
538        assert_eq!(b[(5, 0)].symbol(), " ");
539        assert_ne!(b[(5, 0)].bg, Color::Reset);
540    }
541
542    #[test]
543    fn bands_target_label() {
544        let g = Gauge::new(80.0)
545            .bands([(50.0, Color::Green), (100.0, Color::Red)])
546            .target(25.0)
547            .label("ab");
548        let b = run(g, 20, 3);
549        assert_eq!(b[(5, 0)].symbol(), "┃");
550        assert_eq!(b[(0, 0)].fg, Color::Green);
551        assert_eq!(b[(15, 0)].fg, Color::Red);
552        assert_eq!(b[(9, 1)].symbol(), "a");
553    }
554
555    #[test]
556    fn vertical_fills_from_bottom() {
557        let b = run(
558            Gauge::new(100.0).orientation(GaugeOrientation::Vertical),
559            2,
560            4,
561        );
562        assert_eq!(b[(0, 3)].symbol(), "█");
563        assert_eq!(b[(0, 0)].symbol(), "█");
564        let b = run(
565            Gauge::new(0.0).orientation(GaugeOrientation::Vertical),
566            2,
567            4,
568        );
569        assert_eq!(b[(0, 3)].symbol(), " ");
570    }
571
572    #[test]
573    fn segmented_lights_blocks_with_gaps() {
574        let b = run(Gauge::new(50.0).style(GaugeStyle::Segmented), 12, 1);
575        let s: String = (0..12).map(|x| b[(x, 0)].symbol().to_string()).collect();
576        assert_eq!(&s[..], "██ ██ ██ ██ ");
577        assert_ne!(b[(0, 0)].fg, b[(9, 0)].fg); // lit vs dim
578    }
579
580    #[test]
581    fn arc_shows_scale_and_value() {
582        let g = Gauge::new(42.0).style(GaugeStyle::Arc).range(0.0, 100.0);
583        let b = run(g, 40, 12);
584        let last: String = (0..40).map(|x| b[(x, 11)].symbol().to_string()).collect();
585        assert!(
586            last.contains('0') && last.contains("100") && last.contains("42"),
587            "{last:?}"
588        );
589    }
590
591    #[test]
592    fn bullet_and_arc_and_degenerate() {
593        let b = run(Gauge::new(60.0).style(GaugeStyle::Bullet), 10, 3);
594        assert_eq!(b[(0, 1)].symbol(), "█");
595        assert_eq!(b[(0, 0)].symbol(), " ");
596        assert_ne!(b[(0, 0)].bg, Color::Reset);
597        let b = run(Gauge::new(60.0).style(GaugeStyle::Arc).target(30.0), 20, 6);
598        assert!(b.content().iter().any(|c| c.symbol() != " "));
599        for s in [
600            GaugeStyle::Linear,
601            GaugeStyle::Bullet,
602            GaugeStyle::Arc,
603            GaugeStyle::Segmented,
604        ] {
605            run(
606                Gauge::new(f64::NAN)
607                    .style(s)
608                    .range(1.0, 1.0)
609                    .target(f64::NAN),
610                1,
611                1,
612            );
613            run(Gauge::new(5.0).style(s).label("long label"), 3, 2);
614            run(Gauge::new(5.0).style(s), 0, 0);
615        }
616    }
617
618    #[test]
619    fn every_style_renders_at_every_size() {
620        for s in GaugeStyle::ALL {
621            for (w, h) in [(0, 0), (1, 1), (3, 2), (8, 3), (22, 7), (40, 12)] {
622                for v in [f64::NAN, -5.0, 0.0, 50.0, 100.0, 1e9] {
623                    run(Gauge::new(v).style(s).block(Block::bordered()), w, h);
624                    run(
625                        Gauge::new(v)
626                            .style(s)
627                            .label("x")
628                            .bands([(50.0, Color::Green), (100.0, Color::Red)]),
629                        w,
630                        h,
631                    );
632                }
633            }
634            run(Gauge::new(5.0).style(s).range(3.0, 3.0), 20, 8);
635        }
636    }
637
638    #[test]
639    fn new_styles_draw_and_react_to_value() {
640        let lit = |b: &Buffer| {
641            b.content()
642                .iter()
643                .map(|c| (c.symbol().to_string(), c.fg))
644                .collect::<Vec<_>>()
645        };
646        for s in GaugeStyle::ALL.iter().skip(4) {
647            let (w, h) = s.preferred_size();
648            let (w, h) = (w.max(12), h.max(3));
649            let lo = run(Gauge::new(10.0).style(*s).color(Color::Red), w, h);
650            let hi = run(Gauge::new(90.0).style(*s).color(Color::Red), w, h);
651            assert!(
652                lo.content().iter().any(|c| c.symbol() != " "),
653                "{s:?} blank"
654            );
655            assert_ne!(lit(&lo), lit(&hi), "{s:?} ignores value");
656        }
657    }
658
659    #[test]
660    fn bands_color_new_styles() {
661        let b = run(
662            Gauge::new(95.0)
663                .style(GaugeStyle::Led)
664                .bands([(50.0, Color::Green), (100.0, Color::Red)]),
665            30,
666            1,
667        );
668        assert!(b.content().iter().any(|c| c.fg == Color::Red));
669    }
670}