]> git.lizzy.rs Git - rust.git/blob - src/libterm/lib.rs
Various minor/cosmetic improvements to code
[rust.git] / src / libterm / lib.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Terminal formatting library.
12 //!
13 //! This crate provides the `Terminal` trait, which abstracts over an [ANSI
14 //! Terminal][ansi] to provide color printing, among other things. There are two
15 //! implementations, the `TerminfoTerminal`, which uses control characters from
16 //! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
17 //! API][win].
18 //!
19 //! # Examples
20 //!
21 //! ```no_run
22 //! # #![feature(rustc_private)]
23 //! extern crate term;
24 //! use std::io::prelude::*;
25 //!
26 //! fn main() {
27 //!     let mut t = term::stdout().unwrap();
28 //!
29 //!     t.fg(term::color::GREEN).unwrap();
30 //!     write!(t, "hello, ").unwrap();
31 //!
32 //!     t.fg(term::color::RED).unwrap();
33 //!     writeln!(t, "world!").unwrap();
34 //!
35 //!     assert!(t.reset().unwrap());
36 //! }
37 //! ```
38 //!
39 //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
40 //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
41 //! [ti]: https://en.wikipedia.org/wiki/Terminfo
42
43 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
44        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
45        html_root_url = "https://doc.rust-lang.org/nightly/",
46        html_playground_url = "https://play.rust-lang.org/",
47        test(attr(deny(warnings))))]
48 #![deny(missing_docs)]
49
50 #![cfg_attr(windows, feature(libc))]
51 // Handle rustfmt skips
52 #![feature(custom_attribute)]
53 #![feature(nll)]
54 #![allow(unused_attributes)]
55
56 use std::io::prelude::*;
57
58 pub use terminfo::TerminfoTerminal;
59 #[cfg(windows)]
60 pub use win::WinConsole;
61
62 use std::io::{self, Stdout, Stderr};
63
64 pub mod terminfo;
65
66 #[cfg(windows)]
67 mod win;
68
69 /// Alias for stdout terminals.
70 pub type StdoutTerminal = dyn Terminal<Output = Stdout> + Send;
71 /// Alias for stderr terminals.
72 pub type StderrTerminal = dyn Terminal<Output = Stderr> + Send;
73
74 #[cfg(not(windows))]
75 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
76 /// opened.
77 pub fn stdout() -> Option<Box<StdoutTerminal>> {
78     TerminfoTerminal::new(io::stdout()).map(|t| Box::new(t) as Box<StdoutTerminal>)
79 }
80
81 #[cfg(windows)]
82 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
83 /// opened.
84 pub fn stdout() -> Option<Box<StdoutTerminal>> {
85     TerminfoTerminal::new(io::stdout())
86         .map(|t| Box::new(t) as Box<StdoutTerminal>)
87         .or_else(|| WinConsole::new(io::stdout()).ok().map(|t| Box::new(t) as Box<StdoutTerminal>))
88 }
89
90 #[cfg(not(windows))]
91 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
92 /// opened.
93 pub fn stderr() -> Option<Box<StderrTerminal>> {
94     TerminfoTerminal::new(io::stderr()).map(|t| Box::new(t) as Box<StderrTerminal>)
95 }
96
97 #[cfg(windows)]
98 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
99 /// opened.
100 pub fn stderr() -> Option<Box<StderrTerminal>> {
101     TerminfoTerminal::new(io::stderr())
102         .map(|t| Box::new(t) as Box<StderrTerminal>)
103         .or_else(|| WinConsole::new(io::stderr()).ok().map(|t| Box::new(t) as Box<StderrTerminal>))
104 }
105
106
107 /// Terminal color definitions
108 #[allow(missing_docs)]
109 pub mod color {
110     /// Number for a terminal color
111     pub type Color = u16;
112
113     pub const BLACK: Color = 0;
114     pub const RED: Color = 1;
115     pub const GREEN: Color = 2;
116     pub const YELLOW: Color = 3;
117     pub const BLUE: Color = 4;
118     pub const MAGENTA: Color = 5;
119     pub const CYAN: Color = 6;
120     pub const WHITE: Color = 7;
121
122     pub const BRIGHT_BLACK: Color = 8;
123     pub const BRIGHT_RED: Color = 9;
124     pub const BRIGHT_GREEN: Color = 10;
125     pub const BRIGHT_YELLOW: Color = 11;
126     pub const BRIGHT_BLUE: Color = 12;
127     pub const BRIGHT_MAGENTA: Color = 13;
128     pub const BRIGHT_CYAN: Color = 14;
129     pub const BRIGHT_WHITE: Color = 15;
130 }
131
132 /// Terminal attributes for use with term.attr().
133 ///
134 /// Most attributes can only be turned on and must be turned off with term.reset().
135 /// The ones that can be turned off explicitly take a boolean value.
136 /// Color is also represented as an attribute for convenience.
137 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
138 pub enum Attr {
139     /// Bold (or possibly bright) mode
140     Bold,
141     /// Dim mode, also called faint or half-bright. Often not supported
142     Dim,
143     /// Italics mode. Often not supported
144     Italic(bool),
145     /// Underline mode
146     Underline(bool),
147     /// Blink mode
148     Blink,
149     /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
150     Standout(bool),
151     /// Reverse mode, inverts the foreground and background colors
152     Reverse,
153     /// Secure mode, also called invis mode. Hides the printed text
154     Secure,
155     /// Convenience attribute to set the foreground color
156     ForegroundColor(color::Color),
157     /// Convenience attribute to set the background color
158     BackgroundColor(color::Color),
159 }
160
161 /// A terminal with similar capabilities to an ANSI Terminal
162 /// (foreground/background colors etc).
163 pub trait Terminal: Write {
164     /// The terminal's output writer type.
165     type Output: Write;
166
167     /// Sets the foreground color to the given color.
168     ///
169     /// If the color is a bright color, but the terminal only supports 8 colors,
170     /// the corresponding normal color will be used instead.
171     ///
172     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
173     /// if there was an I/O error.
174     fn fg(&mut self, color: color::Color) -> io::Result<bool>;
175
176     /// Sets the background color to the given color.
177     ///
178     /// If the color is a bright color, but the terminal only supports 8 colors,
179     /// the corresponding normal color will be used instead.
180     ///
181     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
182     /// if there was an I/O error.
183     fn bg(&mut self, color: color::Color) -> io::Result<bool>;
184
185     /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
186     /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
187     /// there was an I/O error.
188     fn attr(&mut self, attr: Attr) -> io::Result<bool>;
189
190     /// Returns whether the given terminal attribute is supported.
191     fn supports_attr(&self, attr: Attr) -> bool;
192
193     /// Resets all terminal attributes and colors to their defaults.
194     ///
195     /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there
196     /// was an I/O error.
197     ///
198     /// *Note: This does not flush.*
199     ///
200     /// That means the reset command may get buffered so, if you aren't planning on doing anything
201     /// else that might flush stdout's buffer (e.g., writing a line of text), you should flush after
202     /// calling reset.
203     fn reset(&mut self) -> io::Result<bool>;
204
205     /// Gets an immutable reference to the stream inside
206     fn get_ref(&self) -> &Self::Output;
207
208     /// Gets a mutable reference to the stream inside
209     fn get_mut(&mut self) -> &mut Self::Output;
210
211     /// Returns the contained stream, destroying the `Terminal`
212     fn into_inner(self) -> Self::Output where Self: Sized;
213 }