summaryrefslogtreecommitdiffstats
path: root/src/corelib/kernel/qsingleshottimer_p.h
blob: d7e33c522129b24d117cc53410e7a99572f94314 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// Copyright (C) 2022 The Qt Company Ltd.
// Copyright (C) 2016 Intel Corporation.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#ifndef QSINGLESHOTTIMER_P_H
#define QSINGLESHOTTIMER_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "qabstracteventdispatcher.h"
#include "qcoreapplication.h"
#include "qmetaobject_p.h"

#include <chrono>

QT_BEGIN_NAMESPACE

class QSingleShotTimer : public QObject
{
    Q_OBJECT

    Qt::TimerId timerId = Qt::TimerId::Invalid;

public:
    // use the same duration type
    using Duration = QAbstractEventDispatcher::Duration;

    inline ~QSingleShotTimer();
    inline QSingleShotTimer(Duration interval, Qt::TimerType timerType,
                            const QObject *r, const char *member);
    inline QSingleShotTimer(Duration interval, Qt::TimerType timerType,
                            const QObject *r, QtPrivate::QSlotObjectBase *slotObj);

    inline void startTimerForReceiver(Duration interval, Qt::TimerType timerType,
                                      const QObject *receiver);

Q_SIGNALS:
    void timeout();

private:
    inline void timerEvent(QTimerEvent *) override;
};

QSingleShotTimer::QSingleShotTimer(Duration interval, Qt::TimerType timerType,
                                   const QObject *r, const char *member)
    : QObject(QAbstractEventDispatcher::instance())
{
    connect(this, SIGNAL(timeout()), r, member);
    startTimerForReceiver(interval, timerType, r);
}

QSingleShotTimer::QSingleShotTimer(Duration interval, Qt::TimerType timerType,
                                   const QObject *r, QtPrivate::QSlotObjectBase *slotObj)
    : QObject(QAbstractEventDispatcher::instance())
{
    int signal_index = QMetaObjectPrivate::signalOffset(&staticMetaObject);
    Q_ASSERT(QMetaObjectPrivate::signal(&staticMetaObject, signal_index).name() == "timeout");
    QObjectPrivate::connectImpl(this, signal_index, r ? r : this, nullptr, slotObj,
                                Qt::AutoConnection, nullptr, &staticMetaObject);

    startTimerForReceiver(interval, timerType, r);
}

QSingleShotTimer::~QSingleShotTimer()
{
    if (timerId > Qt::TimerId::Invalid)
        killTimer(timerId);
}

/*
    Move the timer, and the dispatching and handling of the timer event, into
    the same thread as where it will be handled, so that it fires reliably even
    if the thread that set up the timer is busy.
*/
void QSingleShotTimer::startTimerForReceiver(Duration interval, Qt::TimerType timerType,
                                             const QObject *receiver)
{
    if (receiver && receiver->thread() != thread()) {
        // Avoid leaking the QSingleShotTimer instance in case the application exits before the
        // timer fires
        connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this,
                &QObject::deleteLater);
        setParent(nullptr);
        moveToThread(receiver->thread());

        QDeadlineTimer deadline(interval, timerType);
        auto invokable = [this, deadline, timerType] {
            if (deadline.hasExpired()) {
                Q_EMIT timeout();
            } else {
                timerId = Qt::TimerId{startTimer(deadline.remainingTimeAsDuration(), timerType)};
            }
        };
        QMetaObject::invokeMethod(this, invokable, Qt::QueuedConnection);
    } else {
        timerId = Qt::TimerId{startTimer(interval, timerType)};
    }
}

void QSingleShotTimer::timerEvent(QTimerEvent *)
{
    // need to kill the timer _before_ we emit timeout() in case the
    // slot connected to timeout calls processEvents()
    if (timerId > Qt::TimerId::Invalid)
        killTimer(std::exchange(timerId, Qt::TimerId::Invalid));

    Q_EMIT timeout();

    // we would like to use delete later here, but it feels like a
    // waste to post a new event to handle this event, so we just unset the flag
    // and explicitly delete...
    delete this;
}

QT_END_NAMESPACE

#endif // QSINGLESHOTTIMER_P_H