-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmacos_platform_timer.mm
More file actions
100 lines (85 loc) · 2.64 KB
/
macos_platform_timer.mm
File metadata and controls
100 lines (85 loc) · 2.64 KB
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
/*
This file is part of KDUtils.
SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
Author: Paul Lemire <paul.lemire@kdab.com>
SPDX-License-Identifier: MIT
Contact KDAB at <info@kdab.com> for commercial licensing options.
*/
#include "macos_platform_timer.h"
#include "macos_platform_event_loop.h"
#include "KDFoundation/core_application.h"
#include "KDFoundation/timer.h"
#include "KDFoundation/platform/macos/macos_platform_event_loop.h"
#include <Foundation/Foundation.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <type_traits>
#include <unistd.h>
using namespace KDFoundation;
inline MacOSPlatformEventLoop *eventLoop()
{
return static_cast<MacOSPlatformEventLoop *>(CoreApplication::instance()->eventLoop());
}
MacOSPlatformTimer::MacOSPlatformTimer(Timer *timer)
: m_handler{ timer }, cfTimer{ nullptr }
{
timer->running.valueChanged().connect([this, timer](bool running) {
if (running) {
arm(timer->interval.get());
} else {
disarm();
}
});
timer->interval.valueChanged().connect([this, timer]() {
if (timer->running.get()) {
arm(timer->interval.get());
}
});
}
MacOSPlatformTimer::~MacOSPlatformTimer()
{
disarm();
}
void MacOSPlatformTimer::timerFired(CFRunLoopTimerRef timer, void *)
{
MacOSPlatformEventLoop *ev = eventLoop();
void *key = timer;
if (auto it = ev->timerMap.find(key); it != ev->timerMap.end()) {
it->second->m_handler->timeout.emit();
}
}
void MacOSPlatformTimer::arm(std::chrono::microseconds us)
{
if (cfTimer) {
disarm();
}
CFTimeInterval interval = std::chrono::duration_cast<std::chrono::duration<double>>(us).count();
CFRunLoopTimerContext timerContext = { 0, nullptr, nullptr, nullptr, nullptr };
CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent() + interval;
// Create the timer
cfTimer = CFRunLoopTimerCreate(
kCFAllocatorDefault, // Allocator
fireDate, // Fire time
interval, // Interval
0, // Flags
0, // Order
timerFired, // Callback function
&timerContext // Timer context
);
CFRunLoopAddTimer(CFRunLoopGetCurrent(), cfTimer, kCFRunLoopCommonModes);
if (cfTimer) {
void *key = reinterpret_cast<void *>(cfTimer);
eventLoop()->timerMap[key] = this;
}
}
void MacOSPlatformTimer::disarm()
{
if (cfTimer) {
void *key = reinterpret_cast<void *>(cfTimer);
eventLoop()->timerMap.erase(key);
CFRelease(cfTimer);
cfTimer = nullptr;
}
}