vtui_core/
transport.rs

1use std::{
2    sync::mpsc::{Receiver, Sender},
3    thread::JoinHandle,
4    time::Duration,
5};
6
7use crate::{error::SendError, events::Message};
8
9pub struct EventSource {
10    tx: Sender<Message>,
11    rx: Receiver<Message>,
12}
13
14impl Default for EventSource {
15    fn default() -> Self {
16        let (tx, rx) = std::sync::mpsc::channel();
17        Self { tx, rx }
18    }
19}
20
21impl EventSource {
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    pub fn subscribe(&self, producer: &mut impl EventProducer) {
27        let sink = EventSink(self.tx.clone());
28        producer.spawn(sink);
29    }
30
31    pub(crate) fn recv(&self) -> Message {
32        self.rx.recv().unwrap()
33    }
34
35    pub(crate) fn recv_timeout(&self, budget: Duration) -> Option<Message> {
36        self.rx.recv_timeout(budget).ok()
37    }
38}
39
40#[derive(Clone, Debug)]
41pub struct EventSink(Sender<Message>);
42
43impl EventSink {
44    pub fn send(&self, msg: Message) -> Result<(), SendError> {
45        self.0.send(msg).map_err(|_| SendError)
46    }
47}
48
49pub trait EventProducer {
50    fn spawn(&mut self, tx: EventSink) -> JoinHandle<()>;
51}