summaryrefslogtreecommitdiffstats
blob: b1644c29b4bb3213fed7f95024b0d33a85f4e26b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (c) 2010-2016 Isode Limited.
 * All rights reserved.
 * See the COPYING file for more information.
 */

#pragma once

#include <mutex>

#include <QCoreApplication>
#include <QEvent>
#include <QObject>

#include <Swiften/EventLoop/EventLoop.h>

namespace Swift {
    class QtEventLoop : public QObject, public EventLoop {
        public:
            QtEventLoop() : isEventInQtEventLoop_(false) {}
            virtual ~QtEventLoop() {
                QCoreApplication::removePostedEvents(this);
            }

        protected:
            virtual void eventPosted() {
                std::unique_lock<std::recursive_mutex> lock(isEventInQtEventLoopMutex_);
                if (!isEventInQtEventLoop_) {
                    isEventInQtEventLoop_ = true;
                    QCoreApplication::postEvent(this, new Event());
                }
            }

            virtual bool event(QEvent* qevent) {
                Event* event = dynamic_cast<Event*>(qevent);
                if (event) {
                    {
                        std::unique_lock<std::recursive_mutex> lock(isEventInQtEventLoopMutex_);
                        isEventInQtEventLoop_ = false;
                    }
                    handleNextEvents();
                    //event->deleteLater(); FIXME: Leak?
                    return true;
                }

                return false;
            }

        private:
            struct Event : public QEvent {
                    Event() :
                            QEvent(QEvent::User) {
                    }
            };

            bool isEventInQtEventLoop_;
            std::recursive_mutex isEventInQtEventLoopMutex_;
    };
}