]> git.lizzy.rs Git - rust.git/blob - src/libterm/lib.rs
Convert most code to new inner attribute syntax.
[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 //! Simple ANSI color library
12
13 #![crate_id = "term#0.10-pre"]
14 #![comment = "Simple ANSI color library"]
15 #![license = "MIT/ASL2"]
16 #![crate_type = "rlib"]
17 #![crate_type = "dylib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
20        html_root_url = "http://static.rust-lang.org/doc/master")]
21
22 #![feature(macro_rules)]
23 #![deny(missing_doc)]
24
25 extern crate collections;
26
27 use std::io;
28 use std::os;
29 use terminfo::TermInfo;
30 use terminfo::searcher::open;
31 use terminfo::parser::compiled::{parse, msys_terminfo};
32 use terminfo::parm::{expand, Number, Variables};
33
34 pub mod terminfo;
35
36 // FIXME (#2807): Windows support.
37
38 /// Terminal color definitions
39 pub mod color {
40     /// Number for a terminal color
41     pub type Color = u16;
42
43     pub static BLACK:   Color = 0u16;
44     pub static RED:     Color = 1u16;
45     pub static GREEN:   Color = 2u16;
46     pub static YELLOW:  Color = 3u16;
47     pub static BLUE:    Color = 4u16;
48     pub static MAGENTA: Color = 5u16;
49     pub static CYAN:    Color = 6u16;
50     pub static WHITE:   Color = 7u16;
51
52     pub static BRIGHT_BLACK:   Color = 8u16;
53     pub static BRIGHT_RED:     Color = 9u16;
54     pub static BRIGHT_GREEN:   Color = 10u16;
55     pub static BRIGHT_YELLOW:  Color = 11u16;
56     pub static BRIGHT_BLUE:    Color = 12u16;
57     pub static BRIGHT_MAGENTA: Color = 13u16;
58     pub static BRIGHT_CYAN:    Color = 14u16;
59     pub static BRIGHT_WHITE:   Color = 15u16;
60 }
61
62 /// Terminal attributes
63 pub mod attr {
64     /// Terminal attributes for use with term.attr().
65     ///
66     /// Most attributes can only be turned on and must be turned off with term.reset().
67     /// The ones that can be turned off explicitly take a boolean value.
68     /// Color is also represented as an attribute for convenience.
69     pub enum Attr {
70         /// Bold (or possibly bright) mode
71         Bold,
72         /// Dim mode, also called faint or half-bright. Often not supported
73         Dim,
74         /// Italics mode. Often not supported
75         Italic(bool),
76         /// Underline mode
77         Underline(bool),
78         /// Blink mode
79         Blink,
80         /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
81         Standout(bool),
82         /// Reverse mode, inverts the foreground and background colors
83         Reverse,
84         /// Secure mode, also called invis mode. Hides the printed text
85         Secure,
86         /// Convenience attribute to set the foreground color
87         ForegroundColor(super::color::Color),
88         /// Convenience attribute to set the background color
89         BackgroundColor(super::color::Color)
90     }
91 }
92
93 fn cap_for_attr(attr: attr::Attr) -> &'static str {
94     match attr {
95         attr::Bold               => "bold",
96         attr::Dim                => "dim",
97         attr::Italic(true)       => "sitm",
98         attr::Italic(false)      => "ritm",
99         attr::Underline(true)    => "smul",
100         attr::Underline(false)   => "rmul",
101         attr::Blink              => "blink",
102         attr::Standout(true)     => "smso",
103         attr::Standout(false)    => "rmso",
104         attr::Reverse            => "rev",
105         attr::Secure             => "invis",
106         attr::ForegroundColor(_) => "setaf",
107         attr::BackgroundColor(_) => "setab"
108     }
109 }
110
111 /// A Terminal that knows how many colors it supports, with a reference to its
112 /// parsed TermInfo database record.
113 pub struct Terminal<T> {
114     priv num_colors: u16,
115     priv out: T,
116     priv ti: ~TermInfo
117 }
118
119 impl<T: Writer> Terminal<T> {
120     /// Returns a wrapped output stream (`Terminal<T>`) as a `Result`.
121     ///
122     /// Returns `Err()` if the TERM environment variable is undefined.
123     /// TERM should be set to something like `xterm-color` or `screen-256color`.
124     ///
125     /// Returns `Err()` on failure to open the terminfo database correctly.
126     /// Also, in the event that the individual terminfo database entry can not
127     /// be parsed.
128     pub fn new(out: T) -> Result<Terminal<T>, ~str> {
129         let term = match os::getenv("TERM") {
130             Some(t) => t,
131             None => return Err(~"TERM environment variable undefined")
132         };
133
134         let entry = open(term);
135         if entry.is_err() {
136             if "cygwin" == term { // msys terminal
137                 return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8});
138             }
139             return Err(entry.unwrap_err());
140         }
141
142         let mut file = entry.unwrap();
143         let ti = parse(&mut file, false);
144         if ti.is_err() {
145             return Err(ti.unwrap_err());
146         }
147
148         let inf = ti.unwrap();
149         let nc = if inf.strings.find_equiv(&("setaf")).is_some()
150                  && inf.strings.find_equiv(&("setab")).is_some() {
151                      inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n)
152                  } else { 0 };
153
154         return Ok(Terminal {out: out, ti: inf, num_colors: nc});
155     }
156     /// Sets the foreground color to the given color.
157     ///
158     /// If the color is a bright color, but the terminal only supports 8 colors,
159     /// the corresponding normal color will be used instead.
160     ///
161     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
162     /// if there was an I/O error.
163     pub fn fg(&mut self, color: color::Color) -> io::IoResult<bool> {
164         let color = self.dim_if_necessary(color);
165         if self.num_colors > color {
166             let s = expand(self.ti
167                                .strings
168                                .find_equiv(&("setaf"))
169                                .unwrap()
170                                .as_slice(),
171                            [Number(color as int)], &mut Variables::new());
172             if s.is_ok() {
173                 try!(self.out.write(s.unwrap().as_slice()));
174                 return Ok(true)
175             }
176         }
177         Ok(false)
178     }
179     /// Sets the background color to the given color.
180     ///
181     /// If the color is a bright color, but the terminal only supports 8 colors,
182     /// the corresponding normal color will be used instead.
183     ///
184     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
185     /// if there was an I/O error.
186     pub fn bg(&mut self, color: color::Color) -> io::IoResult<bool> {
187         let color = self.dim_if_necessary(color);
188         if self.num_colors > color {
189             let s = expand(self.ti
190                                .strings
191                                .find_equiv(&("setab"))
192                                .unwrap()
193                                .as_slice(),
194                            [Number(color as int)], &mut Variables::new());
195             if s.is_ok() {
196                 try!(self.out.write(s.unwrap().as_slice()));
197                 return Ok(true)
198             }
199         }
200         Ok(false)
201     }
202
203     /// Sets the given terminal attribute, if supported.
204     /// Returns `Ok(true)` if the attribute was supported, `Ok(false)` otherwise,
205     /// and `Err(e)` if there was an I/O error.
206     pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult<bool> {
207         match attr {
208             attr::ForegroundColor(c) => self.fg(c),
209             attr::BackgroundColor(c) => self.bg(c),
210             _ => {
211                 let cap = cap_for_attr(attr);
212                 let parm = self.ti.strings.find_equiv(&cap);
213                 if parm.is_some() {
214                     let s = expand(parm.unwrap().as_slice(),
215                                    [],
216                                    &mut Variables::new());
217                     if s.is_ok() {
218                         try!(self.out.write(s.unwrap().as_slice()));
219                         return Ok(true)
220                     }
221                 }
222                 Ok(false)
223             }
224         }
225     }
226
227     /// Returns whether the given terminal attribute is supported.
228     pub fn supports_attr(&self, attr: attr::Attr) -> bool {
229         match attr {
230             attr::ForegroundColor(_) | attr::BackgroundColor(_) => {
231                 self.num_colors > 0
232             }
233             _ => {
234                 let cap = cap_for_attr(attr);
235                 self.ti.strings.find_equiv(&cap).is_some()
236             }
237         }
238     }
239
240     /// Resets all terminal attributes and color to the default.
241     /// Returns `Ok()`.
242     pub fn reset(&mut self) -> io::IoResult<()> {
243         let mut cap = self.ti.strings.find_equiv(&("sgr0"));
244         if cap.is_none() {
245             // are there any terminals that have color/attrs and not sgr0?
246             // Try falling back to sgr, then op
247             cap = self.ti.strings.find_equiv(&("sgr"));
248             if cap.is_none() {
249                 cap = self.ti.strings.find_equiv(&("op"));
250             }
251         }
252         let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| {
253             expand(op.as_slice(), [], &mut Variables::new())
254         });
255         if s.is_ok() {
256             return self.out.write(s.unwrap().as_slice())
257         }
258         Ok(())
259     }
260
261     fn dim_if_necessary(&self, color: color::Color) -> color::Color {
262         if color >= self.num_colors && color >= 8 && color < 16 {
263             color-8
264         } else { color }
265     }
266
267     /// Returns the contained stream
268     pub fn unwrap(self) -> T { self.out }
269
270     /// Gets an immutable reference to the stream inside
271     pub fn get_ref<'a>(&'a self) -> &'a T { &self.out }
272
273     /// Gets a mutable reference to the stream inside
274     pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out }
275 }
276
277 impl<T: Writer> Writer for Terminal<T> {
278     fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
279         self.out.write(buf)
280     }
281
282     fn flush(&mut self) -> io::IoResult<()> {
283         self.out.flush()
284     }
285 }