throbberous 0.1.4

An async-native CLI progress bar and throbber (spinner) library for Rust.
Documentation
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! throbberous
//!
//! An async-native CLI progress bar and throbber (spinner) library for Rust.
//!
//! # Example
//!
//! ```rust
//! use throbberous::{Throbber, Bar};
//! use tokio_test::block_on;
//!
//! block_on(async {
//!     // Regular progress bar
//!     let bar = Bar::new(100);
//!     for _i in 0..100 {
//!         bar.inc(1).await;
//!         tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
//!     }
//!     bar.finish().await;
//!
//!     // Indeterminate progress bar
//!     let loading = Bar::indeterminate("Working...");
//!     tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
//!     loading.finish().await;
//!
//!     // Spinner
//!     let throbber = Throbber::new();
//!     throbber.start().await;
//!     tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
//!     throbber.stop().await;
//! });
//! ```

use std::{io, sync::Arc, time::Duration};
use crossterm::{
    execute,
    style::{Color, Print, SetForegroundColor, ResetColor},
    terminal::{Clear, ClearType},
    cursor::MoveToColumn,
};
use tokio::{
    sync::{Mutex, Notify},
    task::{self, JoinHandle},
    time::sleep,
};

// --- Progress Bar Implementation ---

#[derive(Clone)]
pub struct BarConfig {
    pub colors: Option<Vec<Color>>, // None = no colors
    pub color_cycle_delay: u64,
    pub width: usize,
}

impl Default for BarConfig {
    fn default() -> Self {
        Self {
            colors: Some(vec![Color::Green, Color::Yellow, Color::Magenta, Color::Cyan]),
            color_cycle_delay: 600,
            width: 40,
        }
    }
}

impl BarConfig {
    /// Create a config with no colors (plain text only)
    pub fn no_colors() -> Self {
        Self {
            colors: None,
            color_cycle_delay: 600,
            width: 40,
        }
    }
}

#[derive(Clone, Copy)]
pub enum BarMode {
    Determinate { current: u64, total: u64 },
    Indeterminate { position: usize, direction: i8 }, // direction: 1 or -1
}

struct BarState {
    mode: BarMode,
    finished: bool,
    message: String,
    color_index: usize,
}

pub struct Bar {
    inner: Arc<Mutex<BarState>>,
    notify: Arc<Notify>,
    _draw_task: JoinHandle<()>,
    _animate_task: Option<JoinHandle<()>>,
}

impl Bar {
    /// Creates a new determinate progress bar with a known total
    pub fn new(total: u64) -> Self {
        Self::with_config(total, BarConfig::default())
    }

    /// Creates a new determinate progress bar with no colors
    pub fn new_plain(total: u64) -> Self {
        Self::with_config(total, BarConfig::no_colors())
    }

    /// Creates a new determinate progress bar with custom configuration
    pub fn with_config(total: u64, config: BarConfig) -> Self {
        let state = BarState {
            mode: BarMode::Determinate { current: 0, total },
            finished: false,
            message: String::new(),
            color_index: 0,
        };

        let inner = Arc::new(Mutex::new(state));
        let notify = Arc::new(Notify::new());
        
        let draw_task = Self::spawn_draw_task(inner.clone(), notify.clone(), config);

        Bar { 
            inner, 
            notify, 
            _draw_task: draw_task,
            _animate_task: None,
        }
    }

    /// Creates an indeterminate progress bar for unknown duration tasks
    pub fn indeterminate(message: impl Into<String>) -> Self {
        Self::indeterminate_with_config(message, BarConfig::default())
    }

    /// Creates an indeterminate progress bar with no colors
    pub fn indeterminate_plain(message: impl Into<String>) -> Self {
        Self::indeterminate_with_config(message, BarConfig::no_colors())
    }

    /// Creates an indeterminate progress bar with custom configuration
    pub fn indeterminate_with_config(message: impl Into<String>, config: BarConfig) -> Self {
        let state = BarState {
            mode: BarMode::Indeterminate { position: 0, direction: 1 },
            finished: false,
            message: message.into(),
            color_index: 0,
        };

        let inner = Arc::new(Mutex::new(state));
        let notify = Arc::new(Notify::new());
        
        let draw_task = Self::spawn_draw_task(inner.clone(), notify.clone(), config.clone());
        let animate_task = Self::spawn_indeterminate_task(inner.clone(), notify.clone(), config);

        Bar { 
            inner, 
            notify, 
            _draw_task: draw_task,
            _animate_task: Some(animate_task),
        }
    }

    fn spawn_draw_task(
        inner: Arc<Mutex<BarState>>, 
        notify: Arc<Notify>, 
        config: BarConfig
    ) -> JoinHandle<()> {
        task::spawn(async move {
            let mut stdout = io::stdout();
            
            loop {
                notify.notified().await;
                let mut state = inner.lock().await;
                
                if state.finished {
                    Self::draw_bar(&state, &config, &mut stdout);
                    println!();
                    break;
                }

                Self::draw_bar(&state, &config, &mut stdout);
                
                // Only cycle colors if colors are enabled
                if let Some(ref colors) = config.colors {
                    if !colors.is_empty() {
                        state.color_index = (state.color_index + 1) % colors.len();
                    }
                }
            }
        })
    }

    fn spawn_indeterminate_task(
        inner: Arc<Mutex<BarState>>, 
        notify: Arc<Notify>, 
        config: BarConfig
    ) -> JoinHandle<()> {
        task::spawn(async move {
            let bounce_width = config.width / 4; // Size of the moving block
            
            loop {
                sleep(Duration::from_millis(100)).await;
                
                let finished = {
                    let mut state = inner.lock().await;
                    if state.finished {
                        true
                    } else if let BarMode::Indeterminate { ref mut position, ref mut direction } = state.mode {
                        *position = (*position as i32 + *direction as i32) as usize;
                        
                        // Bounce off the edges
                        if *position >= config.width - bounce_width {
                            *direction = -1;
                            *position = config.width - bounce_width;
                        } else if *position == 0 {
                            *direction = 1;
                        }
                        false
                    } else {
                        true // Wrong mode, stop animating
                    }
                };
                
                if finished {
                    break;
                }
                
                notify.notify_one();
            }
        })
    }

    /// Increment the progress bar by the specified amount (determinate mode only)
    pub async fn inc(&self, delta: u64) {
        let mut state = self.inner.lock().await;
        if !state.finished {
            if let BarMode::Determinate { current, total } = &mut state.mode {
                *current = (*current + delta).min(*total);
                
                // Check if we need to update message and if finished - extract values first
                let progress = *current as f64 / *total as f64;
                let current_val = *current;
                let total_val = *total;
                let message_empty = state.message.is_empty();
                
                // Now we can safely update state without conflicting borrows
                if message_empty {
                    state.message = match progress {
                        p if p >= 1.0 => "Complete!".to_string(),
                        p if p >= 0.75 => "Almost there...".to_string(),
                        p if p >= 0.5 => "Halfway done".to_string(),
                        p if p >= 0.25 => "Quarter done".to_string(),
                        _ => "Working...".to_string(),
                    };
                }
                
                if current_val == total_val {
                    state.finished = true;
                }
            }
        }
        drop(state);
        self.notify.notify_one();
    }

    /// Set the current progress directly (determinate mode only)
    pub async fn set_position(&self, pos: u64) {
        let mut state = self.inner.lock().await;
        if !state.finished {
            if let BarMode::Determinate { current, total } = &mut state.mode {
                *current = pos.min(*total);
                
                // Check if we need to update message and if finished - extract values first
                let progress = *current as f64 / *total as f64;
                let current_val = *current;
                let total_val = *total;
                let message_empty = state.message.is_empty();
                
                // Now we can safely update state without conflicting borrows
                if message_empty {
                    state.message = match progress {
                        p if p >= 1.0 => "Complete!".to_string(),
                        p if p >= 0.75 => "Almost there...".to_string(),
                        p if p >= 0.5 => "Halfway done".to_string(),
                        p if p >= 0.25 => "Quarter done".to_string(),
                        _ => "Working...".to_string(),
                    };
                }
                
                if current_val == total_val {
                    state.finished = true;
                }
            }
        }
        drop(state);
        self.notify.notify_one();
    }

    /// Update the message displayed with the progress bar
    pub async fn set_message(&self, msg: impl Into<String>) {
        {
            let mut state = self.inner.lock().await;
            state.message = msg.into();
        }
        self.notify.notify_one();
    }

    /// Finish the progress bar
    pub async fn finish(&self) {
        {
            let mut state = self.inner.lock().await;
            // Set to 100% if determinate
            if let BarMode::Determinate { ref mut current, total } = state.mode {
                *current = total;
            }
            state.finished = true;
        }
        self.notify.notify_one();
    }

    /// Finish the progress bar with a custom message
    pub async fn finish_with_message(&self, msg: impl Into<String>) {
        {
            let mut state = self.inner.lock().await;
            // Set to 100% if determinate
            if let BarMode::Determinate { ref mut current, total } = state.mode {
                *current = total;
            }
            state.finished = true;
            state.message = msg.into();
        }
        self.notify.notify_one();
    }

    fn draw_bar(state: &BarState, config: &BarConfig, stdout: &mut io::Stdout) {
        let display = match state.mode {
            BarMode::Determinate { current, total } => {
                let progress = if total == 0 { 1.0 } else { (current as f64 / total as f64).min(1.0) };
                let filled_len = (progress * config.width as f64).round() as usize;
                let percent = (progress * 100.0).round();
                
                format!(
                    "[{:=<filled$}{:width$}] {:.0}% {}", 
                    "", 
                    "", 
                    percent, 
                    state.message,
                    filled = filled_len,
                    width = config.width - filled_len
                )
            },
            BarMode::Indeterminate { position, .. } => {
                let bounce_width = config.width / 4;
                let mut bar = vec![' '; config.width];
                
                // Fill the bouncing section
                for i in position..=(position + bounce_width).min(config.width - 1) {
                    if i < config.width {
                        bar[i] = '=';
                    }
                }
                
                format!("[{}] {}", bar.iter().collect::<String>(), state.message)
            }
        };

        // Handle colors - if None, just print without colors
        if let Some(ref colors) = config.colors {
            let color = colors.get(state.color_index).unwrap_or(&Color::White);
            let _ = execute!(
                stdout,
                MoveToColumn(0),
                Clear(ClearType::CurrentLine),
                SetForegroundColor(*color),
                Print(&display),
                ResetColor,
            );
        } else {
            // No colors - just plain text
            let _ = execute!(
                stdout,
                MoveToColumn(0),
                Clear(ClearType::CurrentLine),
                Print(&display),
            );
        }
    }
}

// --- Throbber (Spinner) Implementation ---

#[derive(Clone)]
pub struct ThrobberConfig {
    pub frames: Vec<&'static str>,
    pub colors: Option<Vec<Color>>, // None = no colors
    pub frame_delay: u64,
}

impl Default for ThrobberConfig {
    fn default() -> Self {
        Self {
            frames: vec!["|", "/", "-", "\\"],
            colors: Some(vec![
                Color::Green, Color::Yellow, Color::Magenta, Color::Cyan,
                Color::Blue, Color::Red, Color::White, Color::DarkGrey,
            ]),
            frame_delay: 150,
        }
    }
}

impl ThrobberConfig {
    /// Create a config with no colors (plain text only)
    pub fn no_colors() -> Self {
        Self {
            frames: vec!["|", "/", "-", "\\"],
            colors: None,
            frame_delay: 150,
        }
    }
}

struct ThrobberState {
    frame_index: usize,
    color_index: usize,
    running: bool,
    message: String,
}

pub struct Throbber {
    inner: Arc<Mutex<ThrobberState>>,
    _draw_task: JoinHandle<()>,
    _animate_task: JoinHandle<()>,
}

impl Throbber {
    pub fn new() -> Self {
        Self::with_config(ThrobberConfig::default())
    }

    /// Create a new throbber with no colors
    pub fn new_plain() -> Self {
        Self::with_config(ThrobberConfig::no_colors())
    }

    pub fn with_config(config: ThrobberConfig) -> Self {
        let state = ThrobberState {
            frame_index: 0,
            color_index: 0,
            running: false,
            message: "Throbbing...".to_string(),
        };

        let inner = Arc::new(Mutex::new(state));
        let notify = Arc::new(Notify::new());
        
        let draw_task = Self::spawn_draw_task(inner.clone(), notify.clone(), config.clone());
        let animate_task = Self::spawn_animate_task(inner.clone(), notify, config);

        Throbber {
            inner,
            _draw_task: draw_task,
            _animate_task: animate_task,
        }
    }

    fn spawn_draw_task(
        inner: Arc<Mutex<ThrobberState>>, 
        notify: Arc<Notify>, 
        config: ThrobberConfig
    ) -> JoinHandle<()> {
        task::spawn(async move {
            let mut stdout = io::stdout();
            
            loop {
                notify.notified().await;
                let state = inner.lock().await;
                
                if !state.running {
                    let _ = execute!(stdout, MoveToColumn(0), Clear(ClearType::CurrentLine));
                    break;
                }
                
                Self::draw_frame(&state, &config, &mut stdout);
            }
        })
    }

    fn spawn_animate_task(
        inner: Arc<Mutex<ThrobberState>>, 
        notify: Arc<Notify>, 
        config: ThrobberConfig
    ) -> JoinHandle<()> {
        task::spawn(async move {
            loop {
                sleep(Duration::from_millis(config.frame_delay)).await;
                
                let running = {
                    let mut state = inner.lock().await;
                    if !state.running {
                        false
                    } else {
                        state.frame_index = (state.frame_index + 1) % config.frames.len();
                        
                        // Only cycle colors if colors are enabled
                        if let Some(ref colors) = config.colors {
                            if !colors.is_empty() {
                                state.color_index = (state.color_index + 1) % colors.len();
                            }
                        }
                        true
                    }
                };
                
                if !running {
                    break;
                }
                
                notify.notify_one();
            }
        })
    }

    pub async fn start(&self) {
        {
            let mut state = self.inner.lock().await;
            if !state.running {
                state.running = true;
                state.frame_index = 0;
                state.color_index = 0;
            }
        }
    }

    pub async fn stop(&self) {
        {
            let mut state = self.inner.lock().await;
            state.running = false;
        }
        println!("\nFinished");
    }

    pub async fn set_message(&self, msg: impl Into<String>) {
        {
            let mut state = self.inner.lock().await;
            state.message = msg.into();
        }
    }

    fn draw_frame(state: &ThrobberState, config: &ThrobberConfig, stdout: &mut io::Stdout) {
        let frame = config.frames[state.frame_index];
        let display = format!("{} {}", frame, state.message);

        // Handle colors - if None, just print without colors
        if let Some(ref colors) = config.colors {
            let color = colors.get(state.color_index).unwrap_or(&Color::White);
            let _ = execute!(
                stdout,
                MoveToColumn(0),
                Clear(ClearType::CurrentLine),
                SetForegroundColor(*color),
                Print(&display),
                ResetColor,
            );
        } else {
            // No colors - just plain text
            let _ = execute!(
                stdout,
                MoveToColumn(0),
                Clear(ClearType::CurrentLine),
                Print(&display),
            );
        }
    }
}