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
53
54
55
/*!
 * 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, system_thread_local};
use rin_window::{Window, WindowExt, EventsPoll};
use std::sync::mpsc;
use rin_events as 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{
    senders: Vec<Box<dyn Poll>>,
}

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

    pub fn send_stream<T: Clone + Debug + 'static>(&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)
    }
}

pub struct Events;

#[system_thread_local(name = "event dispatcher")]
#[updates("Events")]
impl SystemThreadLocal for EventsDispatcher {
    fn run(&mut self, _: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let mut window = resources.get_mut::<Window>().unwrap();
        let events = resources.get::<EventsPoll>().unwrap();
        window.update();
        events.poll_events();
        for sender in self.senders.iter_mut(){
            sender.poll_stream()
        }
    }
}