1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum GaugeOrientation {
17 #[default]
19 Horizontal,
20 Vertical,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub enum GaugeStyle {
28 #[default]
30 Linear,
31 Bullet,
33 Arc,
36 Segmented,
38 Dial,
40 Meter,
42 Reticle,
44 Ring,
46 Chevron,
48 Smooth,
50 Dots,
52 Led,
54 Battery,
56 Level,
58 Thermometer,
60 Signal,
62}
63
64impl GaugeStyle {
65 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 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#[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 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 pub fn range(mut self, min: f64, max: f64) -> Self {
172 self.min = min;
173 self.max = max;
174 self
175 }
176 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 #[must_use]
185 pub fn zones(self) -> Self {
186 let (lo, hi) = (self.min, self.max);
187 let at = |f: f64| lo + (hi - lo) * f;
188 self.bands([
189 (at(0.6), Color::Green),
190 (at(0.85), Color::Yellow),
191 (hi, Color::Red),
192 ])
193 }
194 opt_setter!(
195 target: f64
197 );
198 pub fn label(mut self, l: impl Into<String>) -> Self {
200 self.label = Some(l.into());
201 self
202 }
203 setter!(
204 orientation: GaugeOrientation
206 );
207 setter!(
208 style: GaugeStyle
210 );
211 opt_setter!(
212 color: Color
214 );
215 theme_setter!(
216 theme
219 );
220 base_style_setter!(base);
221 fn fg(&self) -> Color {
222 self.theme.as_ref().map_or(Color::White, |t| t.foreground)
223 }
224 fn track(&self) -> Color {
225 self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid)
226 }
227 fn bar_color(&self) -> Color {
228 self.color
229 .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Green, |t| t.bull))
230 }
231 setter!(
232 marker: Marker
234 );
235
236 block_setter!(block, 'a);
237
238 fn frac(&self, v: f64) -> f64 {
239 let span = self.max - self.min;
240 if !v.is_finite() || !span.is_finite() || span <= 0.0 {
241 return 0.0;
242 }
243 ((v - self.min) / span).clamp(0.0, 1.0)
244 }
245
246 fn band_color(&self, f: f64) -> Color {
247 let v = self.min + f * (self.max - self.min);
248 self.bands
249 .iter()
250 .find(|b| v <= b.0)
251 .or(self.bands.last())
252 .map_or(self.bar_color(), |b| b.1)
253 }
254
255 fn dim(&self, f: f64) -> Color {
258 let base = if self.bands.is_empty() {
259 self.track()
260 } else {
261 self.band_color(f)
262 };
263 darken(base, if self.bands.is_empty() { 0.35 } else { 0.5 })
264 }
265
266 fn draw_label_at(&self, text: &str, cx: u16, y: u16, clip: Rect, buf: &mut Buffer) {
267 let n = text.chars().count().min(clip.width as usize) as u16;
268 let x0 = cx
269 .saturating_sub(n / 2)
270 .clamp(clip.x, clip.right().saturating_sub(n));
271 for (i, ch) in text.chars().take(n as usize).enumerate() {
272 if let Some(c) = buf.cell_mut((x0 + i as u16, y)) {
273 c.set_char(ch)
274 .set_fg(self.fg())
275 .set_style(Style::default().add_modifier(ratatui::style::Modifier::BOLD));
276 }
277 }
278 }
279
280 fn draw_label(&self, area: Rect, buf: &mut Buffer) {
281 let Some(l) = &self.label else { return };
282 self.draw_label_at(
283 l,
284 area.x + area.width / 2,
285 area.y + area.height / 2,
286 area,
287 buf,
288 );
289 }
290
291 fn draw_linear(&self, area: Rect, buf: &mut Buffer) {
292 let horiz = self.orientation == GaugeOrientation::Horizontal;
293 let (len, cross) = if horiz {
294 (area.width, area.height)
295 } else {
296 (area.height, area.width)
297 };
298 let bullet = self.style == GaugeStyle::Bullet;
299 let segmented = self.style == GaugeStyle::Segmented;
300 let vf = self.frac(self.value);
301 let eighths = (vf * len as f64 * 8.0).round() as i64;
302 let (c0, c1) = if bullet && cross >= 3 {
303 (cross / 3, cross - cross / 3)
304 } else if bullet {
305 (cross / 2, cross / 2 + 1)
306 } else {
307 (0, cross)
308 };
309 let tpos = self
310 .target
311 .map(|t| ((self.frac(t) * len as f64).floor() as u16).min(len.saturating_sub(1)));
312 let seg = if horiz { 2 } else { 1 };
314 let nseg = ((len as usize + 1) / (seg + 1)).max(1);
315 for i in 0..len {
316 let f = (i as f64 + 0.5) / len as f64;
317 let bc = self.band_color(f);
318 let track = self.dim(f);
319 let rem = eighths - i as i64 * 8;
320 for c in 0..cross {
321 let (x, y) = if horiz {
322 (area.x + i, area.y + c)
323 } else {
324 (area.x + c, area.y + area.height - 1 - i)
325 };
326 let Some(cell) = buf.cell_mut((x, y)) else {
327 continue;
328 };
329 if segmented {
330 let slot = i as usize % (seg + 1);
331 if slot == seg {
332 continue; }
334 let idx = i as usize / (seg + 1);
335 let sf = (idx as f64 + 0.5) / nseg as f64;
336 let lit = sf <= vf || (idx == 0 && vf > 0.0);
337 let col = if lit {
338 self.band_color(sf)
339 } else {
340 self.dim(sf)
341 };
342 cell.set_char('█').set_fg(col);
343 continue;
344 }
345 let in_bar = c >= c0 && c < c1;
346 if tpos == Some(i) {
347 cell.set_char(if horiz { '┃' } else { '━' })
348 .set_fg(self.fg())
349 .set_bg(track);
350 } else if in_bar && rem >= 8 {
351 cell.set_char('█').set_fg(bc).set_bg(bc);
352 } else if in_bar && rem > 0 {
353 let k = (rem - 1) as usize;
354 let ch = if horiz {
355 ['▏', '▎', '▍', '▌', '▋', '▊', '▉'][k]
356 } else {
357 ['▁', '▂', '▃', '▄', '▅', '▆', '▇'][k]
358 };
359 cell.set_char(ch).set_fg(bc).set_bg(track);
360 } else {
361 cell.set_char(' ').set_bg(track);
363 }
364 }
365 }
366 if let (Some(_), true) = (tpos, segmented) {
367 if let Some(i) = tpos {
369 for c in 0..cross {
370 let (x, y) = if horiz {
371 (area.x + i, area.y + c)
372 } else {
373 (area.x + c, area.y + area.height - 1 - i)
374 };
375 if let Some(cell) = buf.cell_mut((x, y)) {
376 cell.set_char(if horiz { '┃' } else { '━' })
377 .set_fg(self.fg());
378 }
379 }
380 }
381 }
382 self.draw_label(area, buf);
383 }
384
385 fn draw_arc(&self, area: Rect, buf: &mut Buffer) {
386 let scale_row = area.height >= 3;
388 let canvas_area = if scale_row {
389 Rect::new(area.x, area.y, area.width, area.height - 1)
390 } else {
391 area
392 };
393 let mut cv = Canvas::new(canvas_area.width, canvas_area.height, self.marker);
394 let (pw, ph) = (cv.px_w(), cv.px_h());
395 let tick_len = if ph >= 12 { 3 } else { 0 };
397 let r = (((pw - 1) / 2 - tick_len).min(ph - 1 - tick_len)).max(1) as f64;
398 let thick = (r / 4.0).max(2.0);
399 let (cx, cy) = ((pw - 1) as f64 / 2.0, (ph - 1) as f64);
400 let vf = self.frac(self.value);
401 let mid = r - thick / 2.0;
402 let thumb = 1.6 / (std::f64::consts::PI * mid.max(1.0)); for py in 0..ph {
404 for px in 0..pw {
405 let (dx, dy) = (px as f64 - cx, cy - py as f64);
406 if dy < -0.5 {
407 continue;
408 }
409 let d = (dx * dx + dy * dy).sqrt();
410 if d > r || d < r - thick {
411 continue;
412 }
413 let f = 1.0 - dy.max(0.0).atan2(dx) / std::f64::consts::PI;
414 let col = if (f - vf).abs() <= thumb && vf > 0.0 && vf < 1.0 {
415 self.fg()
416 } else if f <= vf {
417 self.band_color(f)
418 } else {
419 self.dim(f)
420 };
421 cv.set(px, py, col);
422 }
423 }
424 let at = |f: f64, rad: f64| {
425 let a = std::f64::consts::PI * (1.0 - f);
426 (
427 (cx + rad * a.cos()).round() as i32,
428 (cy - rad * a.sin()).round() as i32,
429 )
430 };
431 if tick_len > 0 {
432 let tick = darken(self.fg(), 0.35);
433 for k in 0..=10 {
434 let f = k as f64 / 10.0;
435 let len = if k % 5 == 0 { tick_len as f64 } else { 1.0 };
436 let (a, b) = (at(f, r + 1.0), at(f, r + 1.0 + len));
437 cv.line(a.0, a.1, b.0, b.1, tick);
438 }
439 }
440 if let Some(t) = self.target {
441 let tf = self.frac(t);
442 let (a, b) = (at(tf, r - thick - 1.0), at(tf, r + 1.0 + tick_len as f64));
443 cv.line(a.0, a.1, b.0, b.1, self.fg());
444 }
445 let tip = at(vf, r - thick - 2.0);
447 cv.line(cx.round() as i32, cy as i32, tip.0, tip.1, self.fg());
448 let hub = 2;
449 for dy in -hub..=hub {
450 for dx in -hub..=hub {
451 if dx * dx + dy * dy <= hub * hub {
452 cv.set(cx.round() as i32 + dx, cy as i32 + dy, self.fg());
453 }
454 }
455 }
456 cv.render(buf, canvas_area);
457 if scale_row {
458 let y = area.bottom() - 1;
459 let (rx, _) = self.marker.resolution();
460 let cell_of = |dot: f64| canvas_area.x + (dot / rx as f64).floor().max(0.0) as u16;
461 self.draw_label_at(&format_compact(self.min), cell_of(cx - mid), y, area, buf);
462 self.draw_label_at(&format_compact(self.max), cell_of(cx + mid), y, area, buf);
463 let center = self
464 .label
465 .clone()
466 .unwrap_or_else(|| format_compact(self.value));
467 self.draw_label_at(¢er, area.x + area.width / 2, y, area, buf);
468 } else {
469 self.draw_label(area, buf);
470 }
471 }
472}
473
474impl Gauge<'_> {
475 fn render_into(&self, area: Rect, buf: &mut Buffer) {
476 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
477 if inner.width == 0 || inner.height == 0 {
478 return;
479 }
480 crate::interact::record_point(inner, 0, 0, || {
481 let f = crate::util::format_compact;
482 let frac = self.frac(self.value);
483 (
484 "gauge".to_string(),
485 vec![
486 format!("{} of {} .. {}", f(self.value), f(self.min), f(self.max)),
487 format!("{:.0}%", frac * 100.0),
488 ],
489 )
490 });
491 if let Some(look) = self.style.look() {
492 let frac = self.frac(self.value);
493 let span = self.max - self.min;
494 let bands = self
495 .bands
496 .iter()
497 .map(|(v, c)| (self.frac(*v), *c))
498 .filter(|_| span > 0.0)
499 .collect();
500 let readout = self
501 .label
502 .clone()
503 .unwrap_or_else(|| format!("{:.0}%", frac * 100.0));
504 crate::gauge_kit::Painter {
505 look,
506 frac,
507 readout,
508 label: None,
509 bands,
510 color: self.bar_color(),
511 track: self.track(),
512 fg: self.fg(),
513 }
514 .render(inner, buf);
515 return;
516 }
517 match self.style {
518 GaugeStyle::Arc => self.draw_arc(inner, buf),
519 _ => self.draw_linear(inner, buf),
520 }
521 }
522}
523
524widget_impls!(Gauge<'_>);
525
526#[cfg(feature = "theme")]
527impl<'a> tui_nuances::Themed for Gauge<'a> {
528 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
529 self.theme(theme)
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use ratatui::widgets::Widget;
537
538 fn run(g: Gauge, w: u16, h: u16) -> Buffer {
539 let a = Rect::new(0, 0, w, h);
540 let mut b = Buffer::empty(a);
541 g.render(a, &mut b);
542 b
543 }
544
545 #[test]
546 fn half_filled() {
547 let b = run(Gauge::new(50.0), 10, 1);
548 assert_eq!(b[(0, 0)].symbol(), "█");
549 assert_eq!(b[(4, 0)].symbol(), "█");
550 assert_eq!(b[(5, 0)].symbol(), " ");
551 assert_ne!(b[(5, 0)].bg, Color::Reset);
552 }
553
554 #[test]
555 fn bands_target_label() {
556 let g = Gauge::new(80.0)
557 .bands([(50.0, Color::Green), (100.0, Color::Red)])
558 .target(25.0)
559 .label("ab");
560 let b = run(g, 20, 3);
561 assert_eq!(b[(5, 0)].symbol(), "┃");
562 assert_eq!(b[(0, 0)].fg, Color::Green);
563 assert_eq!(b[(15, 0)].fg, Color::Red);
564 assert_eq!(b[(9, 1)].symbol(), "a");
565 }
566
567 #[test]
568 fn vertical_fills_from_bottom() {
569 let b = run(
570 Gauge::new(100.0).orientation(GaugeOrientation::Vertical),
571 2,
572 4,
573 );
574 assert_eq!(b[(0, 3)].symbol(), "█");
575 assert_eq!(b[(0, 0)].symbol(), "█");
576 let b = run(
577 Gauge::new(0.0).orientation(GaugeOrientation::Vertical),
578 2,
579 4,
580 );
581 assert_eq!(b[(0, 3)].symbol(), " ");
582 }
583
584 #[test]
585 fn segmented_lights_blocks_with_gaps() {
586 let b = run(Gauge::new(50.0).style(GaugeStyle::Segmented), 12, 1);
587 let s: String = (0..12).map(|x| b[(x, 0)].symbol().to_string()).collect();
588 assert_eq!(&s[..], "██ ██ ██ ██ ");
589 assert_ne!(b[(0, 0)].fg, b[(9, 0)].fg); }
591
592 #[test]
593 fn arc_shows_scale_and_value() {
594 let g = Gauge::new(42.0).style(GaugeStyle::Arc).range(0.0, 100.0);
595 let b = run(g, 40, 12);
596 let last: String = (0..40).map(|x| b[(x, 11)].symbol().to_string()).collect();
597 assert!(
598 last.contains('0') && last.contains("100") && last.contains("42"),
599 "{last:?}"
600 );
601 }
602
603 #[test]
604 fn bullet_and_arc_and_degenerate() {
605 let b = run(Gauge::new(60.0).style(GaugeStyle::Bullet), 10, 3);
606 assert_eq!(b[(0, 1)].symbol(), "█");
607 assert_eq!(b[(0, 0)].symbol(), " ");
608 assert_ne!(b[(0, 0)].bg, Color::Reset);
609 let b = run(Gauge::new(60.0).style(GaugeStyle::Arc).target(30.0), 20, 6);
610 assert!(b.content().iter().any(|c| c.symbol() != " "));
611 for s in [
612 GaugeStyle::Linear,
613 GaugeStyle::Bullet,
614 GaugeStyle::Arc,
615 GaugeStyle::Segmented,
616 ] {
617 run(
618 Gauge::new(f64::NAN)
619 .style(s)
620 .range(1.0, 1.0)
621 .target(f64::NAN),
622 1,
623 1,
624 );
625 run(Gauge::new(5.0).style(s).label("long label"), 3, 2);
626 run(Gauge::new(5.0).style(s), 0, 0);
627 }
628 }
629
630 #[test]
631 fn every_style_renders_at_every_size() {
632 for s in GaugeStyle::ALL {
633 for (w, h) in [(0, 0), (1, 1), (3, 2), (8, 3), (22, 7), (40, 12)] {
634 for v in [f64::NAN, -5.0, 0.0, 50.0, 100.0, 1e9] {
635 run(Gauge::new(v).style(s).block(Block::bordered()), w, h);
636 run(
637 Gauge::new(v)
638 .style(s)
639 .label("x")
640 .bands([(50.0, Color::Green), (100.0, Color::Red)]),
641 w,
642 h,
643 );
644 }
645 }
646 run(Gauge::new(5.0).style(s).range(3.0, 3.0), 20, 8);
647 }
648 }
649
650 #[test]
651 fn new_styles_draw_and_react_to_value() {
652 let lit = |b: &Buffer| {
653 b.content()
654 .iter()
655 .map(|c| (c.symbol().to_string(), c.fg))
656 .collect::<Vec<_>>()
657 };
658 for s in GaugeStyle::ALL.iter().skip(4) {
659 let (w, h) = s.preferred_size();
660 let (w, h) = (w.max(12), h.max(3));
661 let lo = run(Gauge::new(10.0).style(*s).color(Color::Red), w, h);
662 let hi = run(Gauge::new(90.0).style(*s).color(Color::Red), w, h);
663 assert!(
664 lo.content().iter().any(|c| c.symbol() != " "),
665 "{s:?} blank"
666 );
667 assert_ne!(lit(&lo), lit(&hi), "{s:?} ignores value");
668 }
669 }
670
671 #[test]
672 fn bands_color_new_styles() {
673 let b = run(
674 Gauge::new(95.0)
675 .style(GaugeStyle::Led)
676 .bands([(50.0, Color::Green), (100.0, Color::Red)]),
677 30,
678 1,
679 );
680 assert!(b.content().iter().any(|c| c.fg == Color::Red));
681 }
682}