1 //! Module that provides functions to display progress bars for compressing and decompressing files.
4 sync::mpsc::{self, Receiver, Sender},
9 use indicatif::{ProgressBar, ProgressStyle};
11 /// Draw a ProgressBar using a function that checks periodically for the progress
13 draw_stop: Sender<()>,
14 clean_done: Receiver<()>,
15 display_handle: DisplayHandle,
18 /// Writes to this struct will be displayed on the progress bar or stdout depending on the
20 struct DisplayHandle {
22 sender: Sender<String>,
24 impl io::Write for DisplayHandle {
25 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
27 // Newline is the signal to flush
28 if matches!(buf.last(), Some(&b'\n')) {
35 fn flush(&mut self) -> io::Result<()> {
36 fn io_error<X>(_: X) -> io::Error {
37 io::Error::new(io::ErrorKind::Other, "failed to flush buffer")
40 .send(String::from_utf8(self.buf.drain(..).collect()).map_err(io_error)?)
46 /// Create a ProgressBar using a function that checks periodically for the progress
47 /// If precise is true, the total_input_size will be displayed as the total_bytes size
48 /// If ACCESSIBLE is set, this function returns None
49 pub fn new_accessible_aware(
50 total_input_size: u64,
52 current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>,
54 if *crate::cli::ACCESSIBLE.get().unwrap() {
57 Some(Self::new(total_input_size, precise, current_position_fn))
60 fn new(total_input_size: u64, precise: bool, current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>) -> Self {
61 let (draw_tx, draw_rx) = mpsc::channel();
62 let (clean_tx, clean_rx) = mpsc::channel();
63 let (msg_tx, msg_rx) = mpsc::channel();
65 thread::spawn(move || {
67 let mut t = String::new();
68 t += "{wide_msg} [{elapsed_precise}] ";
69 if precise && current_position_fn.is_some() {
70 t += "[{bar:.cyan/blue}] ";
72 t += "{spinner:.green} ";
74 if current_position_fn.is_some() {
78 t += "{total_bytes} ";
80 t += "({bytes_per_sec}, {eta}) {path}";
83 let bar = ProgressBar::new(total_input_size);
84 bar.set_style(ProgressStyle::default_bar().template(&template).progress_chars("#>-"));
86 while draw_rx.try_recv().is_err() {
87 if let Some(ref pos_fn) = current_position_fn {
88 bar.set_position(pos_fn());
92 if let Ok(msg) = msg_rx.try_recv() {
95 thread::sleep(Duration::from_millis(100));
98 let _ = clean_tx.send(());
103 clean_done: clean_rx,
104 display_handle: DisplayHandle {
111 pub(crate) fn display_handle(&mut self) -> &mut dyn io::Write {
112 &mut self.display_handle
115 impl Drop for Progress {
117 let _ = self.draw_stop.send(());
118 let _ = self.clean_done.recv();