Use a queue for events
[quassel.git] / src / common / eventmanager.cpp
index 2a20b21..9664864 100644 (file)
@@ -20,6 +20,8 @@
 
 #include "eventmanager.h"
 
+#include <QCoreApplication>
+#include <QEvent>
 #include <QDebug>
 
 #include "event.h"
@@ -28,6 +30,11 @@ EventManager::EventManager(QObject *parent) : QObject(parent) {
 
 }
 
+EventManager::~EventManager() {
+  // pending events won't be delivered anymore, but we do need to delete them
+  qDeleteAll(_eventQueue);
+}
+
 QMetaEnum EventManager::eventEnum() const {
   if(!_enum.isValid()) {
     int eventEnumIndex = metaObject()->indexOfEnumerator("EventType");
@@ -48,6 +55,10 @@ EventManager::EventType EventManager::eventGroupByName(const QString &name) cons
   return type == Invalid? Invalid : static_cast<EventType>(type & EventGroupMask);
 }
 
+QString EventManager::enumName(EventType type) const {
+  return eventEnum().valueToKey(type);
+}
+
 /* NOTE:
    Registering and calling handlers works fine even if they specify a subclass of Event as their parameter.
    However, this most probably is a result from a reinterpret_cast somewhere deep inside Qt, so there is *no*
@@ -102,10 +113,32 @@ void EventManager::registerEventHandler(QList<EventType> events, QObject *object
 
 // not threadsafe! if we should want that, we need to add a mutexed queue somewhere in this general area.
 void EventManager::sendEvent(Event *event) {
-  dispatchEvent(event);
+  // qDebug() << "Sending" << event;
+  _eventQueue.append(event);
+  if(_eventQueue.count() == 1) // we're not currently processing another event
+    processEvents();
+}
+
+void EventManager::customEvent(QEvent *event) {
+  if(event->type() == QEvent::User) {
+    processEvents();
+    event->accept();
+  }
+}
+
+void EventManager::processEvents() {
+  // we only process one event at a time for now, and let Qt's own event processing come in between
+  if(_eventQueue.isEmpty())
+    return;
+  dispatchEvent(_eventQueue.first());
+  _eventQueue.removeFirst();
+  if(_eventQueue.count())
+    QCoreApplication::postEvent(this, new QEvent(QEvent::User));
 }
 
 void EventManager::dispatchEvent(Event *event) {
+  //qDebug() << "Dispatching" << event;
+
   // we try handlers from specialized to generic by masking the enum
 
   // build a list sorted by priorities that contains all eligible handlers