1use std::path::PathBuf;
4use std::thread;
5use std::time::Duration;
6use tokio::sync::mpsc::UnboundedReceiver;
7
8#[derive(Debug, Clone)]
10pub enum Event {
11 Key(KeyEvent),
13 Mouse(MouseEvent),
15 Resize { width: u16, height: u16 },
17 Tick,
19 DragDrop { paths: Vec<PathBuf> },
22}
23
24#[derive(Debug, Clone, Copy)]
26pub struct KeyEvent {
27 pub code: KeyCode,
29 pub modifiers: KeyModifiers,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum KeyCode {
36 Char(char),
38 Enter,
40 Esc,
42 Tab,
44 Backspace,
46 Delete,
48 Up,
50 Down,
51 Left,
52 Right,
53 F(u8),
55 Other,
57}
58
59#[derive(Debug, Clone, Copy, Default)]
61pub struct KeyModifiers {
62 pub shift: bool,
64 pub ctrl: bool,
66 pub alt: bool,
68}
69
70#[derive(Debug, Clone, Copy)]
72pub struct MouseEvent {
73 pub x: u16,
75 pub y: u16,
77 pub button: MouseButton,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum MouseButton {
84 Left,
86 Right,
88 Middle,
90}
91
92pub struct EventLoop {
94 rx: Option<UnboundedReceiver<Event>>,
96 tx: Option<tokio::sync::mpsc::UnboundedSender<Event>>,
98}
99
100impl EventLoop {
101 pub fn new() -> Self {
103 let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
104 let tx_clone = tx.clone();
105
106 thread::spawn(move || {
108 let tick_interval = Duration::from_millis(250);
110 let mut last_tick = std::time::Instant::now();
111
112 loop {
113 if last_tick.elapsed() >= tick_interval {
114 let _ = tx_clone.send(Event::Tick);
115 last_tick = std::time::Instant::now();
116 }
117
118 thread::sleep(Duration::from_millis(10));
120 }
121 });
122
123 Self { rx: Some(rx), tx: Some(tx) }
124 }
125
126 pub async fn poll(&mut self) -> anyhow::Result<Option<Event>> {
128 if let Some(rx) = &mut self.rx {
129 Ok(rx.recv().await)
130 } else {
131 Ok(None)
132 }
133 }
134
135 pub fn send_drag_drop_event(&self, paths: Vec<PathBuf>) -> anyhow::Result<()> {
146 if let Some(tx) = self.tx.as_ref() {
147 tx.send(Event::DragDrop { paths })?;
148 }
149 Ok(())
150 }
151}
152
153impl Default for EventLoop {
154 fn default() -> Self {
155 Self::new()
156 }
157}