mainloop cleanup/speedup
[enigma2.git] / lib / base / ebase.cpp
index 7951f6e76ea25bb6753cb31109c2242eec19504c..6efbf90b17346d6d60c5612db18720552900d463 100644 (file)
@@ -24,7 +24,7 @@ void eSocketNotifier::start()
                stop();
 
        context.addSocketNotifier(this);
-       state=1;
+       state=2;  // running but not in poll yet
 }
 
 void eSocketNotifier::stop()
@@ -45,8 +45,8 @@ void eTimer::start(long msek, bool singleShot)
        bSingleShot = singleShot;
        interval = msek;
        gettimeofday(&nextActivation, 0);
-       nextActivation += (msek<0 ? 0 : msek);
 //     eDebug("this = %p\nnow sec = %d, usec = %d\nadd %d msec", this, nextActivation.tv_sec, nextActivation.tv_usec, msek);
+       nextActivation += (msek<0 ? 0 : msek);
 //     eDebug("next Activation sec = %d, usec = %d", nextActivation.tv_sec, nextActivation.tv_usec );
        context.addTimer(this);
 }
@@ -59,7 +59,7 @@ void eTimer::startLongTimer( int seconds )
        bActive = bSingleShot = true;
        interval = 0;
        gettimeofday(&nextActivation, 0);
-//     eDebug("this = %p\nnow sec = %d, usec = %d\nadd %d msec", this, nextActivation.tv_sec, nextActivation.tv_usec, msek);
+//     eDebug("this = %p\nnow sec = %d, usec = %d\nadd %d sec", this, nextActivation.tv_sec, nextActivation.tv_usec, seconds);
        if ( seconds > 0 )
                nextActivation.tv_sec += seconds;
 //     eDebug("next Activation sec = %d, usec = %d", nextActivation.tv_sec, nextActivation.tv_usec );
@@ -116,53 +116,36 @@ ePtrList<eMainloop> eMainloop::existing_loops;
 
 void eMainloop::addSocketNotifier(eSocketNotifier *sn)
 {
-       notifiers.insert(std::pair<int,eSocketNotifier*> (sn->getFD(), sn));
+       int fd = sn->getFD();
+       ASSERT(notifiers.find(fd) == notifiers.end());
+       notifiers[fd]=sn;
 }
 
 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
 {
-       notifiers.erase(sn->getFD());
+       int fd = sn->getFD();
+       std::map<int,eSocketNotifier*>::iterator i(notifiers.find(fd));
+       if (i != notifiers.end())
+               return notifiers.erase(i);
+       eFatal("removed socket notifier which is not present");
 }
 
-void eMainloop::processOneEvent()
+int eMainloop::processOneEvent(unsigned int user_timeout, PyObject **res, ePyObject additional)
 {
-               /* notes:
-                 - we should use epoll(4)
-                 - timer are checked twice. there was a strong reason for it, but i can't remember. (FIXME)
-                 - for each time, we gettimeofday() and check wether the timer should fire.
-                   we should do this all better - we know how long the poll last, so we know which
-                   timers should fire. Problem is that a timer handler could have required so
-                   much time that another timer fired.
-
-                   A probably structure could look
-
-                   while (1)
-                   {
-                           time = gettimeofday()
-                           timeout = calculate_pending_timers(time);
-
-                     doPoll(timeout or infinite);
-
-                       if (poll_had_results)
-                               handle_poll_handler();
-                       else
-                                   fire_timers(time + timeout)
-                         }
-
-                         the gettimeofday() call is required because fire_timers could last more
-                         than nothing.
-
-                         when poll did no timeout, we don't handle timers, as this will be done
-                         in the next iteration (without adding overhead - we had to get the new
-                         time anyway
-               */
-
+       int return_reason = 0;
                /* get current time */
        timeval now;
        gettimeofday(&now, 0);
-       
+       m_now_is_invalid = 0;
+               
+       if (additional && !PyDict_Check(additional))
+               eFatal("additional, but it's not dict");
+               
+       if (additional && !res)
+               eFatal("additional, but no res");
+               
        int poll_timeout = -1; /* infinite in case of empty timer list */
-       
+               
        if (m_timer_list)
        {
                singleLock s(recalcLock);
@@ -170,68 +153,113 @@ void eMainloop::processOneEvent()
                        /* if current timer already passed, don't delay infinite. */
                if (poll_timeout < 0)
                        poll_timeout = 0;
-                       
-                       /* convert us to ms */
-               poll_timeout /= 1000;
+               else /* convert us to ms */
+                       poll_timeout /= 1000;
        }
        
-       int ret = 0;
-
-       if (poll_timeout)
+       if ((user_timeout > 0) && (poll_timeout > 0) && ((unsigned int)poll_timeout > user_timeout))
        {
-                       // build the poll aray
-               int fdcount = notifiers.size();
-               pollfd* pfd = new pollfd[fdcount];  // make new pollfd array
+               poll_timeout = user_timeout;
+               return_reason = 1;
+       }
 
-               std::map<int,eSocketNotifier*>::iterator it(notifiers.begin());
-               for (int i=0; i < fdcount; i++, it++)
-               {
-                       pfd[i].fd = it->first;
-                       pfd[i].events = it->second->getRequested();
+       int nativecount=notifiers.size(),
+               fdcount=nativecount,
+               ret=0;
+
+       if (additional)
+               fdcount += PyDict_Size(additional);
+               
+               // build the poll aray
+       pollfd pfd[fdcount];  // make new pollfd array
+       std::map<int,eSocketNotifier*>::iterator it = notifiers.begin();
+       int i=0;
+       for (; i < nativecount; ++i, ++it)
+       {
+               it->second->state = 1; // running and in poll
+               pfd[i].fd = it->first;
+               pfd[i].events = it->second->getRequested();
+       }
+       
+       if (additional)
+       {
+               PyObject *key, *val;
+               int pos=0;
+               while (PyDict_Next(additional, &pos, &key, &val)) {
+                       pfd[i].fd = PyObject_AsFileDescriptor(key);
+                       pfd[i++].events = PyInt_AsLong(val);
                }
+       }
 
-               ret = poll(pfd, fdcount, poll_timeout);
+       if (this == eApp)
+               Py_BEGIN_ALLOW_THREADS
+               ret = ::poll(pfd, fdcount, poll_timeout);
+               Py_END_ALLOW_THREADS
+       else
+               ret = ::poll(pfd, fdcount, poll_timeout);
 
                        /* ret > 0 means that there are some active poll entries. */
-               if (ret > 0)
+       if (ret > 0)
+       {
+               int i=0;
+               return_reason = 0;
+               for (; i < nativecount; ++i)
                {
-                       for (int i=0; i < fdcount ; i++)
+                       if (pfd[i].revents)
                        {
-                               if (notifiers.find(pfd[i].fd) == notifiers.end())
-                                       continue;
-                               
-                               int req = notifiers[pfd[i].fd]->getRequested();
-                               
-                               if (pfd[i].revents & req)
+                               it = notifiers.find(pfd[i].fd);
+                               if (it != notifiers.end()
+                                       && it->second->state == 1) // added and in poll
                                {
-                                       notifiers[pfd[i].fd]->activate(pfd[i].revents);
-                               
-                                       if (!--ret)
-                                               break;
-                               } else if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
-                                       eFatal("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d) -> FIX YOUR CODE", pfd[i].fd,pfd[i].revents);
+                                       int req = it->second->getRequested();
+                                       if (pfd[i].revents & req)
+                                               it->second->activate(pfd[i].revents & req);
+                                       pfd[i].revents &= ~req;
+                               }
+                               if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
+                                       eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
                        }
-               } else if (ret < 0)
+               }
+               for (; i < fdcount; ++i)
                {
-                               /* when we got a signal, we get EINTR. we do not care, 
-                                  because we check current time in timers anyway. */
-                       if (errno != EINTR)
-                               eDebug("poll made error (%m)");
-                       else
-                               ret = 0;
+                       if (pfd[i].revents)
+                       {
+                               if (!*res)
+                                       *res = PyList_New(0);
+                               ePyObject it = PyTuple_New(2);
+                               PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
+                               PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
+                               PyList_Append(*res, it);
+                               Py_DECREF(it);
+                       }
                }
-               delete [] pfd;
+       }
+       else if (ret < 0)
+       {
+                       /* when we got a signal, we get EINTR. */
+               if (errno != EINTR)
+                       eDebug("poll made error (%m)");
+               else
+                       return_reason = 2; /* don't assume the timeout has passed when we got a signal */
        }
        
                /* when we not processed anything, check timers. */
-       if (!ret)
+       if (!m_timer_list.empty())
        {
+                       /* we know that this time has passed. */
                singleLock s(recalcLock);
 
+               if (ret || m_now_is_invalid)
+                       gettimeofday(&now, 0);
+               else // poll timeoutet
+                       now += poll_timeout;
+
                        /* process all timers which are ready. first remove them out of the list. */
-               while ((!m_timer_list.empty()) && (m_timer_list.begin()->getNextActivation() < now))
+               while ((!m_timer_list.empty()) && (m_timer_list.begin()->getNextActivation() <= now))
                        m_timer_list.begin()->activate();
        }
+       
+       return return_reason;
 }
 
 void eMainloop::addTimer(eTimer* e)
@@ -244,47 +272,78 @@ void eMainloop::removeTimer(eTimer* e)
        m_timer_list.remove(e);
 }
 
-int eMainloop::exec()
+int eMainloop::iterate(unsigned int user_timeout, PyObject **res, ePyObject dict)
 {
-       if (!loop_level)
+       int ret = 0;
+
+       timeval user_timer;
+       gettimeofday(&user_timer, 0);
+       user_timer += user_timeout;
+
+               /* TODO: this code just became ugly. fix that. */
+       do
        {
-               app_quit_now = false;
-               app_exit_loop = false;
-               enter_loop();
-       }
-       return retval;
+               if (m_interrupt_requested)
+               {
+                       m_interrupt_requested = 0;
+                       return 0;
+               }
+
+               if (app_quit_now)
+                       return -1;
+
+               int to = 0;
+               if (user_timeout)
+               {
+                       timeval now, timeout;
+                       gettimeofday(&now, 0);
+                       if (user_timer<=now) // timeout
+                               return 0;
+                       timeout = user_timer - now;
+                       to = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
+               }
+               ret = processOneEvent(to, res, dict);
+       } while ( !ret && !(res && *res) );
+       
+       return ret;
 }
 
-void eMainloop::enter_loop()
+int eMainloop::runLoop()
 {
-       loop_level++;
-       // Status der vorhandenen Loop merken
-       bool old_exit_loop = app_exit_loop;
-
-       app_exit_loop = false;
+       while (!app_quit_now)
+               iterate();
+       return retval;
+}
 
-       while (!app_exit_loop && !app_quit_now)
-               processOneEvent();
+void eMainloop::reset()
+{
+       app_quit_now=false;
+}
 
-       // wiederherstellen der vorherigen app_exit_loop
-       app_exit_loop = old_exit_loop;
+PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
+{
+       PyObject *res=0;
+       
+       if (app_quit_now)
+               Py_RETURN_NONE;
+       
+       int user_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
 
-       --loop_level;
+       iterate(user_timeout, &res, dict);
+       if (res)
+               return res;
 
-       if (!loop_level)
-       {
-               // do something here on exit the last loop
-       }
+       return PyList_New(0); /* return empty list on timeout */
 }
 
-void eMainloop::exit_loop()  // call this to leave the current loop
+void eMainloop::interruptPoll()
 {
-       app_exit_loop = true;
+       m_interrupt_requested = 1;
 }
 
-void eMainloop::quit( int ret )   // call this to leave all loops
+void eMainloop::quit(int ret)
 {
-       retval=ret;
+       retval = ret;
        app_quit_now = true;
 }
 
@@ -294,6 +353,7 @@ void eMainloop::addTimeOffset(int offset)
                ;it != eMainloop::existing_loops.end(); ++it)
        {
                singleLock s(it->recalcLock);
+               it->m_now_is_invalid = 1;
                for (ePtrList<eTimer>::iterator tit = it->m_timer_list.begin(); tit != it->m_timer_list.end(); ++tit )
                        tit->addTimeOffset(offset);
        }