better structure

This commit is contained in:
2025-06-28 15:02:45 +02:00
parent f401d4a995
commit f43be496c1
5 changed files with 36 additions and 26 deletions
+23 -13
View File
@@ -9,13 +9,13 @@ use crate::{event, state::StateManager};
event!(Close);
pub trait Event {
fn as_any(self: Box<Self>) -> Box<dyn Any>;
fn as_any(&self) -> &dyn Any;
}
pub struct EventManager {
handlers:
Mutex<HashMap<TypeId, Vec<Arc<Mutex<dyn FnMut(&Arc<EventManager>, Box<dyn Event>)>>>>>,
handlers: Mutex<HashMap<TypeId, Vec<Arc<Mutex<dyn FnMut(&Arc<EventManager>, &dyn Event)>>>>>,
states: Mutex<Option<Arc<StateManager>>>,
event_stack: Mutex<Vec<(TypeId, Box<dyn Event>)>>,
}
impl EventManager {
@@ -23,10 +23,11 @@ impl EventManager {
Arc::new(EventManager {
handlers: Mutex::new(HashMap::new()),
states: Mutex::new(None),
event_stack: Mutex::new(Vec::new()),
})
}
pub fn on<E: Event + 'static, F: FnMut(&Arc<EventManager>, Box<E>) + 'static>(
pub fn on<E: Event + 'static, F: FnMut(&Arc<EventManager>, &E) + 'static>(
self: &Arc<Self>,
mut f: F,
) {
@@ -37,8 +38,8 @@ impl EventManager {
.entry(TypeId::of::<E>())
.or_insert_with(Vec::new)
.push(Arc::new(Mutex::new(
move |e: &Arc<EventManager>, evt: Box<dyn Event>| {
if let Ok(concrete) = evt.as_any().downcast::<E>() {
move |e: &Arc<EventManager>, evt: &dyn Event| {
if let Some(concrete) = evt.as_any().downcast_ref::<E>() {
f(&e, concrete);
if let Some(states) = &states {
states.clone().flush();
@@ -48,24 +49,33 @@ impl EventManager {
)));
}
pub fn dispatch<E: Event + 'static + Clone>(self: &Arc<Self>, evt: E) {
let tid = evt.type_id();
fn dispatch_single(self: &Arc<Self>, tid: TypeId, evt: &dyn Event) {
if let Some(handlers) = self.handlers.lock().unwrap().get_mut(&tid) {
// Clone handlers to avoid borrowing self during call
let handler_clones: Vec<_> = handlers.iter().cloned().collect();
for h in handler_clones {
let mut ha = h.lock().unwrap();
(ha)(self, Box::new(evt.clone()));
(ha)(self, evt);
}
}
}
if tid == TypeId::of::<Close>() {
std::process::exit(0);
pub fn dispatch<E: Event + 'static + Clone>(self: &Arc<Self>, evt: E) {
self.event_stack
.lock()
.unwrap()
.push((evt.type_id(), Box::new(evt)));
while self.event_stack.lock().unwrap().len() > 0 {
dis
}
}
pub fn close(self: &Arc<Self>) {
self.dispatch(Close);
std::process::exit(0);
}
pub fn set_state_manager(self: &Arc<Self>, states: Arc<StateManager>) {
*self.states.lock().unwrap() = Some(states);
}