use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, TryLockError, Weak};
use std::thread;
use std::time::Duration;
use crate::output::Output;
pub(crate) fn lock<T: ?Sized>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn lock_patiently<T: ?Sized>(m: &Mutex<T>) -> Option<MutexGuard<'_, T>> {
for _ in 0..50 {
match m.try_lock() {
Ok(guard) => return Some(guard),
Err(TryLockError::Poisoned(e)) => return Some(e.into_inner()),
Err(TryLockError::WouldBlock) => thread::sleep(Duration::from_millis(2)),
}
}
None
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Mode {
Draw,
Plain,
Json,
Quiet,
Headless,
}
impl Mode {
pub(crate) fn pick(out: Output, animated: bool) -> Mode {
match out {
Output::Json => Mode::Json,
Output::Quiet => Mode::Quiet,
Output::Pretty if animated => Mode::Draw,
Output::Pretty => Mode::Plain,
}
}
pub(crate) fn now() -> Mode {
Mode::pick(crate::output::output(), animated())
}
}
pub(crate) trait Shown: Send + Sync {
fn pause(&self);
fn resume(&self);
fn log(&self, lines: &[&str], patient: bool) -> bool;
fn abandon(&self);
}
static SHOWN: Mutex<Vec<Weak<dyn Shown>>> = Mutex::new(Vec::new());
static ACTIVE: AtomicUsize = AtomicUsize::new(0);
pub(crate) fn add(shown: Weak<dyn Shown>) {
crate::term::restore_at_exit();
let mut all = lock(&SHOWN);
all.retain(|w| w.strong_count() > 0);
all.push(shown);
ACTIVE.store(all.len(), Ordering::SeqCst);
}
pub(crate) fn remove<T: ?Sized>(shown: *const T) {
let mut all = lock(&SHOWN);
all.retain(|w| w.strong_count() > 0 && !std::ptr::addr_eq(w.as_ptr(), shown));
ACTIVE.store(all.len(), Ordering::SeqCst);
}
pub(crate) fn any_active() -> bool {
ACTIVE.load(Ordering::SeqCst) > 0
}
fn shown() -> Vec<Arc<dyn Shown>> {
lock(&SHOWN).iter().filter_map(Weak::upgrade).collect()
}
pub(crate) fn pause_all() -> Paused {
let shown = shown();
for d in &shown {
d.pause();
}
Paused { shown }
}
pub(crate) struct Paused {
shown: Vec<Arc<dyn Shown>>,
}
impl Drop for Paused {
fn drop(&mut self) {
for d in &self.shown {
d.resume();
}
}
}
pub(crate) fn print_above<S: AsRef<str>>(lines: &[S], stderr: bool) -> bool {
above(lines, stderr, false)
}
pub(crate) fn print_above_patiently<S: AsRef<str>>(lines: &[S], stderr: bool) -> bool {
above(lines, stderr, true)
}
pub(crate) fn lock_if<T: ?Sized>(m: &Mutex<T>, patient: bool) -> Option<MutexGuard<'_, T>> {
if patient { lock_patiently(m) } else { Some(lock(m)) }
}
fn above<S: AsRef<str>>(lines: &[S], stderr: bool, patient: bool) -> bool {
if !any_active() {
return false;
}
let same_screen = !stderr
|| crate::output::target() == crate::Target::Stderr
|| crate::output::pretended_terminal().unwrap_or_else(|| std::io::IsTerminal::is_terminal(&std::io::stderr()));
if !same_screen {
return false;
}
let Some(newest) = lock_if(&SHOWN, patient).and_then(|all| all.iter().rev().find_map(Weak::upgrade)) else {
return false;
};
let parts: Vec<&str> = lines.iter().flat_map(|line| line.as_ref().split('\n')).collect();
newest.log(&parts, patient)
}
pub(crate) fn abandon_all() -> bool {
let Some(mut all) = lock_patiently(&SHOWN) else {
return false;
};
let taken = std::mem::take(&mut *all);
ACTIVE.store(0, Ordering::SeqCst);
drop(all);
let mut any = false;
for d in taken.iter().filter_map(Weak::upgrade) {
d.abandon();
any = true;
}
any
}
pub(crate) fn animated() -> bool {
if let Some(terminal) = crate::output::pretended_terminal() {
return terminal;
}
crate::output::is_terminal() && !dumb(std::env::var_os("TERM").as_deref())
}
fn dumb(term: Option<&std::ffi::OsStr>) -> bool {
term.is_some_and(|t| t == "dumb")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_dumb_terminal_gets_plain_lines() {
assert!(dumb(Some("dumb".as_ref())));
assert!(!dumb(Some("xterm-256color".as_ref())));
assert!(!dumb(None));
assert_eq!(Mode::pick(Output::Pretty, false), Mode::Plain);
assert_eq!(Mode::pick(Output::Json, true), Mode::Json);
assert!(crate::output::with_terminal(true, animated));
assert!(!crate::output::with_terminal(false, animated));
}
#[test]
fn a_question_holds_regions_and_spinners_still_too() {
use crate::output::{capture, with_terminal, write};
use std::time::Duration;
crate::set_color_mode(crate::ColorMode::None);
let out = capture(|| {
with_terminal(true, || {
let region = crate::Region::new(|| vec!["h-region".to_string()].into()).fps(240);
let progress = crate::Progress::new("h-progress", 10).fps(240);
thread::sleep(Duration::from_millis(30));
let paused = pause_all();
write("[held]");
thread::sleep(Duration::from_millis(40));
write("[free]");
drop(paused);
thread::sleep(Duration::from_millis(30));
progress.finish();
region.finish();
})
});
let held = &out[out.find("[held]").unwrap()..out.find("[free]").unwrap()];
assert!(!held.contains("h-region") && !held.contains("h-progress"), "{held:?}");
let after = &out[out.find("[free]").unwrap()..];
assert!(after.contains("h-region") && after.contains("h-progress"), "{after:?}");
assert!(!any_active(), "both let go when they finished");
}
#[test]
fn a_message_goes_above_a_region_rather_than_under_its_next_frame() {
use crate::output::{capture, with_terminal};
crate::set_color_mode(crate::ColorMode::None);
let out = capture(|| {
with_terminal(true, || {
let region = crate::Region::new(|| vec!["m-region".to_string()].into()).fps(240);
thread::sleep(Duration::from_millis(20));
crate::success("m-message");
crate::Block::from(vec!["m-block".to_string()]).print();
thread::sleep(Duration::from_millis(20));
region.finish();
})
});
assert!(out.contains("m-message\x1b[K\n"), "{out:?}");
assert!(out.contains("m-block\x1b[K\n"), "{out:?}");
}
}