don't crash if time is *really* invalid
[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=1;
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         notifiers.insert(std::pair<int,eSocketNotifier*> (sn->getFD(), sn));
120 }
121
122 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
123 {
124         for (std::multimap<int,eSocketNotifier*>::iterator i = notifiers.find(sn->getFD());
125                         i != notifiers.end();
126                         ++i)
127                 if (i->second == sn)
128                         return notifiers.erase(i);
129         eFatal("removed socket notifier which is not present");
130 }
131
132 int eMainloop::processOneEvent(unsigned int user_timeout, PyObject **res, PyObject *additional)
133 {
134         int return_reason = 0;
135                 /* get current time */
136         timeval now;
137         gettimeofday(&now, 0);
138         m_now_is_invalid = 0;
139                 
140         if (additional && !PyDict_Check(additional))
141                 eFatal("additional, but it's not dict");
142                 
143         if (additional && !res)
144                 eFatal("additional, but no res");
145                 
146         int poll_timeout = -1; /* infinite in case of empty timer list */
147                 
148         if (m_timer_list)
149         {
150                 singleLock s(recalcLock);
151                 poll_timeout = timeval_to_usec(m_timer_list.begin()->getNextActivation() - now);
152                         /* if current timer already passed, don't delay infinite. */
153                 if (poll_timeout < 0)
154                         poll_timeout = 0;
155                         
156                         /* 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 ret = 0;
167                 
168         std::multimap<int,eSocketNotifier*>::iterator it;
169         std::map<int,int> fd_merged;
170         std::map<int,int>::const_iterator fd_merged_it;
171                 
172         for (it = notifiers.begin(); it != notifiers.end(); ++it)
173                 fd_merged[it->first] |= it->second->getRequested();
174                 
175         fd_merged_it = fd_merged.begin();
176                 
177         int nativecount, fdcount;
178                 
179         nativecount = fdcount = fd_merged.size();
180                 
181         if (additional)
182         {
183                 additional = PyDict_Items(additional);
184                 fdcount += PyList_Size(additional);
185         }
186                 
187                 // build the poll aray
188         pollfd* pfd = new pollfd[fdcount];  // make new pollfd array
189                 
190         for (int i=0; i < nativecount; i++, fd_merged_it++)
191         {
192                 pfd[i].fd = fd_merged_it->first;
193                 pfd[i].events = fd_merged_it->second;
194         }
195                 
196         if (additional)
197         {
198                 for (int i=0; i < PyList_Size(additional); ++i)
199                 {
200                         PyObject *it = PyList_GET_ITEM(additional, i);
201                         if (!PyTuple_Check(it))
202                                 eFatal("poll item is not a tuple");
203                         if (PyTuple_Size(it) != 2)
204                                 eFatal("poll tuple size is not 2");
205                         int fd = PyObject_AsFileDescriptor(PyTuple_GET_ITEM(it, 0));
206                         if (fd == -1)
207                                 eFatal("poll tuple not a filedescriptor");
208                         pfd[nativecount + i].fd = fd;
209                         pfd[nativecount + i].events = PyInt_AsLong(PyTuple_GET_ITEM(it, 1));
210                 }
211                 Py_DECREF(additional);
212         }
213                 
214         ret = ::poll(pfd, fdcount, poll_timeout);
215                 
216                         /* ret > 0 means that there are some active poll entries. */
217         if (ret > 0)
218         {
219                 return_reason = 0;
220                 for (int i=0; i < nativecount ; i++)
221                 {
222                         it = notifiers.begin();
223                                 
224                         int handled = 0;
225                                 
226                         std::multimap<int,eSocketNotifier*>::iterator 
227                                 l = notifiers.lower_bound(pfd[i].fd),
228                                 u = notifiers.upper_bound(pfd[i].fd);
229                                 
230                         ePtrList<eSocketNotifier> n;
231                                 
232                         for (; l != u; ++l)
233                                 n.push_back(l->second);
234                                 
235                         for (ePtrList<eSocketNotifier>::iterator li(n.begin()); li != n.end(); ++li)
236                         {
237                                 int req = li->getRequested();
238                                         
239                                 handled |= req;
240                                 
241                                 if (pfd[i].revents & req)
242                                         (*li)->activate(pfd[i].revents);
243                         }
244                         if ((pfd[i].revents&~handled) & (POLLERR|POLLHUP|POLLNVAL))
245                                 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
246                 }
247                         
248                 for (int i = nativecount; i < fdcount; ++i)
249                 {
250                         if (pfd[i].revents)
251                         {
252                                 if (!*res)
253                                         *res = PyList_New(0);
254                                 PyObject *it = PyTuple_New(2);
255                                 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
256                                 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
257                                 PyList_Append(*res, it);
258                                 Py_DECREF(it);
259                         }
260                 }
261                         
262                 ret = 1; /* poll did not timeout. */
263         } else if (ret < 0)
264         {
265                         /* when we got a signal, we get EINTR. */
266                 if (errno != EINTR)
267                         eDebug("poll made error (%m)");
268                 else
269                 {
270                         return_reason = 2;
271                         ret = -1; /* don't assume the timeout has passed when we got a signal */
272                 }
273         }
274         delete [] pfd;
275         
276                 /* when we not processed anything, check timers. */
277         if (!m_timer_list.empty())
278         {
279                         /* we know that this time has passed. */
280                 singleLock s(recalcLock);
281
282                 if (ret || m_now_is_invalid)
283                         gettimeofday(&now, 0);
284                 else
285                         now += poll_timeout;
286
287                         /* process all timers which are ready. first remove them out of the list. */
288                 while ((!m_timer_list.empty()) && (m_timer_list.begin()->getNextActivation() <= now))
289                         m_timer_list.begin()->activate();
290         }
291         
292         return return_reason;
293 }
294
295 void eMainloop::addTimer(eTimer* e)
296 {
297         m_timer_list.insert_in_order(e);
298 }
299
300 void eMainloop::removeTimer(eTimer* e)
301 {
302         m_timer_list.remove(e);
303 }
304
305 int eMainloop::iterate(unsigned int user_timeout, PyObject **res, PyObject *dict)
306 {
307         int ret = 0;
308         
309         timeval user_timer;
310         gettimeofday(&user_timer, 0);
311         user_timer += user_timeout;
312
313                 /* TODO: this code just became ugly. fix that. */
314         do
315         {
316                 if (m_interrupt_requested)
317                 {
318                         m_interrupt_requested = 0;
319                         return 0;
320                 }
321                 if (app_quit_now) return -1;
322                 timeval now, timeout;
323                 gettimeofday(&now, 0);
324                 timeout = user_timer - now;
325                 
326                 if (user_timeout && (user_timer <= now))
327                         return 0;
328                 
329                 int to = 0;
330                 if (user_timeout)
331                         to = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
332                 
333                 ret = processOneEvent(to, res, dict);
334                 if (res && *res)
335                         return ret;
336         } while (ret == 0);
337         
338         return ret;
339 }
340
341 int eMainloop::runLoop()
342 {
343         while (!app_quit_now)
344                 iterate();
345         return retval;
346 }
347
348 void eMainloop::reset()
349 {
350         app_quit_now=false;
351 }
352
353 PyObject *eMainloop::poll(PyObject *timeout, PyObject *dict)
354 {
355         PyObject *res = 0;
356         
357         if (app_quit_now)
358         {
359                 Py_INCREF(Py_None);
360                 return Py_None;
361         }
362         
363         int user_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
364
365         iterate(user_timeout, &res, dict);
366         
367         if (!res) /* return empty list on timeout */
368                 res = PyList_New(0);
369         
370         return res;
371 }
372
373 void eMainloop::interruptPoll()
374 {
375         m_interrupt_requested = 1;
376 }
377
378 void eMainloop::quit(int ret)
379 {
380         retval = ret;
381         app_quit_now = true;
382 }
383
384 void eMainloop::addTimeOffset(int offset)
385 {
386         for (ePtrList<eMainloop>::iterator it(eMainloop::existing_loops)
387                 ;it != eMainloop::existing_loops.end(); ++it)
388         {
389                 singleLock s(it->recalcLock);
390                 it->m_now_is_invalid = 1;
391                 for (ePtrList<eTimer>::iterator tit = it->m_timer_list.begin(); tit != it->m_timer_list.end(); ++tit )
392                         tit->addTimeOffset(offset);
393         }
394 }
395
396 eApplication* eApp = 0;