cursive/src/views/button.rs

111 lines
2.5 KiB
Rust
Raw Normal View History

use unicode_width::UnicodeWidthStr;
2015-05-19 02:41:35 +00:00
use {Cursive, Printer, With};
use align::HAlign;
use event::*;
use direction::Direction;
use theme::ColorStyle;
2015-05-19 02:41:35 +00:00
use vec::Vec2;
2016-07-10 02:05:51 +00:00
use view::View;
2015-05-19 02:41:35 +00:00
2016-07-21 05:08:06 +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.
2016-07-21 05:08:06 +00:00
///
/// # Examples
///
/// ```
/// # use cursive::prelude::*;
/// let quit_button = Button::new("Quit", |s| s.quit());
/// ```
2015-05-19 02:41:35 +00:00
pub struct Button {
label: String,
callback: Callback,
2016-07-17 01:48:20 +00:00
enabled: bool,
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: Callback::from_fn(cb),
2016-07-17 01:48:20 +00:00
enabled: true,
2015-05-19 02:41:35 +00:00
}
}
2016-07-17 01:48:20 +00:00
/// Disables this view.
///
/// A disabled view cannot be selected.
pub fn disable(&mut self) {
self.enabled = false;
}
/// Disables this view.
///
/// Chainable variant.
pub fn disabled(self) -> Self {
self.with(Self::disable)
}
/// Re-enables this view.
pub fn enable(&mut self) {
self.enabled = true;
}
/// Enable or disable this view.
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
}
/// Returns `true` if this view is enabled.
pub fn is_enabled(&self) -> bool {
self.enabled
}
2015-05-19 02:41:35 +00:00
}
impl View for Button {
fn draw(&self, printer: &Printer) {
2016-07-17 01:48:20 +00:00
2016-07-17 08:20:41 +00:00
if printer.size.x == 0 {
return;
}
2016-07-17 01:48:20 +00:00
let style = if !self.enabled {
ColorStyle::Secondary
} else if !printer.focused {
ColorStyle::Primary
2016-03-15 22:37:57 +00:00
} else {
ColorStyle::Highlight
2016-03-15 22:37:57 +00:00
};
let offset =
HAlign::Center.get_offset(self.label.len() + 2, printer.size.x);
printer.with_color(style, |printer| {
printer.print((offset, 0), &format!("<{}>", self.label));
});
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 {
2016-07-17 01:48:20 +00:00
self.enabled
}
2015-05-19 02:41:35 +00:00
}