progress.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. extern crate pbr;
  2. use std::io::{stderr, Stderr};
  3. use std::time::Duration;
  4. use ffsend_api::reader::ProgressReporter;
  5. use self::pbr::{
  6. ProgressBar as Pbr,
  7. Units,
  8. };
  9. /// The refresh rate of the progress bar, in milliseconds.
  10. const PROGRESS_BAR_FPS_MILLIS: u64 = 200;
  11. /// A progress bar reporter.
  12. pub struct ProgressBar<'a> {
  13. progress_bar: Option<Pbr<Stderr>>,
  14. msg_progress: &'a str,
  15. msg_finish: &'a str,
  16. }
  17. impl<'a> ProgressBar<'a> {
  18. /// Construct a new progress bar, with the given messages.
  19. pub fn new(msg_progress: &'a str, msg_finish: &'a str) -> ProgressBar<'a> {
  20. Self {
  21. progress_bar: None,
  22. msg_progress,
  23. msg_finish,
  24. }
  25. }
  26. /// Construct a new progress bar for uploading.
  27. pub fn new_upload() -> ProgressBar<'a> {
  28. Self::new("Encrypt & Upload ", "Upload complete")
  29. }
  30. /// Construct a new progress bar for downloading.
  31. pub fn new_download() -> ProgressBar<'a> {
  32. Self::new("Download & Decrypt ", "Download complete")
  33. }
  34. }
  35. impl<'a> ProgressReporter for ProgressBar<'a> {
  36. /// Start the progress with the given total.
  37. fn start(&mut self, total: u64) {
  38. // Initialize the progress bar
  39. let mut progress_bar = Pbr::on(stderr(), total);
  40. progress_bar.set_max_refresh_rate(
  41. Some(Duration::from_millis(PROGRESS_BAR_FPS_MILLIS))
  42. );
  43. progress_bar.set_units(Units::Bytes);
  44. progress_bar.message(self.msg_progress);
  45. self.progress_bar = Some(progress_bar);
  46. }
  47. /// A progress update.
  48. fn progress(&mut self, progress: u64) {
  49. self.progress_bar.as_mut()
  50. .expect("progress bar not yet instantiated, cannot set progress")
  51. .set(progress);
  52. }
  53. /// Finish the progress.
  54. fn finish(&mut self) {
  55. self.progress_bar.as_mut()
  56. .expect("progress bar not yet instantiated")
  57. .finish_print(self.msg_finish);
  58. }
  59. }