| 1 |
// SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
|
| 3 |
#include "mactimer.h" |
| 4 |
|
| 5 |
#include <QPointer> |
| 6 |
|
| 7 |
MacTimer::MacTimer(QObject *parent) : |
| 8 |
QObject(parent), |
| 9 |
m_interval(0), |
| 10 |
m_tolerance(0), |
| 11 |
m_singleShot(false) |
| 12 |
{ |
| 13 |
} |
| 14 |
|
| 15 |
MacTimer::~MacTimer() |
| 16 |
{ |
| 17 |
stop(); |
| 18 |
} |
| 19 |
|
| 20 |
void MacTimer::stop() |
| 21 |
{ |
| 22 |
if (m_cfTimer) { |
| 23 |
CFRunLoopTimerInvalidate(m_cfTimer); |
| 24 |
m_cfTimer = nullptr; |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
void MacTimer::restart() |
| 29 |
{ |
| 30 |
if (m_cfTimer) { |
| 31 |
stop(); |
| 32 |
start(); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
void MacTimer::setInterval(int msec) |
| 37 |
{ |
| 38 |
if (msec != m_interval) { |
| 39 |
m_interval = msec; |
| 40 |
restart(); |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
void MacTimer::setTolerance(int msec) |
| 45 |
{ |
| 46 |
if (msec != m_tolerance) { |
| 47 |
m_tolerance = msec; |
| 48 |
restart(); |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
void MacTimer::setSingleShot(bool singleShot) |
| 53 |
{ |
| 54 |
if (singleShot != m_singleShot) { |
| 55 |
m_singleShot = singleShot; |
| 56 |
restart(); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
void MacTimer::start() { |
| 61 |
stop(); |
| 62 |
|
| 63 |
// Use QPointer to make it auto-null, and use a 'weak reference' in the |
| 64 |
// block |
| 65 |
QPointer<MacTimer> weakThis(this); |
| 66 |
double intervalSeconds = (double)m_interval / 1000.0; |
| 67 |
|
| 68 |
// Create a timer which kicks into a block |
| 69 |
CFRunLoopTimerRef timer = CFRunLoopTimerCreateWithHandler(NULL, |
| 70 |
CFAbsoluteTimeGetCurrent() + intervalSeconds, |
| 71 |
m_singleShot ? 0 : intervalSeconds, |
| 72 |
0, 0, // These are both ignored |
| 73 |
^(CFRunLoopTimerRef) { |
| 74 |
if (weakThis) { |
| 75 |
emit weakThis->timeout(); |
| 76 |
} |
| 77 |
} |
| 78 |
); |
| 79 |
|
| 80 |
if (!timer) |
| 81 |
return; |
| 82 |
|
| 83 |
// Set tolerance so macOS can coalesce timer firings for power efficiency. |
| 84 |
double toleranceSeconds = (double)m_tolerance / 1000.0; |
| 85 |
CFRunLoopTimerSetTolerance(timer, toleranceSeconds); |
| 86 |
|
| 87 |
// Add timer to the current run loop. The run loop retains its own |
| 88 |
// reference; CFRef adopts the Create-rule +1 for stop()/invalidate. |
| 89 |
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode); |
| 90 |
m_cfTimer = timer; |
| 91 |
} |