]> git.tdb.fi Git - libs/core.git/blob - source/eventdispatcher.cpp
Refactor EventDispatcher::tick to allow arbitary timeouts
[libs/core.git] / source / eventdispatcher.cpp
1 /* $Id$
2
3 This file is part of libmspio
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7 #include <msp/time/units.h>
8 #include "base.h"
9 #include "eventdispatcher.h"
10 #include "poll.h"
11
12 #include <iostream>
13 using namespace std;
14
15 namespace Msp {
16 namespace IO {
17
18 EventDispatcher::EventDispatcher()
19 { }
20
21 void EventDispatcher::add(Base &obj)
22 {
23         //cout<<"evdisp add "<<&obj<<'\n';
24         SlotMap::iterator i=objects.find(&obj);
25         if(i==objects.end())
26         {
27                 i=objects.insert(SlotMap::value_type(&obj, Slot(&obj))).first;
28                 i->second.evch_conn=obj.signal_events_changed.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_events_changed), &obj));
29                 i->second.del_conn=obj.signal_deleted.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_deleted), &obj));
30
31                 if(obj.get_events())
32                         poller.set_object(obj, obj.get_events());
33         }
34 }
35
36 void EventDispatcher::remove(Base &obj)
37 {
38         //cout<<"evdisp remove "<<&obj<<'\n';
39         SlotMap::iterator i=objects.find(&obj);
40         if(i!=objects.end())
41         {
42                 i->second.evch_conn.disconnect();
43                 i->second.del_conn.disconnect();
44                 objects.erase(i);
45
46                 poller.set_object(obj, P_NONE);
47         }
48 }
49
50 void EventDispatcher::tick()
51 {
52         if(objects.empty())
53                 return;
54
55         if(poller.poll()>0)
56                 dispatch();
57 }
58
59 void EventDispatcher::tick(const Time::TimeDelta &dt)
60 {
61         if(objects.empty())
62                 return;
63
64         if(poller.poll(dt)>0)
65                 dispatch();
66 }
67
68 void EventDispatcher::object_events_changed(PollEvent ev, Base *obj)
69 {
70         poller.set_object(*obj, ev);
71 }
72
73 void EventDispatcher::object_deleted(Base *obj)
74 {
75         remove(*obj);
76 }
77
78 void EventDispatcher::dispatch()
79 {
80         const Poller::SlotSeq &result=poller.get_result();
81         for(Poller::SlotSeq::const_iterator i=result.begin(); i!=result.end(); ++i)
82                 i->object->event(i->events);
83 }
84
85 } // namespace IO
86 } // namespace Msp