1 #include <lib/base/ebase.h>
7 #include <lib/base/eerror.h>
8 #include <lib/base/elock.h>
9 #include <lib/gdi/grc.h>
11 DEFINE_REF(eSocketNotifier);
13 eSocketNotifier::eSocketNotifier(eMainloop *context, int fd, int requested, bool startnow): context(*context), fd(fd), state(0), requested(requested)
19 eSocketNotifier::~eSocketNotifier()
24 void eSocketNotifier::start()
29 context.addSocketNotifier(this);
30 state=2; // running but not in poll yet
33 void eSocketNotifier::stop()
38 context.removeSocketNotifier(this);
43 void eTimer::start(long msek, bool singleShot)
49 bSingleShot = singleShot;
51 clock_gettime(CLOCK_MONOTONIC, &nextActivation);
52 // eDebug("this = %p\nnow sec = %d, nsec = %d\nadd %d msec", this, nextActivation.tv_sec, nextActivation.tv_nsec, msek);
53 nextActivation += (msek<0 ? 0 : msek);
54 // eDebug("next Activation sec = %d, nsec = %d", nextActivation.tv_sec, nextActivation.tv_nsec );
55 context.addTimer(this);
58 void eTimer::startLongTimer( int seconds )
63 bActive = bSingleShot = true;
65 clock_gettime(CLOCK_MONOTONIC, &nextActivation);
66 // eDebug("this = %p\nnow sec = %d, nsec = %d\nadd %d sec", this, nextActivation.tv_sec, nextActivation.tv_nsec, seconds);
68 nextActivation.tv_sec += seconds;
69 // eDebug("next Activation sec = %d, nsec = %d", nextActivation.tv_sec, nextActivation.tv_nsec );
70 context.addTimer(this);
78 context.removeTimer(this);
82 void eTimer::changeInterval(long msek)
84 if (bActive) // Timer is running?
86 context.removeTimer(this); // then stop
87 nextActivation -= interval; // sub old interval
90 bActive=true; // then activate Timer
92 interval = msek; // set new Interval
93 nextActivation += interval; // calc nextActivation
95 context.addTimer(this); // add Timer to context TimerList
98 void eTimer::activate() // Internal Funktion... called from eApplication
100 context.removeTimer(this);
104 nextActivation += interval;
105 context.addTimer(this);
114 ePtrList<eMainloop> eMainloop::existing_loops;
116 eMainloop::~eMainloop()
118 existing_loops.remove(this);
119 for (std::map<int, eSocketNotifier*>::iterator it(notifiers.begin());it != notifiers.end();++it)
121 while(m_timer_list.begin() != m_timer_list.end())
122 m_timer_list.begin()->stop();
125 void eMainloop::addSocketNotifier(eSocketNotifier *sn)
127 int fd = sn->getFD();
128 ASSERT(notifiers.find(fd) == notifiers.end());
132 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
134 int fd = sn->getFD();
135 std::map<int,eSocketNotifier*>::iterator i(notifiers.find(fd));
136 if (i != notifiers.end())
141 for (i = notifiers.begin(); i != notifiers.end(); ++i)
142 eDebug("fd=%d, sn=%d", i->second->getFD(), (void*)i->second);
143 eFatal("removed socket notifier which is not present, fd=%d", fd);
146 int eMainloop::processOneEvent(unsigned int twisted_timeout, PyObject **res, ePyObject additional)
148 int return_reason = 0;
149 /* get current time */
151 if (additional && !PyDict_Check(additional))
152 eFatal("additional, but it's not dict");
154 if (additional && !res)
155 eFatal("additional, but no res");
157 long poll_timeout = -1; /* infinite in case of empty timer list */
159 if (!m_timer_list.empty())
161 /* process all timers which are ready. first remove them out of the list. */
162 while (!m_timer_list.empty() && (poll_timeout = timeout_usec( m_timer_list.begin()->getNextActivation() ) ) <= 0 )
163 m_timer_list.begin()->activate();
164 if (poll_timeout < 0)
166 else /* convert us to ms */
167 poll_timeout /= 1000;
170 if ((twisted_timeout > 0) && (poll_timeout > 0) && ((unsigned int)poll_timeout > twisted_timeout))
172 poll_timeout = twisted_timeout;
176 int nativecount=notifiers.size(),
181 fdcount += PyDict_Size(additional);
183 // build the poll aray
184 pollfd pfd[fdcount]; // make new pollfd array
185 std::map<int,eSocketNotifier*>::iterator it = notifiers.begin();
188 for (; i < nativecount; ++i, ++it)
190 it->second->state = 1; // running and in poll
191 pfd[i].fd = it->first;
192 pfd[i].events = it->second->getRequested();
197 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
198 typedef int Py_ssize_t;
199 # define PY_SSIZE_T_MAX INT_MAX
200 # define PY_SSIZE_T_MIN INT_MIN
204 while (PyDict_Next(additional, &pos, &key, &val)) {
205 pfd[i].fd = PyObject_AsFileDescriptor(key);
206 pfd[i++].events = PyInt_AsLong(val);
216 op.opcode = gOpcode::flush;
217 gRC::getInstance()->submit(op);
218 Py_BEGIN_ALLOW_THREADS
219 ret = ::poll(pfd, fdcount, poll_timeout);
223 ret = ::poll(pfd, fdcount, poll_timeout);
227 /* ret > 0 means that there are some active poll entries. */
232 for (; i < nativecount; ++i)
236 it = notifiers.find(pfd[i].fd);
237 if (it != notifiers.end()
238 && it->second->state == 1) // added and in poll
240 eSocketNotifier *sn = it->second;
241 int req = sn->getRequested();
242 if (pfd[i].revents & req) {
244 sn->activate(pfd[i].revents & req);
247 pfd[i].revents &= ~req;
249 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
250 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
253 for (; i < fdcount; ++i)
258 *res = PyList_New(0);
259 ePyObject it = PyTuple_New(2);
260 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
261 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
262 PyList_Append(*res, it);
269 /* when we got a signal, we get EINTR. */
271 eDebug("poll made error (%m)");
273 return_reason = 2; /* don't assume the timeout has passed when we got a signal */
276 return return_reason;
279 void eMainloop::addTimer(eTimer* e)
281 m_timer_list.insert_in_order(e);
284 void eMainloop::removeTimer(eTimer* e)
286 m_timer_list.remove(e);
289 int eMainloop::iterate(unsigned int twisted_timeout, PyObject **res, ePyObject dict)
295 clock_gettime(CLOCK_MONOTONIC, &m_twisted_timer);
296 m_twisted_timer += twisted_timeout;
299 /* TODO: this code just became ugly. fix that. */
302 if (m_interrupt_requested)
304 m_interrupt_requested = 0;
314 timespec now, timeout;
315 clock_gettime(CLOCK_MONOTONIC, &now);
316 if (m_twisted_timer<=now) // timeout
318 timeout = m_twisted_timer - now;
319 to = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
321 ret = processOneEvent(to, res, dict);
322 } while ( !ret && !(res && *res) );
327 int eMainloop::runLoop()
329 while (!app_quit_now)
334 void eMainloop::reset()
339 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
346 int twisted_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
348 iterate(twisted_timeout, &res, dict);
352 return PyList_New(0); /* return empty list on timeout */
355 void eMainloop::interruptPoll()
357 m_interrupt_requested = 1;
360 void eMainloop::quit(int ret)
366 eApplication* eApp = 0;
368 #include "structmember.h"
372 // eTimer replacement
378 PyObject *in_weakreflist; /* List of weak references */
382 eTimerPy_traverse(eTimerPy *self, visitproc visit, void *arg)
384 PyObject *obj = self->tm->timeout.getSteal();
392 eTimerPy_clear(eTimerPy *self)
394 PyObject *obj = self->tm->timeout.getSteal(true);
401 eTimerPy_dealloc(eTimerPy* self)
403 if (self->in_weakreflist != NULL)
404 PyObject_ClearWeakRefs((PyObject *) self);
405 eTimerPy_clear(self);
407 self->ob_type->tp_free((PyObject*)self);
411 eTimerPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
413 eTimerPy *self = (eTimerPy *)type->tp_alloc(type, 0);
414 self->tm = new eTimer(eApp);
415 self->in_weakreflist = NULL;
416 return (PyObject *)self;
420 eTimerPy_is_active(eTimerPy* self)
422 PyObject *ret = NULL;
423 ret = self->tm->isActive() ? Py_True : Py_False;
429 eTimerPy_start(eTimerPy* self, PyObject *args)
433 if (PyTuple_Size(args) > 1)
435 if (!PyArg_ParseTuple(args, "ll", &v, &singleShot)) // when 2nd arg is a value
438 if (!PyArg_ParseTuple(args, "lO", &v, &obj)) // get 2nd arg as python object
440 else if (obj == Py_True)
442 else if (obj != Py_False)
446 else if (!PyArg_ParseTuple(args, "l", &v))
448 self->tm->start(v, singleShot);
453 eTimerPy_start_long(eTimerPy* self, PyObject *args)
456 if (!PyArg_ParseTuple(args, "i", &v)) {
459 self->tm->startLongTimer(v);
464 eTimerPy_change_interval(eTimerPy* self, PyObject *args)
467 if (!PyArg_ParseTuple(args, "l", &v)) {
470 self->tm->changeInterval(v);
475 eTimerPy_stop(eTimerPy* self)
482 eTimerPy_get_callback_list(eTimerPy *self)
483 { //used for compatibilty with the old eTimer
484 return self->tm->timeout.get();
487 static PyMethodDef eTimerPy_methods[] = {
488 {"isActive", (PyCFunction)eTimerPy_is_active, METH_NOARGS,
489 "returns the timer state"
491 {"start", (PyCFunction)eTimerPy_start, METH_VARARGS,
492 "start timer with interval in msecs"
494 {"startLongTimer", (PyCFunction)eTimerPy_start_long, METH_VARARGS,
495 "start timer with interval in secs"
497 {"changeInterval", (PyCFunction)eTimerPy_change_interval, METH_VARARGS,
498 "change interval of a timer (in msecs)"
500 {"stop", (PyCFunction)eTimerPy_stop, METH_NOARGS,
503 //used for compatibilty with the old eTimer
504 {"get", (PyCFunction)eTimerPy_get_callback_list, METH_NOARGS,
505 "get timeout callback list"
507 {NULL} /* Sentinel */
511 eTimerPy_get_cb_list(eTimerPy *self, void *closure)
513 return self->tm->timeout.get();
517 eTimerPy_timeout(eTimerPy *self, void *closure)
518 { //used for compatibilty with the old eTimer
519 Org_Py_INCREF((PyObject*)self);
520 return (PyObject*)self;
523 static PyGetSetDef eTimerPy_getseters[] = {
525 (getter)eTimerPy_get_cb_list, (setter)0,
526 "returns the callback python list",
529 {"timeout", //used for compatibilty with the old eTimer
530 (getter)eTimerPy_timeout, (setter)0,
531 "synonym for our self",
534 {NULL} /* Sentinel */
537 static PyTypeObject eTimerPyType = {
538 PyObject_HEAD_INIT(NULL)
540 "eBaseImpl.eTimer", /*tp_name*/
541 sizeof(eTimerPy), /*tp_basicsize*/
543 (destructor)eTimerPy_dealloc, /*tp_dealloc*/
550 0, /*tp_as_sequence*/
558 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
559 "eTimer objects", /* tp_doc */
560 (traverseproc)eTimerPy_traverse, /* tp_traverse */
561 (inquiry)eTimerPy_clear, /* tp_clear */
562 0, /* tp_richcompare */
563 offsetof(eTimerPy, in_weakreflist), /* tp_weaklistoffset */
566 eTimerPy_methods, /* tp_methods */
568 eTimerPy_getseters, /* tp_getset */
571 0, /* tp_descr_get */
572 0, /* tp_descr_set */
573 0, /* tp_dictoffset */
576 eTimerPy_new, /* tp_new */
579 // eSocketNotifier replacement
581 struct eSocketNotifierPy
585 PyObject *in_weakreflist; /* List of weak references */
589 eSocketNotifierPy_traverse(eSocketNotifierPy *self, visitproc visit, void *arg)
591 PyObject *obj = self->sn->activated.getSteal();
598 eSocketNotifierPy_clear(eSocketNotifierPy *self)
600 PyObject *obj = self->sn->activated.getSteal(true);
607 eSocketNotifierPy_dealloc(eSocketNotifierPy* self)
609 if (self->in_weakreflist != NULL)
610 PyObject_ClearWeakRefs((PyObject *) self);
611 eSocketNotifierPy_clear(self);
613 self->ob_type->tp_free((PyObject*)self);
617 eSocketNotifierPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
619 eSocketNotifierPy *self = (eSocketNotifierPy *)type->tp_alloc(type, 0);
620 int fd, req, immediate_start = 1, size = PyTuple_Size(args);
623 if (!PyArg_ParseTuple(args, "iii", &fd, &req, &immediate_start))
625 PyObject *obj = NULL;
626 if (!PyArg_ParseTuple(args, "iiO", &fd, &req, &immediate_start))
630 else if (obj != Py_True)
634 else if (size < 2 || !PyArg_ParseTuple(args, "ii", &fd, &req))
636 self->sn = eSocketNotifier::create(eApp, fd, req, immediate_start);
638 self->in_weakreflist = NULL;
639 return (PyObject *)self;
643 eSocketNotifierPy_is_running(eSocketNotifierPy* self)
645 PyObject *ret = self->sn->isRunning() ? Py_True : Py_False;
651 eSocketNotifierPy_start(eSocketNotifierPy* self)
658 eSocketNotifierPy_stop(eSocketNotifierPy* self)
665 eSocketNotifierPy_get_fd(eSocketNotifierPy* self)
667 return PyInt_FromLong(self->sn->getFD());
671 eSocketNotifierPy_get_requested(eSocketNotifierPy* self)
673 return PyInt_FromLong(self->sn->getRequested());
677 eSocketNotifierPy_set_requested(eSocketNotifierPy* self, PyObject *args)
680 if (PyTuple_Size(args) != 1 || !PyArg_ParseTuple(args, "i", &req))
682 self->sn->setRequested(req);
686 static PyMethodDef eSocketNotifierPy_methods[] = {
687 {"isRunning", (PyCFunction)eSocketNotifierPy_is_running, METH_NOARGS,
688 "returns the running state"
690 {"start", (PyCFunction)eSocketNotifierPy_start, METH_NOARGS,
693 {"stop", (PyCFunction)eSocketNotifierPy_stop, METH_NOARGS,
696 {"getFD", (PyCFunction)eSocketNotifierPy_get_fd, METH_NOARGS,
697 "get file descriptor"
699 {"getRequested", (PyCFunction)eSocketNotifierPy_get_requested, METH_NOARGS,
702 {"setRequested", (PyCFunction)eSocketNotifierPy_set_requested, METH_VARARGS,
705 {NULL} /* Sentinel */
709 eSocketNotifierPy_get_cb_list(eSocketNotifierPy *self, void *closure)
711 return self->sn->activated.get();
714 static PyGetSetDef eSocketNotifierPy_getseters[] = {
716 (getter)eSocketNotifierPy_get_cb_list, (setter)0,
717 "returns the callback python list",
719 {NULL} /* Sentinel */
722 static PyTypeObject eSocketNotifierPyType = {
723 PyObject_HEAD_INIT(NULL)
725 "eBaseImpl.eSocketNotifier", /*tp_name*/
726 sizeof(eSocketNotifierPy), /*tp_basicsize*/
728 (destructor)eSocketNotifierPy_dealloc, /*tp_dealloc*/
735 0, /*tp_as_sequence*/
743 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
744 "eTimer objects", /* tp_doc */
745 (traverseproc)eSocketNotifierPy_traverse, /* tp_traverse */
746 (inquiry)eSocketNotifierPy_clear, /* tp_clear */
747 0, /* tp_richcompare */
748 offsetof(eSocketNotifierPy, in_weakreflist), /* tp_weaklistoffset */
751 eSocketNotifierPy_methods, /* tp_methods */
753 eSocketNotifierPy_getseters, /* tp_getset */
756 0, /* tp_descr_get */
757 0, /* tp_descr_set */
758 0, /* tp_dictoffset */
761 eSocketNotifierPy_new, /* tp_new */
764 static PyMethodDef module_methods[] = {
765 {NULL} /* Sentinel */
770 PyObject* m = Py_InitModule3("eBaseImpl", module_methods,
771 "Module that implements some enigma classes with working cyclic garbage collection.");
776 if (!PyType_Ready(&eTimerPyType))
778 Org_Py_INCREF((PyObject*)&eTimerPyType);
779 PyModule_AddObject(m, "eTimer", (PyObject*)&eTimerPyType);
781 if (!PyType_Ready(&eSocketNotifierPyType))
783 Org_Py_INCREF((PyObject*)&eSocketNotifierPyType);
784 PyModule_AddObject(m, "eSocketNotifier", (PyObject*)&eSocketNotifierPyType);