Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-15 08:20:26

0001 // Copyright (C) 2018 The Qt Company Ltd.
0002 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
0003 
0004 #ifndef QTESTSUPPORT_CORE_H
0005 #define QTESTSUPPORT_CORE_H
0006 
0007 #include <QtCore/qcoreapplication.h>
0008 #include <QtCore/qdeadlinetimer.h>
0009 
0010 #include <chrono>
0011 
0012 QT_BEGIN_NAMESPACE
0013 
0014 namespace QTest {
0015 
0016 Q_CORE_EXPORT void qSleep(int ms);
0017 Q_CORE_EXPORT void qSleep(std::chrono::milliseconds msecs);
0018 
0019 namespace Internal
0020 {
0021 static inline constexpr std::chrono::milliseconds defaultTryTimeout
0022     = std::chrono::milliseconds(5000);
0023 } // namespace Internal
0024 
0025 template <typename Functor>
0026 [[nodiscard]] bool
0027 qWaitFor(Functor predicate, QDeadlineTimer deadline = QDeadlineTimer(Internal::defaultTryTimeout))
0028 {
0029     // We should not spin the event loop in case the predicate is already true,
0030     // otherwise we might send new events that invalidate the predicate.
0031     if (predicate())
0032         return true;
0033 
0034     // qWait() is expected to spin the event loop at least once, even when
0035     // called with a small timeout like 1ns.
0036 
0037     do {
0038         // We explicitly do not pass the remaining time to processEvents, as
0039         // that would keep spinning processEvents for the whole duration if
0040         // new events were posted as part of processing events, and we need
0041         // to return back to this function to check the predicate between
0042         // each pass of processEvents. Our own timer will take care of the
0043         // timeout.
0044         QCoreApplication::processEvents(QEventLoop::AllEvents);
0045         QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
0046 
0047         if (predicate())
0048             return true;
0049 
0050         using namespace std::chrono;
0051 
0052         if (const auto remaining = deadline.remainingTimeAsDuration(); remaining > 0ns)
0053             qSleep((std::min)(10ms, ceil<milliseconds>(remaining)));
0054 
0055     } while (!deadline.hasExpired());
0056 
0057     return predicate(); // Last chance
0058 }
0059 
0060 template <typename Functor>
0061 [[nodiscard]] bool qWaitFor(Functor predicate, int timeout)
0062 {
0063     return qWaitFor(predicate, QDeadlineTimer{timeout, Qt::PreciseTimer});
0064 }
0065 
0066 Q_CORE_EXPORT void qWait(int ms);
0067 
0068 Q_CORE_EXPORT void qWait(std::chrono::milliseconds msecs);
0069 
0070 } // namespace QTest
0071 
0072 QT_END_NAMESPACE
0073 
0074 #endif