use indicatif::{MultiProgress, ProgressBar, ProgressStyle, WeakProgressBar};
use std::io::IsTerminal;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex};
use std::time::Duration;
pub static MULTI_PROGRESS: LazyLock<MultiProgress> = LazyLock::new(MultiProgress::new);
const BAR_TEMPLATE: &str = "[{elapsed_precise}] {bar:40.cyan/blue} {pos}/{len} ({eta}) {msg}";
const SPINNER_TICKS: &str = "⠁⠂⠄⡀⢀⠠⠐⠈ ";
const STEADY_TICK: Duration = Duration::from_millis(200);
#[must_use]
pub fn new_progress_bar(len: u64) -> ProgressBar {
let prog_bar = MULTI_PROGRESS.add(ProgressBar::new(len));
prog_bar.set_style(
ProgressStyle::with_template(BAR_TEMPLATE)
.unwrap()
.progress_chars("##-"),
);
prog_bar.enable_steady_tick(STEADY_TICK);
lines::watch(&prog_bar);
prog_bar
}
#[must_use]
pub fn new_spinner(template: &str) -> ProgressBar {
let prog_bar = MULTI_PROGRESS.add(ProgressBar::new_spinner());
prog_bar.set_style(
ProgressStyle::with_template(template)
.unwrap()
.tick_chars(SPINNER_TICKS),
);
prog_bar.enable_steady_tick(STEADY_TICK);
lines::watch(&prog_bar);
prog_bar
}
pub const PREFIX: &str = "legume-progress ";
pub const EVERY: Duration = Duration::from_secs(15);
#[derive(Clone, Debug, PartialEq)]
struct Said {
id: u64,
label: String,
pos: u64,
len: Option<u64>,
elapsed_s: u64,
eta_s: Option<u64>,
done: bool,
}
impl Said {
fn of(id: u64, bar: &ProgressBar, done: bool) -> Self {
let len = bar.length();
Self {
id,
label: bar.message(),
pos: bar.position(),
len,
elapsed_s: bar.elapsed().as_secs(),
eta_s: len.map(|_| bar.eta().as_secs()),
done,
}
}
fn line(&self) -> String {
let opt = |v: Option<u64>| v.map_or("null".to_string(), |v| v.to_string());
format!(
"{PREFIX}{{\"id\":{},\"label\":{},\"pos\":{},\"len\":{},\"elapsed_s\":{},\"eta_s\":{},\"done\":{}}}",
self.id,
json_string(&self.label),
self.pos,
opt(self.len),
self.elapsed_s,
opt(self.eta_s),
self.done
)
}
}
fn json_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
mod lines {
use super::*;
struct Watched {
id: u64,
bar: WeakProgressBar,
said: Option<Said>,
}
static WATCHED: Mutex<Vec<Watched>> = Mutex::new(Vec::new());
static NEXT: AtomicU64 = AtomicU64::new(1);
fn every() -> Option<Duration> {
static EVERY_SET: LazyLock<Option<Duration>> = LazyLock::new(|| {
let every = match std::env::var("LEGUME_PROGRESS_EVERY") {
Ok(s) => s.trim().parse::<f64>().ok().map(Duration::from_secs_f64),
Err(_) => Some(EVERY),
};
every.filter(|d| !d.is_zero() && !std::io::stderr().is_terminal())
});
*EVERY_SET
}
pub(super) fn watch(bar: &ProgressBar) {
let Some(every) = every() else { return };
static THREAD: std::sync::Once = std::sync::Once::new();
THREAD.call_once(|| {
let spawned = std::thread::Builder::new()
.name("progress-lines".into())
.spawn(move || loop {
std::thread::sleep(every);
say();
});
if let Err(e) = spawned {
log::warn!("progress lines: {e}");
}
});
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner());
watched.push(Watched {
id,
bar: bar.downgrade(),
said: None,
});
}
pub(super) fn say() {
static ROUND: AtomicU64 = AtomicU64::new(0);
let round = ROUND.fetch_add(1, Ordering::Relaxed);
let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner());
watched.retain_mut(|w| {
let (now, keep) = match w.bar.upgrade() {
Some(bar) if bar.is_finished() => (Said::of(w.id, &bar, true), false),
Some(bar) => (Said::of(w.id, &bar, false), true),
None => match w.said.take() {
Some(last) => (Said { done: true, ..last }, false),
None => return false,
},
};
let moved = w.said.as_ref().is_none_or(|s| {
(s.pos, s.len, &s.label, s.done) != (now.pos, now.len, &now.label, now.done)
});
if moved || !keep || round % 4 == 3 {
eprintln!("{}", now.line());
}
w.said = Some(now);
keep
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_line_is_the_prefix_and_json() {
let said = Said {
id: 3,
label: "a \"b\"\\c".into(),
pos: 12,
len: Some(40),
elapsed_s: 31,
eta_s: Some(72),
done: false,
};
assert_eq!(
said.line(),
r#"legume-progress {"id":3,"label":"a \"b\"\\c","pos":12,"len":40,"elapsed_s":31,"eta_s":72,"done":false}"#
);
let spinner = Said {
len: None,
eta_s: None,
done: true,
label: String::new(),
..said
};
assert!(spinner
.line()
.ends_with(r#""len":null,"elapsed_s":31,"eta_s":null,"done":true}"#));
}
}