Skip to main content

gradient_bar/
progress_bar.rs

1use crate::gradient::Gradient;
2use crate::style::BarStyle;
3use indicatif::ProgressBar;
4
5/// The default gradient used when creating a bar without specifying one.
6pub const DEFAULT_GRADIENT: Gradient = Gradient::Ocean;
7
8/// A self-contained wrapper around [`indicatif::ProgressBar`].
9///
10/// The underlying [`ProgressBar`] is `Clone` / `Send` / `Sync`, so an
11/// [`GradientProgressBar`] is too : share it across worker threads, pass it by
12/// reference, or keep several live at once.
13#[derive(Debug, Clone)]
14pub struct GradientProgressBar {
15    pb: ProgressBar,
16    style: BarStyle,
17    gradient: Option<Gradient>,
18    bar_width: usize,
19}
20
21impl GradientProgressBar {
22    /// Create a bar with a known total, an explicit layout and an explicit
23    /// style (gradient or not).
24    pub fn new(len: u64, msg: impl Into<String>, style: BarStyle, gradient: Option<Gradient>) -> Self {
25        let bar_width = BarStyle::DEFAULT_GRADIENT_WIDTH;
26        let pb = ProgressBar::new(len)
27            .with_message(msg.into())
28            .with_style(style.to_progress_style(gradient, bar_width));
29        Self {
30            pb,
31            style,
32            gradient,
33            bar_width,
34        }
35    }
36
37    /// Create a byte-based bar (the usual entry point) with the default
38    /// gradient ([`DEFAULT_GRADIENT`]).
39    pub fn with_total_bytes(total: u64, msg: impl Into<String>) -> Self {
40        Self::new(total, msg.into(), BarStyle::Main, Some(DEFAULT_GRADIENT))
41    }
42
43    /// Create a step/chunk based bar with the default gradient.
44    pub fn with_total_steps(total: u64, msg: impl Into<String>) -> Self {
45        Self::new(total, msg.into(), BarStyle::Steps, Some(DEFAULT_GRADIENT))
46    }
47
48    /// Create an indeterminate (unknown total) bar animated with a spinner.
49    pub fn new_spinner(msg: impl Into<String>) -> Self {
50        Self::new(u64::MAX, msg.into(), BarStyle::Spinner, None)
51    }
52
53    /// Create a byte-based bar with a specific [`Gradient`].
54    pub fn with_gradient(total: u64, msg: impl Into<String>, gradient: Gradient) -> Self {
55        Self::new(total, msg.into(), BarStyle::Main, Some(gradient))
56    }
57
58    /// Create a byte-based bar keeping the classic two-tone `wide_bar` (no
59    /// true-color gradient).
60    pub fn with_wide_bar(total: u64, msg: impl Into<String>) -> Self {
61        Self::new(total, msg.into(), BarStyle::Main, None)
62    }
63
64    /// Update the progress to an absolute *position*.
65    pub fn update(&self, position: u64) {
66        self.pb.set_position(position);
67    }
68
69    /// Advance the progress by `delta`.
70    pub fn inc(&self, delta: u64) {
71        self.pb.inc(delta);
72    }
73
74    /// Set a new total length.
75    pub fn set_length(&self, len: u64) {
76        self.pb.set_length(len);
77    }
78
79    /// Grow the total length by `delta`.
80    pub fn inc_length(&self, delta: u64) {
81        self.pb.inc_length(delta);
82    }
83
84    /// Change the message shown next to the bar.
85    pub fn set_message(&self, msg: impl Into<String>) {
86        self.pb.set_message(msg.into());
87    }
88
89    /// Advance an indeterminate bar by one "tick" (re-draws the spinner).
90    pub fn tick(&self) {
91        self.pb.tick();
92    }
93
94    /// Mark the bar as finished without clearing it.
95    pub fn finish(&self) {
96        self.pb.finish_using_style();
97    }
98
99    /// Mark the bar as finished, attaching a final summary message.
100    pub fn finish_with_message(&self, msg: impl Into<String>) {
101        self.pb.finish_with_message(msg.into());
102    }
103
104    /// Finish and remove the bar from the terminal entirely (pristine output).
105    pub fn finish_and_clear(&self) {
106        self.pb.finish_and_clear();
107    }
108
109    /// Swap the look & feel of an already-created bar.
110    pub fn set_style(&mut self, style: BarStyle) {
111        self.style = style;
112        self.pb
113            .set_style(style.to_progress_style(self.gradient, self.bar_width));
114    }
115
116    /// Change the gradient (or set `None` for the classic two-tone bar).
117    pub fn set_gradient(&mut self, gradient: Option<Gradient>) {
118        self.gradient = gradient;
119        self.pb
120            .set_style(self.style.to_progress_style(gradient, self.bar_width));
121    }
122
123    /// Set the number of columns the gradient bar occupies.
124    pub fn set_bar_width(&mut self, width: usize) {
125        self.bar_width = width.max(1);
126        self.pb
127            .set_style(self.style.to_progress_style(self.gradient, self.bar_width));
128    }
129
130    /// The current layout of this bar.
131    pub fn style(&self) -> BarStyle {
132        self.style
133    }
134
135    /// The current width of this bar
136    pub fn bar_width(&self) -> usize {
137        self.bar_width
138    } 
139
140    /// The gradient currently attached (if any).
141    pub fn gradient(&self) -> Option<Gradient> {
142        self.gradient
143    }
144
145    /// Borrow the underlying [`indicatif::ProgressBar`] for advanced use.
146    pub fn inner(&self) -> &ProgressBar {
147        &self.pb
148    }
149}
150
151#[cfg(test)]
152mod tests {
153
154use super::*;
155
156    #[test]
157    fn with_total_bytes_defaults_to_main_and_ocean() {
158        let bar = GradientProgressBar::with_total_bytes(1024, "test");
159        assert_eq!(bar.style(), BarStyle::Main);
160        assert_eq!(bar.gradient(), Some(Gradient::Ocean));
161    }
162
163    #[test]
164    fn with_total_steps_defaults_to_steps_and_ocean() {
165        let bar = GradientProgressBar::with_total_steps(100, "test");
166        assert_eq!(bar.style(), BarStyle::Steps);
167        assert_eq!(bar.gradient(), Some(Gradient::Ocean));
168    }
169
170    #[test]
171    fn new_spinner_uses_spinner_style_no_gradient() {
172        let bar = GradientProgressBar::new_spinner("test");
173        assert_eq!(bar.style(), BarStyle::Spinner);
174        assert_eq!(bar.gradient(), None);
175        assert_eq!(bar.inner().length(), Some(u64::MAX));
176    }
177
178    #[test]
179    fn with_gradient_uses_main_style() {
180        let bar = GradientProgressBar::with_gradient(500, "test", Gradient::Ember);
181        assert_eq!(bar.style(), BarStyle::Main);
182        assert_eq!(bar.gradient(), Some(Gradient::Ember));
183    }
184
185    #[test]
186    fn with_wide_bar_no_gradient() {
187        let bar = GradientProgressBar::with_wide_bar(500, "test");
188        assert_eq!(bar.style(), BarStyle::Main);
189        assert_eq!(bar.gradient(), None);
190    }
191
192    #[test]
193    fn new_sets_all_fields() {
194        let bar = GradientProgressBar::new(
195            200,
196            "custom",
197            BarStyle::Minified,
198            Some(Gradient::Ice),
199        );
200        assert_eq!(bar.style(), BarStyle::Minified);
201        assert_eq!(bar.gradient(), Some(Gradient::Ice));
202    }
203
204    #[test]
205    fn all_methods_run_without_panic() {
206        let bar = GradientProgressBar::with_total_bytes(1000, "test");
207        bar.inc(100);
208        bar.update(500);
209        bar.set_length(2000);
210        bar.inc_length(500);
211        bar.set_message("new msg");
212        bar.tick();
213        bar.finish();
214    }
215
216    #[test]
217    fn spinner_methods_run_without_panic() {
218        let bar = GradientProgressBar::new_spinner("spinner");
219        bar.tick();
220        bar.tick();
221        bar.finish_with_message("done");
222    }
223
224    #[test]
225    fn finish_and_clear_runs_without_panic() {
226        let bar = GradientProgressBar::new(100, "clear", BarStyle::ClearOnFinish, None);
227        bar.finish_and_clear();
228    }
229
230    #[test]
231    fn set_style_updates() {
232        let mut bar = GradientProgressBar::with_total_bytes(100, "test");
233        assert_eq!(bar.style(), BarStyle::Main);
234        bar.set_style(BarStyle::Minified);
235        assert_eq!(bar.style(), BarStyle::Minified);
236    }
237
238    #[test]
239    fn set_gradient_updates() {
240        let mut bar = GradientProgressBar::with_total_bytes(100, "test");
241        assert_eq!(bar.gradient(), Some(Gradient::Ocean));
242        bar.set_gradient(Some(Gradient::Violet));
243        assert_eq!(bar.gradient(), Some(Gradient::Violet));
244        bar.set_gradient(None);
245        assert_eq!(bar.gradient(), None);
246    }
247
248    #[test]
249    fn set_bar_width_clamps_to_minimum_one() {
250        let mut bar = GradientProgressBar::with_total_bytes(100, "test");
251        bar.set_bar_width(0);
252        assert_eq!(bar.bar_width, 1);
253        bar.set_bar_width(5);
254        assert_eq!(bar.bar_width, 5);
255    }
256
257    #[test]
258    fn clone_shares_state() {
259        let bar = GradientProgressBar::with_total_bytes(100, "test");
260        let bar2 = bar.clone();
261        bar.inc(10);
262        bar2.inc(10);
263        bar.finish();
264    }
265
266    #[test]
267    fn default_gradient_constant_is_ocean() {
268        assert_eq!(DEFAULT_GRADIENT, Gradient::Ocean);
269    }
270
271    #[test]
272    fn message_accepts_string_and_str() {
273        let bar1 = GradientProgressBar::with_total_bytes(10, String::from("owned"));
274        bar1.set_message("str ref");
275        bar1.finish();
276    }
277    
278    /*
279    use std::{thread, time::Duration};
280
281    #[test]
282    fn print_all_gradients_variants_for_inspection() {
283        let gradients = [Gradient::Rose, Gradient::Coral, Gradient::Twilight, Gradient::Midnight, Gradient::Aurora, Gradient::Forest, Gradient::Ice,
284        Gradient::Ember, Gradient::Mint, Gradient::Neon, Gradient::Ocean, Gradient::Sunset,
285        Gradient::Violet,];
286
287        // We iterate over all the disponible gradients
288        for gradient in gradients {
289            // For each gradient, create a `GradientProgressBar`
290            let pb = GradientProgressBar::with_gradient(1000, gradient.name(), gradient);
291
292            // And make the Pb progress
293            for _ in 0..1000 {
294                pb.inc(1);
295                thread::sleep(Duration::from_millis(2));
296            }
297
298            // This sleep is done so that you can observe the Pb.
299            thread::sleep(Duration::from_secs(3));
300        }
301    }
302    */
303
304}