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