rustpm 0.2.2

A fast, friendly APT frontend with kernel, desktop, and sources management
use anyhow::Result;
use crossterm::event::{self, Event, KeyEvent};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

pub enum AppEvent {
    Key(KeyEvent),
    AptOutput(String),
    Tick,
}

pub struct EventHandler {
    rx: mpsc::Receiver<AppEvent>,
}

impl EventHandler {
    pub fn new(apt_rx: Option<mpsc::Receiver<String>>) -> Self {
        let (tx, rx) = mpsc::channel();

        // Keyboard event thread
        let key_tx = tx.clone();
        thread::spawn(move || loop {
            if event::poll(Duration::from_millis(50)).unwrap_or(false) {
                if let Ok(Event::Key(key)) = event::read() {
                    if key_tx.send(AppEvent::Key(key)).is_err() {
                        break;
                    }
                }
            } else {
                if key_tx.send(AppEvent::Tick).is_err() {
                    break;
                }
            }
        });

        // APT output forwarding thread
        if let Some(apt_rx) = apt_rx {
            let out_tx = tx;
            thread::spawn(move || {
                for line in apt_rx {
                    if out_tx.send(AppEvent::AptOutput(line)).is_err() {
                        break;
                    }
                }
            });
        }

        Self { rx }
    }

    pub fn next(&self) -> Result<AppEvent> {
        Ok(self.rx.recv()?)
    }
}