use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Style;
use crate::text::Line;
use crate::widgets::{Block, Widget};
#[derive(Debug, Default, Clone)]
pub struct LineGauge<'a> {
block: Option<Block<'a>>,
ratio: f64,
label: Option<Line<'a>>,
style: Style,
filled_style: Style,
filled_symbol: char,
unfilled_symbol: char,
}
impl<'a> LineGauge<'a> {
pub fn default() -> LineGauge<'a> {
LineGauge {
block: None,
ratio: 0.0,
label: None,
style: Style::default(),
filled_style: Style::default(),
filled_symbol: '─',
unfilled_symbol: '─',
}
}
pub fn ratio(mut self, ratio: f64) -> LineGauge<'a> {
self.ratio = ratio.clamp(0.0, 1.0);
self
}
pub fn label<T: Into<Line<'a>>>(mut self, label: T) -> LineGauge<'a> {
self.label = Some(label.into());
self
}
pub fn block(mut self, block: Block<'a>) -> LineGauge<'a> {
self.block = Some(block);
self
}
pub fn style(mut self, style: Style) -> LineGauge<'a> {
self.style = style;
self
}
pub fn filled_style(mut self, style: Style) -> LineGauge<'a> {
self.filled_style = style;
self
}
pub fn symbols(mut self, filled: char, unfilled: char) -> LineGauge<'a> {
self.filled_symbol = filled;
self.unfilled_symbol = unfilled;
self
}
}
impl<'a> Widget for LineGauge<'a> {
fn render(mut self, area: Rect, buf: &mut Buffer) {
let area = if let Some(block) = self.block.take() {
let inner = block.inner(area);
block.render(area, buf);
inner
} else {
area
};
if area.area() == 0 || area.height == 0 {
return;
}
buf.set_style(area, self.style);
let y = area.y;
let mut x = area.x;
if let Some(label) = &self.label {
for span in &label.spans {
x = buf.set_stringn(
x,
y,
&span.content,
area.right().saturating_sub(x) as usize,
span.style,
);
}
x += 1;
}
let track_width = area.right().saturating_sub(x);
let filled_width = (track_width as f64 * self.ratio).round() as u16;
for i in 0..track_width {
let cx = x + i;
if i < filled_width {
buf.get_mut(cx, y)
.set_char(self.filled_symbol)
.set_style(self.filled_style);
} else {
buf.get_mut(cx, y)
.set_char(self.unfilled_symbol)
.set_style(self.style);
}
}
}
}