diff --git a/src/main.rs b/src/main.rs index d3f8e66..f6ca8d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -33,77 +33,94 @@ 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(); let mut tb = TextBuffer::new(); 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; + // 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); + } + }, - 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::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; } + + 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; - _ => {break;} + 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; } }