Merge pull request #261 from ouch-org/refac/optimize-current-dir-call
[ouch.git] / src / progress.rs
blob5b318c9c1c4713475b9a367d7ae9b583beb5df76
1 //! Module that provides functions to display progress bars for compressing and decompressing files.
2 use std::{
3     io,
4     sync::mpsc::{self, Receiver, Sender},
5     thread,
6     time::Duration,
7 };
9 use indicatif::{ProgressBar, ProgressStyle};
11 use crate::accessible::is_running_in_accessible_mode;
13 /// Draw a ProgressBar using a function that checks periodically for the progress
14 pub struct Progress {
15     draw_stop: Sender<()>,
16     clean_done: Receiver<()>,
17     display_handle: DisplayHandle,
20 /// Writes to this struct will be displayed on the progress bar or stdout depending on the
21 /// ProgressBarPolicy
22 struct DisplayHandle {
23     buf: Vec<u8>,
24     sender: Sender<String>,
26 impl io::Write for DisplayHandle {
27     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
28         self.buf.extend(buf);
29         // Newline is the signal to flush
30         if matches!(buf.last(), Some(&b'\n')) {
31             self.buf.pop();
32             self.flush()?;
33         }
34         Ok(buf.len())
35     }
37     fn flush(&mut self) -> io::Result<()> {
38         fn io_error<X>(_: X) -> io::Error {
39             io::Error::new(io::ErrorKind::Other, "failed to flush buffer")
40         }
41         self.sender
42             .send(String::from_utf8(self.buf.drain(..).collect()).map_err(io_error)?)
43             .map_err(io_error)
44     }
47 impl Progress {
48     /// Create a ProgressBar using a function that checks periodically for the progress
49     /// If precise is true, the total_input_size will be displayed as the total_bytes size
50     /// If ACCESSIBLE is set, this function returns None
51     pub fn new_accessible_aware(
52         total_input_size: u64,
53         precise: bool,
54         current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>,
55     ) -> Option<Self> {
56         if is_running_in_accessible_mode() {
57             return None;
58         }
59         Some(Self::new(total_input_size, precise, current_position_fn))
60     }
62     fn new(total_input_size: u64, precise: bool, current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>) -> Self {
63         let (draw_tx, draw_rx) = mpsc::channel();
64         let (clean_tx, clean_rx) = mpsc::channel();
65         let (msg_tx, msg_rx) = mpsc::channel();
67         thread::spawn(move || {
68             let template = {
69                 let mut t = String::new();
70                 t += "{wide_msg} [{elapsed_precise}] ";
71                 if precise && current_position_fn.is_some() {
72                     t += "[{bar:.cyan/blue}] ";
73                 } else {
74                     t += "{spinner:.green} ";
75                 }
76                 if current_position_fn.is_some() {
77                     t += "{bytes}/ ";
78                 }
79                 if precise {
80                     t += "{total_bytes} ";
81                 }
82                 t += "({bytes_per_sec}, {eta}) {path}";
83                 t
84             };
85             let bar = ProgressBar::new(total_input_size);
86             bar.set_style(ProgressStyle::default_bar().template(&template).progress_chars("#>-"));
88             while draw_rx.try_recv().is_err() {
89                 if let Some(ref pos_fn) = current_position_fn {
90                     bar.set_position(pos_fn());
91                 } else {
92                     bar.tick();
93                 }
94                 if let Ok(msg) = msg_rx.try_recv() {
95                     bar.set_message(msg);
96                 }
97                 thread::sleep(Duration::from_millis(100));
98             }
99             bar.finish();
100             let _ = clean_tx.send(());
101         });
103         Progress {
104             draw_stop: draw_tx,
105             clean_done: clean_rx,
106             display_handle: DisplayHandle {
107                 buf: Vec::new(),
108                 sender: msg_tx,
109             },
110         }
111     }
113     pub(crate) fn display_handle(&mut self) -> &mut dyn io::Write {
114         &mut self.display_handle
115     }
117 impl Drop for Progress {
118     fn drop(&mut self) {
119         let _ = self.draw_stop.send(());
120         let _ = self.clean_done.recv();
121     }