conciliator 0.3.10

[WIP] Library for interactive CLI programs
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/*! Writing colored text to the terminal */

use std::fmt::Display;
use std::io;
use std::io::{
	Write,
	Result as IoResult,
	ErrorKind,
	Read
};
use std::os::fd::{
	AsFd,
	AsRawFd,
	RawFd
};
use std::ops::{
	Deref,
	DerefMut
};

use termios::{
	ECHO,
	ICANON,
	TCSANOW,
	Termios,
	tcsetattr,
};

#[macro_use]
pub(crate) mod escapes {
	#![allow(dead_code)]
	pub const RESET: &str = "\x1B[0m";
	pub const BOLD: &str = "\x1B[1m";
	pub const DIMMED: &str ="\x1B[2m";
	pub const ITALIC: &str ="\x1B[3m";
	pub const UNDERLINE: &str ="\x1B[4m";
	/*
	const PREFIX: &str = "\x1B[";

	//color spec: PREFIX, [FG, BG], [INTENSE, ], [0-15], SUFFIX
	const FG: &str = "3";
	const BG: &str = "4";

	const INTENSE: &str = "8;5;";

	const SUFFIX: &str = "m";
	*/

	macro_rules! fg_normal {
		($color:literal) => {
			concat!("\x1B[", "3", $color, "m")
		};
	}
	macro_rules! fg_intense {
		($color:literal) => {
			concat!("\x1B[", "3", "8;5;", $color, "m")
		};
	}
}

/// Array of all [`ColorCode`]s, from [`White`](ColorCode::White) to [`IntenseBlack`](ColorCode::IntenseBlack)
///
/// Not ordered like the enum or according to the escape codes, but according to the colors they supposedly represent.
/// Each normal color is followed by its *intense* counterpart.
///
/// ```rust.no_run
/// pub const COLOR_CODES: [ColorCode; 16] = [
///     ColorCode::White,
///     ColorCode::IntenseWhite,
///     ColorCode::Yellow,
///     ColorCode::IntenseYellow,
///     ColorCode::Red,
///     ColorCode::IntenseRed,
///     ColorCode::Magenta,
///     ColorCode::IntenseMagenta,
///     ColorCode::Blue,
///     ColorCode::IntenseBlue,
///     ColorCode::Cyan,
///     ColorCode::IntenseCyan,
///     ColorCode::Green,
///     ColorCode::IntenseGreen,
///     ColorCode::Black,
///     ColorCode::IntenseBlack
/// ];
/// ```
pub const COLOR_CODES: [ColorCode; 16] = [
	ColorCode::White,
	ColorCode::IntenseWhite,
	ColorCode::Yellow,
	ColorCode::IntenseYellow,
	ColorCode::Red,
	ColorCode::IntenseRed,
	ColorCode::Magenta,
	ColorCode::IntenseMagenta,
	ColorCode::Blue,
	ColorCode::IntenseBlue,
	ColorCode::Cyan,
	ColorCode::IntenseCyan,
	ColorCode::Green,
	ColorCode::IntenseGreen,
	ColorCode::Black,
	ColorCode::IntenseBlack
];

/// Terminal colors provided by [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors)
///
/// Currently implements only the basic named set, 8 normal and 8 intense ("bright") colors.
/// Also limited to setting the foreground color, for now.
///
/// | Color          | Number |
/// |:---------------|-------:|
/// | Black          |      0 |
/// | Blue           |      4 |
/// | Green          |      2 |
/// | Red            |      1 |
/// | Cyan           |      6 |
/// | Magenta        |      5 |
/// | Yellow         |      3 |
/// | White          |      7 |
/// | IntenseBlack   |      8 |
/// | IntenseBlue    |     12 |
/// | IntenseGreen   |     10 |
/// | IntenseRed     |      9 |
/// | IntenseCyan    |     14 |
/// | IntenseMagenta |     13 |
/// | IntenseYellow  |     11 |
/// | IntenseWhite   |     15 |
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum ColorCode {
	Black,
	Blue,
	Green,
	Red,
	Cyan,
	Magenta,
	Yellow,
	White,
	IntenseBlack,
	IntenseBlue,
	IntenseGreen,
	IntenseRed,
	IntenseCyan,
	IntenseMagenta,
	IntenseYellow,
	IntenseWhite
}

/*
pub enum TextStyle {
	Bold,
	Dim,
	Italic,
	Underline
}
*/

/// Holds a lock on stdin and sets it to use non-blocking IO.
pub(crate) struct NonBlockingStdin<'l> {
	lock: io::StdinLock<'l>
}

/// RAII guard which resets (enables) terminal echo on the stored file descriptor when dropped.
/// Echo is disabled by the constructors for this struct.
pub(crate) struct EchoDisabler {
	fd: RawFd
}

/// Stores the sender used to fulfill an input request.
/// Sets the terminal to non-canonical input (i.e. not line-buffered) when first created and resets it to regular input when dropped.
pub(crate) struct InputRequest<T> {
	pub sender: T,
	pub buffer: Vec<u8>,
}

/// *[`Write`] for colors*: emit terminal color & style escape sequences *when possible*
///
/// Implementors like `stdout` and `stderr` [`Stream`](crate::core::Stream)s have the ability to prevent any escape codes from being emitted depending on whether a TTY is attached, the capabilites of that TTY, or simply user choice.
///
/// Not intended to be used directly, use [`Paint`](crate::Paint) instead (it is implemented for any `T: EmitEscapes`).
///
/// Currently supports only foreground colors and bold styling.
pub trait EmitEscapes: Write + Sized {
	/// If this returns `true`, escape codes will be emitted.
	///
	/// Otherwise, all calls to [`set_color`](Self::set_color), [`set_bold`](Self::set_bold) and [`reset`](Self::reset) are silently ignored.
	/// Further, [`write_with_color`](Self::write_with_color) and [`write_with_color_bold`](Self::write_with_color_bold) will write only what the `Display` implementor chooses to.
	fn escapes_recognized(&self) -> bool;

	/// Write a "foreground color" escape code (`\x1B[3???m`)
	fn set_color(&mut self, color: ColorCode) -> IoResult<()> {
		if self.escapes_recognized() {
			color.write(self)
		}
		else {Ok(())}
	}
	/// Write a "bold text" escape code (`\x1B[1m`)
	fn set_bold(&mut self) -> IoResult<()> {
		if self.escapes_recognized() {
			self.write_all(escapes::BOLD.as_bytes())
		}
		else {Ok(())}
	}
	/// Write a "reset style and color" escape code (`\x1B[0m`)
	fn reset(&mut self) -> IoResult<()> {
		if self.escapes_recognized() {
			self.write_all(escapes::RESET.as_bytes())
		}
		else {Ok(())}
	}

	/// [`set_color`](Self::set_color), then [`write!`](std::write) and then [`reset`](Self::reset), provided for convenience
	fn write_with_color<T: Display + ?Sized>(
		&mut self,
		color: ColorCode,
		thing: &T)
	{
		self.set_color(color).unwrap();
		write!(self, "{thing}").unwrap();
		self.reset().unwrap();
	}
	/// [`set_bold`](Self::set_bold) & [`set_color`](Self::set_color), then [`write!`](std::write) and then [`reset`](Self::reset), provided for convenience
	fn write_with_color_bold<T: Display + ?Sized>(
		&mut self,
		color: ColorCode,
		thing: &T)
	{
		self.set_bold().unwrap();
		self.set_color(color).unwrap();
		write!(self, "{thing}").unwrap();
		self.reset().unwrap();
	}
}


impl ColorCode {
	fn write<W: Write>(self, writer: &mut W) -> IoResult<()> {
		use ColorCode::*;
		//macros, match: credit termcolor
		let escape = match self {
			Black => fg_normal!("0"),
			Blue => fg_normal!("4"),
			Green => fg_normal!("2"),
			Red => fg_normal!("1"),
			Cyan => fg_normal!("6"),
			Magenta => fg_normal!("5"),
			Yellow => fg_normal!("3"),
			White => fg_normal!("7"),

			IntenseBlack => fg_intense!("8"),
			IntenseBlue => fg_intense!("12"),
			IntenseGreen => fg_intense!("10"),
			IntenseRed => fg_intense!("9"),
			IntenseCyan => fg_intense!("14"),
			IntenseMagenta => fg_intense!("13"),
			IntenseYellow => fg_intense!("11"),
			IntenseWhite => fg_intense!("15")
		};
		writer.write_all(escape.as_bytes())
	}
	pub(crate) const fn from_str(s: &str) -> Option<Self> {
		match s.as_bytes() {
			b"0"  | b"Black" => Some(Self::Black),
			b"4"  | b"Blue" => Some(Self::Blue),
			b"2"  | b"Green" => Some(Self::Green),
			b"1"  | b"Red" => Some(Self::Red),
			b"6"  | b"Cyan" => Some(Self::Cyan),
			b"5"  | b"Magenta" => Some(Self::Magenta),
			b"3"  | b"Yellow" => Some(Self::Yellow),
			b"7"  | b"White" => Some(Self::White),
			b"8"  | b"IntenseBlack" => Some(Self::IntenseBlack),
			b"12" | b"IntenseBlue" => Some(Self::IntenseBlue),
			b"10" | b"IntenseGreen" => Some(Self::IntenseGreen),
			b"9"  | b"IntenseRed" => Some(Self::IntenseRed),
			b"14" | b"IntenseCyan" => Some(Self::IntenseCyan),
			b"13" | b"IntenseMagenta" => Some(Self::IntenseMagenta),
			b"11" | b"IntenseYellow" => Some(Self::IntenseYellow),
			b"15" | b"IntenseWhite" => Some(Self::IntenseWhite),
			_ => None
		}
	}
	pub(crate) const fn as_number(self) -> u8 {
		match self {
			Self::Black => 0,
			Self::Blue => 4,
			Self::Green => 2,
			Self::Red => 1,
			Self::Cyan => 6,
			Self::Magenta => 5,
			Self::Yellow => 3,
			Self::White => 7,
			Self::IntenseBlack => 8,
			Self::IntenseBlue => 12,
			Self::IntenseGreen => 10,
			Self::IntenseRed => 9,
			Self::IntenseCyan => 14,
			Self::IntenseMagenta => 13,
			Self::IntenseYellow => 11,
			Self::IntenseWhite => 15
		}
	}
}


impl<E: EmitEscapes> EmitEscapes for &mut E {
	fn escapes_recognized(&self) -> bool {
		(**self).escapes_recognized()
	}
}

/*
 *	NON-BLOCKING STDIN
 */

impl NonBlockingStdin<'static> {
	pub fn unblock() -> io::Result<Self> {
		let lock = io::stdin().lock();
		set_nonblocking(&lock)?;
		Ok(Self {lock})
	}

	pub(crate) fn drain_input(&mut self, buffer: &mut Vec<u8>)
		-> io::Result<Option<String>>
	{
		const BACKSPACE: u8 = b'\x7F';
		const ESCAPE: u8 = b'\x1B';
		let mut byte = [0u8; 1];
		loop {
			match (self.read(&mut byte), byte[0]) {
				(Ok(0), _) |
				(Ok(1), b'\n' | b'\r' | 0x03 | 0x04) => {
					let buffer = std::mem::take(buffer);
					return match String::from_utf8(buffer) {
						Ok(s) => Ok(Some(s)),
						Err(e) => {
							let cow = String::from_utf8_lossy(e.as_bytes());
							Ok(Some(cow.into_owned()))
						}
					}
				},

				(Ok(1), BACKSPACE) => {
					if let Some((idx, _c)) = String::from_utf8_lossy(buffer)
						.char_indices()
						.next_back()
					{
						buffer.truncate(idx);
					}
				},
				// nerf escape codes
				(Ok(1), ESCAPE) => buffer.push(b'^'),
				(Ok(1), b) => buffer.push(b),

				(Ok(_n), _) => unreachable!(),
				(Err(e), _) if e.kind() == ErrorKind::Interrupted => continue,
				(Err(e), _) if e.kind() == ErrorKind::WouldBlock => break,
				(Err(err), _) => return Err(err)
			}
		}
		Ok(None)
	}
}

impl<'l> Deref for NonBlockingStdin<'l> {
	type Target = io::StdinLock<'l>;
	fn deref(&self) -> &Self::Target {&self.lock}
}

impl<'l> DerefMut for NonBlockingStdin<'l> {
	fn deref_mut(&mut self) -> &mut Self::Target {&mut self.lock}
}

impl<'l> Drop for NonBlockingStdin<'l> {
	fn drop(&mut self) {
		set_blocking(&self.lock)
			.expect("resetting stdin to blocking IO should succeed");
	}
}

/// Sets file descriptor's flags with `O_NONBLOCK` by fcntl.
///
/// Adapted from https://docs.rs/tokio/1.39.3/src/tokio/net/unix/pipe.rs.html#1408
fn set_nonblocking<T: AsFd>(fd: &T) -> io::Result<()> {
	// Safety: it's safe to use `fcntl` to read flags of a valid, open file descriptor.
	let previous = unsafe {
		libc::fcntl(fd.as_fd().as_raw_fd(), libc::F_GETFL)
	};
	if previous == -1 {
		return Err(io::Error::last_os_error());
	}
	let flags = previous | libc::O_NONBLOCK;

	if flags != previous {
		// Safety: it's safe to use `fcntl` to set the `O_NONBLOCK` flag of a valid, open file descriptor.
		let ret = unsafe {
			libc::fcntl(fd.as_fd().as_raw_fd(), libc::F_SETFL, flags)
		};
		if ret < 0 {
			return Err(io::Error::last_os_error());
		}
	}

	Ok(())
}

/// Removes `O_NONBLOCK` from fd's flags.
///
/// Adapted from https://docs.rs/tokio/1.39.3/src/tokio/net/unix/pipe.rs.html#1425
fn set_blocking<T: AsFd>(fd: &T) -> io::Result<()> {
	// Safety: it's safe to use `fcntl` to read flags of a valid, open file descriptor.
	let previous = unsafe {
		libc::fcntl(fd.as_fd().as_raw_fd(), libc::F_GETFL)
	};
	if previous == -1 {
		return Err(io::Error::last_os_error());
	}

	let flags = previous & !libc::O_NONBLOCK;

	if flags != previous {
		// Safety: it's safe to use `fcntl` to unset the `O_NONBLOCK` flag of a valid, open file descriptor.
		let r = unsafe {
			libc::fcntl(fd.as_fd().as_raw_fd(), libc::F_SETFL, flags)
		};
		if r == -1 {
			return Err(io::Error::last_os_error())
		}
	}
	Ok(())
}

/*
 *	ECHO DISABLER
 */

impl EchoDisabler {
	/// Disable terminal echo on stdin. Resets automatically when dropped.
	#[must_use = "Echo is disabled for the lifetime of the struct"]
	pub fn on_stdin() -> Self {
		let fd = std::io::stdin().as_raw_fd();
		Self::disable_with_fd(fd)
	}
	/// Disable terminal echo on stderr. Resets automatically when dropped.
	#[must_use = "Echo is disabled for the lifetime of the struct"]
	pub fn on_stderr() -> Self {
		let fd = std::io::stderr().as_raw_fd();
		Self::disable_with_fd(fd)
	}
	fn disable_with_fd(fd: RawFd) -> Self {
		let mut termios = Termios::from_fd(fd).unwrap();
		termios.c_lflag &= !ECHO;
		tcsetattr(fd, TCSANOW, &termios).unwrap();

		Self {fd}
	}

	/// Reset echo for the stored file descriptor. Equivalent to dropping.
	pub fn reset(self) {}


	/// Manually reset echo
	pub fn reset_stdin() {
		let fd = std::io::stdin().as_raw_fd();
		Self::reset_with_fd(fd)
	}
	/// Manually reset echo
	pub fn reset_stderr() {
		let fd = std::io::stderr().as_raw_fd();
		Self::reset_with_fd(fd)
	}
	fn reset_with_fd(fd: RawFd) {
		let mut termios = Termios::from_fd(fd).unwrap();
		termios.c_lflag |= ECHO;
		tcsetattr(fd, TCSANOW, &termios).unwrap();
	}
}

impl Drop for EchoDisabler {
	/// Reset echo for the stored file descriptor
	fn drop(&mut self) {
		Self::reset_with_fd(self.fd)
	}
}

#[test]
fn set_blocking_nonblocking() -> io::Result<()> {
	let mut stdin = io::stdin();

	set_nonblocking(&stdin)?;
	assert_eq!(
		stdin.read(&mut [0; 1]).map_err(|err| err.kind()),
		Err(io::ErrorKind::WouldBlock)
	);
	set_blocking(&stdin)?;

	Ok(())
}

/*
 *	INPUT REQUEST
 */

impl<T> InputRequest<T> {
	pub fn replace(stored: &mut Option<Self>, new_sender: T) {
		if let Some(old) = stored.as_mut() {
			old.sender = new_sender;
			//TODO why not just keep this around as over-read buffer?
			old.buffer.clear();
		}
		else {
			//TODO: error handling?
			let stdin_fd = io::stdin().as_raw_fd();
			let mut termios = Termios::from_fd(stdin_fd).unwrap();
			termios.c_lflag &= !ICANON;
			tcsetattr(stdin_fd, TCSANOW, &termios).unwrap();

			*stored = Some(Self { sender: new_sender, buffer: Vec::new() });
		}
	}
}

impl<T> Drop for InputRequest<T> {
	fn drop(&mut self) {
		let stdin_fd = io::stdin().as_raw_fd();
		let mut termios = Termios::from_fd(stdin_fd).unwrap();
		termios.c_lflag |= ICANON;
		tcsetattr(stdin_fd, TCSANOW, &termios).unwrap();
	}
}

#[test]
fn block_unblock() -> io::Result<()> {
	let nonblocking = NonBlockingStdin::unblock()?;
	drop(nonblocking);
	Ok(())
}