Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: I4a6b498153eccd5407510dd541b7f4816a6a6964
74 lines
2.1 KiB
Rust
74 lines
2.1 KiB
Rust
use std::time::Duration;
|
|
|
|
use crossterm::event::{self, Event as CrosstermEvent, KeyEvent};
|
|
use tokio::sync::mpsc;
|
|
|
|
#[derive(Debug)]
|
|
pub enum AppEvent {
|
|
Key(KeyEvent),
|
|
Tick,
|
|
ApiResult(ApiResult),
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
#[allow(dead_code)]
|
|
pub enum ApiResult {
|
|
MediaList(Vec<crate::client::MediaResponse>),
|
|
SearchResults(crate::client::SearchResponse),
|
|
Tags(Vec<crate::client::TagResponse>),
|
|
AllTags(Vec<crate::client::TagResponse>),
|
|
Collections(Vec<crate::client::CollectionResponse>),
|
|
ImportDone(crate::client::ImportResponse),
|
|
ScanDone(Vec<crate::client::ScanResponse>),
|
|
AuditLog(Vec<crate::client::AuditEntryResponse>),
|
|
Duplicates(Vec<crate::client::DuplicateGroupResponse>),
|
|
DatabaseStats(crate::client::DatabaseStatsResponse),
|
|
Statistics(crate::client::LibraryStatisticsResponse),
|
|
ScheduledTasks(Vec<crate::client::ScheduledTaskResponse>),
|
|
MediaUpdated,
|
|
Error(String),
|
|
}
|
|
|
|
pub struct EventHandler {
|
|
tx: mpsc::UnboundedSender<AppEvent>,
|
|
rx: mpsc::UnboundedReceiver<AppEvent>,
|
|
}
|
|
|
|
impl EventHandler {
|
|
pub fn new(tick_rate: Duration) -> Self {
|
|
let (tx, rx) = mpsc::unbounded_channel();
|
|
let event_tx = tx.clone();
|
|
|
|
std::thread::spawn(move || {
|
|
loop {
|
|
match event::poll(tick_rate) {
|
|
Ok(true) => {
|
|
if let Ok(CrosstermEvent::Key(key)) = event::read()
|
|
&& event_tx.send(AppEvent::Key(key)).is_err()
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
Ok(false) => {
|
|
if event_tx.send(AppEvent::Tick).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
Err(e) => {
|
|
tracing::warn!(error = %e, "event poll failed");
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
Self { tx, rx }
|
|
}
|
|
|
|
pub fn sender(&self) -> mpsc::UnboundedSender<AppEvent> {
|
|
self.tx.clone()
|
|
}
|
|
|
|
pub async fn next(&mut self) -> Option<AppEvent> {
|
|
self.rx.recv().await
|
|
}
|
|
}
|