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