use crate::align::{Align, HAlign, VAlign};
use crate::direction::Direction;
use crate::event::{
Callback, Event, EventResult, Key, MouseButton, MouseEvent,
};
use crate::menu::MenuTree;
use crate::rect::Rect;
use crate::theme::ColorStyle;
use crate::utils::markup::StyledString;
use crate::vec::Vec2;
use crate::view::{Position, View};
use crate::views::MenuPopup;
use crate::Cursive;
use crate::Printer;
use crate::With;
use std::borrow::Borrow;
use std::cell::Cell;
use std::cmp::min;
use std::rc::Rc;
pub struct SelectView<T = String> {
items: Vec<Item<T>>,
enabled: bool,
focus: Rc<Cell<usize>>,
on_submit: Option<Rc<dyn Fn(&mut Cursive, &T)>>,
on_select: Option<Rc<dyn Fn(&mut Cursive, &T)>>,
autojump: bool,
align: Align,
popup: bool,
last_offset: Cell<Vec2>,
last_size: Vec2,
}
impl<T: 'static> Default for SelectView<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: 'static> SelectView<T> {
pub fn new() -> Self {
SelectView {
items: Vec::new(),
enabled: true,
focus: Rc::new(Cell::new(0)),
on_select: None,
on_submit: None,
align: Align::top_left(),
popup: false,
autojump: false,
last_offset: Cell::new(Vec2::zero()),
last_size: Vec2::zero(),
}
}
pub fn set_autojump(&mut self, autojump: bool) {
self.autojump = autojump;
}
pub fn autojump(self) -> Self {
self.with(|s| s.set_autojump(true))
}
pub fn popup(self) -> Self {
self.with(|s| s.set_popup(true))
}
pub fn set_popup(&mut self, popup: bool) {
self.popup = popup;
}
pub fn disable(&mut self) {
self.enabled = false;
}
pub fn disabled(self) -> Self {
self.with(Self::disable)
}
pub fn enable(&mut self) {
self.enabled = true;
}
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn set_on_select<F>(&mut self, cb: F)
where
F: Fn(&mut Cursive, &T) + 'static,
{
self.on_select = Some(Rc::new(cb));
}
pub fn on_select<F>(self, cb: F) -> Self
where
F: Fn(&mut Cursive, &T) + 'static,
{
self.with(|s| s.set_on_select(cb))
}
pub fn set_on_submit<F, R, V: ?Sized>(&mut self, cb: F)
where
F: 'static + Fn(&mut Cursive, &V) -> R,
T: Borrow<V>,
{
self.on_submit = Some(Rc::new(move |s, t| {
cb(s, t.borrow());
}));
}
pub fn on_submit<F, V: ?Sized>(self, cb: F) -> Self
where
F: Fn(&mut Cursive, &V) + 'static,
T: Borrow<V>,
{
self.with(|s| s.set_on_submit(cb))
}
pub fn align(mut self, align: Align) -> Self {
self.align = align;
self
}
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
pub fn selection(&self) -> Option<Rc<T>> {
let focus = self.focus();
if self.len() <= focus {
None
} else {
Some(Rc::clone(&self.items[focus].value))
}
}
pub fn clear(&mut self) {
self.items.clear();
self.focus.set(0);
}
pub fn add_item<S: Into<StyledString>>(&mut self, label: S, value: T) {
self.items.push(Item::new(label.into(), value));
}
pub fn get_item(&self, i: usize) -> Option<(&str, &T)> {
self.iter().nth(i)
}
pub fn get_item_mut(
&mut self, i: usize,
) -> Option<(&mut StyledString, &mut T)> {
if i >= self.items.len() {
None
} else {
let item = &mut self.items[i];
if let Some(t) = Rc::get_mut(&mut item.value) {
let label = &mut item.label;
Some((label, t))
} else {
None
}
}
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &T)> {
self.items
.iter()
.map(|item| (item.label.source(), &*item.value))
}
pub fn remove_item(&mut self, id: usize) -> Callback {
self.items.remove(id);
let focus = self.focus();
if focus >= id && focus > 0 {
self.focus.set(focus - 1);
}
self.make_select_cb().unwrap_or_else(Callback::dummy)
}
pub fn insert_item<S>(&mut self, index: usize, label: S, value: T)
where
S: Into<StyledString>,
{
self.items.insert(index, Item::new(label.into(), value));
}
pub fn item<S: Into<String>>(self, label: S, value: T) -> Self {
self.with(|s| s.add_item(label, value))
}
pub fn add_all<S, I>(&mut self, iter: I)
where
S: Into<StyledString>,
I: IntoIterator<Item = (S, T)>,
{
for (s, t) in iter {
self.add_item(s, t);
}
}
pub fn with_all<S, I>(self, iter: I) -> Self
where
S: Into<String>,
I: IntoIterator<Item = (S, T)>,
{
self.with(|s| s.add_all(iter))
}
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_styled((x, 0), (&self.items[i].label).into());
if l < printer.size.x {
assert!((l + x) <= printer.size.x);
printer.print_hline((x + l, 0), printer.size.x - (l + x), " ");
}
}
pub fn selected_id(&self) -> Option<usize> {
if self.items.is_empty() {
None
} else {
Some(self.focus())
}
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
fn focus(&self) -> usize {
self.focus.get()
}
pub fn set_selection(&mut self, i: usize) -> Callback {
let i = if self.is_empty() {
0
} else {
min(i, self.len() - 1)
};
self.focus.set(i);
self.make_select_cb().unwrap_or_else(Callback::dummy)
}
pub fn selected(self, i: usize) -> Self {
self.with(|s| {
s.set_selection(i);
})
}
pub fn select_up(&mut self, n: usize) -> Callback {
self.focus_up(n);
self.make_select_cb().unwrap_or_else(Callback::dummy)
}
pub fn select_down(&mut self, n: usize) -> Callback {
self.focus_down(n);
self.make_select_cb().unwrap_or_else(Callback::dummy)
}
fn focus_up(&mut self, n: usize) {
let focus = self.focus().saturating_sub(n);
self.focus.set(focus);
}
fn focus_down(&mut self, n: usize) {
let focus = min(self.focus() + n, self.items.len().saturating_sub(1));
self.focus.set(focus);
}
fn submit(&mut self) -> EventResult {
let cb = self.on_submit.clone().unwrap();
EventResult::Consumed(
self.selection()
.map(|v| Callback::from_fn(move |s| cb(s, &v))),
)
}
fn on_char_event(&mut self, c: char) -> EventResult {
let i = {
let iter = self.iter().chain(self.iter());
let lower_c: Vec<char> = c.to_lowercase().collect();
let lower_c: &[char] = &lower_c;
if let Some((i, _)) = iter.enumerate().skip(self.focus() + 1).find(
|&(_, (label, _))| label.to_lowercase().starts_with(lower_c),
) {
i % self.len()
} else {
return EventResult::Ignored;
}
};
self.focus.set(i);
let cb = self.set_selection(i);
EventResult::Consumed(Some(cb))
}
fn on_event_regular(&mut self, event: Event) -> EventResult {
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().saturating_sub(1))
}
Event::Mouse {
event: MouseEvent::Press(_),
position,
offset,
} if position
.checked_sub(offset)
.map(|position| {
position < self.last_size && position.y < self.len()
})
.unwrap_or(false) =>
{
self.focus.set(position.y - offset.y)
}
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if self.on_submit.is_some()
&& position
.checked_sub(offset)
.map(|position| {
position < self.last_size && position.y == self.focus()
})
.unwrap_or(false) =>
{
return self.submit();
}
Event::Key(Key::Enter) if self.on_submit.is_some() => {
return self.submit();
}
Event::Char(c) if self.autojump => return self.on_char_event(c),
_ => return EventResult::Ignored,
}
EventResult::Consumed(self.make_select_cb())
}
fn make_select_cb(&self) -> Option<Callback> {
self.on_select.clone().and_then(|cb| {
self.selection()
.map(|v| Callback::from_fn(move |s| cb(s, &v)))
})
}
fn open_popup(&mut self) -> EventResult {
let mut tree = MenuTree::new();
for (i, item) in self.items.iter().enumerate() {
let focus = Rc::clone(&self.focus);
let on_submit = self.on_submit.as_ref().cloned();
let value = Rc::clone(&item.value);
tree.add_leaf(item.label.source(), move |s| {
focus.set(i);
if let Some(ref on_submit) = on_submit {
on_submit(s, &value);
}
});
}
let tree = Rc::new(tree);
let focus = self.focus();
let item_length = self.items[focus].label.width();
let text_offset = (self.last_size.x.saturating_sub(item_length)) / 2;
let offset = self.last_offset.get();
let offset = offset + (text_offset, 0);
let offset = offset.saturating_sub((0, focus));
let offset = offset.saturating_sub((2, 1));
EventResult::with_cb(move |s| {
let tree = Rc::clone(&tree);
let current_offset = s.screen().offset();
let offset = offset.signed() - current_offset;
s.screen_mut().add_layer_at(
Position::parent(offset),
MenuPopup::new(tree).focus(focus),
);
})
}
fn on_event_popup(&mut self, event: Event) -> EventResult {
match event {
Event::Key(Key::Enter) => self.open_popup(),
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if position.fits_in_rect(offset, self.last_size) => {
self.open_popup()
}
_ => EventResult::Ignored,
}
}
}
impl SelectView<String> {
pub fn add_item_str<S: Into<String>>(&mut self, label: S) {
let label = label.into();
self.add_item(label.clone(), label);
}
pub fn item_str<S: Into<String>>(self, label: S) -> Self {
self.with(|s| s.add_item_str(label))
}
pub fn insert_item_str<S>(&mut self, index: usize, label: S)
where
S: Into<String>,
{
let label = label.into();
self.insert_item(index, label.clone(), label);
}
pub fn add_all_str<S, I>(&mut self, iter: I)
where
S: Into<String>,
I: IntoIterator<Item = S>,
{
for s in iter {
self.add_item_str(s);
}
}
pub fn with_all_str<S, I>(self, iter: I) -> Self
where
S: Into<String>,
I: IntoIterator<Item = S>,
{
self.with(|s| s.add_all_str(iter))
}
}
impl<T: 'static> View for SelectView<T> {
fn draw(&self, printer: &Printer<'_, '_>) {
self.last_offset.set(printer.offset);
if self.popup {
let style = if !(self.enabled && printer.enabled) {
ColorStyle::secondary()
} else if printer.focused {
ColorStyle::highlight()
} else {
ColorStyle::primary()
};
let x = match printer.size.x.checked_sub(1) {
Some(x) => x,
None => return,
};
printer.with_color(style, |printer| {
printer.print_hline((1, 0), x, " ");
printer.print((0, 0), "<");
printer.print((x, 0), ">");
let label = &self.items[self.focus()].label;
let offset = HAlign::Center.get_offset(label.width(), x + 1);
printer.print_styled((offset, 0), label.into());
});
} else {
let h = self.items.len();
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.offset((0, offset));
for i in 0..self.len() {
printer.offset((0, i)).with_selection(
i == self.focus(),
|printer| {
if i != self.focus()
&& !(self.enabled && printer.enabled)
{
printer.with_color(
ColorStyle::secondary(),
|printer| self.draw_item(printer, i),
);
} else {
self.draw_item(printer, i);
}
},
);
}
}
}
fn required_size(&mut self, _: Vec2) -> Vec2 {
let w = self
.items
.iter()
.map(|item| item.label.width())
.max()
.unwrap_or(1);
if self.popup {
Vec2::new(w + 2, 1)
} else {
let h = self.items.len();
Vec2::new(w, h)
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if self.popup {
self.on_event_popup(event)
} else {
self.on_event_regular(event)
}
}
fn take_focus(&mut self, _: Direction) -> bool {
self.enabled && !self.items.is_empty()
}
fn layout(&mut self, size: Vec2) {
self.last_size = size;
}
fn important_area(&self, size: Vec2) -> Rect {
self.selected_id()
.map(|i| Rect::from_size((0, i), (size.x, 1)))
.unwrap_or_else(|| Rect::from((0, 0)))
}
}
struct Item<T> {
label: StyledString,
value: Rc<T>,
}
impl<T> Item<T> {
fn new(label: StyledString, value: T) -> Self {
let value = Rc::new(value);
Item { label, value }
}
}