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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use core::cell::RefCell;
use std::{io::Write, rc::Rc};

use crate::isbar::{IsBar, IsBarManagerInterface};
use crate::wrapper::BarWrapper;

/**
Manager for all current progress bars and text output.

This can be used, with the new_bar method and
the [`println!`] and [`print!`] (crate) macros
to display progress bars and even print while doing so

to display the bar, simply call `.print()`.
in adition, the bar will be automaticaly printed when using
the [`print!`] and [`println!`] macros.

Please note that you currently cannot use more than one bar type
in a manager. this may change in the future as it *is* kinda a problem,
but fixing it would have some tradeoffs

## Examples

simple bar

```rust
use std::thread;

use stati::BarManager;
use stati::prelude::*;

# fn main() {
let mut manager = BarManager::new();
let mut bar = manager.register_bar(stati::bars::SimpleBar::new("Working...".into(), ()));
for i in 0..=100 {
    bar.set_progress(i);
    manager.print();
    # #[allow(deprecated)]
    thread::sleep_ms(40);
}
# }
```

printing while using progress bar

```rust
use std::thread;

use stati::BarManager;
use stati::prelude::*;

# fn main() {
let mut manager = BarManager::new();
let mut bar = manager.register_bar(stati::bars::SimpleBar::new("Working...".into(), ()));
for i in 0..=100 {
    bar.set_progress(i);
    stati::println!(manager, "Progressed to {} in the first section", i);
    manager.print();
    # #[allow(deprecated)]
    thread::sleep_ms(40);
}
# }
```

# A note on ANSI controll charecters
The way that this uses these charecters to re-print bars is rather finicky,
and if you use ANSI text while using this, it probably will work, but could
also break and cause hard to debug errors.

## Thread Saftey
***n o***

[`print!`]: crate::print
[`println!`]: crate::print
*/
pub struct BarManager<'bar> {
    bars: Vec<Rc<RefCell<dyn IsBarManagerInterface + 'bar>>>,
    print_queue: Vec<String>,
    last_lines: usize,
}

impl<'bar> BarManager<'bar> {
    /// Creates a new [`BarManager`]
    pub fn new() -> Self {
        Self {
            bars: vec![],
            print_queue: vec![],
            last_lines: 0,
        }
    }

    /// Registers a progress bar with the bar manager, to be drawn with the manager.
    /// Returns what is effectively a reference to it, and when that refference is dropped or `.done()` is called,
    /// the bar is finished, and is completed according to `bar.close_method()`
    pub fn register_bar<B: 'bar + IsBar>(&mut self, bar: B) -> BarWrapper<B> {
        let wrapped = Rc::new(RefCell::new(bar));
        self.bars.push(wrapped.clone());
        wrapped.into()
    }

    // /// Formats the current progress bars, along with the text as messages
    // /// that have been printed in this time, to a string.
    // ///
    // /// this assumes that nothing has been written to stdout in the time since it was last called, and as such
    // /// you should not use `std::println!` or `std::print!` with this, and instead `stati::println!` or `stati::print!`
    // /// 
    // /// # Panics
    // /// if it cannot borrow any of the contained bars
    // #[cfg(feature = "nightly")]
    // #[feature(drain_filter)]
    // #[must_use]
    // pub(crate) fn display(&mut self) -> String {
    //     let mut res = String::new();
    //     // ESC CSI n F (move to the start of the line n lines up)
    //     // (this is to overwrite previous bars)
    //     if self.last_lines != 0 {
    //         res += &format!("\x1b[{}F", self.last_lines);
    //     }
    //     // ESC CSI 0 J (clears from cursor to end of screen)
    //     res += "\x1b[0J";
    //     // print stuff
    //     for item in self.print_queue.drain(..) {
    //         res += &item;
    //     }
    //     // res += text;
    //     // go through all bars, removing ones that are done
    //     let _ = self.bars.drain_filter(|b| {
    //         let mut bref = b.borrow_mut();
    //         if bref.is_done() {
    //             match bref.close_method() {
    //                 crate::BarCloseMethod::Clear => {}
    //                 crate::BarCloseMethod::LeaveBehind => {
    //                     res += &bref.display();
    //                     res += "\n";
    //                 }
    //             }
    //             true
    //         } else {
    //             res += &bref.display();
    //             res += "\n";
    //             false
    //         }
    //     });
    //     self.last_lines = self.bars.len();
    //     res
    // }

    /// Formats the current progress bars, along with the text as messages
    /// that have been printed in this time, to a string.
    ///
    /// this assumes that nothing has been written to stdout in the time since it was last called, and as such
    /// you should not use `std::println!` or `std::print!` with this, and instead `stati::println!` or `stati::print!`
    /// 
    /// # Panics
    /// if it cannot borrow any of the contained bars
    #[must_use]
    pub(crate) fn display(&mut self) -> String {
        let mut res = String::new();
        // ESC CSI n F (move to the start of the line n lines up)
        // (this is to overwrite previous bars)
        if self.last_lines != 0 {
            res += &format!("\x1b[{}F", self.last_lines);
        }
        // ESC CSI 0 J (clears from cursor to end of screen)
        res += "\x1b[0J";
        // print stuff
        for item in self.print_queue.drain(..) {
            res += &item;
        }
        // res += text;
        // go through all bars, removing ones that are done
        let mut bar_filterer = |b: &mut Rc<RefCell<dyn IsBarManagerInterface>>| {
            let mut bref = b.borrow_mut();
            if bref.is_done() {
                match bref.close_method() {
                    crate::BarCloseMethod::Clear => {}
                    crate::BarCloseMethod::LeaveBehind => {
                        res += &bref.display();
                        res += "\n";
                    }
                }
                true
            } else {
                res += &bref.display();
                res += "\n";
                false
            }
        };
        let mut i = 0;
        while i < self.bars.len() {
            if bar_filterer(&mut self.bars[i]) {
                let _ = self.bars.remove(i);
            } else {
                i += 1;
            }
        }
        self.last_lines = self.bars.len();
        res
    }

    pub fn try_flush(&mut self) -> std::io::Result<()> {
        std::io::stdout().flush()?;
        Ok(())
    }

    /// Flushes updates to stdout.
    ///
    /// Currently this only flushes stdout, but will hopefully do more in the future
    ///
    /// # Panics
    /// if stdout cannot be flushed
    ///
    /// for a non-panicing alternative, see [`BarManager::try_flush`]
    pub fn flush(&mut self) {
        self.try_flush().unwrap();
    }

    /// Queues text to be printed before the bars. this should NOT be use
    /// directly, but should be used with the println! and print! macros
    ///
    /// this does NOT immediataly print the text
    pub fn queue_text(&mut self, text: &str) {
        self.print_queue.push(text.into());
    }

    /// Prints the bar status and any queued text to stdout, and flushes it.
    ///
    /// # Panics
    /// if stdout cannot be flushed
    ///
    /// for a non-panicing alternative, see [`BarManager::try_print`]
    pub fn print(&mut self) {
        self.try_print().unwrap();
    }

    pub fn try_print(&mut self) -> std::io::Result<()> {
        self.print_no_flush();
        self.try_flush()?;
        Ok(())
    }

    /// Prints the bar status and any queued text to stdout, without flushing it
    pub fn print_no_flush(&mut self) {
        std::print!("{}", self.display());
    }
}

impl<'bar> Default for BarManager<'bar> {
    fn default() -> Self {
        Self::new()
    }
}