1 #include <lib/base/ebase.h>
7 #include <lib/base/eerror.h>
8 #include <lib/base/elock.h>
10 eSocketNotifier::eSocketNotifier(eMainloop *context, int fd, int requested, bool startnow): context(*context), fd(fd), state(0), requested(requested)
16 eSocketNotifier::~eSocketNotifier()
21 void eSocketNotifier::start()
26 context.addSocketNotifier(this);
27 state=2; // running but not in poll yet
30 void eSocketNotifier::stop()
33 context.removeSocketNotifier(this);
39 void eTimer::start(long msek, bool singleShot)
45 bSingleShot = singleShot;
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);
55 void eTimer::startLongTimer( int seconds )
60 bActive = bSingleShot = true;
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);
66 nextActivation.tv_sec += seconds;
67 // eDebug("next Activation sec = %d, usec = %d", nextActivation.tv_sec, nextActivation.tv_usec );
68 context.addTimer(this);
76 context.removeTimer(this);
80 void eTimer::changeInterval(long msek)
82 if (bActive) // Timer is running?
84 context.removeTimer(this); // then stop
85 nextActivation -= interval; // sub old interval
88 bActive=true; // then activate Timer
90 interval = msek; // set new Interval
91 nextActivation += interval; // calc nextActivation
93 context.addTimer(this); // add Timer to context TimerList
96 void eTimer::activate() // Internal Funktion... called from eApplication
98 context.removeTimer(this);
102 nextActivation += interval;
103 context.addTimer(this);
111 void eTimer::addTimeOffset( int offset )
113 nextActivation.tv_sec += offset;
117 ePtrList<eMainloop> eMainloop::existing_loops;
119 eMainloop::~eMainloop()
121 existing_loops.remove(this);
122 pthread_mutex_destroy(&recalcLock);
123 for (std::map<int, eSocketNotifier*>::iterator it(notifiers.begin());it != notifiers.end();++it)
125 while(m_timer_list.begin() != m_timer_list.end())
126 m_timer_list.begin()->stop();
129 void eMainloop::addSocketNotifier(eSocketNotifier *sn)
131 int fd = sn->getFD();
132 ASSERT(notifiers.find(fd) == notifiers.end());
136 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
138 int fd = sn->getFD();
139 std::map<int,eSocketNotifier*>::iterator i(notifiers.find(fd));
140 if (i != notifiers.end())
141 return notifiers.erase(i);
142 eFatal("removed socket notifier which is not present");
145 int eMainloop::processOneEvent(unsigned int twisted_timeout, PyObject **res, ePyObject additional)
147 int return_reason = 0;
148 /* get current time */
150 if (additional && !PyDict_Check(additional))
151 eFatal("additional, but it's not dict");
153 if (additional && !res)
154 eFatal("additional, but no res");
156 long poll_timeout = -1; /* infinite in case of empty timer list */
158 if (!m_timer_list.empty() || twisted_timeout > 0)
161 if (!m_timer_list.empty())
163 /* process all timers which are ready. first remove them out of the list. */
164 while (!m_timer_list.empty() && (poll_timeout = timeout_usec( m_timer_list.begin()->getNextActivation() ) ) <= 0 )
166 m_timer_list.begin()->activate();
169 if (poll_timeout < 0)
171 else /* convert us to ms */
172 poll_timeout /= 1000;
176 if ((twisted_timeout > 0) && (poll_timeout > 0) && ((unsigned int)poll_timeout > twisted_timeout))
178 poll_timeout = twisted_timeout;
182 int nativecount=notifiers.size(),
187 fdcount += PyDict_Size(additional);
189 // build the poll aray
190 pollfd pfd[fdcount]; // make new pollfd array
191 std::map<int,eSocketNotifier*>::iterator it = notifiers.begin();
193 for (; i < nativecount; ++i, ++it)
195 it->second->state = 1; // running and in poll
196 pfd[i].fd = it->first;
197 pfd[i].events = it->second->getRequested();
204 while (PyDict_Next(additional, &pos, &key, &val)) {
205 pfd[i].fd = PyObject_AsFileDescriptor(key);
206 pfd[i++].events = PyInt_AsLong(val);
214 Py_BEGIN_ALLOW_THREADS
215 ret = ::poll(pfd, fdcount, poll_timeout);
218 ret = ::poll(pfd, fdcount, poll_timeout);
222 /* ret > 0 means that there are some active poll entries. */
227 for (; i < nativecount; ++i)
231 it = notifiers.find(pfd[i].fd);
232 if (it != notifiers.end()
233 && it->second->state == 1) // added and in poll
235 int req = it->second->getRequested();
236 if (pfd[i].revents & req)
237 it->second->activate(pfd[i].revents & req);
238 pfd[i].revents &= ~req;
240 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
241 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
244 for (; i < fdcount; ++i)
249 *res = PyList_New(0);
250 ePyObject it = PyTuple_New(2);
251 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
252 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
253 PyList_Append(*res, it);
260 /* when we got a signal, we get EINTR. */
262 eDebug("poll made error (%m)");
264 return_reason = 2; /* don't assume the timeout has passed when we got a signal */
267 return return_reason;
270 void eMainloop::addTimer(eTimer* e)
272 m_timer_list.insert_in_order(e);
275 void eMainloop::removeTimer(eTimer* e)
277 m_timer_list.remove(e);
280 int eMainloop::iterate(unsigned int twisted_timeout, PyObject **res, ePyObject dict)
286 gettimeofday(&m_twisted_timer, 0);
287 m_twisted_timer += twisted_timeout;
290 /* TODO: this code just became ugly. fix that. */
293 if (m_interrupt_requested)
295 m_interrupt_requested = 0;
305 timeval now, timeout;
306 gettimeofday(&now, 0);
307 m_twisted_timer += time_offset; // apply pending offset
308 if (m_twisted_timer<=now) // timeout
310 timeout = m_twisted_timer - now;
311 to = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
312 // remove pending offset .. it is re-applied in next call of processOneEvent.. applyTimeOffset
313 m_twisted_timer -= time_offset;
315 ret = processOneEvent(to, res, dict);
316 } while ( !ret && !(res && *res) );
321 int eMainloop::runLoop()
323 while (!app_quit_now)
328 void eMainloop::reset()
333 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
340 int twisted_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
342 iterate(twisted_timeout, &res, dict);
346 return PyList_New(0); /* return empty list on timeout */
349 void eMainloop::interruptPoll()
351 m_interrupt_requested = 1;
354 void eMainloop::quit(int ret)
360 void eMainloop::addTimeOffset(int offset)
362 for (ePtrList<eMainloop>::iterator it(existing_loops.begin()); it != existing_loops.end(); ++it )
363 it->addInstanceTimeOffset(offset);
366 void eMainloop::addInstanceTimeOffset(int offset)
368 singleLock s(recalcLock);
369 if (m_timer_list.empty())
374 eDebug("time_offset %d avail.. add new offset %d than new is %d",
375 time_offset, offset, time_offset+offset);
380 void eMainloop::applyTimeOffset()
382 singleLock s(recalcLock);
385 for (ePtrList<eTimer>::iterator it(m_timer_list.begin()); it != m_timer_list.end(); ++it )
386 it->addTimeOffset( time_offset );
387 m_twisted_timer += time_offset;
392 eApplication* eApp = 0;
394 #include "structmember.h"
398 // eTimer replacement
404 PyObject *in_weakreflist; /* List of weak references */
408 eTimerPy_traverse(eTimerPy *self, visitproc visit, void *arg)
410 PyObject *obj = self->tm->timeout.get();
416 eTimerPy_clear(eTimerPy *self)
418 PyObject *obj = self->tm->timeout.get();
424 eTimerPy_dealloc(eTimerPy* self)
426 if (self->in_weakreflist != NULL)
427 PyObject_ClearWeakRefs((PyObject *) self);
428 eTimerPy_clear(self);
430 self->ob_type->tp_free((PyObject*)self);
434 eTimerPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
436 eTimerPy *self = (eTimerPy *)type->tp_alloc(type, 0);
437 self->tm = new eTimer(eApp);
438 self->in_weakreflist = NULL;
439 return (PyObject *)self;
443 eTimerPy_is_active(eTimerPy* self)
445 PyObject *ret = NULL;
446 ret = self->tm->isActive() ? Py_True : Py_False;
452 eTimerPy_start(eTimerPy* self, PyObject *args)
456 if (PyTuple_Size(args) > 1)
458 if (!PyArg_ParseTuple(args, "ll", &v, &singleShot)) // when 2nd arg is a value
461 if (!PyArg_ParseTuple(args, "lO", &v, &obj)) // get 2nd arg as python object
463 else if (obj == Py_True)
465 else if (obj != Py_False)
469 else if (!PyArg_ParseTuple(args, "l", &v))
471 self->tm->start(v, singleShot);
476 eTimerPy_start_long(eTimerPy* self, PyObject *args)
479 if (!PyArg_ParseTuple(args, "l", &v)) {
482 self->tm->startLongTimer(v);
487 eTimerPy_change_interval(eTimerPy* self, PyObject *args)
490 if (!PyArg_ParseTuple(args, "l", &v)) {
493 self->tm->changeInterval(v);
498 eTimerPy_stop(eTimerPy* self)
505 eTimerPy_get_callback_list(eTimerPy *self)
506 { //used for compatibilty with the old eTimer
507 return self->tm->timeout.get();
510 static PyMethodDef eTimerPy_methods[] = {
511 {"isActive", (PyCFunction)eTimerPy_is_active, METH_NOARGS,
512 "returns the timer state"
514 {"start", (PyCFunction)eTimerPy_start, METH_VARARGS,
515 "start timer with interval in msecs"
517 {"startLongTimer", (PyCFunction)eTimerPy_start_long, METH_VARARGS,
518 "start timer with interval in secs"
520 {"changeInterval", (PyCFunction)eTimerPy_change_interval, METH_VARARGS,
521 "change interval of a timer (in msecs)"
523 {"stop", (PyCFunction)eTimerPy_stop, METH_NOARGS,
526 //used for compatibilty with the old eTimer
527 {"get", (PyCFunction)eTimerPy_get_callback_list, METH_NOARGS,
528 "get timeout callback list"
530 {NULL} /* Sentinel */
534 eTimerPy_get_cb_list(eTimerPy *self, void *closure)
536 return self->tm->timeout.get();
540 eTimerPy_timeout(eTimerPy *self, void *closure)
541 { //used for compatibilty with the old eTimer
542 Org_Py_INCREF((PyObject*)self);
543 return (PyObject*)self;
546 static PyGetSetDef eTimerPy_getseters[] = {
548 (getter)eTimerPy_get_cb_list, (setter)0,
549 "returns the callback python list",
552 {"timeout", //used for compatibilty with the old eTimer
553 (getter)eTimerPy_timeout, (setter)0,
554 "synonym for our self",
557 {NULL} /* Sentinel */
560 static PyTypeObject eTimerPyType = {
561 PyObject_HEAD_INIT(NULL)
563 "eBaseImpl.eTimer", /*tp_name*/
564 sizeof(eTimerPy), /*tp_basicsize*/
566 (destructor)eTimerPy_dealloc, /*tp_dealloc*/
573 0, /*tp_as_sequence*/
581 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
582 "eTimer objects", /* tp_doc */
583 (traverseproc)eTimerPy_traverse, /* tp_traverse */
584 (inquiry)eTimerPy_clear, /* tp_clear */
585 0, /* tp_richcompare */
586 offsetof(eTimerPy, in_weakreflist), /* tp_weaklistoffset */
589 eTimerPy_methods, /* tp_methods */
591 eTimerPy_getseters, /* tp_getset */
594 0, /* tp_descr_get */
595 0, /* tp_descr_set */
596 0, /* tp_dictoffset */
599 eTimerPy_new, /* tp_new */
602 // eSocketNotifier replacement
604 struct eSocketNotifierPy
608 PyObject *in_weakreflist; /* List of weak references */
612 eSocketNotifierPy_traverse(eSocketNotifierPy *self, visitproc visit, void *arg)
614 PyObject *obj = self->sn->activated.get();
620 eSocketNotifierPy_clear(eSocketNotifierPy *self)
622 PyObject *obj = self->sn->activated.get();
628 eSocketNotifierPy_dealloc(eSocketNotifierPy* self)
630 if (self->in_weakreflist != NULL)
631 PyObject_ClearWeakRefs((PyObject *) self);
632 eSocketNotifierPy_clear(self);
634 self->ob_type->tp_free((PyObject*)self);
638 eSocketNotifierPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
640 eSocketNotifierPy *self = (eSocketNotifierPy *)type->tp_alloc(type, 0);
641 int fd, req, immediate_start = 1, size = PyTuple_Size(args);
644 if (!PyArg_ParseTuple(args, "iii", &fd, &req, &immediate_start))
646 PyObject *obj = NULL;
647 if (!PyArg_ParseTuple(args, "iiO", &fd, &req, &immediate_start))
651 else if (obj != Py_True)
655 else if (size < 2 || !PyArg_ParseTuple(args, "ii", &fd, &req))
657 self->sn = new eSocketNotifier(eApp, fd, req, immediate_start);
658 self->in_weakreflist = NULL;
659 return (PyObject *)self;
663 eSocketNotifierPy_is_running(eSocketNotifierPy* self)
665 PyObject *ret = self->sn->isRunning() ? Py_True : Py_False;
671 eSocketNotifierPy_start(eSocketNotifierPy* self)
678 eSocketNotifierPy_stop(eSocketNotifierPy* self)
685 eSocketNotifierPy_get_fd(eSocketNotifierPy* self)
687 return PyInt_FromLong(self->sn->getFD());
691 eSocketNotifierPy_get_requested(eSocketNotifierPy* self)
693 return PyInt_FromLong(self->sn->getRequested());
697 eSocketNotifierPy_set_requested(eSocketNotifierPy* self, PyObject *args)
700 if (PyTuple_Size(args) != 1 || !PyArg_ParseTuple(args, "i", &req))
702 self->sn->setRequested(req);
706 static PyMethodDef eSocketNotifierPy_methods[] = {
707 {"isRunning", (PyCFunction)eSocketNotifierPy_is_running, METH_NOARGS,
708 "returns the running state"
710 {"start", (PyCFunction)eSocketNotifierPy_start, METH_NOARGS,
713 {"stop", (PyCFunction)eSocketNotifierPy_stop, METH_NOARGS,
716 {"getFD", (PyCFunction)eSocketNotifierPy_get_fd, METH_NOARGS,
717 "get file descriptor"
719 {"getRequested", (PyCFunction)eSocketNotifierPy_get_requested, METH_NOARGS,
722 {"setRequested", (PyCFunction)eSocketNotifierPy_set_requested, METH_VARARGS,
725 {NULL} /* Sentinel */
729 eSocketNotifierPy_get_cb_list(eSocketNotifierPy *self, void *closure)
731 return self->sn->activated.get();
734 static PyGetSetDef eSocketNotifierPy_getseters[] = {
736 (getter)eSocketNotifierPy_get_cb_list, (setter)0,
737 "returns the callback python list",
739 {NULL} /* Sentinel */
742 static PyTypeObject eSocketNotifierPyType = {
743 PyObject_HEAD_INIT(NULL)
745 "eBaseImpl.eSocketNotifier", /*tp_name*/
746 sizeof(eSocketNotifierPy), /*tp_basicsize*/
748 (destructor)eSocketNotifierPy_dealloc, /*tp_dealloc*/
755 0, /*tp_as_sequence*/
763 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
764 "eTimer objects", /* tp_doc */
765 (traverseproc)eSocketNotifierPy_traverse, /* tp_traverse */
766 (inquiry)eSocketNotifierPy_clear, /* tp_clear */
767 0, /* tp_richcompare */
768 offsetof(eSocketNotifierPy, in_weakreflist), /* tp_weaklistoffset */
771 eSocketNotifierPy_methods, /* tp_methods */
773 eSocketNotifierPy_getseters, /* tp_getset */
776 0, /* tp_descr_get */
777 0, /* tp_descr_set */
778 0, /* tp_dictoffset */
781 eSocketNotifierPy_new, /* tp_new */
784 static PyMethodDef module_methods[] = {
785 {NULL} /* Sentinel */
792 m = Py_InitModule3("eBaseImpl", module_methods,
793 "Module that implements some enigma classes with working cyclic garbage collection.");
798 if (!PyType_Ready(&eTimerPyType))
800 Org_Py_INCREF((PyObject*)&eTimerPyType);
801 PyModule_AddObject(m, "eTimer", (PyObject*)&eTimerPyType);
803 if (!PyType_Ready(&eSocketNotifierPyType))
805 Org_Py_INCREF((PyObject*)&eSocketNotifierPyType);
806 PyModule_AddObject(m, "eSocketNotifier", (PyObject*)&eSocketNotifierPyType);