cursive/src/view/select_view.rs

362 lines
11 KiB
Rust
Raw Normal View History

use std::cmp::min;
use std::rc::Rc;
use std::cell::Cell;
2016-03-15 22:37:57 +00:00
use Cursive;
use menu::MenuTree;
use view::MenuPopup;
2016-07-17 01:46:18 +00:00
use With;
use direction::Direction;
use view::{IdView, View};
2016-07-02 08:01:09 +00:00
use align::{Align, HAlign, VAlign};
use view::scroll::ScrollBase;
2016-03-15 22:37:57 +00:00
use event::{Event, EventResult, Key};
2016-07-17 01:46:18 +00:00
use theme::ColorStyle;
use vec::Vec2;
2016-07-14 06:25:54 +00:00
use Printer;
2016-07-04 23:04:32 +00:00
use unicode_width::UnicodeWidthStr;
struct Item<T> {
label: String,
value: Rc<T>,
}
2016-06-25 23:36:22 +00:00
impl<T> Item<T> {
fn new(label: &str, value: T) -> Self {
Item {
label: label.to_string(),
value: Rc::new(value),
}
}
}
/// View to select an item among a list.
///
/// It contains a list of values of type T, with associated labels.
2016-03-15 22:37:57 +00:00
pub struct SelectView<T = String> {
items: Vec<Item<T>>,
2016-07-17 01:46:18 +00:00
enabled: bool,
// the focus needs to be manipulable from callbacks
focus: Rc<Cell<usize>>,
scrollbase: ScrollBase,
// This is a custom callback to include a &T
select_cb: Option<Rc<Fn(&mut Cursive, &T)>>,
align: Align,
// `true` if we show a one-line view, with popup on selection.
popup: bool,
}
2016-06-25 23:36:22 +00:00
impl<T: 'static> SelectView<T> {
/// Creates a new empty SelectView.
pub fn new() -> Self {
SelectView {
items: Vec::new(),
2016-07-17 01:46:18 +00:00
enabled: true,
focus: Rc::new(Cell::new(0)),
scrollbase: ScrollBase::new(),
select_cb: None,
align: Align::top_left(),
popup: false,
}
}
/// Turns `self` into a popup select view.
///
/// Chainable variant.
pub fn popup(self) -> Self {
self.with(|s| s.set_popup(true))
}
/// Turns `self` into a popup select view.
pub fn set_popup(&mut self, popup: bool) {
self.popup = popup;
}
2016-07-17 01:46:18 +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
}
/// Sets a callback to be used when an item is selected.
///
/// (When ENTER is pressed on an item).
2015-07-28 19:54:32 +00:00
pub fn set_on_select<F>(&mut self, cb: F)
where F: Fn(&mut Cursive, &T) + 'static
{
self.select_cb = Some(Rc::new(cb));
2015-07-28 19:54:32 +00:00
}
/// Sets a callback to be used when an item is selected.
///
/// (When ENTER is pressed on an item).
2016-06-28 05:10:59 +00:00
///
/// Chainable variant.
pub fn on_select<F>(mut self, cb: F) -> Self
2015-07-28 19:54:32 +00:00
where F: Fn(&mut Cursive, &T) + 'static
{
2015-07-28 19:54:32 +00:00
self.set_on_select(cb);
self
}
2015-06-03 22:36:51 +00:00
/// Sets the alignment for this view.
pub fn align(mut self, align: Align) -> Self {
self.align = align;
self
}
2015-06-03 22:36:51 +00:00
/// Sets the vertical alignment for this view.
2016-06-26 16:45:53 +00:00
/// (If the view is given too much space vertically.)
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
2015-06-03 22:36:51 +00:00
/// Sets the horizontal alignment for this view.
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
2016-06-28 05:10:59 +00:00
/// Returns the value of the currently selected item.
///
/// Panics if the list is empty.
pub fn selection(&self) -> Rc<T> {
self.items[self.focus()].value.clone()
}
/// Adds a item to the list, with given label and value.
pub fn add_item(&mut self, label: &str, value: T) {
2016-03-15 22:37:57 +00:00
self.items.push(Item::new(label, value));
}
/// Chainable variant of add_item
pub fn item(mut self, label: &str, value: T) -> Self {
self.add_item(label, value);
self
}
/// Wraps this view into an IdView with the given id.
pub fn with_id(self, label: &str) -> IdView<Self> {
IdView::new(label, self)
}
2016-07-17 01:46:18 +00:00
fn draw_item(&self, printer: &Printer, i: usize) {
let l = self.items[i].label.width();
let x = self.align.h.get_offset(l, printer.size.x);
printer.print_hline((0, 0), x, " ");
printer.print((x, 0), &self.items[i].label);
2016-07-17 08:20:41 +00:00
if l < printer.size.x {
printer.print_hline((x + l, 0), printer.size.x - l - x, " ");
}
2016-07-17 01:46:18 +00:00
}
fn focus(&self) -> usize {
self.focus.get()
}
fn focus_up(&mut self, n: usize) {
let focus = self.focus();
let n = min(focus, n);
self.focus.set(focus - n);
}
fn focus_down(&mut self, n: usize) {
let focus = min(self.focus() + n, self.items.len());
self.focus.set(focus);
}
}
impl SelectView<String> {
2016-06-28 05:10:59 +00:00
/// Convenient method to use the label as value.
2015-05-31 23:58:55 +00:00
pub fn add_item_str(&mut self, label: &str) {
self.add_item(label, label.to_string());
}
/// Chainable variant of add_item_str
pub fn item_str(self, label: &str) -> Self {
self.item(label, label.to_string())
}
}
2016-06-25 23:36:22 +00:00
impl<T: 'static> View for SelectView<T> {
fn draw(&self, printer: &Printer) {
if self.popup {
let style = if !self.enabled {
ColorStyle::Secondary
} else if !printer.focused {
ColorStyle::Primary
} else {
ColorStyle::Highlight
};
let x = printer.size.x - 1;
printer.with_color(style, |printer| {
// Prepare the entire background
printer.print_hline((0, 0), x, " ");
// Draw the borders
printer.print((0, 0), "<");
printer.print((x, 0), ">");
let label = &self.items[self.focus()].label;
// And center the text?
let offset = HAlign::Center.get_offset(label.len(), x);
printer.print((offset, 0), label);
});
} else {
let h = self.items.len();
let offset = self.align.v.get_offset(h, printer.size.y);
let printer =
&printer.sub_printer(Vec2::new(0, offset), printer.size, true);
self.scrollbase.draw(printer, |printer, i| {
printer.with_selection(i == self.focus(), |printer| {
if i != self.focus() && !self.enabled {
printer.with_color(ColorStyle::Secondary, |printer| {
self.draw_item(printer, i)
});
} else {
self.draw_item(printer, i);
}
});
});
}
}
fn get_min_size(&mut self, req: Vec2) -> Vec2 {
// Items here are not compressible.
// So no matter what the horizontal requirements are,
// we'll still return our longest item.
2016-06-28 05:10:59 +00:00
let w = self.items
2016-07-10 02:05:51 +00:00
.iter()
.map(|item| item.label.width())
.max()
.unwrap_or(1);
if self.popup {
Vec2::new(w + 2, 1)
} else {
let h = self.items.len();
let scrolling = req.y < h;
// Add 2 spaces for the scrollbar if we need
let w = if scrolling {
w + 2
} else {
w
};
Vec2::new(w, h)
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if self.popup {
match event {
Event::Key(Key::Enter) => {
let mut tree = MenuTree::new();
for (i, item) in self.items.iter().enumerate() {
let focus = self.focus.clone();
let select_cb = self.select_cb.as_ref().cloned();
let value = item.value.clone();
tree.add_leaf(&item.label, move |s| {
focus.set(i);
if let Some(ref select_cb) = select_cb {
select_cb(s, &value);
}
});
}
let tree = Rc::new(tree);
EventResult::with_cb(move |s| {
let tree = tree.clone();
s.add_layer(MenuPopup::new(tree));
})
}
_ => EventResult::Ignored,
2016-03-15 22:37:57 +00:00
}
} else {
match event {
Event::Key(Key::Up) if self.focus() > 0 => self.focus_up(1),
Event::Key(Key::Down) if self.focus() + 1 <
self.items.len() => {
self.focus_down(1)
}
Event::Key(Key::PageUp) => self.focus_up(10),
Event::Key(Key::PageDown) => self.focus_down(10),
Event::Key(Key::Home) => self.focus.set(0),
Event::Key(Key::End) => self.focus.set(self.items.len() - 1),
Event::Key(Key::Enter) if self.select_cb.is_some() => {
let cb = self.select_cb.as_ref().unwrap().clone();
let v = self.selection();
// We return a Callback Rc<|s| cb(s, &*v)>
return EventResult::Consumed(Some(Rc::new(move |s| {
cb(s, &*v)
})));
}
Event::Char(c) => {
// Starting from the current focus,
// find the first item that match the char.
// Cycle back to the beginning of
// the list when we reach the end.
// This is achieved by chaining twice the iterator
let iter = self.items.iter().chain(self.items.iter());
if let Some((i, _)) = iter.enumerate()
.skip(self.focus() + 1)
.find(|&(_, item)| item.label.starts_with(c)) {
// Apply modulo in case we have a hit
// from the chained iterator
self.focus.set(i % self.items.len());
}
}
_ => return EventResult::Ignored,
2016-03-15 22:37:57 +00:00
}
let focus = self.focus();
self.scrollbase.scroll_to(focus);
EventResult::Consumed(None)
}
}
fn take_focus(&mut self, _: Direction) -> bool {
2016-07-17 01:46:18 +00:00
self.enabled && !self.items.is_empty()
}
fn layout(&mut self, size: Vec2) {
if !self.popup {
self.scrollbase.set_heights(size.y, self.items.len());
}
}
}