cursive/src/views/key_event_view.rs

60 lines
1.6 KiB
Rust
Raw Normal View History

2016-10-02 22:22:29 +00:00
2016-03-15 22:37:57 +00:00
use Cursive;
use event::{Callback, Event, EventResult};
2016-10-02 22:22:29 +00:00
use std::collections::HashMap;
2016-07-28 23:36:01 +00:00
use view::{View, ViewWrapper};
/// A simple wrapper view that catches some ignored event from its child.
///
2016-07-21 05:08:06 +00:00
/// If the event doesn't have a corresponding callback, it will stay ignored.
///
/// # Examples
///
/// ```
/// # use cursive::event;;
/// # use cursive::views::{KeyEventView, TextView};
2016-07-21 05:08:06 +00:00
/// let view = KeyEventView::new(TextView::new("This view has an event!"))
/// .register('q', |s| s.quit())
/// .register(event::Key::Esc, |s| s.quit());
2016-07-21 05:08:06 +00:00
/// ```
pub struct KeyEventView<T: View> {
content: T,
callbacks: HashMap<Event, Callback>,
}
2016-09-23 05:10:14 +00:00
impl<T: View> KeyEventView<T> {
/// Wraps the given view in a new KeyEventView.
pub fn new(view: T) -> Self {
KeyEventView {
content: view,
callbacks: HashMap::new(),
}
}
/// Registers a callback when the given key is ignored by the child.
pub fn register<F, E: Into<Event>>(mut self, event: E, cb: F) -> Self
2015-05-24 00:07:22 +00:00
where F: Fn(&mut Cursive) + 'static
{
self.callbacks.insert(event.into(), Callback::from_fn(cb));
self
}
}
2016-09-23 05:10:14 +00:00
impl<T: View> ViewWrapper for KeyEventView<T> {
wrap_impl!(self.content: T);
fn wrap_on_event(&mut self, event: Event) -> EventResult {
match self.content.on_event(event) {
2016-06-25 23:36:22 +00:00
EventResult::Ignored => {
match self.callbacks.get(&event) {
None => EventResult::Ignored,
Some(cb) => EventResult::Consumed(Some(cb.clone())),
}
}
res => res,
}
}
}