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=%d", 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);
248 op.opcode = gOpcode::flush;
249 gRC::getInstance()->submit(op);
250 Py_BEGIN_ALLOW_THREADS
251 ret = ::poll(pfd, fdcount, poll_timeout);
255 ret = ::poll(pfd, fdcount, poll_timeout);
259 /* ret > 0 means that there are some active poll entries. */
264 for (; i < nativecount; ++i)
268 it = notifiers.find(pfd[i].fd);
269 if (it != notifiers.end()
270 && it->second->state == 1) // added and in poll
272 m_inActivate = it->second;
273 int req = m_inActivate->getRequested();
274 if (pfd[i].revents & req) {
275 m_inActivate->AddRef();
276 m_inActivate->activate(pfd[i].revents & req);
277 m_inActivate->Release();
279 pfd[i].revents &= ~req;
282 if (pfd[i].revents & (POLLERR|POLLHUP|POLLNVAL))
283 eDebug("poll: unhandled POLLERR/HUP/NVAL for fd %d(%d)", pfd[i].fd, pfd[i].revents);
286 for (; i < fdcount; ++i)
291 *res = PyList_New(0);
292 ePyObject it = PyTuple_New(2);
293 PyTuple_SET_ITEM(it, 0, PyInt_FromLong(pfd[i].fd));
294 PyTuple_SET_ITEM(it, 1, PyInt_FromLong(pfd[i].revents));
295 PyList_Append(*res, it);
302 /* when we got a signal, we get EINTR. */
304 eDebug("poll made error (%m)");
306 return_reason = 2; /* don't assume the timeout has passed when we got a signal */
309 return return_reason;
312 void eMainloop::addTimer(eTimer* e)
314 m_timer_list.insert_in_order(e);
317 void eMainloop::removeTimer(eTimer* e)
319 m_timer_list.remove(e);
322 int eMainloop::iterate(unsigned int twisted_timeout, PyObject **res, ePyObject dict)
328 clock_gettime(CLOCK_MONOTONIC, &m_twisted_timer);
329 m_twisted_timer += twisted_timeout;
332 /* TODO: this code just became ugly. fix that. */
335 if (m_interrupt_requested)
337 m_interrupt_requested = 0;
347 timespec now, timeout;
348 clock_gettime(CLOCK_MONOTONIC, &now);
349 if (m_twisted_timer<=now) // timeout
351 timeout = m_twisted_timer - now;
352 to = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
354 ret = processOneEvent(to, res, dict);
355 } while ( !ret && !(res && *res) );
360 int eMainloop::runLoop()
362 while (!app_quit_now)
367 void eMainloop::reset()
372 PyObject *eMainloop::poll(ePyObject timeout, ePyObject dict)
379 int twisted_timeout = (timeout == Py_None) ? 0 : PyInt_AsLong(timeout);
381 iterate(twisted_timeout, &res, dict);
385 return PyList_New(0); /* return empty list on timeout */
388 void eMainloop::interruptPoll()
390 m_interrupt_requested = 1;
393 void eMainloop::quit(int ret)
399 eApplication* eApp = 0;
401 #include "structmember.h"
405 // eTimer replacement
411 PyObject *in_weakreflist; /* List of weak references */
415 eTimerPy_traverse(eTimerPy *self, visitproc visit, void *arg)
417 PyObject *obj = self->tm->timeout.getSteal();
425 eTimerPy_clear(eTimerPy *self)
427 PyObject *obj = self->tm->timeout.getSteal(true);
434 eTimerPy_dealloc(eTimerPy* self)
436 if (self->in_weakreflist != NULL)
437 PyObject_ClearWeakRefs((PyObject *) self);
438 eTimerPy_clear(self);
440 self->ob_type->tp_free((PyObject*)self);
444 eTimerPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
446 eTimerPy *self = (eTimerPy *)type->tp_alloc(type, 0);
447 self->tm = eTimer::create(eApp);
449 self->in_weakreflist = NULL;
450 return (PyObject *)self;
454 eTimerPy_is_active(eTimerPy* self)
456 PyObject *ret = NULL;
457 ret = self->tm->isActive() ? Py_True : Py_False;
463 eTimerPy_start(eTimerPy* self, PyObject *args)
467 if (PyTuple_Size(args) > 1)
469 if (!PyArg_ParseTuple(args, "ll", &v, &singleShot)) // when 2nd arg is a value
472 if (!PyArg_ParseTuple(args, "lO", &v, &obj)) // get 2nd arg as python object
474 else if (obj == Py_True)
476 else if (obj != Py_False)
480 else if (!PyArg_ParseTuple(args, "l", &v))
482 self->tm->start(v, singleShot);
487 eTimerPy_start_long(eTimerPy* self, PyObject *args)
490 if (!PyArg_ParseTuple(args, "i", &v)) {
493 self->tm->startLongTimer(v);
498 eTimerPy_change_interval(eTimerPy* self, PyObject *args)
501 if (!PyArg_ParseTuple(args, "l", &v)) {
504 self->tm->changeInterval(v);
509 eTimerPy_stop(eTimerPy* self)
516 eTimerPy_get_callback_list(eTimerPy *self)
517 { //used for compatibilty with the old eTimer
518 return self->tm->timeout.get();
521 static PyMethodDef eTimerPy_methods[] = {
522 {"isActive", (PyCFunction)eTimerPy_is_active, METH_NOARGS,
523 "returns the timer state"
525 {"start", (PyCFunction)eTimerPy_start, METH_VARARGS,
526 "start timer with interval in msecs"
528 {"startLongTimer", (PyCFunction)eTimerPy_start_long, METH_VARARGS,
529 "start timer with interval in secs"
531 {"changeInterval", (PyCFunction)eTimerPy_change_interval, METH_VARARGS,
532 "change interval of a timer (in msecs)"
534 {"stop", (PyCFunction)eTimerPy_stop, METH_NOARGS,
537 //used for compatibilty with the old eTimer
538 {"get", (PyCFunction)eTimerPy_get_callback_list, METH_NOARGS,
539 "get timeout callback list"
541 {NULL} /* Sentinel */
545 eTimerPy_get_cb_list(eTimerPy *self, void *closure)
547 return self->tm->timeout.get();
551 eTimerPy_timeout(eTimerPy *self, void *closure)
552 { //used for compatibilty with the old eTimer
553 Org_Py_INCREF((PyObject*)self);
554 return (PyObject*)self;
557 static PyGetSetDef eTimerPy_getseters[] = {
559 (getter)eTimerPy_get_cb_list, (setter)0,
560 "returns the callback python list",
563 {"timeout", //used for compatibilty with the old eTimer
564 (getter)eTimerPy_timeout, (setter)0,
565 "synonym for our self",
568 {NULL} /* Sentinel */
571 static PyTypeObject eTimerPyType = {
572 PyObject_HEAD_INIT(NULL)
574 "eBaseImpl.eTimer", /*tp_name*/
575 sizeof(eTimerPy), /*tp_basicsize*/
577 (destructor)eTimerPy_dealloc, /*tp_dealloc*/
584 0, /*tp_as_sequence*/
592 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
593 "eTimer objects", /* tp_doc */
594 (traverseproc)eTimerPy_traverse, /* tp_traverse */
595 (inquiry)eTimerPy_clear, /* tp_clear */
596 0, /* tp_richcompare */
597 offsetof(eTimerPy, in_weakreflist), /* tp_weaklistoffset */
600 eTimerPy_methods, /* tp_methods */
602 eTimerPy_getseters, /* tp_getset */
605 0, /* tp_descr_get */
606 0, /* tp_descr_set */
607 0, /* tp_dictoffset */
610 eTimerPy_new, /* tp_new */
613 // eSocketNotifier replacement
615 struct eSocketNotifierPy
619 PyObject *in_weakreflist; /* List of weak references */
623 eSocketNotifierPy_traverse(eSocketNotifierPy *self, visitproc visit, void *arg)
625 PyObject *obj = self->sn->activated.getSteal();
632 eSocketNotifierPy_clear(eSocketNotifierPy *self)
634 PyObject *obj = self->sn->activated.getSteal(true);
641 eSocketNotifierPy_dealloc(eSocketNotifierPy* self)
643 if (self->in_weakreflist != NULL)
644 PyObject_ClearWeakRefs((PyObject *) self);
645 eSocketNotifierPy_clear(self);
647 self->ob_type->tp_free((PyObject*)self);
651 eSocketNotifierPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
653 eSocketNotifierPy *self = (eSocketNotifierPy *)type->tp_alloc(type, 0);
654 int fd, req, immediate_start = 1, size = PyTuple_Size(args);
657 if (!PyArg_ParseTuple(args, "iii", &fd, &req, &immediate_start))
659 PyObject *obj = NULL;
660 if (!PyArg_ParseTuple(args, "iiO", &fd, &req, &immediate_start))
664 else if (obj != Py_True)
668 else if (size < 2 || !PyArg_ParseTuple(args, "ii", &fd, &req))
670 self->sn = eSocketNotifier::create(eApp, fd, req, immediate_start);
672 self->in_weakreflist = NULL;
673 return (PyObject *)self;
677 eSocketNotifierPy_is_running(eSocketNotifierPy* self)
679 PyObject *ret = self->sn->isRunning() ? Py_True : Py_False;
685 eSocketNotifierPy_start(eSocketNotifierPy* self)
692 eSocketNotifierPy_stop(eSocketNotifierPy* self)
699 eSocketNotifierPy_get_fd(eSocketNotifierPy* self)
701 return PyInt_FromLong(self->sn->getFD());
705 eSocketNotifierPy_get_requested(eSocketNotifierPy* self)
707 return PyInt_FromLong(self->sn->getRequested());
711 eSocketNotifierPy_set_requested(eSocketNotifierPy* self, PyObject *args)
714 if (PyTuple_Size(args) != 1 || !PyArg_ParseTuple(args, "i", &req))
716 self->sn->setRequested(req);
720 static PyMethodDef eSocketNotifierPy_methods[] = {
721 {"isRunning", (PyCFunction)eSocketNotifierPy_is_running, METH_NOARGS,
722 "returns the running state"
724 {"start", (PyCFunction)eSocketNotifierPy_start, METH_NOARGS,
727 {"stop", (PyCFunction)eSocketNotifierPy_stop, METH_NOARGS,
730 {"getFD", (PyCFunction)eSocketNotifierPy_get_fd, METH_NOARGS,
731 "get file descriptor"
733 {"getRequested", (PyCFunction)eSocketNotifierPy_get_requested, METH_NOARGS,
736 {"setRequested", (PyCFunction)eSocketNotifierPy_set_requested, METH_VARARGS,
739 {NULL} /* Sentinel */
743 eSocketNotifierPy_get_cb_list(eSocketNotifierPy *self, void *closure)
745 return self->sn->activated.get();
748 static PyGetSetDef eSocketNotifierPy_getseters[] = {
750 (getter)eSocketNotifierPy_get_cb_list, (setter)0,
751 "returns the callback python list",
753 {NULL} /* Sentinel */
756 static PyTypeObject eSocketNotifierPyType = {
757 PyObject_HEAD_INIT(NULL)
759 "eBaseImpl.eSocketNotifier", /*tp_name*/
760 sizeof(eSocketNotifierPy), /*tp_basicsize*/
762 (destructor)eSocketNotifierPy_dealloc, /*tp_dealloc*/
769 0, /*tp_as_sequence*/
777 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
778 "eTimer objects", /* tp_doc */
779 (traverseproc)eSocketNotifierPy_traverse, /* tp_traverse */
780 (inquiry)eSocketNotifierPy_clear, /* tp_clear */
781 0, /* tp_richcompare */
782 offsetof(eSocketNotifierPy, in_weakreflist), /* tp_weaklistoffset */
785 eSocketNotifierPy_methods, /* tp_methods */
787 eSocketNotifierPy_getseters, /* tp_getset */
790 0, /* tp_descr_get */
791 0, /* tp_descr_set */
792 0, /* tp_dictoffset */
795 eSocketNotifierPy_new, /* tp_new */
798 static PyMethodDef module_methods[] = {
799 {NULL} /* Sentinel */
804 PyObject* m = Py_InitModule3("eBaseImpl", module_methods,
805 "Module that implements some enigma classes with working cyclic garbage collection.");
810 if (!PyType_Ready(&eTimerPyType))
812 Org_Py_INCREF((PyObject*)&eTimerPyType);
813 PyModule_AddObject(m, "eTimer", (PyObject*)&eTimerPyType);
815 if (!PyType_Ready(&eSocketNotifierPyType))
817 Org_Py_INCREF((PyObject*)&eSocketNotifierPyType);
818 PyModule_AddObject(m, "eSocketNotifier", (PyObject*)&eSocketNotifierPyType);