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: 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)
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 gradient currently attached (if any).
136    pub fn gradient(&self) -> Option<Gradient> {
137        self.gradient
138    }
139
140    /// Borrow the underlying [`indicatif::ProgressBar`] for advanced use.
141    pub fn inner(&self) -> &ProgressBar {
142        &self.pb
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn with_total_bytes_defaults_to_main_and_ocean() {
152        let bar = GradientProgressBar::with_total_bytes(1024, "test");
153        assert_eq!(bar.style(), BarStyle::Main);
154        assert_eq!(bar.gradient(), Some(Gradient::Ocean));
155    }
156
157    #[test]
158    fn with_total_steps_defaults_to_steps_and_ocean() {
159        let bar = GradientProgressBar::with_total_steps(100, "test");
160        assert_eq!(bar.style(), BarStyle::Steps);
161        assert_eq!(bar.gradient(), Some(Gradient::Ocean));
162    }
163
164    #[test]
165    fn new_spinner_uses_spinner_style_no_gradient() {
166        let bar = GradientProgressBar::new_spinner("test");
167        assert_eq!(bar.style(), BarStyle::Spinner);
168        assert_eq!(bar.gradient(), None);
169        assert_eq!(bar.inner().length(), Some(u64::MAX));
170    }
171
172    #[test]
173    fn with_gradient_uses_main_style() {
174        let bar = GradientProgressBar::with_gradient(500, "test", Gradient::Ember);
175        assert_eq!(bar.style(), BarStyle::Main);
176        assert_eq!(bar.gradient(), Some(Gradient::Ember));
177    }
178
179    #[test]
180    fn with_wide_bar_no_gradient() {
181        let bar = GradientProgressBar::with_wide_bar(500, "test");
182        assert_eq!(bar.style(), BarStyle::Main);
183        assert_eq!(bar.gradient(), None);
184    }
185
186    #[test]
187    fn new_sets_all_fields() {
188        let bar = GradientProgressBar::new(
189            200,
190            "custom".into(),
191            BarStyle::Minified,
192            Some(Gradient::Ice),
193        );
194        assert_eq!(bar.style(), BarStyle::Minified);
195        assert_eq!(bar.gradient(), Some(Gradient::Ice));
196    }
197
198    #[test]
199    fn all_methods_run_without_panic() {
200        let bar = GradientProgressBar::with_total_bytes(1000, "test");
201        bar.inc(100);
202        bar.update(500);
203        bar.set_length(2000);
204        bar.inc_length(500);
205        bar.set_message("new msg");
206        bar.tick();
207        bar.finish();
208    }
209
210    #[test]
211    fn spinner_methods_run_without_panic() {
212        let bar = GradientProgressBar::new_spinner("spinner");
213        bar.tick();
214        bar.tick();
215        bar.finish_with_message("done");
216    }
217
218    #[test]
219    fn finish_and_clear_runs_without_panic() {
220        let bar = GradientProgressBar::new(100, "clear".into(), BarStyle::ClearOnFinish, None);
221        bar.finish_and_clear();
222    }
223
224    #[test]
225    fn set_style_updates() {
226        let mut bar = GradientProgressBar::with_total_bytes(100, "test");
227        assert_eq!(bar.style(), BarStyle::Main);
228        bar.set_style(BarStyle::Minified);
229        assert_eq!(bar.style(), BarStyle::Minified);
230    }
231
232    #[test]
233    fn set_gradient_updates() {
234        let mut bar = GradientProgressBar::with_total_bytes(100, "test");
235        assert_eq!(bar.gradient(), Some(Gradient::Ocean));
236        bar.set_gradient(Some(Gradient::Violet));
237        assert_eq!(bar.gradient(), Some(Gradient::Violet));
238        bar.set_gradient(None);
239        assert_eq!(bar.gradient(), None);
240    }
241
242    #[test]
243    fn set_bar_width_clamps_to_minimum_one() {
244        let mut bar = GradientProgressBar::with_total_bytes(100, "test");
245        bar.set_bar_width(0);
246        assert_eq!(bar.bar_width, 1);
247        bar.set_bar_width(5);
248        assert_eq!(bar.bar_width, 5);
249    }
250
251    #[test]
252    fn clone_shares_state() {
253        let bar = GradientProgressBar::with_total_bytes(100, "test");
254        let bar2 = bar.clone();
255        bar.inc(10);
256        bar2.inc(10);
257        bar.finish();
258    }
259
260    #[test]
261    fn default_gradient_constant_is_ocean() {
262        assert_eq!(DEFAULT_GRADIENT, Gradient::Ocean);
263    }
264
265    #[test]
266    fn message_accepts_string_and_str() {
267        let bar1 = GradientProgressBar::with_total_bytes(10, String::from("owned"));
268        bar1.set_message("str ref");
269        bar1.finish();
270    }
271}