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
#![crate_name = "progress"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]

//! **progress** is meant to be a set of useful tools for showing program running
//! progress (as its name) and steps.
//!
//! Installation
//! ============
//!
//! Add the following lines to your `Cargo.toml` dependencies section, if you
//! use [Cargo](https://crates.io):
//!
//! ```
//! [dependencies]
//! progress = "0.1.0"
//! ```
//!
//! Usage
//! =====
//!
//! Please check documentations for each structs. Life is easy here :)
//!
//! Who create this
//! ===============
//!
//! - [Ying-Ruei Liang (KK)](https://github.com/TheKK)
//!
//! Contribution
//! ============
//!
//! I can't believe you would say that, but if you have any great idea or any
//! bug report, don't be hesitate! It would be more wonderful if someone wants
//! to write some code for this project!
//!
//! TODO list
//! =========
//!
//! - BarBuilder, so we can do some customization, e.g. change the symbols used
//! - Add more type of indicators, e.g. spinning symbol or nayn cat :3
//! - Color/styled text support (print!("{:<50}") will count unprintable text as
//! well, I have to solve it first)
//! - Make output format customizable, despite I have no idea how to achieve this
//! for now.
//!
//! License
//! =======
//!
//! MIT

use std::io::{self, Write};

extern crate terminal_size;
use terminal_size::{terminal_size, Width};

/// A builder that used for creating customize progress bar.
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// extern crate progress;
///
/// fn main() {
///     let mut bar = progress::BarBuilder::new()
///         .left_cap("<")
///         .right_cap(">")
///         .empty_symbol("-")
///         .filled_symbol("/")
///         .build();
///
///     bar.set_job_title("Meow...");
///
///     for i in 0..11 {
///         thread::sleep_ms(500);
///         bar.reach_percent(i * 10);
///     }
/// }
pub struct BarBuilder {
    _left_cap: Option<String>,
    _right_cap: Option<String>,
    _filled_symbol: Option<String>,
    _empty_symbol: Option<String>,
}

impl BarBuilder {
    /// Create a new progress bar builder.
    pub fn new() -> BarBuilder {
        BarBuilder {
            _left_cap: None,
            _right_cap: None,
            _filled_symbol: None,
            _empty_symbol: None,
        }
    }

    /// Set desired symbol used as left cap
    ///
    /// ```shell
    /// [=========-] 90%
    /// ^
    pub fn left_cap(&mut self, symbol: &str) -> &mut BarBuilder {
        self._left_cap = Some(symbol.to_string());

        self
    }

    /// Set desired symbol used as right cap
    ///
    /// ```shell
    /// [=========-] 90%
    ///            ^
    pub fn right_cap(&mut self, symbol: &str) -> &mut BarBuilder {
        self._right_cap = Some(symbol.to_string());

        self
    }

    /// Set desired symbol used as filled bar
    ///
    /// ```shell
    /// [=========-] 90%
    ///  ^^^^^^^^^
    pub fn filled_symbol(&mut self, symbol: &str) -> &mut BarBuilder {
        self._filled_symbol = Some(symbol.to_string());

        self
    }

    /// Set desired symbol used as empty bar
    ///
    /// ```shell
    /// [=========-] 90%
    ///           ^
    ///  ```
    pub fn empty_symbol(&mut self, symbol: &str) -> &mut BarBuilder {
        self._empty_symbol = Some(symbol.to_string());

        self
    }

    /// Build progress bar according to previous configurations.
    pub fn build(&mut self) -> Bar {
        // XXX Does `take()` appropriate way?
        Bar {
            _job_title: String::new(),
            _progress_percentage: 0,
            _left_cap: self._left_cap.take().unwrap_or(String::from("[")),
            _right_cap: self._right_cap.take().unwrap_or(String::from("]")),
            _filled_symbol: self._filled_symbol.take().unwrap_or(String::from("=")),
            _empty_symbol: self._empty_symbol.take().unwrap_or(String::from("-")),
        }
    }
}

/// Struct that used for presenting progress bar with plain texts.
///
/// It looks like:
///
/// ```shell
/// Doing something            [===-------] 70%
/// ```
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// extern crate progress;
///
/// fn main() {
///     let bar = progress::Bar::new();
///
///     bar.set_job_title("Working...");
///
///     for i in 0..11 {
///         thread::sleep_ms(100);
///         bar.reach_percent(i * 10);
///     }
/// }
pub struct Bar {
    _job_title: String,
    _progress_percentage: i32,
    _left_cap: String,
    _right_cap: String,
    _filled_symbol: String,
    _empty_symbol: String,
}

impl Bar {
    /// Create a new progress bar.
    pub fn new() -> Bar {
        Bar {
            _job_title: String::new(),
            _progress_percentage: 0,
            _left_cap: String::from("["),
            _right_cap: String::from("]"),
            _filled_symbol: String::from("="),
            _empty_symbol: String::from("-"),
        }
    }

    /// Reset progress percentage to zero and job title to empty string. Also
    /// prints "\n".
    pub fn jobs_done(&mut self) {
        self._job_title.clear();
        self._progress_percentage = 0;

        print!("\n");
    }

    /// Set text shown in progress bar.
    pub fn set_job_title(&mut self, new_title: &str) {
        self._job_title.clear();
        self._job_title.push_str(new_title);
        self._show_progress();
    }

    /// Put progress to given percentage.
    pub fn reach_percent(&mut self, percent: i32) {
        self._progress_percentage = percent;
        self._show_progress();
    }

    /// Increase progress with given percentage.
    pub fn add_percent(&mut self, progress: i32) {
        self._progress_percentage += progress;
        self._show_progress();
    }
}

impl Bar {
    fn _show_progress(&self) {
        let width = if let Some((Width(w), _)) = terminal_size() {
            w as i32
        } else {
            81 as i32
        };
        let overhead = self._progress_percentage / 100;
        let left_percentage = self._progress_percentage - overhead * 100;
        let bar_len = width - (50 + 5) - 2;
        let bar_finished_len = ((bar_len as f32) *
                                (left_percentage as f32 / 100.0)) as i32;
        let filled_symbol = if overhead & 0b1 == 0 {
            &self._filled_symbol
        } else {
            &self._empty_symbol
        };
        let empty_symbol = if overhead & 0b1 == 0 {
            &self._empty_symbol
        } else {
            &self._filled_symbol
        };

        io::stdout().flush().unwrap();
        print!("\r");

        print!("{:<50}", self._job_title);
        print!("{}", self._left_cap);
        for _ in 0..bar_finished_len {
            print!("{}", filled_symbol);
        }
        for _ in bar_finished_len..bar_len {
            print!("{}", empty_symbol);
        }
        print!("{}", self._right_cap);
        print!("{:>4}%", self._progress_percentage);
    }
}

/// Struct that used for presenting progress with plain texts.
///
/// It looks like:
///
/// ```shell
/// Doing something
/// ```
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// extern crate progress;
///
/// fn main() {
///     let mut text = progress::Text::new();
///
///     text.set_job_title("Drawing...");
///     thread::sleep_ms(1000);
///
///     text.set_job_title("Painting...");
///     thread::sleep_ms(1000);
///
///     text.set_job_title("Sleeping zzz");
///     thread::sleep_ms(1000);
///
///     text.set_job_title("Wait! Is that a nyan cat?");
///     thread::sleep_ms(1000);
///
///     text.set_job_title("This must be my dream zzzzzz");
///     thread::sleep_ms(1000);
///
///     text.jobs_done();
/// }
pub struct Text {
    _job_title: String,
}

impl Text {
    /// Create a new progress text.
    pub fn new() -> Text {
        Text {
            _job_title: String::new(),
        }
    }

    /// Set text shown in progress text.
    pub fn set_job_title(&mut self, new_title: &str) {
        self._job_title.clear();
        self._job_title.push_str(new_title);
        self._show_progress();
    }

    /// Tell progress::Text everything has been done. Also prints "\n".
    pub fn jobs_done(&self) {
        print!("\n");
    }
}

impl Text {
    fn _show_progress(& self) {
        io::stdout().flush().unwrap();
        print!("\r");
        // TODO How to handle extra text?
        print!("{:<81}", self._job_title);
    }
}

/// Struct that used for presenting progress with plain texts.
///
/// It looks like:
///
/// ```shell
/// * Doing something
/// / Doing another thing
/// ```
///
/// # Examples
///
/// ```
/// use std::thread;
///
/// extern crate progress;
///
/// fn main() {
///     let mut spinningCircle = progress::SpinningCircle::new();
///
///     spinningCircle.set_job_title("Writing boring and stupid homeworks");
///     for _ in 0..50 {
///         thread::sleep_ms(50);
///         spinningCircle.tick();
///     }
///     spinningCircle.jobs_done();
///
///     spinningCircle.set_job_title("Previewing boring and stupid subjects");
///     for _ in 0..50 {
///         thread::sleep_ms(50);
///         spinningCircle.tick();
///     }
///     spinningCircle.jobs_done();
///
///     spinningCircle.set_job_title("Learning and creating interesting programs");
///     for _ in 0..50 {
///         thread::sleep_ms(50);
///         spinningCircle.tick();
///     }
///     spinningCircle.jobs_done();
/// }
pub struct SpinningCircle {
    _job_title: String,
    _circle_symbols: Vec<char>,
    _finished_symbol: char,
    _tick_count: usize,
}

impl SpinningCircle {
    /// Create a new progress spinning circle.
    pub fn new() -> SpinningCircle {
        SpinningCircle {
            _job_title: String::new(),
            _circle_symbols: vec!['|', '/', '-', '\\'],
            _finished_symbol: '*',
            _tick_count: 0,
        }
    }

    /// Set text shown in progress spinning circle.
    pub fn set_job_title(&mut self, new_title: &str) {
        self._job_title.clear();
        self._job_title.push_str(new_title);
        self._show_progress();
    }

    /// Tell spinning circle to spin a bit.
    pub fn tick(&mut self) {
        self._tick_count += 1;
        self._show_progress();
    }

    /// Print finished symbol at the position spinning circle symbol used to be.
    /// And print "\n" to jump to next line.
    ///
    /// e.g.
    /// * Collection kitties
    pub fn jobs_done(& self) {
        self._show_finished();
    }
}

impl SpinningCircle {
    fn _print_symbol_and_texts(& self, symbol: &char) {
        io::stdout().flush().unwrap();
        print!("\r");
        print!("{}", symbol);
        // TODO How to handle extra text?
        print!(" {:<81}", self._job_title);
    }

    fn _show_progress(& self) {
        let circle_symbol: &char = self._circle_symbols.get(
            self._tick_count % self._circle_symbols.len()).unwrap();

        self._print_symbol_and_texts(circle_symbol);
    }

    fn _show_finished(& self) {
        self._print_symbol_and_texts(&self._finished_symbol);
        print!("\n");
    }
}