1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*!
 * The events dispatcher is a system resposible for sending external events to other systems
 * it also can convert mpsc senders into seitan streams so systems can send events and still be
 * Send
 */
use rinecs::{SystemThreadLocal, EntitiesThreadLocal, ResourcesThreadLocal};
use rin::window::{Window, WindowT, EventsPoll};
use std::sync::mpsc;
use rin::events;
use std::fmt::Debug;

trait Poll{
    fn poll_stream(&mut self);
}

impl<'a,T: Clone + Debug + 'a> Poll for events::SenderFromReceiver<'a,T>{
    fn poll_stream(&mut self){
        self.poll()
    }
}

pub struct EventsDispatcher{
    events: EventsPoll,
    senders: Vec<Box<dyn Poll>>,
}

impl EventsDispatcher{
    pub fn new(events: EventsPoll) -> EventsDispatcher{
        EventsDispatcher{
            events,
            senders: vec![],
        }
    }

    pub fn send_stream<T: Clone + Debug>(&mut self) -> (mpsc::Sender<T>, events::Stream<'static, T>){
        let (tx, rx) = mpsc::channel();
        let (sender, stream) = events::SenderFromReceiver::new(rx);
        self.senders.push(Box::new(sender));
        (tx, stream)
    }
}

impl<'a> SystemThreadLocal<'a> for EventsDispatcher{
    fn run(&mut self, _entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let mut window = resources.get_mut::<Window>().unwrap();
        self.events.poll_events();
        window.update();
        for sender in self.senders.iter_mut(){
            sender.poll_stream()
        }
    }
}