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