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