terminal_io/terminal.rs
1use duplex::Duplex;
2use std::io::{Read, Write};
3
4/// A trait for devices which may be connected to terminals.
5pub trait Terminal {}
6
7/// An extension trait for input streams connected to terminals.
8pub trait ReadTerminal: Read + Terminal {
9 /// Test whether the input is being sent a line at a time.
10 fn is_line_by_line(&self) -> bool;
11
12 /// Test whether the input is connected to a terminal.
13 ///
14 /// Also known as `isatty`.
15 fn is_input_terminal(&self) -> bool;
16}
17
18/// An extension trait for output streams connected to terminals.
19pub trait WriteTerminal: Write + Terminal {
20 /// Test whether color should be used on this terminal by default. This
21 /// includes both whether color is supported and whether the user has
22 /// not indicated a preference otherwise.
23 fn color_default(&self) -> bool {
24 self.color_support() != TerminalColorSupport::Monochrome && self.color_preference()
25 }
26
27 /// Test whether this output stream supports color control codes.
28 fn color_support(&self) -> TerminalColorSupport;
29
30 /// Test whether the user has indicated a preference for color output by
31 /// default. Respects the `NO_COLOR` environment variable where applicable.
32 fn color_preference(&self) -> bool;
33
34 /// Test whether the output is connected to a terminal.
35 ///
36 /// Also known as `isatty`.
37 fn is_output_terminal(&self) -> bool;
38}
39
40/// An extension trait for input/output streams connected to terminals.
41pub trait DuplexTerminal: ReadTerminal + WriteTerminal + Duplex {
42 /// Test whether both the input stream and output streams are connected to
43 /// terminals.
44 ///
45 /// Also known as `isatty`.
46 fn is_terminal(&self) -> bool {
47 self.is_input_terminal() && self.is_output_terminal()
48 }
49}
50
51/// Color support level, ranging from monochrome (color not supported) to
52/// 24-bit true color.
53#[derive(Copy, Clone, Debug, Eq, PartialEq)]
54pub enum TerminalColorSupport {
55 /// Color is not supported.
56 Monochrome,
57
58 /// Classic ANSI 8 colors. Sometimes extendable to 16 by using bold.
59 Classic8,
60
61 /// 256 colors with a "color cube". See [Wikipedia] for details.
62 ///
63 /// [Wikipedia]: https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
64 ColorCube256,
65
66 /// 24-bit "true color" support. See [Wikipedia] for details.
67 ///
68 /// [Wikipedia]: https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit
69 TrueColor,
70}
71
72impl Default for TerminalColorSupport {
73 #[inline]
74 fn default() -> Self {
75 Self::Monochrome
76 }
77}