use crate::core::ObjectId;
use crate::event::Event;
use crate::render::RenderContext;
use std::collections::HashMap;
pub struct SimpleRegistry {
entries: HashMap<ObjectId, (DrawClosure, EventClosure)>,
}
type DrawClosure = Box<dyn FnMut(&mut RenderContext) + Send>;
type EventClosure = Box<dyn FnMut(&Event) + Send>;
unsafe impl Send for SimpleRegistry {}
unsafe impl Sync for SimpleRegistry {}
impl Default for SimpleRegistry {
fn default() -> Self {
Self::new()
}
}
impl SimpleRegistry {
pub fn new() -> Self {
Self { entries: HashMap::new() }
}
pub fn register<D, E>(&mut self, id: ObjectId, draw: D, event: E)
where
D: FnMut(&mut RenderContext) + Send + 'static,
E: FnMut(&Event) + Send + 'static,
{
self.entries.insert(id, (Box::new(draw), Box::new(event)));
}
pub fn unregister(&mut self, id: ObjectId) {
self.entries.remove(&id);
}
pub fn draw_widget(&mut self, id: ObjectId, context: &mut RenderContext) -> bool {
if let Some((draw_fn, _)) = self.entries.get_mut(&id) {
(draw_fn)(context);
true
} else {
false
}
}
pub fn forward_event(&mut self, id: ObjectId, event: &Event) -> bool {
if let Some((_, event_fn)) = self.entries.get_mut(&id) {
(event_fn)(event);
true
} else {
false
}
}
pub fn contains(&self, id: ObjectId) -> bool {
self.entries.contains_key(&id)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}