2015-05-19 02:41:35 +00:00
|
|
|
use std::rc::Rc;
|
|
|
|
|
2015-06-06 01:08:05 +00:00
|
|
|
use theme::ColorPair;
|
2016-03-15 22:37:57 +00:00
|
|
|
use Cursive;
|
2015-05-19 02:41:35 +00:00
|
|
|
use vec::Vec2;
|
2016-06-28 05:10:59 +00:00
|
|
|
use view::{SizeRequest, View};
|
2015-05-28 01:04:33 +00:00
|
|
|
use event::*;
|
2015-05-19 02:41:35 +00:00
|
|
|
use printer::Printer;
|
|
|
|
|
|
|
|
/// Simple text label with a callback when ENTER is pressed.
|
2015-05-19 22:54:11 +00:00
|
|
|
/// A button shows its content in a single line and has a fixed size.
|
2015-05-19 02:41:35 +00:00
|
|
|
pub struct Button {
|
|
|
|
label: String,
|
|
|
|
callback: Rc<Callback>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Button {
|
2015-05-19 22:54:11 +00:00
|
|
|
/// Creates a new button with the given content and callback.
|
2015-05-19 02:41:35 +00:00
|
|
|
pub fn new<F>(label: &str, cb: F) -> Self
|
2015-05-24 00:07:22 +00:00
|
|
|
where F: Fn(&mut Cursive) + 'static
|
2015-05-19 02:41:35 +00:00
|
|
|
{
|
|
|
|
Button {
|
|
|
|
label: label.to_string(),
|
|
|
|
callback: Rc::new(Box::new(cb)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl View for Button {
|
2015-05-31 04:05:34 +00:00
|
|
|
fn draw(&mut self, printer: &Printer) {
|
2016-03-15 22:37:57 +00:00
|
|
|
let style = if !printer.focused {
|
|
|
|
ColorPair::Primary
|
|
|
|
} else {
|
|
|
|
ColorPair::Highlight
|
|
|
|
};
|
2015-05-22 06:29:49 +00:00
|
|
|
let x = printer.size.x - 1;
|
2015-05-19 22:54:11 +00:00
|
|
|
|
2015-05-27 04:45:00 +00:00
|
|
|
printer.with_color(style, |printer| {
|
2016-03-15 22:37:57 +00:00
|
|
|
printer.print((1, 0), &self.label);
|
|
|
|
printer.print((0, 0), "<");
|
|
|
|
printer.print((x, 0), ">");
|
2015-05-23 22:58:06 +00:00
|
|
|
});
|
2015-05-19 02:41:35 +00:00
|
|
|
}
|
|
|
|
|
2015-05-19 22:54:11 +00:00
|
|
|
fn get_min_size(&self, _: SizeRequest) -> Vec2 {
|
|
|
|
// Meh. Fixed size we are.
|
2015-05-29 00:32:28 +00:00
|
|
|
Vec2::new(2 + self.label.chars().count(), 1)
|
2015-05-19 02:41:35 +00:00
|
|
|
}
|
|
|
|
|
2015-05-28 01:04:33 +00:00
|
|
|
fn on_event(&mut self, event: Event) -> EventResult {
|
|
|
|
match event {
|
2015-05-19 17:58:42 +00:00
|
|
|
// 10 is the ascii code for '\n', that is the return key
|
2016-06-30 00:36:20 +00:00
|
|
|
Event::Key(Key::Enter) => EventResult::Consumed(Some(self.callback.clone())),
|
2015-05-19 02:41:35 +00:00
|
|
|
_ => EventResult::Ignored,
|
|
|
|
}
|
|
|
|
}
|
2015-05-19 22:54:11 +00:00
|
|
|
|
|
|
|
fn take_focus(&mut self) -> bool {
|
|
|
|
true
|
|
|
|
}
|
2015-05-19 02:41:35 +00:00
|
|
|
}
|