From ca09885978618289806f3e246b5a748ac68d33a8 Mon Sep 17 00:00:00 2001 From: Alexandre Bury Date: Wed, 27 May 2015 16:55:49 -0700 Subject: [PATCH] Add key_codes example Prints the code on key press. Useful tool. --- Cargo.toml | 4 ++++ examples/key_codes.rs | 48 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 examples/key_codes.rs diff --git a/Cargo.toml b/Cargo.toml index df49d5b..7850000 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,3 +40,7 @@ path = "examples/mutation.rs" [[example]] name = "edit" path = "examples/edit.rs" + +[[example]] +name = "key_codes" +path = "examples/key_codes.rs" diff --git a/examples/key_codes.rs b/examples/key_codes.rs new file mode 100644 index 0000000..cb4029e --- /dev/null +++ b/examples/key_codes.rs @@ -0,0 +1,48 @@ +extern crate cursive; + +use cursive::Cursive; + +use cursive::view::{View,BoxView}; +use cursive::printer::Printer; +use cursive::event::EventResult; + +fn main() { + let mut siv = Cursive::new(); + + siv.add_layer(BoxView::new((10,4), KeyCodeView::new(4))); + + siv.run(); +} + +struct KeyCodeView { + history: Vec, + size: usize, +} + +impl KeyCodeView { + fn new(size: usize) -> Self { + KeyCodeView { + history: Vec::new(), + size: size, + } + } +} + +impl View for KeyCodeView { + fn draw(&mut self, printer: &Printer, _: bool) { + for (y,n) in self.history.iter().enumerate() { + printer.print((0,y), &format!("{}", n)); + } + } + + fn on_key_event(&mut self, ch: i32) -> EventResult { + self.history.push(ch); + + while self.history.len() > self.size { + self.history.remove(0); + } + + EventResult::Consumed(None) + } +} +