1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//! [`Spinner`] animations
//!
//! A couple of different [`Animation`]s are provided, but you can also define your own using [`Animation::new`] or by implementing [`Animate`].  
//! Check out the example binary to see the provided [`Animation`]s in action!
//!
//! ---
//!
//! Because the animation requires terminal escape codes to work it can't always be displayed.
//! To keep it simple, the [`Spinner`] reuses the determination that the [`Stream`](crate::core::Stream) made on whether to emit color escape codes to decide whether to display the animation.
//! This means there is no way (for the user) to disable color output without also disabling the animation (and vice versa).
//!
//! Obviously, the [`Spinner`] takes care of this for you: it's not an error to use any of it's methods when the animation isn't being displayed.
//!
//! ## Output Stream
//!
//! The [`Spinner`] animation is printed to the `stderr` output stream instead of `stdout`.
//! This makes no difference in normal operation since the terminal emulator will merge the two back together, but it means that the user can still see the animation when they redirect ("pipe") the standard output into another program (i.e. with `|` ) or into a file (`>>`).
//! Of course, it's also possible (though far less common) to redirect the `stderr` stream (with `2>>`, for example).
//! In this case, the animation (probably) won't be rendered for the user, so no escape codes are emitted.
//! In fact, not even the [`Spinner`] [`Message`]s will be printed, only output from using the [`Conciliator`] methods will be written (to `stdout`, as normal).
//!
//! ## Hidden Cursor
//!
//! While the [`Spinner`] is active, the cursor is hidden.
//! Since it would jump around or cover parts of the animation, it looks better that way.
//! Unfortunately, the terminal will not automatically un-hide the cursor when the program ends, which means the cursor might stay hidden when your program crashes, or is killed / interrupted (i.e. `Ctrl+C`) while spinning.
//! You can mitigate this by implementing orderly shutdown and ensuring that destructors get run as the program ends.
//! Of course, there's nothing your program can do if it gets `SIGKILL`'d, but if you avoid [`std::process::exit`] and install a signal handler for `SIGINT`, you probably have most situations covered.
//! Even if your program panics, the Rust panic handler will (try to) run every destructor before exiting, and the escape code for showing the cursor will get printed by one of them.  
//! If all else fails, you can usually still fix your terminal manually using the `reset` command.
//!
//! ## Output while spinning
//!
//! The animation is printed to the terminal using control characters (and `\r`) to stay in the same line and always overwrite the last frame of the animation.
//! Because of this, access to the output needs to be synchronized: whenever there's something to be printed, the line with the animation needs to be erased first, then the thing is printed, and then the animation put back.
//! The [`Spinner`] takes care of this, but it can only do that when you go through its [`Conciliator`] methods -- instead of the [`Claw`]'s.
//! So, to prevent this from happening accidentally, the [`Spinner`] holds a mutable reference to the [`Claw`].
//! Of course, you *can* still mess it up by going to the standard output directly, i.e. using [`std::io::Stdout`], [`println`], [`dbg`], [`eprint`] and so on.
//! You *could* create multiple [`Claw`]s, too.
//! Don't.
//!
//! ## Async
//!
//! By default, creating a [`Spinner`] will spawn a new [thread](std::thread) to do the animation.
//! Then, when it is dropped, finished, or cleared, the "main" thread will *block* until the other thread returns.
//! While these blocks *should* resolve very quickly, it *could* still be an issue when used within a runtime / `async` executor, because while a thread is blocking, the runtime can't schedule something else on it.
//!
//! Because of this, there is another implementation of the [`Spinner`], specifically for use with the Tokio runtime.
//! It spawns a Tokio *task* instead of a thread, and it uses Tokio message queues instead of [`std::sync::mpsc`].
//! To use this implementation instead, enable the `tokio` crate feature.
//!
//! When you enable the `tokio` feature, [`Spinner::clear`] and [`Spinner::finish`] will become `async`, *and* you need to make sure to call one of them, as explained below.
//!
//! ## Dropping the [`Spinner`]
//!
//! **Only the *synchronous* [`Spinner`] should ever be dropped implicitly** (that is, without calling [`Spinner::clear`] or [`Spinner::finish`]).
//!
//! This means: if you enable the `tokio` feature (which is off by default), you have to **make sure to call and await** [`Spinner::clear`] or [`Spinner::finish`] when you're done with it!
//! If you don't explicitly drop it using one of these methods, the destructor for it has to clean it up, and it may do a worse job.
//! Because destructors cannot be `async`, the task will be *aborted* instead of *joined*, which *should* still work, but it *could* cause one or two lines of output being mangled.
//!
//! Again, this is only an issue if you drop the [`Spinner`] without calling either [`Spinner::clear`] or [`Spinner::finish`], **and** the `tokio` feature is enabled.
//! For the default, thread-based implementation, dropping the [`Spinner`] is exactly the same as calling [`Spinner::clear`] explicitly.
//!
//!
//! ## Example
//!
//! Creating a [`Spinner`] with the [`DOT`] [`Animation`] (taken from [FGRibreau/spinners](https://github.com/FGRibreau/spinners)).
//!
//! ```
//! use conciliator::{Conciliator, Spinner};
//! use conciliator::spin::DOT;
#![cfg_attr(
	feature = "tokio",
	doc = "# #[tokio::main] async fn main() {")
]
//! // `mut` so that the Spinner can get an exclusive (mutable) reference
//! let mut con = conciliator::init();
//! con.status("Starting process");
//! let sp = Spinner::new(&mut con, DOT, "Downloading thing...");
//! // < download the thing >
//! sp.status("Download complete");
//! sp.message("Unpacking thing...");
//! // < unpack the thing >
//! sp.status("Thing unpacked");
//! sp.message("Process finished");
#![cfg_attr(
	feature = "tokio",
	doc = "sp.finish().await; // without the tokio feature, this is not async",
)]
#![cfg_attr(
	not(feature = "tokio"),
	doc = "sp.finish(); // with the tokio feature, finish is async"
)]
//! // you can only use the Claw after the Spinner is finished
//! con.info("Doing other thing");
#![cfg_attr(feature = "tokio", doc = "# }")]
//! ```

mod animation;
#[cfg(feature = "tokio")]
mod task;
#[cfg(any(test, not(feature = "tokio")))]
mod thread;
pub use animation::{
	CHASE,
	DOT,
	LOOP,
	LOOP_WIDE,
	SQUARE,
	TRIANGLE,
	Animate,
	Animation
};

mod line;
pub use line::{
	Line,
	Message,
	NoNewLine
};

use crate::{
	Buffer,
	Claw,
	Conciliator,
	GetLine
};
use crate::core::InitialContent;


/// Show that something is ongoing with an animated tag & message
///
/// This starts a separate thread (or [task](self#async)) that periodically overwrites the last line of the output to show the next frame of the animation.
/// Any other output would interfere with this, so this struct tries to guard against that by holding a mutable reference to the [`Claw`] that spawned it.
/// This ensures that that particular [`Claw`] can't be used for the lifetime of the [`Spinner`].
///
/// See the [module-level](self) documentation for more.
pub struct Spinner<'c> {
	claw: &'c mut Claw,
	handle: Handle
}

enum Handle {
	Dummy(Claw),
	#[cfg(any(test, not(feature = "tokio")))]
	Thread(thread::Handle),
	#[cfg(feature = "tokio")]
	Task(task::Handle)
}


/*
 *	SPINNER
 */

impl<'c> Spinner<'c> {
	/// Create a new [`Spinner`] using the given animation and message
	///
	pub fn new<A, I>(claw: &'c mut Claw, animate: A, message: I) -> Self
		where A: Animate + Send + 'static,
			I: InitialContent
	{
		let mut msg = claw.err.buffer();
		message.init_buffer(&mut msg);
		let handle = Handle::spawn(claw.clone(), animate, msg);
		Self { claw, handle }
	}

	pub(crate) fn print_buffer(&self, buffer: Buffer) {
		self.handle.send_line(buffer);
	}
	pub(crate) fn set_message(&self, buffer: Buffer) {
		self.handle.send_message(buffer);
	}

	/// Update the spinner message
	///
	/// The message should be short enough to fit on a single line in the terminal, and it should not contain any newlines.
	/// If the message line wraps to another line, the spinner will get messed up and leave behind lines that it shouldn't.
	pub fn message<I: InitialContent>(&self, init: I) -> Message {
		let mut msg = Message::new(self);
		init.init_buffer(&mut msg);
		msg
	}

	/// Stop spinning
	///
	/// This changes the animation frame to show the spinner is done and un-hides the cursor.
	/// The last [`message`](Self::message) set will be written out and become part of the normal output.
	///
	/// Note that with the `tokio` feature, this function is `async`.
	#[cfg(not(feature = "tokio"))]
	pub fn finish(self) {
		self.handle.finish();
	}

	/// Stop spinning
	///
	/// This changes the animation frame to show the spinner is done and un-hides the cursor.
	/// The last [`message`](Self::message) set will be written out and become part of the normal output.
	///
	/// Note that without the `tokio` feature, this function is *not* `async`.
	#[cfg(feature = "tokio")]
	pub async fn finish(self) {
		self.handle.finish().await;
	}

	/// Stop spinning & remove the message line (equivalent to dropping)
	///
	/// Note that with the `tokio` feature, this function is `async`, and not equivalent to dropping.
	#[cfg(not(feature = "tokio"))]
	pub fn clear(self) {
		self.handle.clear();
	}

	/// Stop spinning & remove the message line
	///
	/// Note that without the `tokio` feature, this function is *not* `async`.
	#[cfg(feature = "tokio")]
	pub async fn clear(self) {
		self.handle.clear().await;
	}

	#[cfg(test)]
	fn spawn_dummy(claw: &'c mut Claw) -> Self {
		let handle = Handle::Dummy(claw.clone());
		Self { claw, handle }
	}

	#[cfg(not(feature = "tokio"))]
	#[cfg(test)]
	fn spawn_thread<A>(claw: &'c mut Claw, anim: A) -> Self
		where A: Animate + Send + 'static
	{
		let msg = claw.err.buffer();
		let handle = Handle::Thread(
			thread::Handle::spawn(claw.clone(), anim, msg)
		);
		Self { claw, handle }
	}

	#[cfg(all(test, feature = "tokio"))]
	fn spawn_task<A>(claw: &'c mut Claw, anim: A) -> Self
		where A: Animate + Send + 'static
	{
		let msg = claw.err.buffer();
		let handle = Handle::Task(
			task::Handle::spawn(claw.clone(), anim, msg)
		);
		Self { claw, handle }
	}
}

impl<'l, 'c> GetLine<'l> for Spinner<'c> {
	type Line = Line<'l>;
	fn get_line(&'l self) -> Self::Line {Line::new(self)}
}

impl<'c> Conciliator for Spinner<'c> {}

/*
 *	HANDLE
 */

impl Handle {
	pub(crate) fn spawn<A>(claw: Claw, anim: A, msg: Buffer) -> Self
		where A: Animate + Send + 'static
	{
		if !claw.err.colors_enabled() {
			return Self::Dummy(claw);
		}
		#[cfg(feature = "tokio")] {
			#[cfg(test)]
			match tokio::runtime::Handle::try_current().is_ok() {
				true => Self::Task(task::Handle::spawn(claw, anim, msg)),
				false => Self::Thread(thread::Handle::spawn(claw, anim, msg))
			}
			#[cfg(not(test))]
			Self::Task(task::Handle::spawn(claw, anim, msg))
		}
		#[cfg(not(feature = "tokio"))] {
			Self::Thread(thread::Handle::spawn(claw, anim, msg))
		}
	}
	pub(crate) fn send_line(&self, buffer: Buffer) {
		match self {
			Self::Dummy(claw) => claw.out.print_buffer(&buffer).unwrap(),
			#[cfg(any(test, not(feature = "tokio")))]
			Self::Thread(handle) => handle.send_line(buffer),
			#[cfg(feature = "tokio")]
			Self::Task(handle) => handle.send_line(buffer)
		}
	}

	pub(crate) fn send_message(&self, buffer: Buffer) {
		match self {
			Self::Dummy(_claw) => {},
			#[cfg(any(test, not(feature = "tokio")))]
			Self::Thread(handle) => handle.send_message(buffer),
			#[cfg(feature = "tokio")]
			Self::Task(handle) => handle.send_message(buffer)
		}
	}
	#[cfg(feature = "tokio")]
	pub(crate) async fn finish(self) {
		match self {
			Self::Dummy(_claw) => {},
			//#[cfg(any(test, not(feature = "tokio")))]
			#[cfg(test)]
			Self::Thread(handle) => handle.finish(),
			#[cfg(feature = "tokio")]
			Self::Task(handle) => handle.finish().await
		}
	}
	#[cfg(feature = "tokio")]
	pub(crate) async fn clear(self) {
		match self {
			Self::Dummy(_claw) => {},
			//#[cfg(any(test, not(feature = "tokio")))]
			#[cfg(test)]
			Self::Thread(handle) => handle.clear(),
			#[cfg(feature = "tokio")]
			Self::Task(handle) => handle.clear().await
		}
	}
	#[cfg(not(feature = "tokio"))]
	pub(crate) fn finish(self) {
		match self {
			Self::Dummy(_claw) => {},
			Self::Thread(handle) => handle.finish(),
		}
	}
	#[cfg(not(feature = "tokio"))]
	pub(crate) fn clear(self) {
		match self {
			Self::Dummy(_claw) => {},
			Self::Thread(handle) => handle.clear(),
		}
	}
}

#[test]
fn dummy_spin() {
	let mut con = crate::init();
	let sp = Spinner::spawn_dummy(&mut con);
	drop(sp);
}

#[cfg(not(feature = "tokio"))]
#[test]
fn thread_spin() {
	let mut con = crate::init();
	let sp = Spinner::spawn_thread(&mut con, LOOP);
	drop(sp);
	let sp = Spinner::spawn_thread(&mut con, LOOP);
	sp.clear();
	let sp = Spinner::spawn_thread(&mut con, LOOP);
	sp.finish();
}

#[cfg(feature = "tokio")]
#[tokio::test]
async fn task_spin() {
	let mut con = crate::init();
	let sp = Spinner::spawn_task(&mut con, SQUARE);
	sp.clear().await;
	let sp = Spinner::spawn_task(&mut con, SQUARE);
	sp.finish().await;
	let sp = Spinner::spawn_task(&mut con, SQUARE);
	drop(sp);
}