mainloop cleanup/speedup
[openblackhole/openblackhole-enigma2.git] / lib / base / ebase.cpp
1 #include <lib/base/ebase.h>
2
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <errno.h>
6
7 #include <lib/base/eerror.h>
8 #include <lib/base/elock.h>
9
10 eSocketNotifier::eSocketNotifier(eMainloop *context, int fd, int requested, bool startnow): context(*context), fd(fd), state(0), requested(requested)
11 {
12         if (startnow)   
13                 start();
14 }
15
16 eSocketNotifier::~eSocketNotifier()
17 {
18         stop();
19 }
20
21 void eSocketNotifier::start()
22 {
23         if (state)
24                 stop();
25
26         context.addSocketNotifier(this);
27         state=2;  // running but not in poll yet
28 }
29
30 void eSocketNotifier::stop()
31 {
32         if (state)
33                 context.removeSocketNotifier(this);
34
35         state=0;
36 }
37
38                                         // timer
39 void eTimer::start(long msek, bool singleShot)
40 {
41         if (bActive)
42                 stop();
43
44         bActive = true;
45         bSingleShot = singleShot;
46         interval = msek;
47         gettimeofday(&nextActivation, 0);
48 //      eDebug("this = %p\nnow sec = %d, usec = %d\nadd %d msec", this, nextActivation.tv_sec, nextActivation.tv_usec, msek);
49         nextActivation += (msek<0 ? 0 : msek);
50 //      eDebug("next Activation sec = %d, usec = %d", nextActivation.tv_sec, nextActivation.tv_usec );
51         context.addTimer(this);
52 }
53
54 void eTimer::startLongTimer( int seconds )
55 {
56         if (bActive)
57                 stop();
58
59         bActive = bSingleShot = true;
60         interval = 0;
61         gettimeofday(&nextActivation, 0);
62 //      eDebug("this = %p\nnow sec = %d, usec = %d\nadd %d sec", this, nextActivation.tv_sec, nextActivation.tv_usec, seconds);
63         if ( seconds > 0 )
64                 nextActivation.tv_sec += seconds;
65 //      eDebug("next Activation sec = %d, usec = %d", nextActivation.tv_sec, nextActivation.tv_usec );
66         context.addTimer(this);
67 }
68
69 void eTimer::stop()
70 {
71         if (bActive)
72         {
73                 bActive=false;
74                 context.removeTimer(this);
75         }
76 }
77
78 void eTimer::changeInterval(long msek)
79 {
80         if (bActive)  // Timer is running?
81         {
82                 context.removeTimer(this);       // then stop
83                 nextActivation -= interval;  // sub old interval
84         }
85         else
86                 bActive=true; // then activate Timer
87
88         interval = msek;                                                // set new Interval
89         nextActivation += interval;             // calc nextActivation
90
91         context.addTimer(this);                         // add Timer to context TimerList
92 }
93
94 void eTimer::activate()   // Internal Funktion... called from eApplication
95 {
96         context.removeTimer(this);
97
98         if (!bSingleShot)
99         {
100                 nextActivation += interval;
101                 context.addTimer(this);
102         }
103         else
104                 bActive=false;
105
106         /*emit*/ timeout();
107 }
108
109 void eTimer::addTimeOffset( int offset )
110 {
111         nextActivation.tv_sec += offset;
112 }
113
114 // mainloop
115 ePtrList<eMainloop> eMainloop::existing_loops;
116
117 void eMainloop::addSocketNotifier(eSocketNotifier *sn)
118 {
119         int fd = sn->getFD();
120         ASSERT(notifiers.find(fd) == notifiers.end());
121         notifiers[fd]=sn;
122 }
123
124 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
125 {
126         int fd = sn->getFD();
127         std::map<int,eSocketNotifier*>::iterator i(notifiers.find(fd));
128         if (i != notifiers.end())
129                 return notifiers.erase(i);
130         eFatal("removed socket notifier which is not present");
131 }
132
133 int eMainloop::processOneEvent(unsigned int user_timeout, PyObject **res, ePyObject additional)
134 {
135         int return_reason = 0;
136                 /* get current time */
137         timeval now;
138         gettimeofday(&now, 0);
139         m_now_is_invalid = 0;
140                 
141         if (additional && !PyDict_Check(additional))
142                 eFatal("additional, but it's not dict");
143                 
144         if (additional && !res)
145                 eFatal("additional, but no res");
146                 
147         int poll_timeout = -1; /* infinite in case of empty timer list */
148                 
149         if (m_timer_list)
150         {
151                 singleLock s(recalcLock);
152                 poll_timeout = timeval_to_usec(m_timer_list.begin()->getNextActivation() - now);
153                         /* if current timer already passed, don't delay infinite. */
154                 if (poll_timeout < 0)
155                         poll_timeout = 0;
156                 else /* convert us to ms */
157                         poll_timeout /= 1000;
158         }
159         
160         if ((user_timeout > 0) && (poll_timeout > 0) && ((unsigned int)poll_timeout > user_timeout))
161         {
162                 poll_timeout = user_timeout;
163                 return_reason = 1;
164         }
165
166         int nativecount=notifiers.size(),
167                 fdcount=nativecount,
168                 ret=0;
169
170         if (additional)
171                 fdcount += PyDict_Size(additional);
172                 
173                 // build the poll aray
174         pollfd pfd[fdcount];  // make new pollfd array
175         std::map<int,eSocketNotifier*>::iterator it = notifiers.begin();
176         int i=0;
177         for (; i < nativecount; ++i, ++it)
178         {
179                 it->second->state = 1; // running and in poll
180                 pfd[i].fd = it->first;
181                 pfd[i].events = it->second->getRequested();
182         }
183         
184         if (additional)
185         {
186                 PyObject *key, *val;
187                 int pos=0;
188                 while (PyDict_Next(additional, &pos, &key, &val)) {
189                         pfd[i].fd = PyObject_AsFileDescriptor(key);
190                         pfd[i++].events = PyInt_AsLong(val);
191                 }
192         }
193
194         if (this == eApp)
195                 Py_BEGIN_ALLOW_THREADS
196                 ret = ::poll(pfd, fdcount, poll_timeout);
197                 Py_END_ALLOW_THREADS
198         else
199                 ret = ::poll(pfd, fdcount, poll_timeout);
200
201                         /* ret > 0 means that there are some active poll entries. */
202         if (ret > 0)
203         {
204                 int i=0;
205                 return_reason = 0;
206                 for (; i < nativecount; ++i)
207                 {
208                         if (pfd[i].revents)
209                         {
210                                 it = notifiers.find(pfd[i].fd);
211                                 if (it != notifiers.end()
212                                         && it->second->state == 1) // added and in poll
213                                 {
214                                         int req = it->second->getRequested();
215                                         if (pfd[i].revents & req)
216                                                 it->second->activate(pfd[i].revents & req);
217                                         pfd[i].revents &= ~req;
218                                 }
219                                 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
220                                         eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
221                         }
222                 }
223                 for (; i < fdcount; ++i)
224                 {
225                         if (pfd[i].revents)
226                         {
227                                 if (!*res)
228                                         *res = PyList_New(0);
229                                 ePyObject it = PyTuple_New(2);
230                                 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
231                                 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
232                                 PyList_Append(*res, it);
233                                 Py_DECREF(it);
234                         }
235                 }
236         }
237         else if (ret < 0)
238         {
239                         /* when we got a signal, we get EINTR. */
240                 if (errno != EINTR)
241                         eDebug("poll made error (%m)");
242                 else
243                         return_reason = 2; /* don't assume the timeout has passed when we got a signal */
244         }
245         
246                 /* when we not processed anything, check timers. */
247         if (!m_timer_list.empty())
248         {
249                         /* we know that this time has passed. */
250                 singleLock s(recalcLock);
251
252                 if (ret || m_now_is_invalid)
253                         gettimeofday(&now, 0);
254                 else // poll timeoutet
255                         now += poll_timeout;
256
257                         /* process all timers which are ready. first remove them out of the list. */
258                 while ((!m_timer_list.empty()) && (m_timer_list.begin()->getNextActivation() <= now))
259                         m_timer_list.begin()->activate();
260         }
261         
262         return return_reason;
263 }
264
265 void eMainloop::addTimer(eTimer* e)
266 {
267         m_timer_list.insert_in_order(e);
268 }
269
270 void eMainloop::removeTimer(eTimer* e)
271 {
272         m_timer_list.remove(e);
273 }
274
275 int eMainloop::iterate(unsigned int user_timeout, PyObject **res, ePyObject dict)
276 {
277         int ret = 0;
278
279         timeval user_timer;
280         gettimeofday(&user_timer, 0);
281         user_timer += user_timeout;
282
283                 /* TODO: this code just became ugly. fix that. */
284         do
285         {
286                 if (m_interrupt_requested)
287                 {
288                         m_interrupt_requested = 0;
289                         return 0;
290                 }
291
292                 if (app_quit_now)
293                         return -1;
294
295                 int to = 0;
296                 if (user_timeout)
297                 {
298                         timeval now, timeout;
299                         gettimeofday(&now, 0);
300                         if (user_timer<=now) // timeout
301                                 return 0;
302                         timeout = user_timer - now;
303                         to = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
304                 }
305                 ret = processOneEvent(to, res, dict);
306         } while ( !ret && !(res && *res) );
307         
308         return ret;
309 }
310
311 int eMainloop::runLoop()
312 {
313         while (!app_quit_now)
314                 iterate();
315         return retval;
316 }
317
318 void eMainloop::reset()
319 {
320         app_quit_now=false;
321 }
322
323 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
324 {
325         PyObject *res=0;
326         
327         if (app_quit_now)
328                 Py_RETURN_NONE;
329         
330         int user_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
331
332         iterate(user_timeout, &res, dict);
333         if (res)
334                 return res;
335
336         return PyList_New(0); /* return empty list on timeout */
337 }
338
339 void eMainloop::interruptPoll()
340 {
341         m_interrupt_requested = 1;
342 }
343
344 void eMainloop::quit(int ret)
345 {
346         retval = ret;
347         app_quit_now = true;
348 }
349
350 void eMainloop::addTimeOffset(int offset)
351 {
352         for (ePtrList<eMainloop>::iterator it(eMainloop::existing_loops)
353                 ;it != eMainloop::existing_loops.end(); ++it)
354         {
355                 singleLock s(it->recalcLock);
356                 it->m_now_is_invalid = 1;
357                 for (ePtrList<eTimer>::iterator tit = it->m_timer_list.begin(); tit != it->m_timer_list.end(); ++tit )
358                         tit->addTimeOffset(offset);
359         }
360 }
361
362 eApplication* eApp = 0;