Skip to main content

alf/tui/
events.rs

1//! Event handling for the TUI.
2
3use anyhow::Result;
4use crossterm::event::{self, Event as CrosstermEvent, KeyEvent};
5use std::time::Duration;
6
7/// Application events
8#[derive(Debug, Clone)]
9pub enum Event {
10   /// Keyboard input event
11   Key(KeyEvent),
12   /// Terminal resize event
13   Resize(u16, u16),
14   /// Periodic tick for updates
15   Tick,
16}
17
18/// Event handler for polling terminal events
19pub struct EventHandler {
20   tick_rate: Duration,
21}
22
23impl EventHandler {
24   /// Create a new event handler with the given tick rate
25   pub fn new(tick_rate: Duration) -> Self {
26      Self {
27         tick_rate,
28      }
29   }
30
31   /// Poll for the next event.
32   ///
33   /// Blocks until either a terminal event occurs or the tick rate elapses.
34   /// Returns `Event::Tick` on timeout, or the appropriate event variant.
35   pub fn next(&self) -> Result<Event> {
36      if event::poll(self.tick_rate)? {
37         match event::read()? {
38            CrosstermEvent::Key(key) => Ok(Event::Key(key)),
39            CrosstermEvent::Resize(w, h) => Ok(Event::Resize(w, h)),
40            // Ignore mouse, focus, and paste events
41            _ => Ok(Event::Tick),
42         }
43      } else {
44         Ok(Event::Tick)
45      }
46   }
47}