1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QTESTSUPPORT_CORE_H
5#define QTESTSUPPORT_CORE_H
6
7#include <QtCore/qcoreapplication.h>
8#include <QtCore/qdeadlinetimer.h>
9
10#include <chrono>
11
12QT_BEGIN_NAMESPACE
13
14namespace QTest {
15
16Q_CORE_EXPORT void qSleep(int ms);
17Q_CORE_EXPORT void qSleep(std::chrono::milliseconds msecs);
18
19namespace Internal
20{
21static inline constexpr std::chrono::milliseconds defaultTryTimeout
22 = std::chrono::milliseconds(5000);
23} // namespace Internal
24
25template <typename Functor>
26[[nodiscard]] bool
27qWaitFor(Functor predicate, QDeadlineTimer deadline = QDeadlineTimer(Internal::defaultTryTimeout))
28{
29 // We should not spin the event loop in case the predicate is already true,
30 // otherwise we might send new events that invalidate the predicate.
31 if (predicate())
32 return true;
33
34 // qWait() is expected to spin the event loop at least once, even when
35 // called with a small timeout like 1ns.
36
37 do {
38 // We explicitly do not pass the remaining time to processEvents, as
39 // that would keep spinning processEvents for the whole duration if
40 // new events were posted as part of processing events, and we need
41 // to return back to this function to check the predicate between
42 // each pass of processEvents. Our own timer will take care of the
43 // timeout.
44 QCoreApplication::processEvents(flags: QEventLoop::AllEvents);
45 QCoreApplication::sendPostedEvents(receiver: nullptr, event_type: QEvent::DeferredDelete);
46
47 if (predicate())
48 return true;
49
50 using namespace std::chrono;
51
52 if (const auto remaining = deadline.remainingTimeAsDuration(); remaining > 0ns)
53 qSleep(msecs: (std::min)(a: 10ms, b: ceil<milliseconds>(d: remaining)));
54
55 } while (!deadline.hasExpired());
56
57 return predicate(); // Last chance
58}
59
60template <typename Functor>
61[[nodiscard]] bool qWaitFor(Functor predicate, int timeout)
62{
63 return qWaitFor(predicate, QDeadlineTimer{timeout, Qt::PreciseTimer});
64}
65
66Q_CORE_EXPORT void qWait(int ms);
67
68Q_CORE_EXPORT void qWait(std::chrono::milliseconds msecs);
69
70} // namespace QTest
71
72QT_END_NAMESPACE
73
74#endif
75

source code of qtbase/src/corelib/kernel/qtestsupport_core.h