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