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);
44 void eTimer::start(long msek, bool singleShot)
50 bSingleShot = singleShot;
52 clock_gettime(CLOCK_MONOTONIC, &nextActivation);
53 // eDebug("this = %p\nnow sec = %d, nsec = %d\nadd %d msec", this, nextActivation.tv_sec, nextActivation.tv_nsec, msek);
54 nextActivation += (msek<0 ? 0 : msek);
55 // eDebug("next Activation sec = %d, nsec = %d", nextActivation.tv_sec, nextActivation.tv_nsec );
56 context.addTimer(this);
59 void eTimer::startLongTimer( int seconds )
64 bActive = bSingleShot = true;
66 clock_gettime(CLOCK_MONOTONIC, &nextActivation);
67 // eDebug("this = %p\nnow sec = %d, nsec = %d\nadd %d sec", this, nextActivation.tv_sec, nextActivation.tv_nsec, seconds);
69 nextActivation.tv_sec += seconds;
70 // eDebug("next Activation sec = %d, nsec = %d", nextActivation.tv_sec, nextActivation.tv_nsec );
71 context.addTimer(this);
79 context.removeTimer(this);
83 void eTimer::changeInterval(long msek)
85 if (bActive) // Timer is running?
87 context.removeTimer(this); // then stop
88 nextActivation -= interval; // sub old interval
91 bActive=true; // then activate Timer
93 interval = msek; // set new Interval
94 nextActivation += interval; // calc nextActivation
96 context.addTimer(this); // add Timer to context TimerList
99 void eTimer::activate() // Internal Funktion... called from eApplication
101 context.removeTimer(this);
105 nextActivation += interval;
106 context.addTimer(this);
115 ePtrList<eMainloop> eMainloop::existing_loops;
117 eMainloop::~eMainloop()
119 existing_loops.remove(this);
120 for (std::map<int, eSocketNotifier*>::iterator it(notifiers.begin());it != notifiers.end();++it)
122 while(m_timer_list.begin() != m_timer_list.end())
123 m_timer_list.begin()->stop();
126 void eMainloop::addSocketNotifier(eSocketNotifier *sn)
128 int fd = sn->getFD();
129 if (m_inActivate && m_inActivate->ref.count == 1)
131 /* when the current active SocketNotifier's refcount is one,
132 then no more external references are existing.
133 So it gets destroyed when the activate callback is finished (->AddRef() / ->Release() calls in processOneEvent).
134 But then the sn->stop() is called to late for the next Asserion.
135 Thus we call sn->stop() here (this implicitly calls eMainloop::removeSocketNotifier) and we don't get trouble
136 with the next Assertion.
138 m_inActivate->stop();
140 ASSERT(notifiers.find(fd) == notifiers.end());
144 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
146 int fd = sn->getFD();
147 std::map<int,eSocketNotifier*>::iterator i(notifiers.find(fd));
148 if (i != notifiers.end())
153 for (i = notifiers.begin(); i != notifiers.end(); ++i)
154 eDebug("fd=%d, sn=%d", i->second->getFD(), (void*)i->second);
155 eFatal("removed socket notifier which is not present, fd=%d", fd);
158 int eMainloop::processOneEvent(unsigned int twisted_timeout, PyObject **res, ePyObject additional)
160 int return_reason = 0;
161 /* get current time */
163 if (additional && !PyDict_Check(additional))
164 eFatal("additional, but it's not dict");
166 if (additional && !res)
167 eFatal("additional, but no res");
169 long poll_timeout = -1; /* infinite in case of empty timer list */
171 if (!m_timer_list.empty())
173 /* process all timers which are ready. first remove them out of the list. */
174 while (!m_timer_list.empty() && (poll_timeout = timeout_usec( m_timer_list.begin()->getNextActivation() ) ) <= 0 )
176 eTimer *tmr = m_timer_list.begin();
181 if (poll_timeout < 0)
183 else /* convert us to ms */
184 poll_timeout /= 1000;
187 if ((twisted_timeout > 0) && (poll_timeout > 0) && ((unsigned int)poll_timeout > twisted_timeout))
189 poll_timeout = twisted_timeout;
193 int nativecount=notifiers.size(),
198 fdcount += PyDict_Size(additional);
200 // build the poll aray
201 pollfd pfd[fdcount]; // make new pollfd array
202 std::map<int,eSocketNotifier*>::iterator it = notifiers.begin();
205 for (; i < nativecount; ++i, ++it)
207 it->second->state = 1; // running and in poll
208 pfd[i].fd = it->first;
209 pfd[i].events = it->second->getRequested();
214 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
215 typedef int Py_ssize_t;
216 # define PY_SSIZE_T_MAX INT_MAX
217 # define PY_SSIZE_T_MIN INT_MIN
221 while (PyDict_Next(additional, &pos, &key, &val)) {
222 pfd[i].fd = PyObject_AsFileDescriptor(key);
223 pfd[i++].events = PyInt_AsLong(val);
233 op.opcode = gOpcode::flush;
234 gRC::getInstance()->submit(op);
235 Py_BEGIN_ALLOW_THREADS
236 ret = ::poll(pfd, fdcount, poll_timeout);
240 ret = ::poll(pfd, fdcount, poll_timeout);
244 /* ret > 0 means that there are some active poll entries. */
249 for (; i < nativecount; ++i)
253 it = notifiers.find(pfd[i].fd);
254 if (it != notifiers.end()
255 && it->second->state == 1) // added and in poll
257 m_inActivate = it->second;
258 int req = m_inActivate->getRequested();
259 if (pfd[i].revents & req) {
260 m_inActivate->AddRef();
261 m_inActivate->activate(pfd[i].revents & req);
262 m_inActivate->Release();
264 pfd[i].revents &= ~req;
267 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
268 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
271 for (; i < fdcount; ++i)
276 *res = PyList_New(0);
277 ePyObject it = PyTuple_New(2);
278 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
279 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
280 PyList_Append(*res, it);
287 /* when we got a signal, we get EINTR. */
289 eDebug("poll made error (%m)");
291 return_reason = 2; /* don't assume the timeout has passed when we got a signal */
294 return return_reason;
297 void eMainloop::addTimer(eTimer* e)
299 m_timer_list.insert_in_order(e);
302 void eMainloop::removeTimer(eTimer* e)
304 m_timer_list.remove(e);
307 int eMainloop::iterate(unsigned int twisted_timeout, PyObject **res, ePyObject dict)
313 clock_gettime(CLOCK_MONOTONIC, &m_twisted_timer);
314 m_twisted_timer += twisted_timeout;
317 /* TODO: this code just became ugly. fix that. */
320 if (m_interrupt_requested)
322 m_interrupt_requested = 0;
332 timespec now, timeout;
333 clock_gettime(CLOCK_MONOTONIC, &now);
334 if (m_twisted_timer<=now) // timeout
336 timeout = m_twisted_timer - now;
337 to = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
339 ret = processOneEvent(to, res, dict);
340 } while ( !ret && !(res && *res) );
345 int eMainloop::runLoop()
347 while (!app_quit_now)
352 void eMainloop::reset()
357 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
364 int twisted_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
366 iterate(twisted_timeout, &res, dict);
370 return PyList_New(0); /* return empty list on timeout */
373 void eMainloop::interruptPoll()
375 m_interrupt_requested = 1;
378 void eMainloop::quit(int ret)
384 eApplication* eApp = 0;
386 #include "structmember.h"
390 // eTimer replacement
396 PyObject *in_weakreflist; /* List of weak references */
400 eTimerPy_traverse(eTimerPy *self, visitproc visit, void *arg)
402 PyObject *obj = self->tm->timeout.getSteal();
410 eTimerPy_clear(eTimerPy *self)
412 PyObject *obj = self->tm->timeout.getSteal(true);
419 eTimerPy_dealloc(eTimerPy* self)
421 if (self->in_weakreflist != NULL)
422 PyObject_ClearWeakRefs((PyObject *) self);
423 eTimerPy_clear(self);
425 self->ob_type->tp_free((PyObject*)self);
429 eTimerPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
431 eTimerPy *self = (eTimerPy *)type->tp_alloc(type, 0);
432 self->tm = eTimer::create(eApp);
434 self->in_weakreflist = NULL;
435 return (PyObject *)self;
439 eTimerPy_is_active(eTimerPy* self)
441 PyObject *ret = NULL;
442 ret = self->tm->isActive() ? Py_True : Py_False;
448 eTimerPy_start(eTimerPy* self, PyObject *args)
452 if (PyTuple_Size(args) > 1)
454 if (!PyArg_ParseTuple(args, "ll", &v, &singleShot)) // when 2nd arg is a value
457 if (!PyArg_ParseTuple(args, "lO", &v, &obj)) // get 2nd arg as python object
459 else if (obj == Py_True)
461 else if (obj != Py_False)
465 else if (!PyArg_ParseTuple(args, "l", &v))
467 self->tm->start(v, singleShot);
472 eTimerPy_start_long(eTimerPy* self, PyObject *args)
475 if (!PyArg_ParseTuple(args, "i", &v)) {
478 self->tm->startLongTimer(v);
483 eTimerPy_change_interval(eTimerPy* self, PyObject *args)
486 if (!PyArg_ParseTuple(args, "l", &v)) {
489 self->tm->changeInterval(v);
494 eTimerPy_stop(eTimerPy* self)
501 eTimerPy_get_callback_list(eTimerPy *self)
502 { //used for compatibilty with the old eTimer
503 return self->tm->timeout.get();
506 static PyMethodDef eTimerPy_methods[] = {
507 {"isActive", (PyCFunction)eTimerPy_is_active, METH_NOARGS,
508 "returns the timer state"
510 {"start", (PyCFunction)eTimerPy_start, METH_VARARGS,
511 "start timer with interval in msecs"
513 {"startLongTimer", (PyCFunction)eTimerPy_start_long, METH_VARARGS,
514 "start timer with interval in secs"
516 {"changeInterval", (PyCFunction)eTimerPy_change_interval, METH_VARARGS,
517 "change interval of a timer (in msecs)"
519 {"stop", (PyCFunction)eTimerPy_stop, METH_NOARGS,
522 //used for compatibilty with the old eTimer
523 {"get", (PyCFunction)eTimerPy_get_callback_list, METH_NOARGS,
524 "get timeout callback list"
526 {NULL} /* Sentinel */
530 eTimerPy_get_cb_list(eTimerPy *self, void *closure)
532 return self->tm->timeout.get();
536 eTimerPy_timeout(eTimerPy *self, void *closure)
537 { //used for compatibilty with the old eTimer
538 Org_Py_INCREF((PyObject*)self);
539 return (PyObject*)self;
542 static PyGetSetDef eTimerPy_getseters[] = {
544 (getter)eTimerPy_get_cb_list, (setter)0,
545 "returns the callback python list",
548 {"timeout", //used for compatibilty with the old eTimer
549 (getter)eTimerPy_timeout, (setter)0,
550 "synonym for our self",
553 {NULL} /* Sentinel */
556 static PyTypeObject eTimerPyType = {
557 PyObject_HEAD_INIT(NULL)
559 "eBaseImpl.eTimer", /*tp_name*/
560 sizeof(eTimerPy), /*tp_basicsize*/
562 (destructor)eTimerPy_dealloc, /*tp_dealloc*/
569 0, /*tp_as_sequence*/
577 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
578 "eTimer objects", /* tp_doc */
579 (traverseproc)eTimerPy_traverse, /* tp_traverse */
580 (inquiry)eTimerPy_clear, /* tp_clear */
581 0, /* tp_richcompare */
582 offsetof(eTimerPy, in_weakreflist), /* tp_weaklistoffset */
585 eTimerPy_methods, /* tp_methods */
587 eTimerPy_getseters, /* tp_getset */
590 0, /* tp_descr_get */
591 0, /* tp_descr_set */
592 0, /* tp_dictoffset */
595 eTimerPy_new, /* tp_new */
598 // eSocketNotifier replacement
600 struct eSocketNotifierPy
604 PyObject *in_weakreflist; /* List of weak references */
608 eSocketNotifierPy_traverse(eSocketNotifierPy *self, visitproc visit, void *arg)
610 PyObject *obj = self->sn->activated.getSteal();
617 eSocketNotifierPy_clear(eSocketNotifierPy *self)
619 PyObject *obj = self->sn->activated.getSteal(true);
626 eSocketNotifierPy_dealloc(eSocketNotifierPy* self)
628 if (self->in_weakreflist != NULL)
629 PyObject_ClearWeakRefs((PyObject *) self);
630 eSocketNotifierPy_clear(self);
632 self->ob_type->tp_free((PyObject*)self);
636 eSocketNotifierPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
638 eSocketNotifierPy *self = (eSocketNotifierPy *)type->tp_alloc(type, 0);
639 int fd, req, immediate_start = 1, size = PyTuple_Size(args);
642 if (!PyArg_ParseTuple(args, "iii", &fd, &req, &immediate_start))
644 PyObject *obj = NULL;
645 if (!PyArg_ParseTuple(args, "iiO", &fd, &req, &immediate_start))
649 else if (obj != Py_True)
653 else if (size < 2 || !PyArg_ParseTuple(args, "ii", &fd, &req))
655 self->sn = eSocketNotifier::create(eApp, fd, req, immediate_start);
657 self->in_weakreflist = NULL;
658 return (PyObject *)self;
662 eSocketNotifierPy_is_running(eSocketNotifierPy* self)
664 PyObject *ret = self->sn->isRunning() ? Py_True : Py_False;
670 eSocketNotifierPy_start(eSocketNotifierPy* self)
677 eSocketNotifierPy_stop(eSocketNotifierPy* self)
684 eSocketNotifierPy_get_fd(eSocketNotifierPy* self)
686 return PyInt_FromLong(self->sn->getFD());
690 eSocketNotifierPy_get_requested(eSocketNotifierPy* self)
692 return PyInt_FromLong(self->sn->getRequested());
696 eSocketNotifierPy_set_requested(eSocketNotifierPy* self, PyObject *args)
699 if (PyTuple_Size(args) != 1 || !PyArg_ParseTuple(args, "i", &req))
701 self->sn->setRequested(req);
705 static PyMethodDef eSocketNotifierPy_methods[] = {
706 {"isRunning", (PyCFunction)eSocketNotifierPy_is_running, METH_NOARGS,
707 "returns the running state"
709 {"start", (PyCFunction)eSocketNotifierPy_start, METH_NOARGS,
712 {"stop", (PyCFunction)eSocketNotifierPy_stop, METH_NOARGS,
715 {"getFD", (PyCFunction)eSocketNotifierPy_get_fd, METH_NOARGS,
716 "get file descriptor"
718 {"getRequested", (PyCFunction)eSocketNotifierPy_get_requested, METH_NOARGS,
721 {"setRequested", (PyCFunction)eSocketNotifierPy_set_requested, METH_VARARGS,
724 {NULL} /* Sentinel */
728 eSocketNotifierPy_get_cb_list(eSocketNotifierPy *self, void *closure)
730 return self->sn->activated.get();
733 static PyGetSetDef eSocketNotifierPy_getseters[] = {
735 (getter)eSocketNotifierPy_get_cb_list, (setter)0,
736 "returns the callback python list",
738 {NULL} /* Sentinel */
741 static PyTypeObject eSocketNotifierPyType = {
742 PyObject_HEAD_INIT(NULL)
744 "eBaseImpl.eSocketNotifier", /*tp_name*/
745 sizeof(eSocketNotifierPy), /*tp_basicsize*/
747 (destructor)eSocketNotifierPy_dealloc, /*tp_dealloc*/
754 0, /*tp_as_sequence*/
762 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
763 "eTimer objects", /* tp_doc */
764 (traverseproc)eSocketNotifierPy_traverse, /* tp_traverse */
765 (inquiry)eSocketNotifierPy_clear, /* tp_clear */
766 0, /* tp_richcompare */
767 offsetof(eSocketNotifierPy, in_weakreflist), /* tp_weaklistoffset */
770 eSocketNotifierPy_methods, /* tp_methods */
772 eSocketNotifierPy_getseters, /* tp_getset */
775 0, /* tp_descr_get */
776 0, /* tp_descr_set */
777 0, /* tp_dictoffset */
780 eSocketNotifierPy_new, /* tp_new */
783 static PyMethodDef module_methods[] = {
784 {NULL} /* Sentinel */
789 PyObject* m = Py_InitModule3("eBaseImpl", module_methods,
790 "Module that implements some enigma classes with working cyclic garbage collection.");
795 if (!PyType_Ready(&eTimerPyType))
797 Org_Py_INCREF((PyObject*)&eTimerPyType);
798 PyModule_AddObject(m, "eTimer", (PyObject*)&eTimerPyType);
800 if (!PyType_Ready(&eSocketNotifierPyType))
802 Org_Py_INCREF((PyObject*)&eSocketNotifierPyType);
803 PyModule_AddObject(m, "eSocketNotifier", (PyObject*)&eSocketNotifierPyType);