1 //! Terminal formatting module.
3 //! This module provides the `Terminal` trait, which abstracts over an [ANSI
4 //! Terminal][ansi] to provide color printing, among other things. There are two
5 //! implementations, the `TerminfoTerminal`, which uses control characters from
6 //! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
9 //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
10 //! [win]: https://docs.microsoft.com/en-us/windows/console/character-mode-applications
11 //! [ti]: https://en.wikipedia.org/wiki/Terminfo
13 #![deny(missing_docs)]
15 use std::io::{self, prelude::*};
17 pub(crate) use terminfo::TerminfoTerminal;
19 pub(crate) use win::WinConsole;
21 pub(crate) mod terminfo;
26 /// Alias for stdout terminals.
27 pub(crate) type StdoutTerminal = dyn Terminal + Send;
30 /// Returns a Terminal wrapping stdout, or None if a terminal couldn't be
32 pub(crate) fn stdout() -> Option<Box<StdoutTerminal>> {
33 TerminfoTerminal::new(io::stdout()).map(|t| Box::new(t) as Box<StdoutTerminal>)
37 /// Returns a Terminal wrapping stdout, or None if a terminal couldn't be
39 pub(crate) fn stdout() -> Option<Box<StdoutTerminal>> {
40 TerminfoTerminal::new(io::stdout())
41 .map(|t| Box::new(t) as Box<StdoutTerminal>)
42 .or_else(|| WinConsole::new(io::stdout()).ok().map(|t| Box::new(t) as Box<StdoutTerminal>))
45 /// Terminal color definitions
46 #[allow(missing_docs)]
47 #[cfg_attr(not(windows), allow(dead_code))]
48 pub(crate) mod color {
49 /// Number for a terminal color
50 pub(crate) type Color = u32;
52 pub(crate) const BLACK: Color = 0;
53 pub(crate) const RED: Color = 1;
54 pub(crate) const GREEN: Color = 2;
55 pub(crate) const YELLOW: Color = 3;
56 pub(crate) const BLUE: Color = 4;
57 pub(crate) const MAGENTA: Color = 5;
58 pub(crate) const CYAN: Color = 6;
59 pub(crate) const WHITE: Color = 7;
62 /// A terminal with similar capabilities to an ANSI Terminal
63 /// (foreground/background colors etc).
64 pub trait Terminal: Write {
65 /// Sets the foreground color to the given color.
67 /// If the color is a bright color, but the terminal only supports 8 colors,
68 /// the corresponding normal color will be used instead.
70 /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
71 /// if there was an I/O error.
72 fn fg(&mut self, color: color::Color) -> io::Result<bool>;
74 /// Resets all terminal attributes and colors to their defaults.
76 /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there
79 /// *Note: This does not flush.*
81 /// That means the reset command may get buffered so, if you aren't planning on doing anything
82 /// else that might flush stdout's buffer (e.g., writing a line of text), you should flush after
84 fn reset(&mut self) -> io::Result<bool>;