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