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 // Get command-line arguments
let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit()); 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 width = rustbox::width();
let mut height = rustbox::height(); let mut height = rustbox::height();
@ -40,11 +43,47 @@ fn main() {
rustbox::init(); rustbox::init();
let enough_time_has_passed: bool = true;
loop { loop {
// 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);
}
// Esc
else if key == 27 {
quit = true;
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 // Draw the text buffer to screen
if enough_time_has_passed {
rustbox::clear(); rustbox::clear();
{ {
let mut tb_iter = tb.root_iter(); let mut tb_iter = tb.root_iter();
@ -77,34 +116,12 @@ fn main() {
} }
} }
rustbox::present(); rustbox::present();
}
// Handle events
match rustbox::poll_event() { // Quit if quit flag is set
rustbox::Event::KeyEvent(modifier, key, character) => { if quit {
// Return
if key == 13 {
let p = tb.len();
tb.insert_text("\n", p);
}
// Esc
else if key == 27 {
break; 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;}
}
} }
rustbox::shutdown(); rustbox::shutdown();