Skip to content

Commit

Permalink
auto merge of #6826 : cmr/rust/terminfo, r=thestinger
Browse files Browse the repository at this point in the history
This will let *everyone* (non-windows, at least) who can see colors see the glorious colors rustc produces.
  • Loading branch information
bors committed May 31, 2013
2 parents 5028ac7 + c91e97f commit 71f9dde
Show file tree
Hide file tree
Showing 9 changed files with 778 additions and 81 deletions.
2 changes: 2 additions & 0 deletions src/libextra/std.rc
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ pub mod flate;
#[cfg(unicode)]
mod unicode;

#[path="terminfo/terminfo.rs"]
pub mod terminfo;

// Compiler support modules

Expand Down
116 changes: 83 additions & 33 deletions src/libextra/term.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
Expand All @@ -15,9 +15,13 @@
use core::prelude::*;

use core::io;
use core::option;
use core::os;

use terminfo::*;
use terminfo::searcher::open;
use terminfo::parser::compiled::parse;
use terminfo::parm::{expand, Number};

// FIXME (#2807): Windows support.

pub static color_black: u8 = 0u8;
Expand All @@ -39,43 +43,89 @@ pub static color_bright_magenta: u8 = 13u8;
pub static color_bright_cyan: u8 = 14u8;
pub static color_bright_white: u8 = 15u8;

pub fn esc(writer: @io::Writer) { writer.write([0x1bu8, '[' as u8]); }
#[cfg(not(target_os = "win32"))]
pub struct Terminal {
color_supported: bool,
priv out: @io::Writer,
priv ti: ~TermInfo
}

/// Reset the foreground and background colors to default
pub fn reset(writer: @io::Writer) {
esc(writer);
writer.write(['0' as u8, 'm' as u8]);
#[cfg(target_os = "win32")]
pub struct Terminal {
color_supported: bool,
priv out: @io::Writer,
}

/// Returns true if the terminal supports color
pub fn color_supported() -> bool {
let supported_terms = ~[~"xterm-color", ~"xterm",
~"screen-bce", ~"xterm-256color"];
return match os::getenv("TERM") {
option::Some(ref env) => {
for supported_terms.each |term| {
if *term == *env { return true; }
#[cfg(not(target_os = "win32"))]
pub impl Terminal {
pub fn new(out: @io::Writer) -> Result<Terminal, ~str> {
let term = os::getenv("TERM");
if term.is_none() {
return Err(~"TERM environment variable undefined");
}

let entry = open(term.unwrap());
if entry.is_err() {
return Err(entry.get_err());
}

let ti = parse(entry.get(), false);
if ti.is_err() {
return Err(entry.get_err());
}

let mut inf = ti.get();
let cs = *inf.numbers.find_or_insert(~"colors", 0) >= 16 && inf.strings.find(&~"setaf").is_some()
&& inf.strings.find_equiv(&("setab")).is_some();

return Ok(Terminal {out: out, ti: inf, color_supported: cs});
}
fn fg(&self, color: u8) {
if self.color_supported {
let s = expand(*self.ti.strings.find_equiv(&("setaf")).unwrap(),
[Number(color as int)], [], []);
if s.is_ok() {
self.out.write(s.get());
} else {
warn!(s.get_err());
}
false
}
option::None => false
};
}
}
fn bg(&self, color: u8) {
if self.color_supported {
let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(),
[Number(color as int)], [], []);
if s.is_ok() {
self.out.write(s.get());
} else {
warn!(s.get_err());
}
}
}
fn reset(&self) {
if self.color_supported {
let s = expand(*self.ti.strings.find_equiv(&("op")).unwrap(), [], [], []);
if s.is_ok() {
self.out.write(s.get());
} else {
warn!(s.get_err());
}
}
}
}

pub fn set_color(writer: @io::Writer, first_char: u8, color: u8) {
assert!((color < 16u8));
esc(writer);
let mut color = color;
if color >= 8u8 { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}
#[cfg(target_os = "win32")]
pub impl Terminal {
pub fn new(out: @io::Writer) -> Result<Terminal, ~str> {
return Ok(Terminal {out: out, color_supported: false});
}

/// Set the foreground color
pub fn fg(writer: @io::Writer, color: u8) {
return set_color(writer, '3' as u8, color);
}
fn fg(&self, color: u8) {
}

fn bg(&self, color: u8) {
}

/// Set the background color
pub fn bg(writer: @io::Writer, color: u8) {
return set_color(writer, '4' as u8, color);
fn reset(&self) {
}
}
209 changes: 209 additions & 0 deletions src/libextra/terminfo/parm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Parameterized string expansion
use core::prelude::*;
use core::{char, int, vec};

#[deriving(Eq)]
enum States {
Nothing,
Percent,
SetVar,
GetVar,
PushParam,
CharConstant,
CharClose,
IntConstant,
IfCond,
IfBody
}

/// Types of parameters a capability can use
pub enum Param {
String(~str),
Char(char),
Number(int)
}

/**
Expand a parameterized capability
# Arguments
* `cap` - string to expand
* `params` - vector of params for %p1 etc
* `sta` - vector of params corresponding to static variables
* `dyn` - vector of params corresponding to stativ variables
To be compatible with ncurses, `sta` and `dyn` should be the same between calls to `expand` for
multiple capabilities for the same terminal.
*/
pub fn expand(cap: &[u8], params: &mut [Param], sta: &mut [Param], dyn: &mut [Param])
-> Result<~[u8], ~str> {
assert!(cap.len() != 0, "expanding an empty capability makes no sense");
assert!(params.len() <= 9, "only 9 parameters are supported by capability strings");

assert!(sta.len() <= 26, "only 26 static vars are able to be used by capability strings");
assert!(dyn.len() <= 26, "only 26 dynamic vars are able to be used by capability strings");

let mut state = Nothing;
let mut i = 0;

// expanded cap will only rarely be smaller than the cap itself
let mut output = vec::with_capacity(cap.len());

let mut cur;

let mut stack: ~[Param] = ~[];

let mut intstate = ~[];

while i < cap.len() {
cur = cap[i] as char;
let mut old_state = state;
match state {
Nothing => {
if cur == '%' {
state = Percent;
} else {
output.push(cap[i]);
}
},
Percent => {
match cur {
'%' => { output.push(cap[i]); state = Nothing },
'c' => match stack.pop() {
Char(c) => output.push(c as u8),
_ => return Err(~"a non-char was used with %c")
},
's' => match stack.pop() {
String(s) => output.push_all(s.to_bytes()),
_ => return Err(~"a non-str was used with %s")
},
'd' => match stack.pop() {
Number(x) => output.push_all(x.to_str().to_bytes()),
_ => return Err(~"a non-number was used with %d")
},
'p' => state = PushParam,
'P' => state = SetVar,
'g' => state = GetVar,
'\'' => state = CharConstant,
'{' => state = IntConstant,
'l' => match stack.pop() {
String(s) => stack.push(Number(s.len() as int)),
_ => return Err(~"a non-str was used with %l")
},
'+' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x + y)),
(_, _) => return Err(~"non-numbers on stack with +")
},
'-' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x - y)),
(_, _) => return Err(~"non-numbers on stack with -")
},
'*' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x * y)),
(_, _) => return Err(~"non-numbers on stack with *")
},
'/' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x / y)),
(_, _) => return Err(~"non-numbers on stack with /")
},
'm' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x % y)),
(_, _) => return Err(~"non-numbers on stack with %")
},
'&' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x & y)),
(_, _) => return Err(~"non-numbers on stack with &")
},
'|' => match (stack.pop(), stack.pop()) {
(Number(x), Number(y)) => stack.push(Number(x | y)),
(_, _) => return Err(~"non-numbers on stack with |")
},
'A' => return Err(~"logical operations unimplemented"),
'O' => return Err(~"logical operations unimplemented"),
'!' => return Err(~"logical operations unimplemented"),
'~' => match stack.pop() {
Number(x) => stack.push(Number(!x)),
_ => return Err(~"non-number on stack with %~")
},
'i' => match (copy params[0], copy params[1]) {
(Number(x), Number(y)) => {
params[0] = Number(x + 1);
params[1] = Number(y + 1);
},
(_, _) => return Err(~"first two params not numbers with %i")
},
'?' => state = return Err(fmt!("if expressions unimplemented (%?)", cap)),
_ => return Err(fmt!("unrecognized format option %c", cur))
}
},
PushParam => {
// params are 1-indexed
stack.push(copy params[char::to_digit(cur, 10).expect("bad param number") - 1]);
},
SetVar => {
if cur >= 'A' && cur <= 'Z' {
let idx = (cur as u8) - ('A' as u8);
sta[idx] = stack.pop();
} else if cur >= 'a' && cur <= 'z' {
let idx = (cur as u8) - ('a' as u8);
dyn[idx] = stack.pop();
} else {
return Err(~"bad variable name in %P");
}
},
GetVar => {
if cur >= 'A' && cur <= 'Z' {
let idx = (cur as u8) - ('A' as u8);
stack.push(copy sta[idx]);
} else if cur >= 'a' && cur <= 'z' {
let idx = (cur as u8) - ('a' as u8);
stack.push(copy dyn[idx]);
} else {
return Err(~"bad variable name in %g");
}
},
CharConstant => {
stack.push(Char(cur));
state = CharClose;
},
CharClose => {
assert!(cur == '\'', "malformed character constant");
},
IntConstant => {
if cur == '}' {
stack.push(Number(int::parse_bytes(intstate, 10).expect("bad int constant")));
state = Nothing;
}
intstate.push(cur as u8);
old_state = Nothing;
}
_ => return Err(~"unimplemented state")
}
if state == old_state {
state = Nothing;
}
i += 1;
}
Ok(output)
}

#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_basic_setabf() {
let s = bytes!("\\E[48;5;%p1%dm");
assert_eq!(expand(s, [Number(1)], [], []), bytes!("\\E[48;5;1m").to_owned());
}
}
Loading

0 comments on commit 71f9dde

Please sign in to comment.