gradient_tui_fork/widgets/
gauge.rs

1use crate::{
2    buffer::Buffer,
3    layout::Rect,
4    style::{Color, Style},
5    symbols,
6    text::{Span, Spans},
7    widgets::{Block, Widget},
8};
9
10/// A widget to display a task progress.
11///
12/// # Examples:
13///
14/// ```
15/// # use tui::widgets::{Widget, Gauge, Block, Borders};
16/// # use tui::style::{Style, Color, Modifier};
17/// Gauge::default()
18///     .block(Block::default().borders(Borders::ALL).title("Progress"))
19///     .gauge_style(Style::default().fg(Color::White).bg(Color::Black).add_modifier(Modifier::ITALIC))
20///     .percent(20);
21/// ```
22#[derive(Debug, Clone)]
23pub struct Gauge<'a> {
24    block: Option<Block<'a>>,
25    ratio: f64,
26    label: Option<Span<'a>>,
27    use_unicode: bool,
28    style: Style,
29    gauge_style: Style,
30}
31
32impl<'a> Default for Gauge<'a> {
33    fn default() -> Gauge<'a> {
34        Gauge {
35            block: None,
36            ratio: 0.0,
37            label: None,
38            use_unicode: false,
39            style: Style::default(),
40            gauge_style: Style::default(),
41        }
42    }
43}
44
45impl<'a> Gauge<'a> {
46    pub fn block(mut self, block: Block<'a>) -> Gauge<'a> {
47        self.block = Some(block);
48        self
49    }
50
51    pub fn percent(mut self, percent: u16) -> Gauge<'a> {
52        assert!(
53            percent <= 100,
54            "Percentage should be between 0 and 100 inclusively."
55        );
56        self.ratio = f64::from(percent) / 100.0;
57        self
58    }
59
60    /// Sets ratio ([0.0, 1.0]) directly.
61    pub fn ratio(mut self, ratio: f64) -> Gauge<'a> {
62        assert!(
63            (0.0..=1.0).contains(&ratio),
64            "Ratio should be between 0 and 1 inclusively."
65        );
66        self.ratio = ratio;
67        self
68    }
69
70    pub fn label<T>(mut self, label: T) -> Gauge<'a>
71    where
72        T: Into<Span<'a>>,
73    {
74        self.label = Some(label.into());
75        self
76    }
77
78    pub fn style(mut self, style: Style) -> Gauge<'a> {
79        self.style = style;
80        self
81    }
82
83    pub fn gauge_style(mut self, style: Style) -> Gauge<'a> {
84        self.gauge_style = style;
85        self
86    }
87
88    pub fn use_unicode(mut self, unicode: bool) -> Gauge<'a> {
89        self.use_unicode = unicode;
90        self
91    }
92}
93
94impl<'a> Widget for Gauge<'a> {
95    fn render(mut self, area: Rect, buf: &mut Buffer) {
96        buf.set_style(area, self.style);
97        let gauge_area = match self.block.take() {
98            Some(b) => {
99                let inner_area = b.inner(area);
100                b.render(area, buf);
101                inner_area
102            }
103            None => area,
104        };
105        buf.set_style(gauge_area, self.gauge_style);
106        if gauge_area.height < 1 {
107            return;
108        }
109
110        // compute label value and its position
111        // label is put at the center of the gauge_area
112        let label = {
113            let pct = f64::round(self.ratio * 100.0);
114            self.label
115                .unwrap_or_else(|| Span::from(format!("{}%", pct)))
116        };
117        let clamped_label_width = gauge_area.width.min(label.width() as u16);
118        let label_col = gauge_area.left() + (gauge_area.width - clamped_label_width) / 2;
119        let label_row = gauge_area.top() + gauge_area.height / 2;
120
121        // the gauge will be filled proportionally to the ratio
122        let filled_width = f64::from(gauge_area.width) * self.ratio;
123        let end = if self.use_unicode {
124            gauge_area.left() + filled_width.floor() as u16
125        } else {
126            gauge_area.left() + filled_width.round() as u16
127        };
128        for y in gauge_area.top()..gauge_area.bottom() {
129            // render the filled area (left to end)
130            for x in gauge_area.left()..end {
131                // spaces are needed to apply the background styling
132                buf.get_mut(x, y)
133                    .set_symbol(" ")
134                    .set_fg(self.gauge_style.bg.unwrap_or(Color::Reset))
135                    .set_bg(self.gauge_style.fg.unwrap_or(Color::Reset));
136            }
137            if self.use_unicode && self.ratio < 1.0 {
138                buf.get_mut(end, y)
139                    .set_symbol(get_unicode_block(filled_width % 1.0));
140            }
141        }
142        // set the span
143        buf.set_span(label_col, label_row, &label, clamped_label_width);
144    }
145}
146
147fn get_unicode_block<'a>(frac: f64) -> &'a str {
148    match (frac * 8.0).round() as u16 {
149        1 => symbols::block::ONE_EIGHTH,
150        2 => symbols::block::ONE_QUARTER,
151        3 => symbols::block::THREE_EIGHTHS,
152        4 => symbols::block::HALF,
153        5 => symbols::block::FIVE_EIGHTHS,
154        6 => symbols::block::THREE_QUARTERS,
155        7 => symbols::block::SEVEN_EIGHTHS,
156        8 => symbols::block::FULL,
157        _ => " ",
158    }
159}
160
161/// A compact widget to display a task progress over a single line.
162///
163/// # Examples:
164///
165/// ```
166/// # use tui::widgets::{Widget, LineGauge, Block, Borders};
167/// # use tui::style::{Style, Color, Modifier};
168/// # use tui::symbols;
169/// LineGauge::default()
170///     .block(Block::default().borders(Borders::ALL).title("Progress"))
171///     .gauge_style(Style::default().fg(Color::White).bg(Color::Black).add_modifier(Modifier::BOLD))
172///     .line_set(symbols::line::THICK)
173///     .ratio(0.4);
174/// ```
175pub struct LineGauge<'a> {
176    block: Option<Block<'a>>,
177    ratio: f64,
178    label: Option<Spans<'a>>,
179    line_set: symbols::line::Set,
180    style: Style,
181    gauge_style: Style,
182}
183
184impl<'a> Default for LineGauge<'a> {
185    fn default() -> Self {
186        Self {
187            block: None,
188            ratio: 0.0,
189            label: None,
190            style: Style::default(),
191            line_set: symbols::line::NORMAL,
192            gauge_style: Style::default(),
193        }
194    }
195}
196
197impl<'a> LineGauge<'a> {
198    pub fn block(mut self, block: Block<'a>) -> Self {
199        self.block = Some(block);
200        self
201    }
202
203    pub fn ratio(mut self, ratio: f64) -> Self {
204        assert!(
205            (0.0..=1.0).contains(&ratio),
206            "Ratio should be between 0 and 1 inclusively."
207        );
208        self.ratio = ratio;
209        self
210    }
211
212    pub fn line_set(mut self, set: symbols::line::Set) -> Self {
213        self.line_set = set;
214        self
215    }
216
217    pub fn label<T>(mut self, label: T) -> Self
218    where
219        T: Into<Spans<'a>>,
220    {
221        self.label = Some(label.into());
222        self
223    }
224
225    pub fn style(mut self, style: Style) -> Self {
226        self.style = style;
227        self
228    }
229
230    pub fn gauge_style(mut self, style: Style) -> Self {
231        self.gauge_style = style;
232        self
233    }
234}
235
236impl<'a> Widget for LineGauge<'a> {
237    fn render(mut self, area: Rect, buf: &mut Buffer) {
238        buf.set_style(area, self.style);
239        let gauge_area = match self.block.take() {
240            Some(b) => {
241                let inner_area = b.inner(area);
242                b.render(area, buf);
243                inner_area
244            }
245            None => area,
246        };
247
248        if gauge_area.height < 1 {
249            return;
250        }
251
252        let ratio = self.ratio;
253        let label = self
254            .label
255            .unwrap_or_else(move || Spans::from(format!("{:.0}%", ratio * 100.0)));
256        let (col, row) = buf.set_spans(
257            gauge_area.left(),
258            gauge_area.top(),
259            &label,
260            gauge_area.width,
261        );
262        let start = col + 1;
263        if start >= gauge_area.right() {
264            return;
265        }
266
267        let end = start
268            + (f64::from(gauge_area.right().saturating_sub(start)) * self.ratio).floor() as u16;
269        for col in start..end {
270            buf.get_mut(col, row)
271                .set_symbol(self.line_set.horizontal)
272                .set_style(Style {
273                    fg: self.gauge_style.fg,
274                    bg: None,
275                    add_modifier: self.gauge_style.add_modifier,
276                    sub_modifier: self.gauge_style.sub_modifier,
277                });
278        }
279        for col in end..gauge_area.right() {
280            buf.get_mut(col, row)
281                .set_symbol(self.line_set.horizontal)
282                .set_style(Style {
283                    fg: self.gauge_style.bg,
284                    bg: None,
285                    add_modifier: self.gauge_style.add_modifier,
286                    sub_modifier: self.gauge_style.sub_modifier,
287                });
288        }
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    #[test]
297    #[should_panic]
298    fn gauge_invalid_percentage() {
299        Gauge::default().percent(110);
300    }
301
302    #[test]
303    #[should_panic]
304    fn gauge_invalid_ratio_upper_bound() {
305        Gauge::default().ratio(1.1);
306    }
307
308    #[test]
309    #[should_panic]
310    fn gauge_invalid_ratio_lower_bound() {
311        Gauge::default().ratio(-0.5);
312    }
313}