]> git.proxmox.com Git - rustc.git/blob - src/libterm/lib.rs
5131e0b34e380ebf84e378ab443333a397f4ae82
[rustc.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 #![staged_api]
50 #![crate_type = "rlib"]
51 #![crate_type = "dylib"]
52 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
53 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
54 html_root_url = "http://doc.rust-lang.org/nightly/",
55 html_playground_url = "http://play.rust-lang.org/")]
56 #![deny(missing_docs)]
57
58 #![feature(box_syntax)]
59 #![feature(owned_ascii_ext)]
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 pub mod color {
156 /// Number for a terminal color
157 pub type Color = u16;
158
159 pub const BLACK: Color = 0;
160 pub const RED: Color = 1;
161 pub const GREEN: Color = 2;
162 pub const YELLOW: Color = 3;
163 pub const BLUE: Color = 4;
164 pub const MAGENTA: Color = 5;
165 pub const CYAN: Color = 6;
166 pub const WHITE: Color = 7;
167
168 pub const BRIGHT_BLACK: Color = 8;
169 pub const BRIGHT_RED: Color = 9;
170 pub const BRIGHT_GREEN: Color = 10;
171 pub const BRIGHT_YELLOW: Color = 11;
172 pub const BRIGHT_BLUE: Color = 12;
173 pub const BRIGHT_MAGENTA: Color = 13;
174 pub const BRIGHT_CYAN: Color = 14;
175 pub const BRIGHT_WHITE: Color = 15;
176 }
177
178 /// Terminal attributes
179 pub mod attr {
180 pub use self::Attr::*;
181
182 /// Terminal attributes for use with term.attr().
183 ///
184 /// Most attributes can only be turned on and must be turned off with term.reset().
185 /// The ones that can be turned off explicitly take a boolean value.
186 /// Color is also represented as an attribute for convenience.
187 #[derive(Copy, Clone)]
188 pub enum Attr {
189 /// Bold (or possibly bright) mode
190 Bold,
191 /// Dim mode, also called faint or half-bright. Often not supported
192 Dim,
193 /// Italics mode. Often not supported
194 Italic(bool),
195 /// Underline mode
196 Underline(bool),
197 /// Blink mode
198 Blink,
199 /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
200 Standout(bool),
201 /// Reverse mode, inverts the foreground and background colors
202 Reverse,
203 /// Secure mode, also called invis mode. Hides the printed text
204 Secure,
205 /// Convenience attribute to set the foreground color
206 ForegroundColor(super::color::Color),
207 /// Convenience attribute to set the background color
208 BackgroundColor(super::color::Color)
209 }
210 }
211
212 /// A terminal with similar capabilities to an ANSI Terminal
213 /// (foreground/background colors etc).
214 pub trait Terminal<T: Write>: Write {
215 /// Sets the foreground color to the given color.
216 ///
217 /// If the color is a bright color, but the terminal only supports 8 colors,
218 /// the corresponding normal color will be used instead.
219 ///
220 /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
221 /// if there was an I/O error.
222 fn fg(&mut self, color: color::Color) -> io::Result<bool>;
223
224 /// Sets the background color to the given color.
225 ///
226 /// If the color is a bright color, but the terminal only supports 8 colors,
227 /// the corresponding normal color will be used instead.
228 ///
229 /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
230 /// if there was an I/O error.
231 fn bg(&mut self, color: color::Color) -> io::Result<bool>;
232
233 /// Sets the given terminal attribute, if supported. Returns `Ok(true)`
234 /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
235 /// there was an I/O error.
236 fn attr(&mut self, attr: attr::Attr) -> io::Result<bool>;
237
238 /// Returns whether the given terminal attribute is supported.
239 fn supports_attr(&self, attr: attr::Attr) -> bool;
240
241 /// Resets all terminal attributes and color to the default.
242 /// Returns `Ok()`.
243 fn reset(&mut self) -> io::Result<()>;
244
245 /// Gets an immutable reference to the stream inside
246 fn get_ref<'a>(&'a self) -> &'a T;
247
248 /// Gets a mutable reference to the stream inside
249 fn get_mut<'a>(&'a mut self) -> &'a mut T;
250 }
251
252 /// A terminal which can be unwrapped.
253 pub trait UnwrappableTerminal<T: Write>: Terminal<T> {
254 /// Returns the contained stream, destroying the `Terminal`
255 fn unwrap(self) -> T;
256 }