Skip to main content

itools_tui/components/
progress_bar.rs

1//! 进度条组件
2
3use crate::{layout::Rect, render::Frame, style::Style};
4
5/// 进度条组件
6pub struct ProgressBar {
7    /// 总进度
8    total: u64,
9    /// 当前进度
10    current: u64,
11    /// 进度条宽度
12    width: u16,
13    /// 进度条样式
14    style: Style,
15    /// 填充样式
16    filled_style: Style,
17}
18
19impl ProgressBar {
20    /// 创建新的进度条
21    pub fn new(total: u64, width: u16) -> Self {
22        Self { total, current: 0, width, style: Style::new(), filled_style: Style::new().reversed() }
23    }
24
25    /// 设置样式
26    pub fn style(mut self, style: Style) -> Self {
27        self.style = style;
28        self
29    }
30
31    /// 设置填充样式
32    pub fn filled_style(mut self, style: Style) -> Self {
33        self.filled_style = style;
34        self
35    }
36
37    /// 更新进度
38    pub fn update(&mut self, current: u64) {
39        self.current = current;
40    }
41
42    /// 增加进度
43    pub fn inc(&mut self, delta: u64) {
44        self.current += delta;
45    }
46
47    /// 完成进度
48    pub fn finish(&mut self) {
49        self.current = self.total;
50    }
51
52    /// 获取当前进度百分比
53    pub fn percentage(&self) -> f64 {
54        if self.total > 0 { (self.current as f64 / self.total as f64) * 100.0 } else { 0.0 }
55    }
56}
57
58impl super::Component for ProgressBar {
59    fn render(&self, frame: &mut Frame, area: Rect) {
60        frame.render_progress_bar(self.current, self.total, self.width, area, self.style.clone(), self.filled_style.clone());
61    }
62
63    fn handle_event(&mut self, _event: &crate::event::Event) -> bool {
64        false
65    }
66}