cursive/src/view/checkbox.rs

116 lines
2.7 KiB
Rust
Raw Normal View History

2016-07-17 00:22:24 +00:00
use With;
2016-07-17 01:18:33 +00:00
use Cursive;
2016-07-17 00:22:24 +00:00
use Printer;
use vec::Vec2;
use view::View;
use event::{Event, EventResult, Key};
use direction::Direction;
2016-07-17 01:18:33 +00:00
use std::rc::Rc;
2016-07-17 00:22:24 +00:00
/// Checkable box.
pub struct Checkbox {
checked: bool,
2016-07-17 01:18:33 +00:00
on_change: Option<Rc<Fn(&mut Cursive, bool)>>,
2016-07-17 00:22:24 +00:00
}
2016-07-17 00:28:42 +00:00
new_default!(Checkbox);
2016-07-17 00:22:24 +00:00
impl Checkbox {
/// Creates a new, unchecked checkbox.
pub fn new() -> Self {
2016-07-17 01:18:33 +00:00
Checkbox {
checked: false,
on_change: None,
}
}
/// Sets a callback to be used when the state changes.
pub fn set_on_change<F: 'static + Fn(&mut Cursive, bool)>(&mut self, on_change: F) {
self.on_change = Some(Rc::new(on_change));
}
/// Sets a callback to be used when the state changes.
///
/// Chainable variant.
pub fn on_change<F: 'static + Fn(&mut Cursive, bool)>(self, on_change: F) -> Self {
self.with(|s| s.set_on_change(on_change))
2016-07-17 00:22:24 +00:00
}
/// Toggles the checkbox state.
2016-07-17 01:18:33 +00:00
pub fn toggle(&mut self) -> EventResult {
let checked = !self.checked;
self.set_checked(checked)
2016-07-17 00:22:24 +00:00
}
/// Check the checkbox.
2016-07-17 01:18:33 +00:00
pub fn check(&mut self) -> EventResult {
self.set_checked(true)
2016-07-17 00:22:24 +00:00
}
/// Check the checkbox.
///
/// Chainable variant.
pub fn checked(self) -> Self {
2016-07-17 01:18:33 +00:00
self.with(|s| {s.check();})
2016-07-17 00:22:24 +00:00
}
/// Returns `true` if the checkbox is checked.
pub fn is_checked(&self) -> bool {
self.checked
}
/// Uncheck the checkbox.
2016-07-17 01:18:33 +00:00
pub fn uncheck(&mut self) -> EventResult {
self.set_checked(false)
2016-07-17 00:22:24 +00:00
}
/// Uncheck the checkbox.
///
/// Chainable variant.
pub fn unchecked(self) -> Self {
2016-07-17 01:18:33 +00:00
self.with(|s| { s.uncheck(); })
}
/// Sets the checkbox state.
pub fn set_checked(&mut self, checked: bool) -> EventResult {
self.checked = checked;
if let Some(ref on_change) = self.on_change {
let on_change = on_change.clone();
EventResult::with_cb(move |s| on_change(s, checked))
} else {
EventResult::Consumed(None)
}
2016-07-17 00:22:24 +00:00
}
}
impl View for Checkbox {
fn get_min_size(&mut self, _: Vec2) -> Vec2 {
Vec2::new(3, 1)
}
fn take_focus(&mut self, _: Direction) -> bool {
true
}
fn draw(&self, printer: &Printer) {
printer.with_selection(printer.focused, |printer| {
2016-07-17 00:28:42 +00:00
printer.print((0, 0), "[ ]");
2016-07-17 00:22:24 +00:00
if self.checked {
printer.print((1, 0), "X");
}
});
}
fn on_event(&mut self, event: Event) -> EventResult {
match event {
Event::Key(Key::Enter) |
Event::Char(' ') => self.toggle(),
2016-07-17 01:18:33 +00:00
_ => EventResult::Ignored,
2016-07-17 00:22:24 +00:00
}
}
}