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 use crate::accessible::is_running_in_accessible_mode;
13 /// Draw a ProgressBar using a function that checks periodically for the 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
22 struct DisplayHandle {
24 sender: Sender<String>,
26 impl io::Write for DisplayHandle {
27 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
29 // Newline is the signal to flush
30 if matches!(buf.last(), Some(&b'\n')) {
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")
42 .send(String::from_utf8(self.buf.drain(..).collect()).map_err(io_error)?)
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,
54 current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>,
56 if is_running_in_accessible_mode() {
59 Some(Self::new(total_input_size, precise, current_position_fn))
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 || {
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}] ";
74 t += "{spinner:.green} ";
76 if current_position_fn.is_some() {
80 t += "{total_bytes} ";
82 t += "({bytes_per_sec}, {eta}) {path}";
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());
94 if let Ok(msg) = msg_rx.try_recv() {
97 thread::sleep(Duration::from_millis(100));
100 let _ = clean_tx.send(());
105 clean_done: clean_rx,
106 display_handle: DisplayHandle {
113 pub(crate) fn display_handle(&mut self) -> &mut dyn io::Write {
114 &mut self.display_handle
117 impl Drop for Progress {
119 let _ = self.draw_stop.send(());
120 let _ = self.clean_done.recv();