Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:07:39

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 template <typename Functor>
0020 [[nodiscard]] bool
0021 qWaitFor(Functor predicate, QDeadlineTimer deadline = QDeadlineTimer(std::chrono::seconds{5}))
0022 {
0023     // We should not spin the event loop in case the predicate is already true,
0024     // otherwise we might send new events that invalidate the predicate.
0025     if (predicate())
0026         return true;
0027 
0028     // qWait() is expected to spin the event loop at least once, even when
0029     // called with a small timeout like 1ns.
0030 
0031     do {
0032         // We explicitly do not pass the remaining time to processEvents, as
0033         // that would keep spinning processEvents for the whole duration if
0034         // new events were posted as part of processing events, and we need
0035         // to return back to this function to check the predicate between
0036         // each pass of processEvents. Our own timer will take care of the
0037         // timeout.
0038         QCoreApplication::processEvents(QEventLoop::AllEvents);
0039         QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
0040 
0041         if (predicate())
0042             return true;
0043 
0044         using namespace std::chrono;
0045 
0046         if (const auto remaining = deadline.remainingTimeAsDuration(); remaining > 0ns)
0047             qSleep((std::min)(10ms, ceil<milliseconds>(remaining)));
0048 
0049     } while (!deadline.hasExpired());
0050 
0051     return predicate(); // Last chance
0052 }
0053 
0054 template <typename Functor>
0055 [[nodiscard]] bool qWaitFor(Functor predicate, int timeout)
0056 {
0057     return qWaitFor(predicate, QDeadlineTimer{timeout, Qt::PreciseTimer});
0058 }
0059 
0060 Q_CORE_EXPORT void qWait(int ms);
0061 
0062 Q_CORE_EXPORT void qWait(std::chrono::milliseconds msecs);
0063 
0064 } // namespace QTest
0065 
0066 QT_END_NAMESPACE
0067 
0068 #endif