| 1 | // Copyright (C) 2020 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 QBASICTIMER_H |
| 5 | #define QBASICTIMER_H |
| 6 | |
| 7 | #include <QtCore/qglobal.h> |
| 8 | #include <QtCore/qabstracteventdispatcher.h> |
| 9 | #include <QtCore/qnamespace.h> |
| 10 | |
| 11 | #include <chrono> |
| 12 | |
| 13 | QT_BEGIN_NAMESPACE |
| 14 | |
| 15 | |
| 16 | class QObject; |
| 17 | |
| 18 | class Q_CORE_EXPORT QBasicTimer |
| 19 | { |
| 20 | Qt::TimerId m_id; |
| 21 | Q_DISABLE_COPY(QBasicTimer) |
| 22 | |
| 23 | public: |
| 24 | // use the same duration type |
| 25 | using Duration = QAbstractEventDispatcher::Duration; |
| 26 | |
| 27 | constexpr QBasicTimer() noexcept : m_id{Qt::TimerId::Invalid} {} |
| 28 | ~QBasicTimer() { if (isActive()) stop(); } |
| 29 | |
| 30 | QBasicTimer(QBasicTimer &&other) noexcept |
| 31 | : m_id{std::exchange(obj&: other.m_id, new_val: Qt::TimerId::Invalid)} |
| 32 | {} |
| 33 | |
| 34 | QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_MOVE_AND_SWAP(QBasicTimer) |
| 35 | |
| 36 | void swap(QBasicTimer &other) noexcept { std::swap(a&: m_id, b&: other.m_id); } |
| 37 | |
| 38 | bool isActive() const noexcept { return m_id != Qt::TimerId::Invalid; } |
| 39 | int timerId() const noexcept { return qToUnderlying(e: id()); } |
| 40 | Qt::TimerId id() const noexcept { return m_id; } |
| 41 | QT_CORE_INLINE_SINCE(6, 5) |
| 42 | void start(int msec, QObject *obj); |
| 43 | QT_CORE_INLINE_SINCE(6, 5) |
| 44 | void start(int msec, Qt::TimerType timerType, QObject *obj); |
| 45 | |
| 46 | #if QT_CORE_REMOVED_SINCE(6, 9) |
| 47 | void start(std::chrono::milliseconds duration, QObject *obj); |
| 48 | void start(std::chrono::milliseconds duration, Qt::TimerType timerType, QObject *obj); |
| 49 | #endif |
| 50 | void start(Duration duration, QObject *obj) |
| 51 | { start(duration, timerType: Qt::CoarseTimer, obj); } |
| 52 | void start(Duration duration, Qt::TimerType timerType, QObject *obj); |
| 53 | void stop(); |
| 54 | }; |
| 55 | Q_DECLARE_TYPEINFO(QBasicTimer, Q_RELOCATABLE_TYPE); |
| 56 | |
| 57 | #if QT_CORE_INLINE_IMPL_SINCE(6, 5) |
| 58 | void QBasicTimer::start(int msec, QObject *obj) |
| 59 | { |
| 60 | start(duration: std::chrono::milliseconds{msec}, obj); |
| 61 | } |
| 62 | |
| 63 | void QBasicTimer::start(int msec, Qt::TimerType t, QObject *obj) |
| 64 | { |
| 65 | start(duration: std::chrono::milliseconds{msec}, timerType: t, obj); |
| 66 | } |
| 67 | #endif |
| 68 | |
| 69 | inline void swap(QBasicTimer &lhs, QBasicTimer &rhs) noexcept { lhs.swap(other&: rhs); } |
| 70 | |
| 71 | QT_END_NAMESPACE |
| 72 | |
| 73 | #endif // QBASICTIMER_H |
| 74 | |