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 if (eMainloop::isValid(&context))
31 context.addSocketNotifier(this);
32 state=2; // running but not in poll yet
36 void eSocketNotifier::stop()
41 context.removeSocketNotifier(this);
47 void eTimer::start(long msek, bool singleShot)
52 if (eMainloop::isValid(&context))
55 bSingleShot = singleShot;
57 clock_gettime(CLOCK_MONOTONIC, &nextActivation);
58 // eDebug("this = %p\nnow sec = %d, nsec = %d\nadd %d msec", this, nextActivation.tv_sec, nextActivation.tv_nsec, msek);
59 nextActivation += (msek<0 ? 0 : msek);
60 // eDebug("next Activation sec = %d, nsec = %d", nextActivation.tv_sec, nextActivation.tv_nsec );
61 context.addTimer(this);
65 void eTimer::startLongTimer(int seconds)
70 if (eMainloop::isValid(&context))
72 bActive = bSingleShot = true;
74 clock_gettime(CLOCK_MONOTONIC, &nextActivation);
75 // eDebug("this = %p\nnow sec = %d, nsec = %d\nadd %d sec", this, nextActivation.tv_sec, nextActivation.tv_nsec, seconds);
77 nextActivation.tv_sec += seconds;
78 // eDebug("next Activation sec = %d, nsec = %d", nextActivation.tv_sec, nextActivation.tv_nsec );
79 context.addTimer(this);
88 context.removeTimer(this);
92 void eTimer::changeInterval(long msek)
94 if (bActive) // Timer is running?
96 context.removeTimer(this); // then stop
97 nextActivation -= interval; // sub old interval
100 bActive=true; // then activate Timer
102 interval = msek; // set new Interval
103 nextActivation += interval; // calc nextActivation
105 context.addTimer(this); // add Timer to context TimerList
108 void eTimer::activate() // Internal Funktion... called from eApplication
110 context.removeTimer(this);
114 nextActivation += interval;
115 context.addTimer(this);
124 ePtrList<eMainloop> eMainloop::existing_loops;
126 bool eMainloop::isValid(eMainloop *ml)
128 return std::find(existing_loops.begin(), existing_loops.end(), ml) != existing_loops.end();
131 eMainloop::~eMainloop()
133 existing_loops.remove(this);
134 for (std::map<int, eSocketNotifier*>::iterator it(notifiers.begin());it != notifiers.end();++it)
136 while(m_timer_list.begin() != m_timer_list.end())
137 m_timer_list.begin()->stop();
140 void eMainloop::addSocketNotifier(eSocketNotifier *sn)
142 int fd = sn->getFD();
143 if (m_inActivate && m_inActivate->ref.count == 1)
145 /* when the current active SocketNotifier's refcount is one,
146 then no more external references are existing.
147 So it gets destroyed when the activate callback is finished (->AddRef() / ->Release() calls in processOneEvent).
148 But then the sn->stop() is called to late for the next Asserion.
149 Thus we call sn->stop() here (this implicitly calls eMainloop::removeSocketNotifier) and we don't get trouble
150 with the next Assertion.
152 m_inActivate->stop();
154 ASSERT(notifiers.find(fd) == notifiers.end());
158 void eMainloop::removeSocketNotifier(eSocketNotifier *sn)
160 int fd = sn->getFD();
161 std::map<int,eSocketNotifier*>::iterator i(notifiers.find(fd));
162 if (i != notifiers.end())
167 for (i = notifiers.begin(); i != notifiers.end(); ++i)
168 eDebug("fd=%d, sn=%p", i->second->getFD(), (void*)i->second);
169 eFatal("removed socket notifier which is not present, fd=%d", fd);
172 int eMainloop::processOneEvent(unsigned int twisted_timeout, PyObject **res, ePyObject additional)
174 int return_reason = 0;
175 /* get current time */
177 if (additional && !PyDict_Check(additional))
178 eFatal("additional, but it's not dict");
180 if (additional && !res)
181 eFatal("additional, but no res");
183 long poll_timeout = -1; /* infinite in case of empty timer list */
185 if (!m_timer_list.empty())
187 /* process all timers which are ready. first remove them out of the list. */
188 while (!m_timer_list.empty() && (poll_timeout = timeout_usec( m_timer_list.begin()->getNextActivation() ) ) <= 0 )
190 eTimer *tmr = m_timer_list.begin();
195 if (poll_timeout < 0)
197 else /* convert us to ms */
198 poll_timeout /= 1000;
201 if ((twisted_timeout > 0) && (poll_timeout > 0) && ((unsigned int)poll_timeout > twisted_timeout))
203 poll_timeout = twisted_timeout;
207 int nativecount=notifiers.size(),
212 fdcount += PyDict_Size(additional);
214 // build the poll aray
215 pollfd pfd[fdcount]; // make new pollfd array
216 std::map<int,eSocketNotifier*>::iterator it = notifiers.begin();
219 for (; i < nativecount; ++i, ++it)
221 it->second->state = 1; // running and in poll
222 pfd[i].fd = it->first;
223 pfd[i].events = it->second->getRequested();
228 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
229 typedef int Py_ssize_t;
230 # define PY_SSIZE_T_MAX INT_MAX
231 # define PY_SSIZE_T_MIN INT_MIN
235 while (PyDict_Next(additional, &pos, &key, &val)) {
236 pfd[i].fd = PyObject_AsFileDescriptor(key);
237 pfd[i++].events = PyInt_AsLong(val);
246 Py_BEGIN_ALLOW_THREADS
247 ret = ::poll(pfd, fdcount, poll_timeout);
250 ret = ::poll(pfd, fdcount, poll_timeout);
254 /* ret > 0 means that there are some active poll entries. */
259 for (; i < nativecount; ++i)
263 it = notifiers.find(pfd[i].fd);
264 if (it != notifiers.end()
265 && it->second->state == 1) // added and in poll
267 m_inActivate = it->second;
268 int req = m_inActivate->getRequested();
269 if (pfd[i].revents & req) {
270 m_inActivate->AddRef();
271 m_inActivate->activate(pfd[i].revents & req);
272 m_inActivate->Release();
274 pfd[i].revents &= ~req;
277 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
278 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
281 for (; i < fdcount; ++i)
286 *res = PyList_New(0);
287 ePyObject it = PyTuple_New(2);
288 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
289 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
290 PyList_Append(*res, it);
297 /* when we got a signal, we get EINTR. */
299 eDebug("poll made error (%m)");
301 return_reason = 2; /* don't assume the timeout has passed when we got a signal */
304 return return_reason;
307 void eMainloop::addTimer(eTimer* e)
309 m_timer_list.insert_in_order(e);
312 void eMainloop::removeTimer(eTimer* e)
314 m_timer_list.remove(e);
317 int eMainloop::iterate(unsigned int twisted_timeout, PyObject **res, ePyObject dict)
323 clock_gettime(CLOCK_MONOTONIC, &m_twisted_timer);
324 m_twisted_timer += twisted_timeout;
327 /* TODO: this code just became ugly. fix that. */
330 if (m_interrupt_requested)
332 m_interrupt_requested = 0;
342 timespec now, timeout;
343 clock_gettime(CLOCK_MONOTONIC, &now);
344 if (m_twisted_timer<=now) // timeout
346 timeout = m_twisted_timer - now;
347 to = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
349 ret = processOneEvent(to, res, dict);
350 } while ( !ret && !(res && *res) );
355 int eMainloop::runLoop()
357 while (!app_quit_now)
362 void eMainloop::reset()
367 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
374 int twisted_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
376 iterate(twisted_timeout, &res, dict);
380 return PyList_New(0); /* return empty list on timeout */
383 void eMainloop::interruptPoll()
385 m_interrupt_requested = 1;
388 void eMainloop::quit(int ret)
394 eApplication* eApp = 0;
396 #include "structmember.h"
400 // eTimer replacement
406 PyObject *in_weakreflist; /* List of weak references */
410 eTimerPy_traverse(eTimerPy *self, visitproc visit, void *arg)
412 PyObject *obj = self->tm->timeout.getSteal();
420 eTimerPy_clear(eTimerPy *self)
422 PyObject *obj = self->tm->timeout.getSteal(true);
429 eTimerPy_dealloc(eTimerPy* self)
431 if (self->in_weakreflist != NULL)
432 PyObject_ClearWeakRefs((PyObject *) self);
433 eTimerPy_clear(self);
435 self->ob_type->tp_free((PyObject*)self);
439 eTimerPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
441 eTimerPy *self = (eTimerPy *)type->tp_alloc(type, 0);
442 self->tm = eTimer::create(eApp);
444 self->in_weakreflist = NULL;
445 return (PyObject *)self;
449 eTimerPy_is_active(eTimerPy* self)
451 PyObject *ret = NULL;
452 ret = self->tm->isActive() ? Py_True : Py_False;
458 eTimerPy_start(eTimerPy* self, PyObject *args)
462 if (PyTuple_Size(args) > 1)
464 if (!PyArg_ParseTuple(args, "ll", &v, &singleShot)) // when 2nd arg is a value
467 if (!PyArg_ParseTuple(args, "lO", &v, &obj)) // get 2nd arg as python object
469 else if (obj == Py_True)
471 else if (obj != Py_False)
475 else if (!PyArg_ParseTuple(args, "l", &v))
477 self->tm->start(v, singleShot);
482 eTimerPy_start_long(eTimerPy* self, PyObject *args)
485 if (!PyArg_ParseTuple(args, "i", &v)) {
488 self->tm->startLongTimer(v);
493 eTimerPy_change_interval(eTimerPy* self, PyObject *args)
496 if (!PyArg_ParseTuple(args, "l", &v)) {
499 self->tm->changeInterval(v);
504 eTimerPy_stop(eTimerPy* self)
511 eTimerPy_get_callback_list(eTimerPy *self)
512 { //used for compatibilty with the old eTimer
513 return self->tm->timeout.get();
516 static PyMethodDef eTimerPy_methods[] = {
517 {"isActive", (PyCFunction)eTimerPy_is_active, METH_NOARGS,
518 "returns the timer state"
520 {"start", (PyCFunction)eTimerPy_start, METH_VARARGS,
521 "start timer with interval in msecs"
523 {"startLongTimer", (PyCFunction)eTimerPy_start_long, METH_VARARGS,
524 "start timer with interval in secs"
526 {"changeInterval", (PyCFunction)eTimerPy_change_interval, METH_VARARGS,
527 "change interval of a timer (in msecs)"
529 {"stop", (PyCFunction)eTimerPy_stop, METH_NOARGS,
532 //used for compatibilty with the old eTimer
533 {"get", (PyCFunction)eTimerPy_get_callback_list, METH_NOARGS,
534 "get timeout callback list"
536 {NULL} /* Sentinel */
540 eTimerPy_get_cb_list(eTimerPy *self, void *closure)
542 return self->tm->timeout.get();
546 eTimerPy_timeout(eTimerPy *self, void *closure)
547 { //used for compatibilty with the old eTimer
548 Org_Py_INCREF((PyObject*)self);
549 return (PyObject*)self;
552 static PyGetSetDef eTimerPy_getseters[] = {
554 (getter)eTimerPy_get_cb_list, (setter)0,
555 "returns the callback python list",
558 {"timeout", //used for compatibilty with the old eTimer
559 (getter)eTimerPy_timeout, (setter)0,
560 "synonym for our self",
563 {NULL} /* Sentinel */
566 static PyTypeObject eTimerPyType = {
567 PyObject_HEAD_INIT(NULL)
569 "eBaseImpl.eTimer", /*tp_name*/
570 sizeof(eTimerPy), /*tp_basicsize*/
572 (destructor)eTimerPy_dealloc, /*tp_dealloc*/
579 0, /*tp_as_sequence*/
587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
588 "eTimer objects", /* tp_doc */
589 (traverseproc)eTimerPy_traverse, /* tp_traverse */
590 (inquiry)eTimerPy_clear, /* tp_clear */
591 0, /* tp_richcompare */
592 offsetof(eTimerPy, in_weakreflist), /* tp_weaklistoffset */
595 eTimerPy_methods, /* tp_methods */
597 eTimerPy_getseters, /* tp_getset */
600 0, /* tp_descr_get */
601 0, /* tp_descr_set */
602 0, /* tp_dictoffset */
605 eTimerPy_new, /* tp_new */
608 // eSocketNotifier replacement
610 struct eSocketNotifierPy
614 PyObject *in_weakreflist; /* List of weak references */
618 eSocketNotifierPy_traverse(eSocketNotifierPy *self, visitproc visit, void *arg)
620 PyObject *obj = self->sn->activated.getSteal();
627 eSocketNotifierPy_clear(eSocketNotifierPy *self)
629 PyObject *obj = self->sn->activated.getSteal(true);
636 eSocketNotifierPy_dealloc(eSocketNotifierPy* self)
638 if (self->in_weakreflist != NULL)
639 PyObject_ClearWeakRefs((PyObject *) self);
640 eSocketNotifierPy_clear(self);
642 self->ob_type->tp_free((PyObject*)self);
646 eSocketNotifierPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
648 eSocketNotifierPy *self = (eSocketNotifierPy *)type->tp_alloc(type, 0);
649 int fd, req, immediate_start = 1, size = PyTuple_Size(args);
652 if (!PyArg_ParseTuple(args, "iii", &fd, &req, &immediate_start))
654 PyObject *obj = NULL;
655 if (!PyArg_ParseTuple(args, "iiO", &fd, &req, &immediate_start))
659 else if (obj != Py_True)
663 else if (size < 2 || !PyArg_ParseTuple(args, "ii", &fd, &req))
665 self->sn = eSocketNotifier::create(eApp, fd, req, immediate_start);
667 self->in_weakreflist = NULL;
668 return (PyObject *)self;
672 eSocketNotifierPy_is_running(eSocketNotifierPy* self)
674 PyObject *ret = self->sn->isRunning() ? Py_True : Py_False;
680 eSocketNotifierPy_start(eSocketNotifierPy* self)
687 eSocketNotifierPy_stop(eSocketNotifierPy* self)
694 eSocketNotifierPy_get_fd(eSocketNotifierPy* self)
696 return PyInt_FromLong(self->sn->getFD());
700 eSocketNotifierPy_get_requested(eSocketNotifierPy* self)
702 return PyInt_FromLong(self->sn->getRequested());
706 eSocketNotifierPy_set_requested(eSocketNotifierPy* self, PyObject *args)
709 if (PyTuple_Size(args) != 1 || !PyArg_ParseTuple(args, "i", &req))
711 self->sn->setRequested(req);
715 static PyMethodDef eSocketNotifierPy_methods[] = {
716 {"isRunning", (PyCFunction)eSocketNotifierPy_is_running, METH_NOARGS,
717 "returns the running state"
719 {"start", (PyCFunction)eSocketNotifierPy_start, METH_NOARGS,
722 {"stop", (PyCFunction)eSocketNotifierPy_stop, METH_NOARGS,
725 {"getFD", (PyCFunction)eSocketNotifierPy_get_fd, METH_NOARGS,
726 "get file descriptor"
728 {"getRequested", (PyCFunction)eSocketNotifierPy_get_requested, METH_NOARGS,
731 {"setRequested", (PyCFunction)eSocketNotifierPy_set_requested, METH_VARARGS,
734 {NULL} /* Sentinel */
738 eSocketNotifierPy_get_cb_list(eSocketNotifierPy *self, void *closure)
740 return self->sn->activated.get();
743 static PyGetSetDef eSocketNotifierPy_getseters[] = {
745 (getter)eSocketNotifierPy_get_cb_list, (setter)0,
746 "returns the callback python list",
748 {NULL} /* Sentinel */
751 static PyTypeObject eSocketNotifierPyType = {
752 PyObject_HEAD_INIT(NULL)
754 "eBaseImpl.eSocketNotifier", /*tp_name*/
755 sizeof(eSocketNotifierPy), /*tp_basicsize*/
757 (destructor)eSocketNotifierPy_dealloc, /*tp_dealloc*/
764 0, /*tp_as_sequence*/
772 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
773 "eTimer objects", /* tp_doc */
774 (traverseproc)eSocketNotifierPy_traverse, /* tp_traverse */
775 (inquiry)eSocketNotifierPy_clear, /* tp_clear */
776 0, /* tp_richcompare */
777 offsetof(eSocketNotifierPy, in_weakreflist), /* tp_weaklistoffset */
780 eSocketNotifierPy_methods, /* tp_methods */
782 eSocketNotifierPy_getseters, /* tp_getset */
785 0, /* tp_descr_get */
786 0, /* tp_descr_set */
787 0, /* tp_dictoffset */
790 eSocketNotifierPy_new, /* tp_new */
793 static PyMethodDef module_methods[] = {
794 {NULL} /* Sentinel */
799 PyObject* m = Py_InitModule3("eBaseImpl", module_methods,
800 "Module that implements some enigma classes with working cyclic garbage collection.");
805 if (!PyType_Ready(&eTimerPyType))
807 Org_Py_INCREF((PyObject*)&eTimerPyType);
808 PyModule_AddObject(m, "eTimer", (PyObject*)&eTimerPyType);
810 if (!PyType_Ready(&eSocketNotifierPyType))
812 Org_Py_INCREF((PyObject*)&eSocketNotifierPyType);
813 PyModule_AddObject(m, "eSocketNotifier", (PyObject*)&eSocketNotifierPyType);