use std::io::{IsTerminal as _, Write as _};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const TICK: Duration = Duration::from_millis(80);
const GRACE: Duration = Duration::from_millis(150);
pub struct Spinner {
done: Arc<AtomicBool>,
thread: Mutex<Option<JoinHandle<()>>>,
}
impl Spinner {
#[must_use]
pub fn start(message: &str) -> Self {
let done = Arc::new(AtomicBool::new(false));
if quiet() {
return Self { done, thread: Mutex::new(None) };
}
let flag = Arc::clone(&done);
let message = message.to_owned();
let thread = std::thread::Builder::new()
.name("zoning-spinner".to_owned())
.spawn(move || spin(&flag, &message))
.ok();
Self { done, thread: Mutex::new(thread) }
}
pub fn stop(&self) {
self.done.store(true, Ordering::Relaxed);
if let Ok(mut held) = self.thread.lock()
&& let Some(thread) = held.take()
{
let _ = thread.join();
}
}
}
impl Drop for Spinner {
fn drop(&mut self) {
self.stop();
}
}
fn quiet() -> bool {
std::env::var_os("CI").is_some()
|| std::env::var_os("ZONING_NO_SETUP").is_some()
|| !std::io::stderr().is_terminal()
}
fn spin(done: &AtomicBool, message: &str) {
let start = Instant::now();
let mut stderr = std::io::stderr();
let mut shown = false;
for frame in FRAMES.iter().cycle() {
if done.load(Ordering::Relaxed) {
break;
}
if shown || start.elapsed() >= GRACE {
shown = true;
let _ = write!(stderr, "\r{frame} {message}");
let _ = stderr.flush();
}
std::thread::sleep(TICK);
}
if shown {
let _ = write!(stderr, "\r{}\r", " ".repeat(message.chars().count() + 2));
let _ = stderr.flush();
}
}