From 13eb1f63306b1da3ba446e942a58189840e3f827 Mon Sep 17 00:00:00 2001 From: Felix Geyer Date: Thu, 12 Jul 2012 13:51:50 +0200 Subject: [PATCH] Add Tools::sleep() and Tools::wait(). --- src/core/Tools.cpp | 53 +++++++++++++++++++++++++++++++++++++++++++++- src/core/Tools.h | 4 ++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/core/Tools.cpp b/src/core/Tools.cpp index 20d2c3128..019ff8a92 100644 --- a/src/core/Tools.cpp +++ b/src/core/Tools.cpp @@ -17,11 +17,21 @@ #include "Tools.h" +#include +#include #include #include #include #include +#ifdef Q_OS_WIN +#include // for Sleep() +#endif + +#ifdef Q_OS_UNIX +#include // for nanosleep() +#endif + namespace Tools { QString humanReadableFileSize(qint64 bytes) @@ -94,7 +104,7 @@ bool readAllFromDevice(QIODevice* device, QByteArray& data) QDateTime currentDateTimeUtc() { -#if QT_VERSION >= 0x040700 +#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) return QDateTime::currentDateTimeUtc(); #else return QDateTime::currentDateTime().toUTC(); @@ -130,4 +140,45 @@ bool isHex(const QByteArray& ba) return true; } +void sleep(int ms) +{ + Q_ASSERT(ms >= 0); + + if (ms == 0) { + return; + } + +#ifdef Q_OS_WIN + Sleep(uint(ms)); +#else + timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000 * 1000; + nanosleep(&ts, Q_NULLPTR); +#endif +} + +void wait(int ms) +{ + Q_ASSERT(ms > 0); + + QElapsedTimer timer; + timer.start(); + + if (ms <= 50) { + QCoreApplication::processEvents(QEventLoop::AllEvents, ms); + sleep(qMax(ms - static_cast(timer.elapsed()), 0)); + } + else { + int timeLeft; + do { + timeLeft = ms - timer.elapsed(); + if (timeLeft > 0) { + QCoreApplication::processEvents(QEventLoop::AllEvents, timeLeft); + sleep(10); + } + } while (timer.elapsed() < ms); + } +} + } // namespace Tools diff --git a/src/core/Tools.h b/src/core/Tools.h index e5188d175..aacbbe12f 100644 --- a/src/core/Tools.h +++ b/src/core/Tools.h @@ -22,6 +22,8 @@ #include #include +#include "core/Global.h" + class QIODevice; namespace Tools { @@ -33,6 +35,8 @@ bool readAllFromDevice(QIODevice* device, QByteArray& data); QDateTime currentDateTimeUtc(); QString imageReaderFilter(); bool isHex(const QByteArray& ba); +void sleep(int ms); +void wait(int ms); } // namespace Tools