1use std::io::{self, IsTerminal, Write};
2use std::sync::{
3 Arc, Mutex,
4 atomic::{AtomicBool, Ordering},
5};
6use std::thread::{self, JoinHandle};
7use std::time::Duration;
8
9use crossterm::{
10 cursor::{Hide, Show},
11 queue,
12 style::{Color as TermColor, Print, ResetColor, SetForegroundColor},
13};
14
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum Stream {
17 Stdout,
18 Stderr,
19}
20
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum Color {
23 Black,
24 Red,
25 Green,
26 Yellow,
27 Blue,
28 Magenta,
29 Cyan,
30 White,
31}
32
33impl Color {
34 fn into_term(self) -> TermColor {
35 match self {
36 Self::Black => TermColor::Black,
37 Self::Red => TermColor::Red,
38 Self::Green => TermColor::Green,
39 Self::Yellow => TermColor::Yellow,
40 Self::Blue => TermColor::Blue,
41 Self::Magenta => TermColor::Magenta,
42 Self::Cyan => TermColor::Cyan,
43 Self::White => TermColor::White,
44 }
45 }
46}
47
48#[derive(Clone, Debug, Eq, PartialEq)]
49pub struct SpinnerStyle {
50 pub interval: Duration,
51 pub frames: Vec<String>,
52}
53
54impl SpinnerStyle {
55 pub fn new<I, S>(interval: Duration, frames: I) -> Self
56 where
57 I: IntoIterator<Item = S>,
58 S: Into<String>,
59 {
60 Self {
61 interval,
62 frames: frames.into_iter().map(Into::into).collect(),
63 }
64 }
65
66 pub fn dots() -> Self {
67 Self::new(
68 Duration::from_millis(80),
69 ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
70 )
71 }
72
73 pub fn line() -> Self {
74 Self::new(Duration::from_millis(130), ["-", "\\", "|", "/"])
75 }
76
77 pub fn arrow() -> Self {
78 Self::new(
79 Duration::from_millis(100),
80 ["←", "↖", "↑", "↗", "→", "↘", "↓", "↙"],
81 )
82 }
83}
84
85impl Default for SpinnerStyle {
86 fn default() -> Self {
87 Self::dots()
88 }
89}
90
91#[derive(Clone, Debug)]
92pub struct SpinnerOptions {
93 pub text: String,
94 pub prefix_text: String,
95 pub suffix_text: String,
96 pub color: Option<Color>,
97 pub spinner: SpinnerStyle,
98 pub indent: usize,
99 pub hide_cursor: bool,
100 pub enabled: bool,
101 pub stream: Stream,
102}
103
104impl SpinnerOptions {
105 pub fn new(text: impl Into<String>) -> Self {
106 Self {
107 text: text.into(),
108 prefix_text: String::new(),
109 suffix_text: String::new(),
110 color: Some(Color::Cyan),
111 spinner: SpinnerStyle::default(),
112 indent: 0,
113 hide_cursor: true,
114 enabled: true,
115 stream: Stream::Stderr,
116 }
117 }
118
119 pub fn builder() -> SpinnerBuilder {
120 SpinnerBuilder::default()
121 }
122
123 pub fn with_text(mut self, text: impl Into<String>) -> Self {
124 self.text = text.into();
125 self
126 }
127
128 pub fn with_prefix_text(mut self, text: impl Into<String>) -> Self {
129 self.prefix_text = text.into();
130 self
131 }
132
133 pub fn with_suffix_text(mut self, text: impl Into<String>) -> Self {
134 self.suffix_text = text.into();
135 self
136 }
137
138 pub fn with_color(mut self, color: Option<Color>) -> Self {
139 self.color = color;
140 self
141 }
142
143 pub fn with_spinner(mut self, spinner: SpinnerStyle) -> Self {
144 self.spinner = spinner;
145 self
146 }
147
148 pub fn with_indent(mut self, indent: usize) -> Self {
149 self.indent = indent;
150 self
151 }
152
153 pub fn with_hide_cursor(mut self, hide_cursor: bool) -> Self {
154 self.hide_cursor = hide_cursor;
155 self
156 }
157
158 pub fn with_enabled(mut self, enabled: bool) -> Self {
159 self.enabled = enabled;
160 self
161 }
162
163 pub fn with_stream(mut self, stream: Stream) -> Self {
164 self.stream = stream;
165 self
166 }
167}
168
169impl Default for SpinnerOptions {
170 fn default() -> Self {
171 Self::new("")
172 }
173}
174
175#[derive(Clone, Debug, Default)]
176pub struct SpinnerBuilder {
177 options: SpinnerOptions,
178}
179
180impl SpinnerBuilder {
181 pub fn new() -> Self {
182 Self::default()
183 }
184
185 pub fn text(mut self, text: impl Into<String>) -> Self {
186 self.options.text = text.into();
187 self
188 }
189
190 pub fn prefix_text(mut self, text: impl Into<String>) -> Self {
191 self.options.prefix_text = text.into();
192 self
193 }
194
195 pub fn suffix_text(mut self, text: impl Into<String>) -> Self {
196 self.options.suffix_text = text.into();
197 self
198 }
199
200 pub fn color(mut self, color: Color) -> Self {
201 self.options.color = Some(color);
202 self
203 }
204
205 pub fn no_color(mut self) -> Self {
206 self.options.color = None;
207 self
208 }
209
210 pub fn spinner(mut self, spinner: SpinnerStyle) -> Self {
211 self.options.spinner = spinner;
212 self
213 }
214
215 pub fn indent(mut self, indent: usize) -> Self {
216 self.options.indent = indent;
217 self
218 }
219
220 pub fn hide_cursor(mut self, hide_cursor: bool) -> Self {
221 self.options.hide_cursor = hide_cursor;
222 self
223 }
224
225 pub fn enabled(mut self, enabled: bool) -> Self {
226 self.options.enabled = enabled;
227 self
228 }
229
230 pub fn stream(mut self, stream: Stream) -> Self {
231 self.options.stream = stream;
232 self
233 }
234
235 pub fn build(self) -> Spinner {
236 Spinner::with_options(self.options)
237 }
238
239 pub fn build_options(self) -> SpinnerOptions {
240 self.options
241 }
242}
243
244#[derive(Clone, Debug)]
245struct SpinnerState {
246 text: String,
247 prefix_text: String,
248 suffix_text: String,
249 frame_index: usize,
250 color: Option<Color>,
251 spinner: SpinnerStyle,
252 indent: usize,
253 hide_cursor: bool,
254 enabled: bool,
255 stream: Stream,
256 last_width: usize,
257}
258
259impl From<SpinnerOptions> for SpinnerState {
260 fn from(value: SpinnerOptions) -> Self {
261 Self {
262 text: value.text,
263 prefix_text: value.prefix_text,
264 suffix_text: value.suffix_text,
265 frame_index: 0,
266 color: value.color,
267 spinner: value.spinner,
268 indent: value.indent,
269 hide_cursor: value.hide_cursor,
270 enabled: value.enabled,
271 stream: value.stream,
272 last_width: 0,
273 }
274 }
275}
276
277pub struct Spinner {
278 state: Arc<Mutex<SpinnerState>>,
279 running: Arc<AtomicBool>,
280 worker: Option<JoinHandle<io::Result<()>>>,
281}
282
283#[derive(Clone, Debug, Eq, PartialEq)]
284pub struct SpinnerSnapshot {
285 pub text: String,
286 pub prefix_text: String,
287 pub suffix_text: String,
288 pub color: Option<Color>,
289 pub spinner: SpinnerStyle,
290 pub indent: usize,
291 pub hide_cursor: bool,
292 pub enabled: bool,
293 pub stream: Stream,
294 pub is_spinning: bool,
295}
296
297impl Spinner {
298 pub fn new(text: impl Into<String>) -> Self {
299 Self::with_options(SpinnerOptions::new(text))
300 }
301
302 pub fn builder() -> SpinnerBuilder {
303 SpinnerBuilder::default()
304 }
305
306 pub fn with_options(options: SpinnerOptions) -> Self {
307 Self {
308 state: Arc::new(Mutex::new(options.into())),
309 running: Arc::new(AtomicBool::new(false)),
310 worker: None,
311 }
312 }
313
314 pub fn start(&mut self) -> io::Result<&mut Self> {
315 if self.running.swap(true, Ordering::SeqCst) {
316 return Ok(self);
317 }
318
319 let state = Arc::clone(&self.state);
320 let running = Arc::clone(&self.running);
321
322 self.worker = Some(thread::spawn(move || {
323 let mut cursor_hidden = false;
324
325 while running.load(Ordering::SeqCst) {
326 let mut guard = state.lock().expect("spinner state poisoned");
327 let enabled = guard.enabled && is_terminal(guard.stream);
328 let interval = guard.spinner.interval;
329
330 if enabled && guard.hide_cursor && !cursor_hidden {
331 let writer = writer_for(guard.stream);
332 let mut writer = writer.lock().expect("writer poisoned");
333 queue!(&mut *writer, Hide)?;
334 writer.flush()?;
335 cursor_hidden = true;
336 }
337
338 render_active(&mut guard)?;
339 drop(guard);
340 thread::sleep(interval);
341 }
342
343 let guard = state.lock().expect("spinner state poisoned");
344 if cursor_hidden && guard.enabled && is_terminal(guard.stream) {
345 let writer = writer_for(guard.stream);
346 let mut writer = writer.lock().expect("writer poisoned");
347 queue!(&mut *writer, Show)?;
348 writer.flush()?;
349 }
350
351 Ok(())
352 }));
353
354 Ok(self)
355 }
356
357 pub fn stop(&mut self) -> io::Result<&mut Self> {
358 self.stop_internal()?;
359 self.clear()?;
360 Ok(self)
361 }
362
363 pub fn clear(&mut self) -> io::Result<&mut Self> {
364 {
365 let mut guard = self.state.lock().expect("spinner state poisoned");
366 clear_line(&mut guard)?;
367 }
368 Ok(self)
369 }
370
371 pub fn stop_and_persist<T>(
372 &mut self,
373 symbol: impl Into<String>,
374 text: Option<T>,
375 ) -> io::Result<&mut Self>
376 where
377 T: Into<String>,
378 {
379 self.stop_internal()?;
380 {
381 let mut guard = self.state.lock().expect("spinner state poisoned");
382 if let Some(text) = text {
383 guard.text = text.into();
384 }
385 render_persisted(&mut guard, &symbol.into(), None)?;
386 }
387 Ok(self)
388 }
389
390 pub fn succeed<T>(&mut self, text: Option<T>) -> io::Result<&mut Self>
391 where
392 T: Into<String>,
393 {
394 self.stop_internal()?;
395 {
396 let mut guard = self.state.lock().expect("spinner state poisoned");
397 if let Some(text) = text {
398 guard.text = text.into();
399 }
400 render_persisted(&mut guard, "✔", Some(Color::Green))?;
401 }
402 Ok(self)
403 }
404
405 pub fn fail<T>(&mut self, text: Option<T>) -> io::Result<&mut Self>
406 where
407 T: Into<String>,
408 {
409 self.stop_internal()?;
410 {
411 let mut guard = self.state.lock().expect("spinner state poisoned");
412 if let Some(text) = text {
413 guard.text = text.into();
414 }
415 render_persisted(&mut guard, "✖", Some(Color::Red))?;
416 }
417 Ok(self)
418 }
419
420 pub fn warn<T>(&mut self, text: Option<T>) -> io::Result<&mut Self>
421 where
422 T: Into<String>,
423 {
424 self.stop_internal()?;
425 {
426 let mut guard = self.state.lock().expect("spinner state poisoned");
427 if let Some(text) = text {
428 guard.text = text.into();
429 }
430 render_persisted(&mut guard, "⚠", Some(Color::Yellow))?;
431 }
432 Ok(self)
433 }
434
435 pub fn info<T>(&mut self, text: Option<T>) -> io::Result<&mut Self>
436 where
437 T: Into<String>,
438 {
439 self.stop_internal()?;
440 {
441 let mut guard = self.state.lock().expect("spinner state poisoned");
442 if let Some(text) = text {
443 guard.text = text.into();
444 }
445 render_persisted(&mut guard, "ℹ", Some(Color::Blue))?;
446 }
447 Ok(self)
448 }
449
450 pub fn text(&self) -> String {
451 self.state
452 .lock()
453 .expect("spinner state poisoned")
454 .text
455 .clone()
456 }
457
458 pub fn set_text(&mut self, text: impl Into<String>) -> &mut Self {
459 self.state.lock().expect("spinner state poisoned").text = text.into();
460 self
461 }
462
463 pub fn set_prefix_text(&mut self, text: impl Into<String>) -> &mut Self {
464 self.state
465 .lock()
466 .expect("spinner state poisoned")
467 .prefix_text = text.into();
468 self
469 }
470
471 pub fn set_suffix_text(&mut self, text: impl Into<String>) -> &mut Self {
472 self.state
473 .lock()
474 .expect("spinner state poisoned")
475 .suffix_text = text.into();
476 self
477 }
478
479 pub fn set_color(&mut self, color: Option<Color>) -> &mut Self {
480 self.state.lock().expect("spinner state poisoned").color = color;
481 self
482 }
483
484 pub fn set_spinner(&mut self, spinner: SpinnerStyle) -> &mut Self {
485 {
486 let mut guard = self.state.lock().expect("spinner state poisoned");
487 guard.spinner = spinner;
488 guard.frame_index = 0;
489 }
490 self
491 }
492
493 pub fn snapshot(&self) -> SpinnerSnapshot {
494 let guard = self.state.lock().expect("spinner state poisoned");
495
496 SpinnerSnapshot {
497 text: guard.text.clone(),
498 prefix_text: guard.prefix_text.clone(),
499 suffix_text: guard.suffix_text.clone(),
500 color: guard.color,
501 spinner: guard.spinner.clone(),
502 indent: guard.indent,
503 hide_cursor: guard.hide_cursor,
504 enabled: guard.enabled,
505 stream: guard.stream,
506 is_spinning: self.is_spinning(),
507 }
508 }
509
510 pub fn is_spinning(&self) -> bool {
511 self.running.load(Ordering::SeqCst)
512 }
513
514 fn stop_internal(&mut self) -> io::Result<()> {
515 self.running.store(false, Ordering::SeqCst);
516 if let Some(worker) = self.worker.take() {
517 match worker.join() {
518 Ok(result) => result?,
519 Err(_) => return Err(io::Error::other("spinner thread panicked")),
520 }
521 }
522 Ok(())
523 }
524}
525
526impl Drop for Spinner {
527 fn drop(&mut self) {
528 let _ = self.stop();
529 }
530}
531
532fn render_active(state: &mut SpinnerState) -> io::Result<()> {
533 if !state.enabled || !is_terminal(state.stream) {
534 return Ok(());
535 }
536
537 let frame = if state.spinner.frames.is_empty() {
538 "-".to_string()
539 } else {
540 state.spinner.frames[state.frame_index % state.spinner.frames.len()].clone()
541 };
542 state.frame_index = state.frame_index.wrapping_add(1);
543
544 let line = compose_line(state, &frame);
545 write_line(state, &line, state.color)?;
546 Ok(())
547}
548
549fn render_persisted(
550 state: &mut SpinnerState,
551 symbol: &str,
552 symbol_color: Option<Color>,
553) -> io::Result<()> {
554 let line = compose_line(state, symbol);
555 write_line(state, &line, symbol_color)?;
556 let writer = writer_for(state.stream);
557 let mut writer = writer.lock().expect("writer poisoned");
558 writer.write_all(b"\n")?;
559 writer.flush()?;
560 state.last_width = 0;
561 Ok(())
562}
563
564fn clear_line(state: &mut SpinnerState) -> io::Result<()> {
565 if !state.enabled || !is_terminal(state.stream) {
566 return Ok(());
567 }
568
569 let writer = writer_for(state.stream);
570 let mut writer = writer.lock().expect("writer poisoned");
571 let clear_width = state.last_width.max(1);
572 write!(&mut *writer, "\r{}\r", " ".repeat(clear_width))?;
573 writer.flush()?;
574 state.last_width = 0;
575 Ok(())
576}
577
578fn write_line(state: &mut SpinnerState, line: &str, symbol_color: Option<Color>) -> io::Result<()> {
579 let writer = writer_for(state.stream);
580 let mut writer = writer.lock().expect("writer poisoned");
581 let clear_width = state.last_width.max(line.chars().count());
582
583 write!(&mut *writer, "\r{}\r", " ".repeat(clear_width))?;
584 if let Some(color) = symbol_color {
585 queue!(&mut *writer, SetForegroundColor(color.into_term()))?;
586 }
587 queue!(&mut *writer, Print(line))?;
588 if symbol_color.is_some() {
589 queue!(&mut *writer, ResetColor)?;
590 }
591 writer.flush()?;
592 state.last_width = line.chars().count();
593 Ok(())
594}
595
596fn compose_line(state: &SpinnerState, symbol: &str) -> String {
597 let indent = " ".repeat(state.indent);
598 let mut line = format!("{indent}{symbol}");
599
600 if !state.prefix_text.is_empty() {
601 line.push(' ');
602 line.push_str(&state.prefix_text);
603 }
604
605 if !state.text.is_empty() {
606 line.push(' ');
607 line.push_str(&state.text);
608 }
609
610 if !state.suffix_text.is_empty() {
611 line.push(' ');
612 line.push_str(&state.suffix_text);
613 }
614
615 line
616}
617
618fn is_terminal(stream: Stream) -> bool {
619 match stream {
620 Stream::Stdout => io::stdout().is_terminal(),
621 Stream::Stderr => io::stderr().is_terminal(),
622 }
623}
624
625fn writer_for(stream: Stream) -> &'static Mutex<Box<dyn Write + Send>> {
626 use std::sync::OnceLock;
627
628 static STDOUT: OnceLock<Mutex<Box<dyn Write + Send>>> = OnceLock::new();
629 static STDERR: OnceLock<Mutex<Box<dyn Write + Send>>> = OnceLock::new();
630
631 match stream {
632 Stream::Stdout => STDOUT.get_or_init(|| Mutex::new(Box::new(io::stdout()))),
633 Stream::Stderr => STDERR.get_or_init(|| Mutex::new(Box::new(io::stderr()))),
634 }
635}
636
637#[cfg(test)]
638mod tests {
639 use super::*;
640
641 #[test]
642 fn options_new_sets_expected_defaults() {
643 let options = SpinnerOptions::new("loading");
644
645 assert_eq!(options.text, "loading");
646 assert_eq!(options.prefix_text, "");
647 assert_eq!(options.suffix_text, "");
648 assert_eq!(options.color, Some(Color::Cyan));
649 assert_eq!(options.spinner.frames.len(), 10);
650 assert_eq!(options.indent, 0);
651 assert!(options.hide_cursor);
652 assert!(options.enabled);
653 assert_eq!(options.stream, Stream::Stderr);
654 }
655
656 #[test]
657 fn style_presets_are_available() {
658 let dots = SpinnerStyle::dots();
659 let line = SpinnerStyle::line();
660 let arrow = SpinnerStyle::arrow();
661
662 assert_eq!(dots.frames.len(), 10);
663 assert_eq!(line.frames, vec!["-", "\\", "|", "/"]);
664 assert_eq!(arrow.frames.len(), 8);
665 }
666
667 #[test]
668 fn custom_style_constructor_collects_frames() {
669 let style = SpinnerStyle::new(Duration::from_millis(50), ["a", "b", "c"]);
670
671 assert_eq!(style.interval, Duration::from_millis(50));
672 assert_eq!(style.frames, vec!["a", "b", "c"]);
673 }
674
675 #[test]
676 fn builder_build_options_sets_all_fields() {
677 let options = SpinnerBuilder::new()
678 .text("compile")
679 .prefix_text("worker")
680 .suffix_text("queued")
681 .color(Color::Green)
682 .spinner(SpinnerStyle::arrow())
683 .indent(4)
684 .hide_cursor(false)
685 .enabled(false)
686 .stream(Stream::Stdout)
687 .build_options();
688
689 assert_eq!(options.text, "compile");
690 assert_eq!(options.prefix_text, "worker");
691 assert_eq!(options.suffix_text, "queued");
692 assert_eq!(options.color, Some(Color::Green));
693 assert_eq!(options.spinner, SpinnerStyle::arrow());
694 assert_eq!(options.indent, 4);
695 assert!(!options.hide_cursor);
696 assert!(!options.enabled);
697 assert_eq!(options.stream, Stream::Stdout);
698 }
699
700 #[test]
701 fn compose_line_combines_all_segments() {
702 let state = SpinnerState {
703 text: "compile".into(),
704 prefix_text: "job-7".into(),
705 suffix_text: "done".into(),
706 frame_index: 0,
707 color: Some(Color::Blue),
708 spinner: SpinnerStyle::line(),
709 indent: 2,
710 hide_cursor: false,
711 enabled: true,
712 stream: Stream::Stderr,
713 last_width: 0,
714 };
715
716 assert_eq!(compose_line(&state, "*"), " * job-7 compile done");
717 }
718
719 #[test]
720 fn spinner_mutators_update_text_fields() {
721 let mut spinner = Spinner::new("boot");
722
723 spinner
724 .set_text("compile")
725 .set_prefix_text("worker")
726 .set_suffix_text("queued")
727 .set_color(Some(Color::Green))
728 .set_spinner(SpinnerStyle::arrow());
729
730 let guard = spinner.state.lock().expect("spinner state poisoned");
731 assert_eq!(guard.text, "compile");
732 assert_eq!(guard.prefix_text, "worker");
733 assert_eq!(guard.suffix_text, "queued");
734 assert_eq!(guard.color, Some(Color::Green));
735 assert_eq!(guard.spinner.frames.len(), 8);
736 }
737
738 #[test]
739 fn start_and_stop_toggle_running_state() {
740 let mut spinner = Spinner::with_options(SpinnerOptions {
741 text: "build".into(),
742 enabled: false,
743 ..SpinnerOptions::default()
744 });
745
746 spinner.start().expect("spinner should start");
747 assert!(spinner.is_spinning());
748
749 spinner.stop().expect("spinner should stop");
750 assert!(!spinner.is_spinning());
751 }
752
753 #[test]
754 fn snapshot_reflects_mutations() {
755 let mut spinner = Spinner::builder()
756 .text("start")
757 .prefix_text("unit")
758 .suffix_text("pending")
759 .build();
760
761 spinner.set_text("finish").set_color(Some(Color::Magenta));
762
763 let snapshot = spinner.snapshot();
764 assert_eq!(snapshot.text, "finish");
765 assert_eq!(snapshot.prefix_text, "unit");
766 assert_eq!(snapshot.suffix_text, "pending");
767 assert_eq!(snapshot.color, Some(Color::Magenta));
768 assert!(!snapshot.is_spinning);
769 }
770}