]> git.lizzy.rs Git - rust.git/blob - src/libterm/lib.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / libterm / lib.rs
1 // Copyright 2013-2014 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 implementations,
15 //! the `TerminfoTerminal`, which uses control characters from a
16 //! [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
17 //! API][win].
18 //!
19 //! # Examples
20 //!
21 //! ```no_run
22 //! extern crate term;
23 //!
24 //! fn main() {
25 //!     let mut t = term::stdout().unwrap();
26 //!
27 //!     t.fg(term::color::GREEN).unwrap();
28 //!     (write!(t, "hello, ")).unwrap();
29 //!
30 //!     t.fg(term::color::RED).unwrap();
31 //!     (writeln!(t, "world!")).unwrap();
32 //!
33 //!     t.reset().unwrap();
34 //! }
35 //! ```
36 //!
37 //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
38 //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
39 //! [ti]: https://en.wikipedia.org/wiki/Terminfo
40
41 #![crate_name = "term"]
42 #![unstable(feature = "rustc_private",
43             reason = "use the crates.io `term` library instead")]
44 #![staged_api]
45 #![crate_type = "rlib"]
46 #![crate_type = "dylib"]
47 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
48        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
49        html_root_url = "http://doc.rust-lang.org/nightly/",
50        html_playground_url = "http://play.rust-lang.org/")]
51 #![deny(missing_docs)]
52
53 #![feature(box_syntax)]
54 #![feature(collections)]
55 #![feature(int_uint)]
56 #![feature(old_io)]
57 #![feature(old_path)]
58 #![feature(rustc_private)]
59 #![feature(staged_api)]
60 #![feature(unicode)]
61 #![feature(std_misc)]
62 #![feature(env)]
63 #![cfg_attr(windows, feature(libc))]
64
65 #[macro_use] extern crate log;
66
67 pub use terminfo::TerminfoTerminal;
68 #[cfg(windows)]
69 pub use win::WinConsole;
70
71 use std::old_io::IoResult;
72
73 pub mod terminfo;
74
75 #[cfg(windows)]
76 mod win;
77
78 /// A hack to work around the fact that `Box<Writer + Send>` does not
79 /// currently implement `Writer`.
80 pub struct WriterWrapper {
81     wrapped: Box<Writer + Send>,
82 }
83
84 impl Writer for WriterWrapper {
85     #[inline]
86     fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
87         self.wrapped.write_all(buf)
88     }
89
90     #[inline]
91     fn flush(&mut self) -> IoResult<()> {
92         self.wrapped.flush()
93     }
94 }
95
96 #[cfg(not(windows))]
97 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
98 /// opened.
99 pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> {
100     TerminfoTerminal::new(WriterWrapper {
101         wrapped: box std::old_io::stdout() as Box<Writer + Send>,
102     })
103 }
104
105 #[cfg(windows)]
106 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
107 /// opened.
108 pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> {
109     let ti = TerminfoTerminal::new(WriterWrapper {
110         wrapped: box std::old_io::stdout() as Box<Writer + Send>,
111     });
112
113     match ti {
114         Some(t) => Some(t),
115         None => {
116             WinConsole::new(WriterWrapper {
117                 wrapped: box std::old_io::stdout() as Box<Writer + Send>,
118             })
119         }
120     }
121 }
122
123 #[cfg(not(windows))]
124 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
125 /// opened.
126 pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> {
127     TerminfoTerminal::new(WriterWrapper {
128         wrapped: box std::old_io::stderr() as Box<Writer + Send>,
129     })
130 }
131
132 #[cfg(windows)]
133 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
134 /// opened.
135 pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> {
136     let ti = TerminfoTerminal::new(WriterWrapper {
137         wrapped: box std::old_io::stderr() as Box<Writer + Send>,
138     });
139
140     match ti {
141         Some(t) => Some(t),
142         None => {
143             WinConsole::new(WriterWrapper {
144                 wrapped: box std::old_io::stderr() as Box<Writer + Send>,
145             })
146         }
147     }
148 }
149
150
151 /// Terminal color definitions
152 pub mod color {
153     /// Number for a terminal color
154     pub type Color = u16;
155
156     pub const BLACK:   Color = 0u16;
157     pub const RED:     Color = 1u16;
158     pub const GREEN:   Color = 2u16;
159     pub const YELLOW:  Color = 3u16;
160     pub const BLUE:    Color = 4u16;
161     pub const MAGENTA: Color = 5u16;
162     pub const CYAN:    Color = 6u16;
163     pub const WHITE:   Color = 7u16;
164
165     pub const BRIGHT_BLACK:   Color = 8u16;
166     pub const BRIGHT_RED:     Color = 9u16;
167     pub const BRIGHT_GREEN:   Color = 10u16;
168     pub const BRIGHT_YELLOW:  Color = 11u16;
169     pub const BRIGHT_BLUE:    Color = 12u16;
170     pub const BRIGHT_MAGENTA: Color = 13u16;
171     pub const BRIGHT_CYAN:    Color = 14u16;
172     pub const BRIGHT_WHITE:   Color = 15u16;
173 }
174
175 /// Terminal attributes
176 pub mod attr {
177     pub use self::Attr::*;
178
179     /// Terminal attributes for use with term.attr().
180     ///
181     /// Most attributes can only be turned on and must be turned off with term.reset().
182     /// The ones that can be turned off explicitly take a boolean value.
183     /// Color is also represented as an attribute for convenience.
184     #[derive(Copy)]
185     pub enum Attr {
186         /// Bold (or possibly bright) mode
187         Bold,
188         /// Dim mode, also called faint or half-bright. Often not supported
189         Dim,
190         /// Italics mode. Often not supported
191         Italic(bool),
192         /// Underline mode
193         Underline(bool),
194         /// Blink mode
195         Blink,
196         /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
197         Standout(bool),
198         /// Reverse mode, inverts the foreground and background colors
199         Reverse,
200         /// Secure mode, also called invis mode. Hides the printed text
201         Secure,
202         /// Convenience attribute to set the foreground color
203         ForegroundColor(super::color::Color),
204         /// Convenience attribute to set the background color
205         BackgroundColor(super::color::Color)
206     }
207 }
208
209 /// A terminal with similar capabilities to an ANSI Terminal
210 /// (foreground/background colors etc).
211 pub trait Terminal<T: Writer>: Writer {
212     /// Sets the foreground color to the given color.
213     ///
214     /// If the color is a bright color, but the terminal only supports 8 colors,
215     /// the corresponding normal color will be used instead.
216     ///
217     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
218     /// if there was an I/O error.
219     fn fg(&mut self, color: color::Color) -> IoResult<bool>;
220
221     /// Sets the background color to the given color.
222     ///
223     /// If the color is a bright color, but the terminal only supports 8 colors,
224     /// the corresponding normal color will be used instead.
225     ///
226     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
227     /// if there was an I/O error.
228     fn bg(&mut self, color: color::Color) -> IoResult<bool>;
229
230     /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
231     /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
232     /// there was an I/O error.
233     fn attr(&mut self, attr: attr::Attr) -> IoResult<bool>;
234
235     /// Returns whether the given terminal attribute is supported.
236     fn supports_attr(&self, attr: attr::Attr) -> bool;
237
238     /// Resets all terminal attributes and color to the default.
239     /// Returns `Ok()`.
240     fn reset(&mut self) -> IoResult<()>;
241
242     /// Gets an immutable reference to the stream inside
243     fn get_ref<'a>(&'a self) -> &'a T;
244
245     /// Gets a mutable reference to the stream inside
246     fn get_mut<'a>(&'a mut self) -> &'a mut T;
247 }
248
249 /// A terminal which can be unwrapped.
250 pub trait UnwrappableTerminal<T: Writer>: Terminal<T> {
251     /// Returns the contained stream, destroying the `Terminal`
252     fn unwrap(self) -> T;
253 }