poppin/kernel/src/events/mod.rs

63 lines
1.4 KiB
Rust

use core::mem::discriminant;
use lazy_static::lazy_static;
#[macro_use]
mod types;
use spin::Mutex;
pub use types::*;
const MAX_EVENT_LISTENERS: usize = 255;
lazy_static!(
pub static ref EVENTMAN: Mutex<EventManager> = Mutex::new(EventManager::new());
);
pub struct EventManager {
listeners: [Option<EventManagerEntry>; MAX_EVENT_LISTENERS],
listener_count: usize,
}
type EventListenerFunc = fn(ev: &Event) -> Result<(), ()>;
pub struct EventManagerEntry {
pub func: EventListenerFunc,
pub typ: Event
}
const ARRAY_REPEAT_VALUE: Option<EventManagerEntry> = None;
impl EventManager {
pub fn new() -> Self {
Self {
listeners: [ARRAY_REPEAT_VALUE; MAX_EVENT_LISTENERS],
listener_count: 0
}
}
pub fn dispatch(&self, ev: &Event){
for listener in &self.listeners {
if let Some(l) = listener {
if discriminant(ev) == discriminant(&l.typ) {
// TODO: Do something with the result
let _ = (l.func)(ev);
}
}
}
}
pub fn add_listener(&mut self, typ: Event, func: EventListenerFunc) {
self.listeners[self.listener_count] = Some(EventManagerEntry {
func, typ
})
}
#[allow(dead_code)]
pub fn remove_listener(&mut self, _: &str) {
todo!()
}
}