use super::types::{ComponentId, Event, EventContext, EventKind, EventType};
use crate::action::Action;
use crossterm::event::{self, KeyModifiers, MouseEventKind};
use std::collections::{HashMap, HashSet};
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info};
#[derive(Debug)]
pub enum RawEvent {
Key(crossterm::event::KeyEvent),
Mouse(crossterm::event::MouseEvent),
Resize(u16, u16),
}
pub struct EventBus {
subscriptions: HashMap<EventType, HashSet<ComponentId>>,
context: EventContext,
action_tx: mpsc::UnboundedSender<Action>,
}
impl EventBus {
pub fn new(action_tx: mpsc::UnboundedSender<Action>) -> Self {
Self {
subscriptions: HashMap::new(),
context: EventContext::default(),
action_tx,
}
}
pub fn subscribe(&mut self, component: ComponentId, event_type: EventType) {
self.subscriptions
.entry(event_type)
.or_default()
.insert(component);
}
pub fn subscribe_many(&mut self, component: ComponentId, event_types: &[EventType]) {
for &event_type in event_types {
self.subscribe(component, event_type);
}
}
pub fn unsubscribe(&mut self, component: ComponentId, event_type: EventType) {
if let Some(subscribers) = self.subscriptions.get_mut(&event_type) {
subscribers.remove(&component);
}
}
pub fn unsubscribe_all(&mut self, component: ComponentId) {
for subscribers in self.subscriptions.values_mut() {
subscribers.remove(&component);
}
}
pub fn get_subscribers(&self, event_type: EventType) -> Vec<ComponentId> {
self.subscriptions
.get(&event_type)
.map(|s| s.iter().copied().collect())
.unwrap_or_default()
}
pub fn get_event_subscribers(&self, event: &Event) -> Vec<ComponentId> {
let mut subscribers = HashSet::new();
if event.is_global() {
if let Some(global_subs) = self.subscriptions.get(&EventType::Global) {
subscribers.extend(global_subs.iter().copied());
}
}
if let Some(type_subs) = self.subscriptions.get(&event.event_type()) {
subscribers.extend(type_subs.iter().copied());
}
subscribers.into_iter().collect()
}
pub fn context_mut(&mut self) -> &mut EventContext {
&mut self.context
}
pub fn context(&self) -> &EventContext {
&self.context
}
pub fn create_event(&self, kind: EventKind) -> Event {
Event::new(kind, self.context.clone())
}
pub fn action_tx(&self) -> &mpsc::UnboundedSender<Action> {
&self.action_tx
}
pub fn update_mouse_position(&mut self, x: u16, y: u16) {
self.context.mouse_position = Some((x, y));
}
pub fn update_modifiers(&mut self, modifiers: KeyModifiers) {
self.context.modifiers = modifiers;
}
}
pub fn spawn_event_poller(
tx: mpsc::UnboundedSender<RawEvent>,
poll_timeout: Duration,
loop_sleep: Duration,
cancel_token: CancellationToken,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
const MAX_EVENTS_PER_BATCH: usize = 20;
loop {
tokio::select! {
_ = cancel_token.cancelled() => {
info!("Event poller cancelled, draining buffer");
while event::poll(Duration::ZERO).unwrap_or(false) {
let _ = event::read();
}
break;
}
_ = tokio::time::sleep(loop_sleep) => {
let mut events_processed = 0;
while events_processed < MAX_EVENTS_PER_BATCH
&& event::poll(poll_timeout).unwrap_or(false)
{
events_processed += 1;
if let Ok(evt) = event::read() {
let raw = match evt {
event::Event::Key(key) => Some(RawEvent::Key(key)),
event::Event::Mouse(mouse) => Some(RawEvent::Mouse(mouse)),
event::Event::Resize(w, h) => Some(RawEvent::Resize(w, h)),
_ => None,
};
if let Some(raw) = raw {
if tx.send(raw).is_err() {
debug!("Event channel closed, stopping poller");
return;
}
}
}
}
}
}
}
})
}
pub fn process_raw_event(raw: RawEvent) -> EventKind {
match raw {
RawEvent::Key(key) => EventKind::Key(key),
RawEvent::Mouse(mouse) => match mouse.kind {
MouseEventKind::ScrollDown => EventKind::Scroll {
column: mouse.column,
row: mouse.row,
delta: 1,
},
MouseEventKind::ScrollUp => EventKind::Scroll {
column: mouse.column,
row: mouse.row,
delta: -1,
},
_ => EventKind::Mouse(mouse),
},
RawEvent::Resize(w, h) => EventKind::Resize(w, h),
}
}