1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! A log-friendly command-line progress bar.
//!
//! Many progress bar implementations update the progress report in place,
//! by going back and overwriting previous output. This allows for beautiful
//! progress displays, but becomes a problem when moving backwards is not
//! possible, for example when writing to a pipe. This crate's progress bar
//! never tries to modify what was printed before, so the output can be
//! piped directly to a log file.
//!
//! # Usage
//!
//! Add this to your Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! logbar = "0.1"
//! ```
//!
//! # Examples
//!
//!
//! This example creates a default progress bar for a ten-step process:
//! ```rust
//! let bar = logbar::ProgressBar::new(10);
//! // first step (10%) done
//! bar.inc(1);
//! // next three steps done
//! bar.inc(3);
//! // everything done
//! bar.finish();
//! ```
//!
//! We can also customise the style of the progress bar:
//! ```rust
//! let style = Style::default()
//!     .width(80) // 80 characters wide
//!     .labels(false) // no XX% labels
//!     .tick('↓').bar('-') // rendered as ↓---↓---↓ etc.
//!     .indicator('█') // indicating the progress with '█' characters
//! ;
//! let bar = logbar::ProgressBar::with_style(10, style);
//! bar.finish();
//! ```
//!
use std::{sync,cmp,default};
use std::default::Default;

static DEFAULT_WIDTH: usize = 50;
static DEFAULT_TICK: char = '|';
static DEFAULT_BAR: char = '=';
static DEFAULT_INDICATOR: char = '#';
static SEGMENTS: [usize; 4] = [10, 5, 4, 2];

/// Progress bar style
#[derive(Clone,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]
pub struct Style {
    width: usize,
    labels: bool,
    tick: char,
    bar: char,
    indicator: char,
}

impl Style {
    /// Default progress bar style
    ///
    /// # Example
    ///
    /// Create a progress bar, explicitly asking for the default style:
    /// ```rust
    /// let style = logbar::Style::new();
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    pub fn new() -> Self {
        Style::default()
    }

    /// Set the progress bar width in characters
    ///
    /// # Example
    ///
    /// Create a progress bar with a width of 80 characters:
    /// ```rust
    /// let style = logbar::Style::new().width(80);
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    pub fn width(mut self, width: usize) -> Self {
        self.width = width;
        self
    }

    /// Toggle progress bar labels of the form XX%
    ///
    /// # Example
    ///
    /// Create a progress bar without labels:
    /// ```rust
    /// let style = logbar::Style::new().labels(false);
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    pub fn labels(mut self, labels: bool) -> Self {
        self.labels = labels;
        self
    }

    /// Choose a "tick" character separating the progress bar segments
    ///
    /// # Example
    ///
    /// Create a progress bar with '↓' as tick character:
    /// ```rust
    /// let style = logbar::Style::new().tick('↓');
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    pub fn tick(mut self, tick: char) -> Self {
        self.tick = tick;
        self
    }

    /// Choose a character for the progress bar segments
    ///
    /// # Example
    ///
    /// Create a progress bar made out of '-' characters, separated
    /// by the default "tick" character.
    /// ```rust
    /// let style = logbar::Style::new().bar('-');
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    #[allow(clippy::blacklisted_name)]
    pub fn bar(mut self, bar: char) -> Self {
        self.bar = bar;
        self
    }

    /// Choose a progress indicator
    ///
    /// # Example
    ///
    /// Create a progress bar where the progress is indicated by the
    /// number of '█' characters.
    /// ```rust
    /// let style = logbar::Style::new().indicator('█');
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    pub fn indicator(mut self, indicator: char) -> Self {
        self.indicator = indicator;
        self
    }
}

impl default::Default for Style {
    /// Default progress bar style
    ///
    /// # Example
    ///
    /// Create a progress bar, explicitly asking for the default style:
    /// ```rust
    /// let style = logbar::Style::default();
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    fn default() -> Self {
        Style{
            width: DEFAULT_WIDTH,
            labels: true,
            tick: DEFAULT_TICK,
            bar: DEFAULT_BAR,
            indicator: DEFAULT_INDICATOR,
        }
    }
}

#[derive(Clone,Default,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]
struct Counter {
    count: usize,
    progress: usize,
    finished: bool,
}

/// A log-friendly progress bar
#[derive(Debug)]
pub struct ProgressBar {
    counter: sync::Arc<sync::Mutex<Counter>>,
    max_progress: usize,
    style: Style,
}

fn num_segments(width: usize) -> usize {
    for s in SEGMENTS.iter() {
        // the number of segments must divide the total width
        // and each segment must be large enough for labels
        if width % s == 0 && width/s  > 3 {
            return *s;
        }
    }
    1
}

fn draw_labels(width: usize, segments: usize) {
    debug_assert_eq!(width % segments, 0);
    eprint!("0% ");
    let seg_width = width/segments;
    for p in 1..=segments {
        for _ in 0..(seg_width-3) {
            eprint!(" ");
        }
        eprint!("{}%", p*100/segments)
    }
    eprintln!("")
}

fn draw_tickbar(style: &Style, segments: usize) {
    let width = style.width;
    debug_assert_eq!(width % segments, 0);
    eprint!("{}", style.tick);
    let seg_width = width/segments;
    for _ in 1..=segments {
        for _ in 0..(seg_width-1) {
            eprint!("{}", style.bar);
        }
        eprint!("{}", style.tick)
    }
    eprintln!("")
}

fn draw_bar(style: &Style) {
    let width = style.width;
    let segments = num_segments(width);
    if width > 3 && style.labels {
        draw_labels(width, segments)
    }
    if width > 1 {
        draw_tickbar(style, segments)
    }
    else if width == 1 {
        eprintln!("{}", style.tick)
    }
}

impl ProgressBar {
    /// Create a new progress bar with default style
    ///
    /// # Example
    ///
    /// ```rust
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::new(max_progress);
    /// ```
    pub fn new(max_progress: usize) -> Self {
        ProgressBar::with_style(max_progress, Style::default())
    }

    /// Create a new progress bar with custom style
    ///
    /// # Example
    ///
    /// Create a progress bar with a width of 80 characters:
    /// ```rust
    /// let style = logbar::Style::new().width(80);
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::with_style(max_progress, style);
    /// ```
    pub fn with_style(max_progress: usize, style: Style) -> Self {
        let counter = sync::Arc::new(sync::Mutex::new(Counter::default()));
        draw_bar(&style);
        ProgressBar{counter, max_progress, style}
    }

    /// Get the style of the current progress bar
    ///
    /// # Example
    ///
    /// ```rust
    /// let max_progress = 100;
    /// let bar = logbar::ProgressBar::new(max_progress);
    /// assert_eq!(bar.style(), &logbar::Style::default())
    /// ```
    pub fn style(&self) -> &Style {
        &self.style
    }

    /// Increment the progress
    ///
    /// This method increments the internal progress counter, up to the
    /// maximum defined during the construction of the progress bar. It
    /// then updates the progress display.
    ///
    /// # Example
    ///
    /// ```rust
    /// let max_progress = 50;
    /// let bar = logbar::ProgressBar::new(max_progress);
    /// bar.inc(10); // Increment progress to 10 out of 50.
    /// // The progress bar is at 20% now
    /// bar.inc(10); // Increment progress to 20 out of 50.
    /// // The progress bar is at 40% now
    /// bar.inc(100); // Increment progress to 50 out of 50.
    /// // The progress bar is at 100% now
    /// ```
    pub fn inc(&self, i: usize) {
        let new_progress = {
            let mut c = self.counter.lock().unwrap();
            let new_count = cmp::min(c.count + i, self.max_progress);
            let new_progress = new_count*self.style.width/self.max_progress;
            let diff = new_progress - c.progress;
            *c = Counter{count: new_count, progress: new_progress, finished: false};
            diff
        };
        for _ in 0..new_progress {
            eprint!("{}", self.style.indicator);
        }
    }

    /// Finish the progress bar
    ///
    /// This method sets the progress to 100% and moves to the next line
    /// after the progress bar
    ///
    /// # Example
    ///
    /// ```rust
    /// let max_progress = 50;
    /// let bar = logbar::ProgressBar::new(max_progress);
    /// bar.finish();
    /// // The progress bar is at 100% now
    /// ```
    pub fn finish(&self) {
        self.inc(self.max_progress);
        let mut c = self.counter.lock().unwrap();
        if !c.finished {
            eprintln!("");
            c.finished = true;
        }
    }

}

#[cfg(test)]
mod tests {
    use super::*;

    //TODO: capture stderr and check
    // for the time being, run
    // cargo test -- --nocapture --test_threads=1
    // and check the output manually

    #[test]
    fn construct() {
        eprintln!("");
        let max_progress = 1000;
        {
            let bar = ProgressBar::new(max_progress);
            assert_eq!(bar.style().width, DEFAULT_WIDTH);
        }

        {
            let width = 80;
            let mut style = Style::default();
            style.width = width;
            let bar = ProgressBar::with_style(max_progress, style);
            assert_eq!(bar.style().width, width);
        }

    }

    #[test]
    fn inc() {
        eprintln!("");
        let max_progress = 20;
        let ten_millis = std::time::Duration::from_millis(10);

        let bar = ProgressBar::new(max_progress);
        for _ in 0..max_progress {
            std::thread::sleep(ten_millis);
            bar.inc(1);
        }
        eprintln!("");

        let bar = ProgressBar::new(max_progress);
        bar.inc(2*max_progress);
        eprintln!("");

        let _bar = ProgressBar::new(max_progress);
        eprintln!("");
    }

    #[test]
    fn finish() {
        eprintln!("");
        let max_progress = 200;
        let bar = ProgressBar::new(max_progress);
        bar.finish();
    }

    #[test]
    fn abort() {
        eprintln!("");
        let max_progress = 200;
        let bar = ProgressBar::new(max_progress);
        bar.inc(50);
    }

    #[test]
    fn alt_styles() {
        eprintln!("");
        let max_progress = 200;
        eprintln!("indicator █:");
        let style = Style::new().indicator('█');
        let bar = ProgressBar::with_style(max_progress, style);
        bar.finish();

        eprintln!("\ntick ↓:");
        let style = Style::new().tick('↓');
        let bar = ProgressBar::with_style(max_progress, style);
        bar.finish();

        eprintln!("\nbar -:");
        let style = Style::new().bar('-');
        let bar = ProgressBar::with_style(max_progress, style);
        bar.finish();

        eprintln!("\nno labels:");
        let style = Style::new().labels(false);
        let bar = ProgressBar::with_style(max_progress, style);
        bar.finish();

        eprintln!("\nall of the above:");
        let style = Style::new().indicator('█').labels(false).tick('↓').bar('-');
        let bar = ProgressBar::with_style(max_progress, style);
        bar.finish();

        for w in 0..=20 {
            eprintln!("\nwidth {}:", w);
            let style = Style::new().width(w);
            let bar = ProgressBar::with_style(max_progress, style);
            bar.finish();
        }
        let w = 40;
        eprintln!("\nwidth {}:", w);
        let style = Style::new().width(w);
        let bar = ProgressBar::with_style(max_progress, style.clone());
        bar.finish();
    }
}