use std::fmt::Display;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex, Once, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::display::{self, lock};
use crate::live::one_row;
use crate::output::{self, Val};
use crate::style::palette::{MUTED, RED, ROSE, SOFT, TEXT};
use crate::style::{Rgb, mix, paint};
use crate::widgets::{BarStyle, Spinner, shimmer};
use crate::{format, term, text};
struct Ticker {
line: Arc<Mutex<LineState>>,
stop: Arc<AtomicBool>,
fps: Arc<AtomicU32>,
thread: Option<JoinHandle<()>>,
prev_interrupt: Option<usize>,
}
#[derive(Default)]
struct LineState {
paused: u32,
logs: Vec<String>,
abandoned: bool,
}
const TAKE_OVER: &str = "\x1b[?25l\x1b[?7l";
const GIVE_BACK: &str = "\x1b[?7h\x1b[?25h";
impl Ticker {
fn start(frame: impl Fn(f64) -> String + Send + 'static) -> Ticker {
let prev_interrupt = term::guard_interrupt();
output::write(TAKE_OVER);
let line = Arc::new(Mutex::new(LineState::default()));
let stop = Arc::new(AtomicBool::new(false));
let fps = Arc::new(AtomicU32::new(0));
let (state, flag, rate) = (line.clone(), stop.clone(), fps.clone());
let thread = thread::spawn(move || {
let t0 = Instant::now();
while !flag.load(Ordering::Relaxed) {
{
let s = lock(&state);
if s.paused == 0 && !s.abandoned {
let line = frame(t0.elapsed().as_secs_f64());
output::write(&format!("\r{}\x1b[K", one_row(&line)));
}
}
thread::sleep(crate::fps::frame(rate.load(Ordering::Relaxed)));
}
});
display::add(Arc::downgrade(&line) as Weak<dyn display::Shown>);
Ticker {
line,
stop,
fps,
thread: Some(thread),
prev_interrupt,
}
}
fn finish(&mut self, last: &str) {
let Some(thread) = self.thread.take() else {
return;
};
self.stop.store(true, Ordering::Relaxed);
let _ = thread.join();
display::remove(Arc::as_ptr(&self.line));
let mut s = lock(&self.line);
if !s.abandoned {
let mut out: String = s.logs.drain(..).map(|l| format!("\r{l}\x1b[K\n")).collect();
out += &format!("\r{}\x1b[K\n{GIVE_BACK}", one_row(last));
output::write(&out);
}
drop(s);
term::restore_interrupt(self.prev_interrupt.take());
}
}
impl Drop for Ticker {
fn drop(&mut self) {
self.finish("");
}
}
impl display::Shown for Mutex<LineState> {
fn pause(&self) {
let mut s = lock(self);
if s.paused == 0 && !s.abandoned {
output::write(&format!("\r\x1b[K{GIVE_BACK}"));
}
s.paused += 1;
}
fn resume(&self) {
let mut s = lock(self);
s.paused -= 1;
if s.paused == 0 && !s.abandoned {
let logs: String = s.logs.drain(..).map(|l| format!("{l}\n")).collect();
output::write(&format!("{logs}{TAKE_OVER}"));
}
}
fn log(&self, lines: &[&str], patient: bool) -> bool {
let Some(mut s) = display::lock_if(self, patient) else {
return false;
};
if s.paused > 0 || s.abandoned {
s.logs.extend(lines.iter().map(|l| l.to_string()));
return true;
}
let text: String = lines.iter().map(|l| format!("\r\x1b[K{l}\n")).collect();
output::write(&format!("\x1b[?7h{text}\x1b[?7l"));
true
}
fn abandon(&self) {
if let Some(mut s) = display::lock_patiently(self) {
s.abandoned = true;
}
output::write(&format!("\n{GIVE_BACK}"));
}
}
fn finished_line(mark: &str, color: Rgb, label: &str, label_color: Rgb, time_color: Rgb, took: Duration) -> String {
let gutter = Spinner::default().width();
let (before, after) = ((gutter - 1) / 2, gutter - 1 - (gutter - 1) / 2);
let left = format!(
" {}{}{} {}",
" ".repeat(before),
paint(color, mark),
" ".repeat(after),
paint(label_color, label)
);
let took = format::duration(took);
let pad = term::content_width().saturating_sub(text::width(&left) + took.chars().count() + 2);
format!("{left}{}{}", " ".repeat(pad.max(2)), paint(time_color, &took))
}
fn done_line(label: &str, took: Duration) -> String {
finished_line("โ", ROSE, label, TEXT, MUTED, took)
}
pub fn spin<T>(label: &str, f: impl FnOnce() -> T) -> T {
match try_spin(label, || Ok::<T, std::convert::Infallible>(f())) {
Ok(v) => v,
Err(never) => match never {},
}
}
pub fn try_spin<T, E: Display>(label: &str, f: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
let spinning = Spinning::start(label);
let result = f();
spinning.end(result.as_ref().err().map(ToString::to_string));
result
}
struct Spinning<'a> {
label: &'a str,
start: Instant,
ticker: Option<Ticker>,
}
impl<'a> Spinning<'a> {
fn start(label: &'a str) -> Spinning<'a> {
let drawn = !output::json() && !output::quiet() && crate::display::animated();
let ticker = drawn.then(|| {
let owned = label.to_string();
Ticker::start(move |t| format!(" {} {}", Spinner::default().frame(t), shimmer(&owned, t)))
});
Spinning {
label,
start: Instant::now(),
ticker,
}
}
fn end(self, error: Option<String>) {
let (label, took) = (self.label, self.start.elapsed());
if output::json() {
let mut fields = vec![
("label", Val::Str(label)),
("outcome", Val::Str(if error.is_none() { "ok" } else { "fail" })),
("secs", Val::Num(took.as_secs_f64())),
];
if let Some(e) = &error {
fields.push(("error", Val::Str(e)));
}
return output::emit("task", &fields);
}
let Some(mut ticker) = self.ticker else {
let took = format::duration(took);
match error {
Some(e) => crate::output::err_line(&format!(" [FAIL] {label} ({took}) - {e}")),
None if !output::quiet() => output::line(&format!(" [ok] {label} ({took})")),
None => {}
}
return;
};
match error {
None => ticker.finish(&done_line(label, took)),
Some(e) => {
ticker.finish(&finished_line("โ", RED, label, RED, RED, took));
let indent = " ".repeat(2 + Spinner::default().width() + 2);
output::line(&format!("{indent}{}", paint(mix(RED, SOFT, 0.3), &e)));
}
}
}
}
struct Counts {
done: u64,
total: Option<u64>,
bytes: bool,
bar: BarStyle,
}
#[must_use = "a progress line finishes as soon as it's dropped"]
pub struct Progress {
counts: Arc<Mutex<Counts>>,
label: String,
start: Instant,
drawn: bool,
shown: Once,
ticker: Mutex<Option<Ticker>>,
fps: u32,
finished: bool,
}
impl std::fmt::Debug for Progress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c = lock(&self.counts);
f.debug_struct("Progress")
.field("label", &self.label)
.field("done", &c.done)
.field("total", &c.total)
.finish_non_exhaustive()
}
}
impl Progress {
pub fn new(label: impl Into<String>, total: u64) -> Self {
Progress::start(label.into(), Some(total))
}
pub fn unknown(label: impl Into<String>) -> Self {
Progress::start(label.into(), None)
}
fn start(label: String, total: Option<u64>) -> Self {
let counts = Arc::new(Mutex::new(Counts {
done: 0,
total,
bytes: false,
bar: BarStyle::default(),
}));
Progress {
counts,
label,
start: Instant::now(),
drawn: output::output() == output::Output::Pretty && crate::display::animated(),
shown: Once::new(),
ticker: Mutex::new(None),
fps: 0,
finished: false,
}
}
fn show(&self) {
if !self.drawn {
return;
}
self.shown.call_once(|| {
let (counts, label, start) = (self.counts.clone(), self.label.clone(), self.start);
let ticker = Ticker::start(move |t| progress_line(&label, &lock(&counts), start.elapsed(), t));
ticker.fps.store(self.fps, Ordering::Relaxed);
*lock(&self.ticker) = Some(ticker);
});
}
pub fn fps(mut self, fps: u32) -> Self {
self.fps = fps.clamp(1, 240);
if let Some(ticker) = lock(&self.ticker).as_ref() {
ticker.fps.store(self.fps, Ordering::Relaxed);
}
self
}
pub fn bytes(self) -> Self {
lock(&self.counts).bytes = true;
self
}
pub fn bar(self, bar: BarStyle) -> Self {
lock(&self.counts).bar = bar;
self
}
pub fn inc(&self, n: u64) {
{
let mut c = lock(&self.counts);
c.done += n;
if let Some(total) = c.total {
c.done = c.done.min(total);
}
}
self.show();
}
pub fn set(&self, n: u64) {
{
let mut c = lock(&self.counts);
c.done = c.total.map_or(n, |total| n.min(total));
}
self.show();
}
pub fn set_total(&self, total: u64) {
{
let mut c = lock(&self.counts);
c.total = Some(total);
c.done = c.done.min(total);
}
self.show();
}
pub fn add_total(&self, n: u64) {
{
let mut c = lock(&self.counts);
c.total = Some(c.total.unwrap_or(0) + n);
}
self.show();
}
pub fn finish(mut self) {
self.end(Ended::Done);
}
fn end(&mut self, ended: Ended) {
if std::mem::replace(&mut self.finished, true) {
return;
}
let took = self.start.elapsed();
self.show();
let label = one_row(&self.label);
if let Some(t) = lock(&self.ticker).as_mut() {
return t.finish(&match ended {
Ended::Done => done_line(&label, took),
Ended::Stopped => finished_line("โ", SOFT, &label, SOFT, MUTED, took),
Ended::Panicked => finished_line("โ", RED, &label, RED, RED, took),
});
}
if output::json() {
let c = lock(&self.counts);
let mut fields = vec![
("label", Val::Str(&self.label)),
("done", Val::Num(c.done as f64)),
("secs", Val::Num(took.as_secs_f64())),
];
if ended != Ended::Done {
fields.push(("outcome", Val::Str(ended.name())));
}
if let Some(total) = c.total {
fields.push(("total", Val::Num(total as f64)));
}
output::emit("progress", &fields);
} else if ended == Ended::Panicked {
output::err_line(&format!(" [FAIL] {label} ({})", format::duration(took)));
} else if !output::quiet() {
output::line(&format!(" [{}] {label} ({})", ended.name(), format::duration(took)));
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Ended {
Done,
Stopped,
Panicked,
}
impl Ended {
fn name(self) -> &'static str {
match self {
Ended::Done => "ok",
Ended::Stopped => "stopped",
Ended::Panicked => "fail",
}
}
}
impl Drop for Progress {
fn drop(&mut self) {
let short = {
let c = lock(&self.counts);
c.total.is_some_and(|total| c.done < total)
};
let ended = if thread::panicking() {
Ended::Panicked
} else if short {
Ended::Stopped
} else {
Ended::Done
};
self.end(ended);
}
}
pub trait ProgressIterator: Iterator + Sized {
fn progress(self, label: impl Into<String>) -> WithProgress<Self>;
}
impl<I: Iterator> ProgressIterator for I {
fn progress(self, label: impl Into<String>) -> WithProgress<Self> {
let total = match self.size_hint() {
(lo, Some(hi)) if lo == hi => Some(lo as u64),
_ => None,
};
WithProgress {
inner: self,
bar: Some(Progress::start(label.into(), total)),
}
}
}
#[must_use = "iterators do nothing until they're used, and the progress line finishes when dropped"]
pub struct WithProgress<I> {
inner: I,
bar: Option<Progress>,
}
impl<I: std::fmt::Debug> std::fmt::Debug for WithProgress<I> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WithProgress")
.field("inner", &self.inner)
.field("progress", &self.bar)
.finish()
}
}
impl<I> WithProgress<I> {
pub fn bar(self, bar: BarStyle) -> Self {
if let Some(p) = &self.bar {
lock(&p.counts).bar = bar;
}
self
}
pub fn as_progress(&self) -> Option<&Progress> {
self.bar.as_ref()
}
}
impl<I: Iterator> Iterator for WithProgress<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
if let Some(bar) = &self.bar {
bar.show();
}
let item = self.inner.next();
match &item {
Some(_) => {
if let Some(bar) = &self.bar {
bar.inc(1);
}
}
None => {
if let Some(bar) = self.bar.take() {
bar.finish();
}
}
}
item
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
fn progress_line(label: &str, c: &Counts, elapsed: Duration, t: f64) -> String {
let amount = |n: u64| {
if c.bytes { format::bytes(n) } else { format::count(n) }
};
let rate = c.done as f64 / elapsed.as_secs_f64().max(0.001);
let spinner = Spinner::default().frame(t);
let Some(total) = c.total else {
let mut stats = amount(c.done);
if c.done > 0 {
stats += &format!(" ยท {}/s", amount(rate as u64));
}
return format!(" {spinner} {} {}", shimmer(label, t), paint(SOFT, &stats));
};
let f = if total == 0 { 1.0 } else { c.done as f32 / total as f32 };
let mut stats = format!("{:>3.0}% {} / {}", f * 100.0, amount(c.done), amount(total));
if c.done > 0 && rate > 0.0 {
let left = Duration::from_secs_f64(total.saturating_sub(c.done) as f64 / rate);
stats += &format!(" ยท {}/s ยท {} left", amount(rate as u64), format::duration(left));
}
format!(
" {spinner} {} {} {}",
paint(TEXT, label),
c.bar.draw(f, 24, t),
paint(SOFT, &stats)
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::output::{Output, capture, with_output, with_terminal};
fn plain() {
crate::set_color_mode(crate::ColorMode::None);
}
#[test]
fn spinning_on_a_terminal_ends_on_a_mark() {
plain();
let out = capture(|| {
with_terminal(true, || {
let slept = spin("s-ok", || {
std::thread::sleep(Duration::from_millis(30));
"slept"
});
assert_eq!(slept, "slept");
let failed: Result<(), &str> = try_spin("s-fail", || Err("it broke"));
assert!(failed.is_err());
})
});
assert!(out.contains("\x1b[?25l") && out.contains("โ s-ok"), "{out:?}");
assert!(out.contains("โ s-fail") && out.contains("it broke\n"), "{out:?}");
}
#[test]
fn spinning_elsewhere_prints_a_line_an_event_or_nothing() {
plain();
let out = capture(|| {
with_terminal(false, || {
spin("p-ok", || ());
let _ = try_spin("p-fail", || Err::<(), _>("nope"));
})
});
assert!(
out.contains(" [ok] p-ok (") && out.contains(" [FAIL] p-fail (") && out.contains("nope"),
"{out:?}"
);
let quiet = capture(|| with_output(Output::Quiet, || spin("q-ok", || ())));
assert!(!quiet.contains("q-ok"));
let json = capture(|| {
with_output(Output::Json, || {
spin("j-ok", || ());
let _ = try_spin("j-fail", || Err::<(), _>("nope"));
})
});
assert!(json.contains(r#""label":"j-ok","outcome":"ok""#), "{json}");
assert!(
json.contains(r#""label":"j-fail","outcome":"fail""#) && json.contains(r#""error":"nope""#),
"{json}"
);
}
#[test]
fn progress_draws_on_a_terminal_and_finishes_on_a_mark() {
plain();
let out = capture(|| {
with_terminal(true, || {
let p = Progress::new("p-draw", 100).fps(240).bytes().bar(BarStyle::Waveform);
p.inc(30);
p.set(50);
std::thread::sleep(Duration::from_millis(30));
p.finish();
})
});
assert!(out.contains("p-draw") && out.contains("โ p-draw"), "{out:?}");
}
#[test]
fn progress_dropped_short_of_its_total_doesnt_claim_success() {
plain();
let out = capture(|| {
with_terminal(true, || {
let p = Progress::new("p-short", 10).fps(240);
p.inc(3);
std::thread::sleep(Duration::from_millis(20));
drop(p);
let mut it = [1, 2, 3].iter().progress("p-break");
it.next();
drop(it);
let p = Progress::new("p-whole", 10).fps(240);
p.inc(10);
drop(p);
let p = Progress::new("p-told", 10).fps(240);
p.inc(1);
p.finish();
})
});
assert!(out.contains("โ p-short") && !out.contains("โ p-short"), "{out:?}");
assert!(out.contains("โ p-break"), "{out:?}");
assert!(out.contains("โ p-whole") && out.contains("โ p-told"), "{out:?}");
let plain_out = capture(|| {
with_terminal(false, || {
let p = Progress::new("p-plain", 4);
p.inc(1);
drop(p);
let _ = std::panic::catch_unwind(|| {
let p = Progress::new("p-panic", 4);
p.inc(4);
panic!("mid-loop");
});
})
});
assert!(plain_out.contains("[stopped] p-plain ("), "{plain_out:?}");
assert!(plain_out.contains("[FAIL] p-panic ("), "{plain_out:?}");
let json = capture(|| with_output(Output::Json, || drop(Progress::new("pj-short", 4))));
assert!(json.contains(r#""outcome":"stopped","total":4}"#), "{json}");
}
#[test]
fn a_label_with_a_line_break_stays_on_one_row() {
plain();
let out = capture(|| {
with_terminal(true, || {
let p = Progress::new("two\nrows", 1).fps(240);
p.set(0);
std::thread::sleep(Duration::from_millis(20));
p.finish();
spin("s-two\nrows", || std::thread::sleep(Duration::from_millis(20)));
})
});
assert!(!out.contains("two\n") && out.contains("two rows"), "{out:?}");
assert!(out.contains("s-two rows"), "{out:?}");
}
#[test]
fn progress_draws_from_its_first_update_so_its_settings_hold_from_the_start() {
plain();
let out = capture(|| {
with_terminal(true, || {
let p = Progress::new("p-lazy", 100).fps(240).bytes();
std::thread::sleep(Duration::from_millis(30));
assert!(lock(&p.ticker).is_none(), "nothing drawn before an update");
p.inc(1_000);
assert!(lock(&p.ticker).is_some());
std::thread::sleep(Duration::from_millis(30));
p.finish();
})
});
let frames = out.split('\r').filter(|f| f.contains("p-lazy") && f.contains('%'));
assert!(frames.clone().count() > 0, "{out:?}");
assert!(frames.clone().all(|f| f.contains("100 B / 100 B")), "{out:?}");
}
#[test]
fn progress_counts_within_its_total() {
let p = with_terminal(false, || Progress::new("count", 10).fps(30));
p.inc(25);
assert_eq!(lock(&p.counts).done, 10);
p.set(40);
assert_eq!(lock(&p.counts).done, 10);
p.set_total(5);
assert_eq!(lock(&p.counts).done, 5);
p.add_total(5);
assert_eq!(lock(&p.counts).total, Some(10));
capture(|| p.finish());
let u = with_terminal(false, || Progress::unknown("unknown"));
u.inc(7);
u.set(9);
assert_eq!(lock(&u.counts).done, 9);
u.add_total(3);
assert_eq!(lock(&u.counts).total, Some(3));
assert!(capture(|| drop(u)).contains("[ok] unknown"));
}
#[test]
fn progress_off_a_terminal_reports_once() {
let json = capture(|| {
with_output(Output::Json, || {
let p = Progress::new("pj", 4);
p.inc(2);
p.finish();
Progress::unknown("pu").finish();
})
});
assert!(
json.contains(r#"{"event":"progress","label":"pj","done":2,"#) && json.contains(r#""total":4}"#),
"{json}"
);
assert!(json.contains(r#""label":"pu","done":0,"#), "{json}");
let quiet = capture(|| with_output(Output::Quiet, || Progress::new("pq", 1).finish()));
assert!(!quiet.contains("pq"));
}
#[test]
fn iterators_count_as_they_go() {
let out = capture(|| {
with_terminal(false, || {
let mut it = [1, 2, 3].iter().progress("known").bar(BarStyle::Line);
assert_eq!(it.size_hint(), (3, Some(3)));
assert_eq!(lock(&it.as_progress().unwrap().counts).total, Some(3));
assert_eq!(it.by_ref().count(), 3);
assert!(it.as_progress().is_none());
assert!(it.bar(BarStyle::Line).next().is_none());
let unknown = (0..10).filter(|n| n % 2 == 0).progress("filtered");
assert_eq!(lock(&unknown.as_progress().unwrap().counts).total, None);
assert_eq!(unknown.sum::<i32>(), 20);
})
});
assert!(out.contains("[ok] known") && out.contains("[ok] filtered"), "{out:?}");
}
#[test]
fn the_progress_line_shows_rate_and_time_left() {
plain();
let counts = |done, total| Counts {
done,
total,
bytes: false,
bar: BarStyle::Line,
};
let line = progress_line("work", &counts(50, Some(100)), Duration::from_secs(5), 0.0);
assert!(
line.contains(" 50% 50 / 100") && line.contains("10/s") && line.contains("5.0s left"),
"{line}"
);
let line = progress_line("work", &counts(0, Some(0)), Duration::from_secs(1), 0.0);
assert!(line.contains("100% 0 / 0") && !line.contains("/s"), "{line}");
let line = progress_line("work", &counts(0, None), Duration::from_secs(1), 0.0);
assert!(line.ends_with(" 0"), "{line}");
let bytes = Counts {
bytes: true,
..counts(2048, None)
};
let line = progress_line("work", &bytes, Duration::from_secs(1), 0.0);
assert!(line.contains("2.0 KB ยท 2.0 KB/s"), "{line}");
}
#[test]
fn an_iterator_that_carries_on_after_running_out_isnt_counted_twice() {
let mut calls = 0;
let resumes = std::iter::from_fn(move || {
calls += 1;
(calls != 2).then_some(calls)
});
let out = capture(|| {
with_terminal(false, || {
let mut it = resumes.progress("resumes");
assert_eq!((it.next(), it.next(), it.next()), (Some(1), None, Some(3)));
})
});
assert_eq!(out.matches("[ok] resumes").count(), 1, "{out:?}");
}
}