Skip to main content

gradient_bar/
progress_bar.rs

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