swift
Loading...
Searching...
No Matches
eventloop.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (C) 2017 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#ifndef SWIFT_MISC_EVENTLOOP_H
7#define SWIFT_MISC_EVENTLOOP_H
8
9#include <QEventLoop>
10#include <QObject>
11#include <QPointer>
12#include <QTimer>
13
14namespace swift::misc
15{
20 {
21 public:
23 CEventLoop() : m_guard(&m_eventLoop) {}
24
26 CEventLoop(QObject *guard) : m_guard(guard)
27 {
28 Q_ASSERT(guard);
29 QObject::connect(guard, &QObject::destroyed, &m_eventLoop, [this] { m_eventLoop.exit(TimedOut); });
30 }
31
33 template <typename T, typename F>
34 void stopWhen(const T *sender, F signal)
35 {
36 QObject::connect(sender, signal, &m_eventLoop, [this] { m_eventLoop.exit(GotSignal); });
37 }
38
40 template <typename T, typename F1, typename F2>
41 void stopWhen(const T *sender, F1 signal, F2 &&condition)
42 {
43 QObject::connect(sender, signal, &m_eventLoop,
44 [this, condition = std::forward<F2>(condition)](auto &&...args) {
45 if (condition(std::forward<decltype(args)>(args)...))
46 {
47 m_eventLoop.exit(GotSignal);
48 }
49 });
50 }
51
54 bool exec(int timeoutMs)
55 {
56 if (timeoutMs >= 0)
57 {
58 QTimer::singleShot(timeoutMs, &m_eventLoop, [this] { m_eventLoop.exit(TimedOut); });
59 }
60 return m_eventLoop.exec() == GotSignal && isGuardAlive();
61 }
62
64 bool isGuardAlive() const { return m_guard; }
65
66 private:
67 enum Result
68 {
69 GotSignal = 0,
70 TimedOut,
71 };
72 QEventLoop m_eventLoop;
73 QPointer<QObject> m_guard;
74 };
75} // namespace swift::misc
76
77#endif // SWIFT_MISC_EVENTLOOP_H
CEventLoop(QObject *guard)
Constructor. Guard object must exist, and will be checked again when the loop quits.
Definition eventloop.h:26
bool exec(int timeoutMs)
Begin processing events until the timeout or stop condition occurs.
Definition eventloop.h:54
bool isGuardAlive() const
True if the guard object still exists.
Definition eventloop.h:64
CEventLoop()
Constructor.
Definition eventloop.h:23
void stopWhen(const T *sender, F1 signal, F2 &&condition)
Event loop will stop if the given signal is received and condition returns true.
Definition eventloop.h:41
void stopWhen(const T *sender, F signal)
Event loop will stop if the given signal is received.
Definition eventloop.h:34
Free functions in swift::misc.
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void destroyed(QObject *obj)