1use std::{
21 env,
22 ffi::OsString,
23 io::{IsTerminal, Write, stderr},
24 sync::{
25 Arc, Mutex, OnceLock,
26 atomic::{AtomicBool, Ordering},
27 },
28 thread::{self, JoinHandle},
29 time::Duration,
30};
31
32use crossterm::{
33 QueueableCommand, cursor,
34 style::{Color, Print, PrintStyledContent, Stylize},
35 terminal::{Clear, ClearType},
36};
37
38use crate::signal;
39
40const FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
41
42const FRAME_INTERVAL: Duration = Duration::from_millis(80);
43
44pub struct Spinner {
46 message: Arc<Mutex<String>>,
47 stop: Arc<AtomicBool>,
48 handle: Option<JoinHandle<()>>,
49 colour: bool,
50}
51
52impl Spinner {
53 pub fn start(message: impl Into<String>) -> Self {
66 let message = Arc::new(Mutex::new(message.into()));
67 let stop = Arc::new(AtomicBool::new(false));
68 let terminal = stderr().is_terminal();
69 let colour = colour_wanted(terminal, env::var_os("NO_COLOR"));
70
71 let handle = if terminal {
72 install_terminal_guards();
73 let message = message.clone();
74 let stop = stop.clone();
75 Some(thread::spawn(move || render_loop(message, stop, colour)))
76 } else {
77 None
78 };
79
80 Self {
81 message,
82 stop,
83 handle,
84 colour,
85 }
86 }
87
88 pub fn set_message(&self, message: impl Into<String>) {
90 if let Ok(mut current) = self.message.lock() {
91 *current = message.into();
92 }
93 }
94
95 pub fn success(self, message: impl AsRef<str>) {
97 self.finish("✓", Color::Green, message.as_ref());
98 }
99
100 pub fn failure(self, message: impl AsRef<str>) {
102 self.finish("✗", Color::Red, message.as_ref());
103 }
104
105 pub fn clear(mut self) {
108 self.shutdown();
109 }
110
111 fn finish(mut self, glyph: &str, color: Color, message: &str) {
112 self.shutdown();
113
114 let mut out = stderr();
115 queue_glyph(&mut out, glyph, color, self.colour);
116 out.queue(Print(format!(" {message}\n"))).ok();
117 out.flush().ok();
118 }
119
120 fn shutdown(&mut self) {
121 self.stop.store(true, Ordering::Relaxed);
122 if let Some(handle) = self.handle.take() {
123 handle.join().ok();
124 }
125 }
126}
127
128impl Drop for Spinner {
129 fn drop(&mut self) {
130 self.shutdown();
131 }
132}
133
134static TERMINAL_GUARDS: OnceLock<()> = OnceLock::new();
135
136fn install_terminal_guards() {
137 TERMINAL_GUARDS.get_or_init(|| {
138 let _ = signal::install_handler_with(restore_terminal);
144
145 let default_hook = std::panic::take_hook();
149 std::panic::set_hook(Box::new(move |info| {
150 restore_terminal();
151 default_hook(info);
152 }));
153 });
154}
155
156fn restore_terminal() {
157 let mut out = stderr();
158 out.queue(cursor::MoveToColumn(0)).ok();
159 out.queue(Clear(ClearType::CurrentLine)).ok();
160 out.queue(cursor::Show).ok();
161 out.flush().ok();
162}
163
164fn colour_wanted(terminal: bool, no_color: Option<OsString>) -> bool {
166 terminal && no_color.is_none_or(|value| value.is_empty())
167}
168
169fn queue_glyph(out: &mut impl Write, glyph: &str, color: Color, colour: bool) {
172 if colour {
173 out.queue(PrintStyledContent(glyph.with(color))).ok();
174 } else {
175 out.queue(Print(glyph)).ok();
176 }
177}
178
179fn render_loop(message: Arc<Mutex<String>>, stop: Arc<AtomicBool>, colour: bool) {
180 let mut out = stderr();
181
182 out.queue(cursor::Hide).ok();
183 out.flush().ok();
184
185 let mut frame = 0;
186 while !stop.load(Ordering::Relaxed) {
187 let snapshot = message.lock().map(|m| m.clone()).unwrap_or_default();
188
189 out.queue(cursor::MoveToColumn(0)).ok();
190 out.queue(Clear(ClearType::CurrentLine)).ok();
191 queue_glyph(&mut out, FRAMES[frame], Color::Cyan, colour);
192 out.queue(Print(format!(" {snapshot}"))).ok();
193 out.flush().ok();
194
195 frame = (frame + 1) % FRAMES.len();
196 thread::sleep(FRAME_INTERVAL);
197 }
198
199 out.queue(cursor::MoveToColumn(0)).ok();
200 out.queue(Clear(ClearType::CurrentLine)).ok();
201 out.queue(cursor::Show).ok();
202 out.flush().ok();
203}
204
205#[cfg(test)]
206mod tests {
207 use std::{env, ffi::OsString, process::Command};
208
209 use super::{Spinner, colour_wanted};
210
211 const CHILD: &str = "PIMALAYA_CLI_SPINNER_CHILD";
212
213 #[test]
214 fn an_empty_no_color_keeps_the_colour() {
215 assert!(colour_wanted(true, None));
216 assert!(colour_wanted(true, Some(OsString::new())));
217 assert!(!colour_wanted(true, Some(OsString::from("0"))));
218 assert!(!colour_wanted(false, None));
219 }
220
221 #[test]
222 fn a_stream_that_is_no_terminal_gets_plain_lines() {
223 if env::var_os(CHILD).is_some() {
224 Spinner::start("Checking…").success("Checked");
225 Spinner::start("Sending…").failure("Not sent");
226 return;
227 }
228
229 for no_color in [None, Some("1")] {
231 let mut child = Command::new(env::current_exe().unwrap());
232 child
233 .args([
234 "--exact",
235 "spinner::tests::a_stream_that_is_no_terminal_gets_plain_lines",
236 ])
237 .env(CHILD, "1");
238 match no_color {
239 Some(value) => child.env("NO_COLOR", value),
240 None => child.env_remove("NO_COLOR"),
241 };
242
243 let output = child.output().unwrap();
244 assert!(output.status.success());
245 assert_eq!(
246 String::from_utf8_lossy(&output.stderr),
247 "✓ Checked\n✗ Not sent\n",
248 "NO_COLOR={no_color:?}",
249 );
250 }
251 }
252}