use crate::{
direction::Direction,
event::{Event, EventResult, Key, MouseButton, MouseEvent},
theme::PaletteStyle,
utils::markup::StyledString,
view::{CannotFocus, View},
Cursive, Printer, Vec2,
};
use std::any::Any;
use std::any::TypeId;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
type Callback<T> = dyn Fn(&mut Cursive, &T);
thread_local! {
static GROUPS: RefCell<BTreeMap<(String, TypeId), Box<dyn Any>>> =
RefCell::new(BTreeMap::new());
}
struct SharedState<T> {
selection: usize,
values: Vec<Rc<T>>,
on_change: Option<Rc<Callback<T>>>,
}
impl<T> SharedState<T> {
pub fn selection(&self) -> Rc<T> {
Rc::clone(&self.values[self.selection])
}
}
pub struct RadioGroup<T> {
state: Rc<RefCell<SharedState<T>>>,
}
impl<T> Clone for RadioGroup<T> {
fn clone(&self) -> Self {
Self {
state: Rc::clone(&self.state),
}
}
}
impl<T: 'static> Default for RadioGroup<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: 'static> RadioGroup<T> {
pub fn new() -> Self {
RadioGroup {
state: Rc::new(RefCell::new(SharedState {
selection: 0,
values: Vec::new(),
on_change: None,
})),
}
}
pub fn with_global<F, R>(key: &str, f: F) -> R
where
F: FnOnce(&mut RadioGroup<T>) -> R,
{
let type_id = TypeId::of::<T>();
GROUPS.with(|groups| {
let mut groups = groups.borrow_mut();
let group = groups
.entry((key.to_string(), type_id))
.or_insert(Box::new(RadioGroup::<T>::new()));
let group = group.downcast_mut().unwrap();
f(group)
})
}
pub fn button<S: Into<StyledString>>(
&mut self,
value: T,
label: S,
) -> RadioButton<T> {
let count = self.state.borrow().values.len();
self.state.borrow_mut().values.push(Rc::new(value));
RadioButton::new(Rc::clone(&self.state), count, label.into())
}
pub fn selected_id(&self) -> usize {
self.state.borrow().selection
}
pub fn selection(&self) -> Rc<T> {
self.state.borrow().selection()
}
pub fn set_on_change<F: 'static + Fn(&mut Cursive, &T)>(
&mut self,
on_change: F,
) {
self.state.borrow_mut().on_change = Some(Rc::new(on_change));
}
#[must_use]
pub fn on_change<F: 'static + Fn(&mut Cursive, &T)>(
self,
on_change: F,
) -> Self {
crate::With::with(self, |s| s.set_on_change(on_change))
}
}
impl RadioGroup<String> {
pub fn button_str<S: Into<String>>(
&mut self,
text: S,
) -> RadioButton<String> {
let text = text.into();
self.button(text.clone(), text)
}
}
impl RadioButton<String> {
pub fn global_str<S: Into<String>>(key: &str, text: S) -> Self {
RadioGroup::with_global(key, move |group| group.button_str(text))
}
}
pub struct RadioButton<T> {
state: Rc<RefCell<SharedState<T>>>,
id: usize,
enabled: bool,
label: StyledString,
}
impl<T: 'static> RadioButton<T> {
impl_enabled!(self.enabled);
fn new(
state: Rc<RefCell<SharedState<T>>>,
id: usize,
label: StyledString,
) -> Self {
RadioButton {
state,
id,
enabled: true,
label,
}
}
pub fn global<S: Into<StyledString>>(
key: &str,
value: T,
label: S,
) -> Self {
RadioGroup::with_global(key, move |group| group.button(value, label))
}
pub fn is_selected(&self) -> bool {
self.state.borrow().selection == self.id
}
pub fn select(&mut self) -> EventResult {
let mut state = self.state.borrow_mut();
state.selection = self.id;
if let Some(ref on_change) = state.on_change {
let on_change = Rc::clone(on_change);
let value = state.selection();
EventResult::with_cb(move |s| on_change(s, &value))
} else {
EventResult::Consumed(None)
}
}
#[must_use]
pub fn selected(self) -> Self {
crate::With::with(self, |s| {
s.select();
})
}
fn draw_internal(&self, printer: &Printer) {
printer.print((0, 0), "( )");
if self.is_selected() {
printer.print((1, 0), "X");
}
if !self.label.is_empty() {
printer.print((3, 0), " ");
printer.print_styled((4, 0), &self.label);
}
}
fn req_size(&self) -> Vec2 {
if self.label.is_empty() {
Vec2::new(3, 1)
} else {
Vec2::new(3 + 1 + self.label.width(), 1)
}
}
}
impl<T: 'static> View for RadioButton<T> {
fn required_size(&mut self, _: Vec2) -> Vec2 {
self.req_size()
}
fn take_focus(
&mut self,
_: Direction,
) -> Result<EventResult, CannotFocus> {
self.enabled.then(EventResult::consumed).ok_or(CannotFocus)
}
fn draw(&self, printer: &Printer) {
if self.enabled && printer.enabled {
printer.with_selection(printer.focused, |printer| {
self.draw_internal(printer)
});
} else {
printer.with_style(PaletteStyle::Secondary, |printer| {
self.draw_internal(printer)
});
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if !self.enabled {
return EventResult::Ignored;
}
match event {
Event::Key(Key::Enter) | Event::Char(' ') => self.select(),
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if position.fits_in_rect(offset, self.req_size()) => {
self.select()
}
_ => EventResult::Ignored,
}
}
}