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);
234 op.opcode = gOpcode::flush;
235 gRC::getInstance()->submit(op);
236 Py_BEGIN_ALLOW_THREADS
237 ret = ::poll(pfd, fdcount, poll_timeout);
241 ret = ::poll(pfd, fdcount, poll_timeout);
245 /* ret > 0 means that there are some active poll entries. */
250 for (; i < nativecount; ++i)
254 it = notifiers.find(pfd[i].fd);
255 if (it != notifiers.end()
256 && it->second->state == 1) // added and in poll
258 m_inActivate = it->second;
259 int req = m_inActivate->getRequested();
260 if (pfd[i].revents & req) {
261 m_inActivate->AddRef();
262 m_inActivate->activate(pfd[i].revents & req);
263 m_inActivate->Release();
265 pfd[i].revents &= ~req;
268 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
269 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
272 for (; i < fdcount; ++i)
277 *res = PyList_New(0);
278 ePyObject it = PyTuple_New(2);
279 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
280 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
281 PyList_Append(*res, it);
288 /* when we got a signal, we get EINTR. */
290 eDebug("poll made error (%m)");
292 return_reason = 2; /* don't assume the timeout has passed when we got a signal */
295 return return_reason;
298 void eMainloop::addTimer(eTimer* e)
300 m_timer_list.insert_in_order(e);
303 void eMainloop::removeTimer(eTimer* e)
305 m_timer_list.remove(e);
308 int eMainloop::iterate(unsigned int twisted_timeout, PyObject **res, ePyObject dict)
314 clock_gettime(CLOCK_MONOTONIC, &m_twisted_timer);
315 m_twisted_timer += twisted_timeout;
318 /* TODO: this code just became ugly. fix that. */
321 if (m_interrupt_requested)
323 m_interrupt_requested = 0;
333 timespec now, timeout;
334 clock_gettime(CLOCK_MONOTONIC, &now);
335 if (m_twisted_timer<=now) // timeout
337 timeout = m_twisted_timer - now;
338 to = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
340 ret = processOneEvent(to, res, dict);
341 } while ( !ret && !(res && *res) );
346 int eMainloop::runLoop()
348 while (!app_quit_now)
353 void eMainloop::reset()
358 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
365 int twisted_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
367 iterate(twisted_timeout, &res, dict);
371 return PyList_New(0); /* return empty list on timeout */
374 void eMainloop::interruptPoll()
376 m_interrupt_requested = 1;
379 void eMainloop::quit(int ret)
385 eApplication* eApp = 0;
387 #include "structmember.h"
391 // eTimer replacement
397 PyObject *in_weakreflist; /* List of weak references */
401 eTimerPy_traverse(eTimerPy *self, visitproc visit, void *arg)
403 PyObject *obj = self->tm->timeout.getSteal();
411 eTimerPy_clear(eTimerPy *self)
413 PyObject *obj = self->tm->timeout.getSteal(true);
420 eTimerPy_dealloc(eTimerPy* self)
422 if (self->in_weakreflist != NULL)
423 PyObject_ClearWeakRefs((PyObject *) self);
424 eTimerPy_clear(self);
426 self->ob_type->tp_free((PyObject*)self);
430 eTimerPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
432 eTimerPy *self = (eTimerPy *)type->tp_alloc(type, 0);
433 self->tm = eTimer::create(eApp);
435 self->in_weakreflist = NULL;
436 return (PyObject *)self;
440 eTimerPy_is_active(eTimerPy* self)
442 PyObject *ret = NULL;
443 ret = self->tm->isActive() ? Py_True : Py_False;
449 eTimerPy_start(eTimerPy* self, PyObject *args)
453 if (PyTuple_Size(args) > 1)
455 if (!PyArg_ParseTuple(args, "ll", &v, &singleShot)) // when 2nd arg is a value
458 if (!PyArg_ParseTuple(args, "lO", &v, &obj)) // get 2nd arg as python object
460 else if (obj == Py_True)
462 else if (obj != Py_False)
466 else if (!PyArg_ParseTuple(args, "l", &v))
468 self->tm->start(v, singleShot);
473 eTimerPy_start_long(eTimerPy* self, PyObject *args)
476 if (!PyArg_ParseTuple(args, "i", &v)) {
479 self->tm->startLongTimer(v);
484 eTimerPy_change_interval(eTimerPy* self, PyObject *args)
487 if (!PyArg_ParseTuple(args, "l", &v)) {
490 self->tm->changeInterval(v);
495 eTimerPy_stop(eTimerPy* self)
502 eTimerPy_get_callback_list(eTimerPy *self)
503 { //used for compatibilty with the old eTimer
504 return self->tm->timeout.get();
507 static PyMethodDef eTimerPy_methods[] = {
508 {"isActive", (PyCFunction)eTimerPy_is_active, METH_NOARGS,
509 "returns the timer state"
511 {"start", (PyCFunction)eTimerPy_start, METH_VARARGS,
512 "start timer with interval in msecs"
514 {"startLongTimer", (PyCFunction)eTimerPy_start_long, METH_VARARGS,
515 "start timer with interval in secs"
517 {"changeInterval", (PyCFunction)eTimerPy_change_interval, METH_VARARGS,
518 "change interval of a timer (in msecs)"
520 {"stop", (PyCFunction)eTimerPy_stop, METH_NOARGS,
523 //used for compatibilty with the old eTimer
524 {"get", (PyCFunction)eTimerPy_get_callback_list, METH_NOARGS,
525 "get timeout callback list"
527 {NULL} /* Sentinel */
531 eTimerPy_get_cb_list(eTimerPy *self, void *closure)
533 return self->tm->timeout.get();
537 eTimerPy_timeout(eTimerPy *self, void *closure)
538 { //used for compatibilty with the old eTimer
539 Org_Py_INCREF((PyObject*)self);
540 return (PyObject*)self;
543 static PyGetSetDef eTimerPy_getseters[] = {
545 (getter)eTimerPy_get_cb_list, (setter)0,
546 "returns the callback python list",
549 {"timeout", //used for compatibilty with the old eTimer
550 (getter)eTimerPy_timeout, (setter)0,
551 "synonym for our self",
554 {NULL} /* Sentinel */
557 static PyTypeObject eTimerPyType = {
558 PyObject_HEAD_INIT(NULL)
560 "eBaseImpl.eTimer", /*tp_name*/
561 sizeof(eTimerPy), /*tp_basicsize*/
563 (destructor)eTimerPy_dealloc, /*tp_dealloc*/
570 0, /*tp_as_sequence*/
578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
579 "eTimer objects", /* tp_doc */
580 (traverseproc)eTimerPy_traverse, /* tp_traverse */
581 (inquiry)eTimerPy_clear, /* tp_clear */
582 0, /* tp_richcompare */
583 offsetof(eTimerPy, in_weakreflist), /* tp_weaklistoffset */
586 eTimerPy_methods, /* tp_methods */
588 eTimerPy_getseters, /* tp_getset */
591 0, /* tp_descr_get */
592 0, /* tp_descr_set */
593 0, /* tp_dictoffset */
596 eTimerPy_new, /* tp_new */
599 // eSocketNotifier replacement
601 struct eSocketNotifierPy
605 PyObject *in_weakreflist; /* List of weak references */
609 eSocketNotifierPy_traverse(eSocketNotifierPy *self, visitproc visit, void *arg)
611 PyObject *obj = self->sn->activated.getSteal();
618 eSocketNotifierPy_clear(eSocketNotifierPy *self)
620 PyObject *obj = self->sn->activated.getSteal(true);
627 eSocketNotifierPy_dealloc(eSocketNotifierPy* self)
629 if (self->in_weakreflist != NULL)
630 PyObject_ClearWeakRefs((PyObject *) self);
631 eSocketNotifierPy_clear(self);
633 self->ob_type->tp_free((PyObject*)self);
637 eSocketNotifierPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
639 eSocketNotifierPy *self = (eSocketNotifierPy *)type->tp_alloc(type, 0);
640 int fd, req, immediate_start = 1, size = PyTuple_Size(args);
643 if (!PyArg_ParseTuple(args, "iii", &fd, &req, &immediate_start))
645 PyObject *obj = NULL;
646 if (!PyArg_ParseTuple(args, "iiO", &fd, &req, &immediate_start))
650 else if (obj != Py_True)
654 else if (size < 2 || !PyArg_ParseTuple(args, "ii", &fd, &req))
656 self->sn = eSocketNotifier::create(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 */
790 PyObject* m = Py_InitModule3("eBaseImpl", module_methods,
791 "Module that implements some enigma classes with working cyclic garbage collection.");
796 if (!PyType_Ready(&eTimerPyType))
798 Org_Py_INCREF((PyObject*)&eTimerPyType);
799 PyModule_AddObject(m, "eTimer", (PyObject*)&eTimerPyType);
801 if (!PyType_Ready(&eSocketNotifierPyType))
803 Org_Py_INCREF((PyObject*)&eSocketNotifierPyType);
804 PyModule_AddObject(m, "eSocketNotifier", (PyObject*)&eSocketNotifierPyType);