Refactored event loop.

This allows large numbers of events to be handled in bulk, but without
the program eating up CPU when idle.
This commit is contained in:
Nathan Vegdahl 2014-12-19 21:10:03 -08:00
parent ef64bd8f1c
commit fec361ad29

View File

@ -33,6 +33,9 @@ fn main() {
// Get command-line arguments
let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
// Quitting flag
let mut quit = false;
let mut width = rustbox::width();
let mut height = rustbox::height();
@ -40,70 +43,84 @@ fn main() {
rustbox::init();
let enough_time_has_passed: bool = true;
loop {
// Draw the text buffer to screen
if enough_time_has_passed {
rustbox::clear();
{
let mut tb_iter = tb.root_iter();
let mut line: uint = 0;
let mut column: uint = 0;
loop {
if let Option::Some(c) = tb_iter.next() {
if c == '\n' {
line += 1;
column = 0;
continue;
}
rustbox::print(column, line, Style::Normal, Color::White, Color::Black, c.to_string());
column += 1;
// Handle events. We block on the first event, so that the
// program doesn't loop like crazy, but then continue pulling
// events in a non-blocking way until we run out of events
// to handle.
let mut e = rustbox::poll_event(); // Block until we get an event
loop {
match e {
rustbox::Event::KeyEvent(modifier, key, character) => {
// Return
if key == 13 {
let p = tb.len();
tb.insert_text("\n", p);
}
else {
// Esc
else if key == 27 {
quit = true;
break;
}
if line > height {
break;
// Some key
else if let Option::Some(c) = char::from_u32(character) {
let p = tb.len();
tb.insert_text(c.to_string().as_slice(), p);
}
},
if column > width {
tb_iter.next_line();
line += 1;
column = 0;
}
rustbox::Event::ResizeEvent(w, h) => {
width = w as uint;
height = h as uint;
}
}
rustbox::present();
}
// Handle events
match rustbox::poll_event() {
rustbox::Event::KeyEvent(modifier, key, character) => {
// Return
if key == 13 {
let p = tb.len();
tb.insert_text("\n", p);
}
// Esc
else if key == 27 {
_ => {
break;
}
// Some key
else if let Option::Some(c) = char::from_u32(character) {
let p = tb.len();
tb.insert_text(c.to_string().as_slice(), p);
}
},
rustbox::Event::ResizeEvent(w, h) => {
width = w as uint;
height = h as uint;
}
_ => {break;}
e = rustbox::peek_event(0); // Get next event (if any)
}
// Draw the text buffer to screen
rustbox::clear();
{
let mut tb_iter = tb.root_iter();
let mut line: uint = 0;
let mut column: uint = 0;
loop {
if let Option::Some(c) = tb_iter.next() {
if c == '\n' {
line += 1;
column = 0;
continue;
}
rustbox::print(column, line, Style::Normal, Color::White, Color::Black, c.to_string());
column += 1;
}
else {
break;
}
if line > height {
break;
}
if column > width {
tb_iter.next_line();
line += 1;
column = 0;
}
}
}
rustbox::present();
// Quit if quit flag is set
if quit {
break;
}
}