Skip to content

extra::term overhaul #6826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 3, 2013
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/libextra/std.rc
Original file line number Diff line number Diff line change
@@ -118,6 +118,8 @@ pub mod flate;
#[cfg(unicode)]
mod unicode;

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

// Compiler support modules

117 changes: 84 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.
//
@@ -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;
@@ -39,43 +43,90 @@ 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)], [], []).unwrap(), bytes!("\\E[48;5;1m").to_owned());
}
}
332 changes: 332 additions & 0 deletions src/libextra/terminfo/parser/compiled.rs

Large diffs are not rendered by default.

89 changes: 89 additions & 0 deletions src/libextra/terminfo/searcher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// 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.

/// Implement ncurses-compatible database discovery
/// Does not support hashed database, only filesystem!
use core::prelude::*;
use core::{os, str};
use core::os::getenv;
use core::io::{file_reader, Reader};
use path = core::path::Path;

/// Return path to database entry for `term`
pub fn get_dbpath_for_term(term: &str) -> Option<~path> {
if term.len() == 0 {
return None;
}

let homedir = os::homedir();

let mut dirs_to_search = ~[];
let first_char = term.substr(0, 1);

// Find search directory
match getenv("TERMINFO") {
Some(dir) => dirs_to_search.push(path(dir)),
None => {
if homedir.is_some() {
dirs_to_search.push(homedir.unwrap().push(".terminfo")); // ncurses compatability
}
match getenv("TERMINFO_DIRS") {
Some(dirs) => for str::each_split_char(dirs, ':') |i| {
if i == "" {
dirs_to_search.push(path("/usr/share/terminfo"));
} else {
dirs_to_search.push(path(i.to_owned()));
}
},
// Found nothing, use the default path
None => dirs_to_search.push(path("/usr/share/terminfo"))
}
}
};

// Look for the terminal in all of the search directories
for dirs_to_search.each |p| {
let newp = ~p.push_many(&[first_char.to_owned(), term.to_owned()]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you have to allocate here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returns Option<~path>, not Option<path>

if os::path_exists(p) && os::path_exists(newp) {
return Some(newp);
}
}
None
}

/// Return open file for `term`
pub fn open(term: &str) -> Result<@Reader, ~str> {
match get_dbpath_for_term(term) {
Some(x) => file_reader(x),
None => Err(fmt!("could not find terminfo entry for %s", term))
}
}

#[test]
#[ignore(reason = "buildbots don't have ncurses installed and I can't mock everything I need")]
fn test_get_dbpath_for_term() {
// woefully inadequate test coverage
use std::os::{setenv, unsetenv};
fn x(t: &str) -> ~str { get_dbpath_for_term(t).expect("no terminfo entry found").to_str() };
assert!(x("screen") == ~"/usr/share/terminfo/s/screen");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this is a test, so it doesn't matter, but "/usr/share/terminfo/s/screen" == x("screen") would be faster.

assert!(get_dbpath_for_term("") == None);
setenv("TERMINFO_DIRS", ":");
assert!(x("screen") == ~"/usr/share/terminfo/s/screen");
unsetenv("TERMINFO_DIRS");
}
#[test]
#[ignore(reason = "see test_get_dbpath_for_term")]
fn test_open() {
open("screen");
let t = open("nonexistent terminal that hopefully does not exist");
assert!(t.is_err());
}
29 changes: 29 additions & 0 deletions src/libextra/terminfo/terminfo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// 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.

use core::hashmap::HashMap;

/// A parsed terminfo entry.
pub struct TermInfo {
/// Names for the terminal
names: ~[~str],
/// Map of capability name to boolean value
bools: HashMap<~str, bool>,
/// Map of capability name to numeric value
numbers: HashMap<~str, u16>,
/// Map of capability name to raw (unexpanded) string
strings: HashMap<~str, ~[u8]>
}

pub mod searcher;
pub mod parser {
pub mod compiled;
}
pub mod parm;
19 changes: 12 additions & 7 deletions src/libextra/test.rs
Original file line number Diff line number Diff line change
@@ -210,7 +210,6 @@ struct ConsoleTestState {
// A simple console test runner
pub fn run_tests_console(opts: &TestOpts,
tests: ~[TestDescAndFn]) -> bool {

fn callback(event: &TestEvent, st: &mut ConsoleTestState) {
debug!("callback(event=%?)", event);
match copy *event {
@@ -347,12 +346,18 @@ pub fn run_tests_console(opts: &TestOpts,
word: &str,
color: u8,
use_color: bool) {
if use_color && term::color_supported() {
term::fg(out, color);
}
out.write_str(word);
if use_color && term::color_supported() {
term::reset(out);
let t = term::Terminal::new(out);
match t {
Ok(term) => {
if use_color && term.color_supported {
term.fg(color);
}
out.write_str(word);
if use_color && term.color_supported {
term.reset();
}
},
Err(_) => out.write_str(word)
}
}
}
50 changes: 19 additions & 31 deletions src/librustpkg/util.rs
Original file line number Diff line number Diff line change
@@ -277,43 +277,31 @@ pub fn need_dir(s: &Path) {
}
}

pub fn note(msg: ~str) {
let out = io::stdout();

if term::color_supported() {
term::fg(out, term::color_green);
out.write_str("note: ");
term::reset(out);
out.write_line(msg);
} else {
out.write_line(~"note: " + msg);
fn pretty_message<'a>(msg: &'a str, prefix: &'a str, color: u8, out: @io::Writer) {
let term = term::Terminal::new(out);
match term {
Ok(ref t) => {
t.fg(color);
out.write_str(prefix);
t.reset();
},
_ => {
out.write_str(prefix);
}
}
out.write_line(msg);
}

pub fn warn(msg: ~str) {
let out = io::stdout();
if term::color_supported() {
term::fg(out, term::color_yellow);
out.write_str("warning: ");
term::reset(out);
out.write_line(msg);
} else {
out.write_line(~"warning: " + msg);
}
pub fn note(msg: &str) {
pretty_message(msg, "note: ", term::color_green, io::stdout())
}

pub fn error(msg: ~str) {
let out = io::stdout();
pub fn warn(msg: &str) {
pretty_message(msg, "warning: ", term::color_yellow, io::stdout())
}

if term::color_supported() {
term::fg(out, term::color_red);
out.write_str("error: ");
term::reset(out);
out.write_line(msg);
} else {
out.write_line(~"error: " + msg);
}
pub fn error(msg: &str) {
pretty_message(msg, "error: ", term::color_red, io::stdout())
}

pub fn hash(data: ~str) -> ~str {
28 changes: 18 additions & 10 deletions src/libsyntax/diagnostic.rs
Original file line number Diff line number Diff line change
@@ -191,19 +191,27 @@ fn diagnosticcolor(lvl: level) -> u8 {
}

fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let use_color = term::color_supported() &&
io::stderr().get_type() == io::Screen;
let t = term::Terminal::new(io::stderr());

let stderr = io::stderr();

if !topic.is_empty() {
io::stderr().write_str(fmt!("%s ", topic));
stderr.write_str(fmt!("%s ", topic));
}
if use_color {
term::fg(io::stderr(), diagnosticcolor(lvl));
}
io::stderr().write_str(fmt!("%s:", diagnosticstr(lvl)));
if use_color {
term::reset(io::stderr());

match t {
Ok(term) => {
if stderr.get_type() == io::Screen {
term.fg(diagnosticcolor(lvl));
stderr.write_str(fmt!("%s: ", diagnosticstr(lvl)));
term.reset();
stderr.write_str(fmt!("%s\n", msg));
} else {
stderr.write_str(fmt!("%s: %s\n", diagnosticstr(lvl), msg));
}
},
_ => stderr.write_str(fmt!("%s: %s\n", diagnosticstr(lvl), msg))
}
io::stderr().write_str(fmt!(" %s\n", msg));
}

pub fn collect(messages: @mut ~[~str])