cf37c1e7e1fbd81155608895bd14ebe9bd882e10
[libs/core.git] / source / io / eventdispatcher.cpp
1 #include <msp/time/utils.h>
2 #include "base.h"
3 #include "eventdispatcher.h"
4 #include "eventobject.h"
5 #include "poll.h"
6
7 namespace Msp {
8 namespace IO {
9
10 EventDispatcher::EventDispatcher()
11 { }
12
13 EventDispatcher::~EventDispatcher()
14 { }
15
16 void EventDispatcher::add(EventObject &obj)
17 {
18         SlotMap::iterator i = objects.find(&obj);
19         if(i==objects.end())
20         {
21                 i = objects.insert(SlotMap::value_type(&obj, Slot(&obj))).first;
22                 i->second.evch_conn = obj.signal_events_changed.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_events_changed), &obj));
23                 i->second.del_conn = obj.signal_deleted.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_deleted), &obj));
24
25                 if(obj.get_events())
26                         poller.set_object(obj, obj.get_events());
27         }
28 }
29
30 void EventDispatcher::remove(EventObject &obj)
31 {
32         SlotMap::iterator i = objects.find(&obj);
33         if(i!=objects.end())
34         {
35                 i->second.evch_conn.disconnect();
36                 i->second.del_conn.disconnect();
37                 objects.erase(i);
38
39                 poller.set_object(obj, P_NONE);
40         }
41 }
42
43 void EventDispatcher::tick()
44 {
45         if(objects.empty())
46                 return;
47
48         if(poller.poll()>0)
49                 dispatch();
50 }
51
52 void EventDispatcher::tick(const Time::TimeDelta &dt)
53 {
54         if(objects.empty())
55                 return;
56
57         if(poller.poll(dt)>0)
58                 dispatch();
59 }
60
61 void EventDispatcher::tick(const Time::Timer &timer)
62 {
63         const Time::TimeStamp &timeout = timer.get_next_timeout();
64         if(timeout)
65                 tick(timeout-Time::now());
66         else
67                 tick();
68 }
69
70 void EventDispatcher::object_events_changed(PollEvent ev, EventObject *obj)
71 {
72         poller.set_object(*obj, ev);
73 }
74
75 void EventDispatcher::object_deleted(EventObject *obj)
76 {
77         remove(*obj);
78 }
79
80 void EventDispatcher::dispatch()
81 {
82         const Poller::SlotList &result = poller.get_result();
83         for(Poller::SlotList::const_iterator i=result.begin(); i!=result.end(); ++i)
84                 i->object->event(i->events);
85 }
86
87 } // namespace IO
88 } // namespace Msp