swift
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 
14 namespace swift::misc
15 {
19  class CEventLoop
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)...)) { m_eventLoop.exit(GotSignal); }
46  });
47  }
48 
51  bool exec(int timeoutMs)
52  {
53  if (timeoutMs >= 0)
54  {
55  QTimer::singleShot(timeoutMs, &m_eventLoop, [this] { m_eventLoop.exit(TimedOut); });
56  }
57  return m_eventLoop.exec() == GotSignal && isGuardAlive();
58  }
59 
61  bool isGuardAlive() const { return m_guard; }
62 
63  private:
64  enum Result
65  {
66  GotSignal = 0,
67  TimedOut,
68  };
69  QEventLoop m_eventLoop;
70  QPointer<QObject> m_guard;
71  };
72 } // namespace swift::misc
73 
74 #endif // SWIFT_MISC_EVENTLOOP_H
Utility class which blocks until a signal is emitted or timeout reached.
Definition: eventloop.h:20
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:51
bool isGuardAlive() const
True if the guard object still exists.
Definition: eventloop.h:61
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.
auto singleShot(int msec, QObject *target, F &&task)
Starts a single-shot timer which will call a task in the thread of the given object when it times out...
Definition: threadutils.h:30