use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use crate::view::ViewDelegate;
type CellFactoryMap = HashMap<&'static str, Box<dyn Fn() -> Box<dyn Any>>>;
#[derive(Clone)]
pub struct CellFactory(pub Rc<RefCell<CellFactoryMap>>);
impl CellFactory {
pub fn new() -> Self {
CellFactory(Rc::new(RefCell::new(HashMap::new())))
}
pub fn insert<F, T>(&self, identifier: &'static str, vendor: F)
where
F: Fn() -> T + 'static,
T: ViewDelegate + 'static
{
let mut lock = self.0.borrow_mut();
lock.insert(
identifier,
Box::new(move || {
let cell = vendor();
Box::new(cell) as Box<dyn Any>
})
);
}
pub fn get<R>(&self, identifier: &'static str) -> Box<R>
where
R: ViewDelegate + 'static
{
let lock = self.0.borrow();
let vendor = match lock.get(identifier) {
Some(v) => v,
None => {
panic!("Unable to dequeue cell for {}: did you forget to register it?", identifier);
}
};
let view = vendor();
if let Ok(view) = view.downcast::<R>() {
view
} else {
panic!("Asking for cell of type {}, but failed to match the type!", identifier);
}
}
}
impl std::fmt::Debug for CellFactory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CellFactory").finish()
}
}