use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Style;
use crate::widgets::{Block, Widget};
#[derive(Debug, Default, Clone)]
pub struct Gauge<'a> {
ratio: f64,
label: Option<String>,
block: Option<Block<'a>>,
style: Style,
gauge_style: Style,
}
impl<'a> Gauge<'a> {
pub fn default() -> Gauge<'a> {
Gauge {
ratio: 0.0,
label: None,
block: None,
style: Style::default(),
gauge_style: Style::default(),
}
}
pub fn ratio(mut self, ratio: f64) -> Gauge<'a> {
self.ratio = ratio.clamp(0.0, 1.0);
self
}
pub fn percent(mut self, percent: u16) -> Gauge<'a> {
self.ratio = (percent.min(100) as f64) / 100.0;
self
}
pub fn label<T: Into<String>>(mut self, label: T) -> Gauge<'a> {
self.label = Some(label.into());
self
}
pub fn block(mut self, block: Block<'a>) -> Gauge<'a> {
self.block = Some(block);
self
}
pub fn style(mut self, style: Style) -> Gauge<'a> {
self.style = style;
self
}
pub fn gauge_style(mut self, style: Style) -> Gauge<'a> {
self.gauge_style = style;
self
}
}
impl<'a> Widget for Gauge<'a> {
fn render(mut self, area: Rect, buf: &mut Buffer) {
let gauge_area = if let Some(block) = self.block.take() {
let inner = block.inner(area);
block.render(area, buf);
inner
} else {
area
};
if gauge_area.area() == 0 || gauge_area.height == 0 {
return;
}
buf.set_style(gauge_area, self.style);
let label = self
.label
.clone()
.unwrap_or_else(|| format!("{:.0}%", self.ratio * 100.0));
let filled_width = (gauge_area.width as f64 * self.ratio).round() as u16;
let y = gauge_area.y + gauge_area.height / 2;
for x in gauge_area.left()..gauge_area.right() {
let style = if x < gauge_area.left() + filled_width {
self.gauge_style
} else {
self.style
};
buf.get_mut(x, y).set_char(' ').set_style(style);
}
let label_x = gauge_area.x + gauge_area.width.saturating_sub(label.len() as u16) / 2;
buf.set_string(label_x, y, &label, self.style);
for (i, ch) in label.chars().enumerate() {
let x = label_x + i as u16;
if x < gauge_area.left() + filled_width {
buf.get_mut(x, y).set_char(ch).set_style(self.gauge_style);
}
}
}
}