]> git.lizzy.rs Git - rust.git/blob - src/libterm/lib.rs
76118f642abe0480722ffed527cd58ac3aeb7640
[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_id = "term#0.11.0-pre"]
42 #![comment = "Simple ANSI color library"]
43 #![license = "MIT/ASL2"]
44 #![crate_type = "rlib"]
45 #![crate_type = "dylib"]
46 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
47        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
48        html_root_url = "http://doc.rust-lang.org/",
49        html_playground_url = "http://play.rust-lang.org/")]
50
51 #![feature(macro_rules, phase)]
52
53 #![deny(missing_doc)]
54
55 #[cfg(stage0)] #[phase(syntax, link)] extern crate log;
56 #[cfg(not(stage0))] #[phase(plugin, link)] extern crate log;
57
58 pub use terminfo::TerminfoTerminal;
59 #[cfg(windows)]
60 pub use win::WinConsole;
61
62 use std::io::IoResult;
63
64 pub mod terminfo;
65
66 #[cfg(windows)]
67 mod win;
68
69 #[cfg(not(windows))]
70 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
71 /// opened.
72 pub fn stdout() -> Option<Box<Terminal<Box<Writer:Send>>:Send>> {
73     let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
74         = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
75     ti.map(|t| box t as Box<Terminal<Box<Writer:Send>:Send>:Send>)
76 }
77
78 #[cfg(windows)]
79 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
80 /// opened.
81 pub fn stdout() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>> {
82     let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
83         = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
84
85     match ti {
86         Some(t) => Some(box t as Box<Terminal<Box<Writer:Send>:Send>:Send>),
87         None => {
88             let wc: Option<WinConsole<Box<Writer:Send>>>
89                 = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
90             wc.map(|w| box w as Box<Terminal<Box<Writer:Send>:Send>:Send>)
91         }
92     }
93 }
94
95 #[cfg(not(windows))]
96 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
97 /// opened.
98 pub fn stderr() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>:Send> {
99     let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
100         = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
101     ti.map(|t| box t as Box<Terminal<Box<Writer:Send>:Send>:Send>)
102 }
103
104 #[cfg(windows)]
105 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
106 /// opened.
107 pub fn stderr() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>> {
108     let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
109         = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
110
111     match ti {
112         Some(t) => Some(box t as Box<Terminal<Box<Writer:Send>:Send>:Send>),
113         None => {
114             let wc: Option<WinConsole<Box<Writer:Send>>>
115                 = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
116             wc.map(|w| box w as Box<Terminal<Box<Writer:Send>:Send>:Send>)
117         }
118     }
119 }
120
121
122 /// Terminal color definitions
123 pub mod color {
124     /// Number for a terminal color
125     pub type Color = u16;
126
127     pub static BLACK:   Color = 0u16;
128     pub static RED:     Color = 1u16;
129     pub static GREEN:   Color = 2u16;
130     pub static YELLOW:  Color = 3u16;
131     pub static BLUE:    Color = 4u16;
132     pub static MAGENTA: Color = 5u16;
133     pub static CYAN:    Color = 6u16;
134     pub static WHITE:   Color = 7u16;
135
136     pub static BRIGHT_BLACK:   Color = 8u16;
137     pub static BRIGHT_RED:     Color = 9u16;
138     pub static BRIGHT_GREEN:   Color = 10u16;
139     pub static BRIGHT_YELLOW:  Color = 11u16;
140     pub static BRIGHT_BLUE:    Color = 12u16;
141     pub static BRIGHT_MAGENTA: Color = 13u16;
142     pub static BRIGHT_CYAN:    Color = 14u16;
143     pub static BRIGHT_WHITE:   Color = 15u16;
144 }
145
146 /// Terminal attributes
147 pub mod attr {
148     /// Terminal attributes for use with term.attr().
149     ///
150     /// Most attributes can only be turned on and must be turned off with term.reset().
151     /// The ones that can be turned off explicitly take a boolean value.
152     /// Color is also represented as an attribute for convenience.
153     pub enum Attr {
154         /// Bold (or possibly bright) mode
155         Bold,
156         /// Dim mode, also called faint or half-bright. Often not supported
157         Dim,
158         /// Italics mode. Often not supported
159         Italic(bool),
160         /// Underline mode
161         Underline(bool),
162         /// Blink mode
163         Blink,
164         /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
165         Standout(bool),
166         /// Reverse mode, inverts the foreground and background colors
167         Reverse,
168         /// Secure mode, also called invis mode. Hides the printed text
169         Secure,
170         /// Convenience attribute to set the foreground color
171         ForegroundColor(super::color::Color),
172         /// Convenience attribute to set the background color
173         BackgroundColor(super::color::Color)
174     }
175 }
176
177 /// A terminal with similar capabilities to an ANSI Terminal
178 /// (foreground/background colors etc).
179 pub trait Terminal<T: Writer>: Writer {
180     /// Returns `None` whenever the terminal cannot be created for some
181     /// reason.
182     fn new(out: T) -> Option<Self>;
183
184     /// Sets the foreground color to the given color.
185     ///
186     /// If the color is a bright color, but the terminal only supports 8 colors,
187     /// the corresponding normal color will be used instead.
188     ///
189     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
190     /// if there was an I/O error.
191     fn fg(&mut self, color: color::Color) -> IoResult<bool>;
192
193     /// Sets the background color to the given color.
194     ///
195     /// If the color is a bright color, but the terminal only supports 8 colors,
196     /// the corresponding normal color will be used instead.
197     ///
198     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
199     /// if there was an I/O error.
200     fn bg(&mut self, color: color::Color) -> IoResult<bool>;
201
202     /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
203     /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
204     /// there was an I/O error.
205     fn attr(&mut self, attr: attr::Attr) -> IoResult<bool>;
206
207     /// Returns whether the given terminal attribute is supported.
208     fn supports_attr(&self, attr: attr::Attr) -> bool;
209
210     /// Resets all terminal attributes and color to the default.
211     /// Returns `Ok()`.
212     fn reset(&mut self) -> IoResult<()>;
213
214     /// Returns the contained stream, destroying the `Terminal`
215     fn unwrap(self) -> T;
216
217     /// Gets an immutable reference to the stream inside
218     fn get_ref<'a>(&'a self) -> &'a T;
219
220     /// Gets a mutable reference to the stream inside
221     fn get_mut<'a>(&'a mut self) -> &'a mut T;
222 }