cursive/src/view/button.rs

66 lines
1.6 KiB
Rust
Raw Normal View History

2015-05-19 02:41:35 +00:00
use std::rc::Rc;
use direction::Direction;
use theme::ColorStyle;
2016-03-15 22:37:57 +00:00
use Cursive;
2015-05-19 02:41:35 +00:00
use vec::Vec2;
2016-07-10 02:05:51 +00:00
use view::View;
use event::*;
2016-07-14 06:25:54 +00:00
use Printer;
2016-07-04 23:04:32 +00:00
use unicode_width::UnicodeWidthStr;
2015-05-19 02:41:35 +00:00
/// Simple text label with a callback when ENTER is pressed.
/// 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: Callback,
2015-05-19 02:41:35 +00:00
}
impl Button {
/// 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(cb),
2015-05-19 02:41:35 +00:00
}
}
}
impl View for Button {
fn draw(&mut self, printer: &Printer) {
2016-03-15 22:37:57 +00:00
let style = if !printer.focused {
ColorStyle::Primary
2016-03-15 22:37:57 +00:00
} else {
ColorStyle::Highlight
2016-03-15 22:37:57 +00:00
};
2015-05-22 06:29:49 +00:00
let x = printer.size.x - 1;
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-19 02:41:35 +00:00
}
fn get_min_size(&mut self, _: Vec2) -> Vec2 {
// Meh. Fixed size we are.
2016-07-04 23:04:32 +00:00
Vec2::new(2 + self.label.width(), 1)
2015-05-19 02:41:35 +00:00
}
fn on_event(&mut self, event: Event) -> EventResult {
match event {
// 10 is the ascii code for '\n', that is the return key
2016-07-10 02:05:51 +00:00
Event::Key(Key::Enter) => {
EventResult::Consumed(Some(self.callback.clone()))
}
2015-05-19 02:41:35 +00:00
_ => EventResult::Ignored,
}
}
fn take_focus(&mut self, _: Direction) -> bool {
true
}
2015-05-19 02:41:35 +00:00
}