]> git.lizzy.rs Git - rust.git/blob - src/libterm/lib.rs
3584d2bd162284a8276bdc006fc45eed0c31c827
[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 #[allow(deprecated_owned_vector)]; // NOTE: remove after stage0
24
25 extern crate collections;
26
27 use std::os;
28 use std::io;
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 pub mod color {
39     pub type Color = u16;
40
41     pub static BLACK:   Color = 0u16;
42     pub static RED:     Color = 1u16;
43     pub static GREEN:   Color = 2u16;
44     pub static YELLOW:  Color = 3u16;
45     pub static BLUE:    Color = 4u16;
46     pub static MAGENTA: Color = 5u16;
47     pub static CYAN:    Color = 6u16;
48     pub static WHITE:   Color = 7u16;
49
50     pub static BRIGHT_BLACK:   Color = 8u16;
51     pub static BRIGHT_RED:     Color = 9u16;
52     pub static BRIGHT_GREEN:   Color = 10u16;
53     pub static BRIGHT_YELLOW:  Color = 11u16;
54     pub static BRIGHT_BLUE:    Color = 12u16;
55     pub static BRIGHT_MAGENTA: Color = 13u16;
56     pub static BRIGHT_CYAN:    Color = 14u16;
57     pub static BRIGHT_WHITE:   Color = 15u16;
58 }
59
60 pub mod attr {
61     /// Terminal attributes for use with term.attr().
62     /// Most attributes can only be turned on and must be turned off with term.reset().
63     /// The ones that can be turned off explicitly take a boolean value.
64     /// Color is also represented as an attribute for convenience.
65     pub enum Attr {
66         /// Bold (or possibly bright) mode
67         Bold,
68         /// Dim mode, also called faint or half-bright. Often not supported
69         Dim,
70         /// Italics mode. Often not supported
71         Italic(bool),
72         /// Underline mode
73         Underline(bool),
74         /// Blink mode
75         Blink,
76         /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
77         Standout(bool),
78         /// Reverse mode, inverts the foreground and background colors
79         Reverse,
80         /// Secure mode, also called invis mode. Hides the printed text
81         Secure,
82         /// Convenience attribute to set the foreground color
83         ForegroundColor(super::color::Color),
84         /// Convenience attribute to set the background color
85         BackgroundColor(super::color::Color)
86     }
87 }
88
89 fn cap_for_attr(attr: attr::Attr) -> &'static str {
90     match attr {
91         attr::Bold               => "bold",
92         attr::Dim                => "dim",
93         attr::Italic(true)       => "sitm",
94         attr::Italic(false)      => "ritm",
95         attr::Underline(true)    => "smul",
96         attr::Underline(false)   => "rmul",
97         attr::Blink              => "blink",
98         attr::Standout(true)     => "smso",
99         attr::Standout(false)    => "rmso",
100         attr::Reverse            => "rev",
101         attr::Secure             => "invis",
102         attr::ForegroundColor(_) => "setaf",
103         attr::BackgroundColor(_) => "setab"
104     }
105 }
106
107 pub struct Terminal<T> {
108     priv num_colors: u16,
109     priv out: T,
110     priv ti: ~TermInfo
111 }
112
113 impl<T: Writer> Terminal<T> {
114     pub fn new(out: T) -> Result<Terminal<T>, ~str> {
115         let term = match os::getenv("TERM") {
116             Some(t) => t,
117             None => return Err(~"TERM environment variable undefined")
118         };
119
120         let entry = open(term);
121         if entry.is_err() {
122             if "cygwin" == term { // msys terminal
123                 return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8});
124             }
125             return Err(entry.unwrap_err());
126         }
127
128         let mut file = entry.unwrap();
129         let ti = parse(&mut file, false);
130         if ti.is_err() {
131             return Err(ti.unwrap_err());
132         }
133
134         let inf = ti.unwrap();
135         let nc = if inf.strings.find_equiv(&("setaf")).is_some()
136                  && inf.strings.find_equiv(&("setab")).is_some() {
137                      inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n)
138                  } else { 0 };
139
140         return Ok(Terminal {out: out, ti: inf, num_colors: nc});
141     }
142     /// Sets the foreground color to the given color.
143     ///
144     /// If the color is a bright color, but the terminal only supports 8 colors,
145     /// the corresponding normal color will be used instead.
146     ///
147     /// Returns Ok(true) if the color was set, Ok(false) otherwise, and Err(e)
148     /// if there was an I/O error
149     pub fn fg(&mut self, color: color::Color) -> io::IoResult<bool> {
150         let color = self.dim_if_necessary(color);
151         if self.num_colors > color {
152             let s = expand(*self.ti.strings.find_equiv(&("setaf")).unwrap(),
153                            [Number(color as int)], &mut Variables::new());
154             if s.is_ok() {
155                 try!(self.out.write(s.unwrap()));
156                 return Ok(true)
157             }
158         }
159         Ok(false)
160     }
161     /// Sets the background color to the given color.
162     ///
163     /// If the color is a bright color, but the terminal only supports 8 colors,
164     /// the corresponding normal color will be used instead.
165     ///
166     /// Returns Ok(true) if the color was set, Ok(false) otherwise, and Err(e)
167     /// if there was an I/O error
168     pub fn bg(&mut self, color: color::Color) -> io::IoResult<bool> {
169         let color = self.dim_if_necessary(color);
170         if self.num_colors > color {
171             let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(),
172                            [Number(color as int)], &mut Variables::new());
173             if s.is_ok() {
174                 try!(self.out.write(s.unwrap()));
175                 return Ok(true)
176             }
177         }
178         Ok(false)
179     }
180
181     /// Sets the given terminal attribute, if supported.
182     /// Returns Ok(true) if the attribute was supported, Ok(false) otherwise,
183     /// and Err(e) if there was an I/O error.
184     pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult<bool> {
185         match attr {
186             attr::ForegroundColor(c) => self.fg(c),
187             attr::BackgroundColor(c) => self.bg(c),
188             _ => {
189                 let cap = cap_for_attr(attr);
190                 let parm = self.ti.strings.find_equiv(&cap);
191                 if parm.is_some() {
192                     let s = expand(*parm.unwrap(), [], &mut Variables::new());
193                     if s.is_ok() {
194                         try!(self.out.write(s.unwrap()));
195                         return Ok(true)
196                     }
197                 }
198                 Ok(false)
199             }
200         }
201     }
202
203     /// Returns whether the given terminal attribute is supported.
204     pub fn supports_attr(&self, attr: attr::Attr) -> bool {
205         match attr {
206             attr::ForegroundColor(_) | attr::BackgroundColor(_) => {
207                 self.num_colors > 0
208             }
209             _ => {
210                 let cap = cap_for_attr(attr);
211                 self.ti.strings.find_equiv(&cap).is_some()
212             }
213         }
214     }
215
216     /// Resets all terminal attributes and color to the default.
217     pub fn reset(&mut self) -> io::IoResult<()> {
218         let mut cap = self.ti.strings.find_equiv(&("sgr0"));
219         if cap.is_none() {
220             // are there any terminals that have color/attrs and not sgr0?
221             // Try falling back to sgr, then op
222             cap = self.ti.strings.find_equiv(&("sgr"));
223             if cap.is_none() {
224                 cap = self.ti.strings.find_equiv(&("op"));
225             }
226         }
227         let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| {
228             expand(*op, [], &mut Variables::new())
229         });
230         if s.is_ok() {
231             return self.out.write(s.unwrap())
232         }
233         Ok(())
234     }
235
236     fn dim_if_necessary(&self, color: color::Color) -> color::Color {
237         if color >= self.num_colors && color >= 8 && color < 16 {
238             color-8
239         } else { color }
240     }
241
242     pub fn unwrap(self) -> T { self.out }
243
244     pub fn get_ref<'a>(&'a self) -> &'a T { &self.out }
245
246     pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out }
247 }
248
249 impl<T: Writer> Writer for Terminal<T> {
250     fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
251         self.out.write(buf)
252     }
253
254     fn flush(&mut self) -> io::IoResult<()> {
255         self.out.flush()
256     }
257 }