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
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright (C) 2020 Tobias Hunger <tobias.hunger@gmail.com>

//! Progress reporting code

// ----------------------------------------------------------------------
// - Types:
// ----------------------------------------------------------------------

/// A Progress reporter to use for the `Download`
pub type Progress = std::sync::Arc<dyn Reporter>;

// ----------------------------------------------------------------------
// - Traits:
// ----------------------------------------------------------------------

/// An interface for `ProgressReporter`s
pub trait Reporter: Send + Sync {
    /// Setup a TUI element for the next progress
    fn setup(&self, max_progress: Option<u64>, message: &str);
    /// Report progress
    fn progress(&self, current: u64);
    /// Report progress
    fn set_message(&self, message: &str);
    /// Finish up after progress reporting is done
    fn done(&self);
}

/// A `Factory` used to create `Reporter` when a Download does
/// not come with a defined way to report progress already.
pub trait Factory {
    /// Create an `Reporter`
    fn create_reporter(&self) -> crate::Progress;

    /// Wait for all progresses to finish
    fn join(&self);
}

// ----------------------------------------------------------------------
// - Noop:
// ----------------------------------------------------------------------

/// Do not print anything
#[derive(Default)]
pub struct Noop {}

impl Reporter for Noop {
    fn setup(&self, _: Option<u64>, _: &str) {}

    fn progress(&self, _: u64) {}

    fn set_message(&self, _: &str) {}

    fn done(&self) {}
}

impl Noop {
    /// Create a `Noop` `Reporter`.
    #[must_use]
    pub fn create() -> crate::Progress {
        std::sync::Arc::new(Self {})
    }
}

impl Factory for Noop {
    fn create_reporter(&self) -> crate::Progress {
        Self::create()
    }

    fn join(&self) {}
}

// ----------------------------------------------------------------------
// - TUI:
// ----------------------------------------------------------------------

#[cfg(feature = "tui")]
mod tui {
    /// Manage multiple progress reporters combined into one set of progress bars
    pub struct Tui {
        progress_group: indicatif::MultiProgress,
    }

    impl Default for Tui {
        fn default() -> Self {
            Self {
                progress_group: indicatif::MultiProgress::with_draw_target(
                    indicatif::ProgressDrawTarget::stderr_with_hz(4),
                ),
            }
        }
    }

    impl super::Factory for Tui {
        /// Create a `Reporter` connected to this set of UI primitives.
        fn create_reporter(&self) -> crate::Progress {
            std::sync::Arc::new(TuiBar {
                progress_bar: std::sync::Mutex::new(
                    self.progress_group.add(indicatif::ProgressBar::new(1)),
                ),
            })
        }

        /// Wait for all progresses to finish
        fn join(&self) {
            self.progress_group
                .join()
                .expect("No ui if this fails, which is OK for us");
        }
    }

    struct TuiBar {
        progress_bar: std::sync::Mutex<indicatif::ProgressBar>,
    }

    impl super::Reporter for TuiBar {
        fn setup(&self, max_progress: Option<u64>, message: &str) {
            let lock = self.progress_bar.lock().unwrap();
            if let Some(t) = max_progress {
                lock.set_length(t);
                lock.set_style(indicatif::ProgressStyle::default_bar()
                .template("[{bar:20.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta}) - {msg}")
                .progress_chars("#- "));
                lock.set_message(message);
                lock.reset_eta();
            } else {
                lock.set_style(
                    indicatif::ProgressStyle::default_spinner()
                        // For more spinners check out the cli-spinners project:
                        // https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json
                        .tick_strings(&[
                            "▹▹▹▹▹",
                            "▸▹▹▹▹",
                            "▹▸▹▹▹",
                            "▹▹▸▹▹",
                            "▹▹▹▸▹",
                            "▹▹▹▹▸",
                            "▪▪▪▪▪",
                        ])
                        .template("{spinner:.blue} {msg}"),
                );
                lock.set_message(message)
            };
        }

        fn progress(&self, current: u64) {
            let lock = self.progress_bar.lock().unwrap();
            lock.set_position(current);
        }

        fn set_message(&self, message: &str) {
            let lock = self.progress_bar.lock().unwrap();
            lock.set_message(message);
        }

        fn done(&self) {
            let lock = self.progress_bar.lock().unwrap();
            lock.finish();
        }
    }
}

#[cfg(feature = "tui")]
pub use tui::Tui;