Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MacOS: Add support for timers to the platform integrations #10

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/KDFoundation/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
platform/macos/macos_platform_event_loop.h
platform/macos/macos_platform_integration.mm
platform/macos/macos_platform_integration.h
platform/macos/macos_platform_timer.mm
platform/macos/macos_platform_timer.h
)
endif()

Expand Down
6 changes: 6 additions & 0 deletions src/KDFoundation/platform/macos/macos_platform_event_loop.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@

#include <KDFoundation/platform/abstract_platform_event_loop.h>
#include <KDFoundation/kdfoundation_global.h>
#include <unordered_map>

namespace KDFoundation {

class MacOSPlatformTimer;

class KDFOUNDATION_API MacOSPlatformEventLoop : public AbstractPlatformEventLoop
{
public:
Expand All @@ -37,6 +40,9 @@ class KDFOUNDATION_API MacOSPlatformEventLoop : public AbstractPlatformEventLoop

private:
std::unique_ptr<AbstractPlatformTimer> createPlatformTimerImpl(Timer *timer) override;

std::unordered_map<void *, MacOSPlatformTimer *> timerMap;
friend class MacOSPlatformTimer;
};

} // namespace KDFoundation
15 changes: 8 additions & 7 deletions src/KDFoundation/platform/macos/macos_platform_event_loop.mm
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@
*/

#include "macos_platform_event_loop.h"

#include "macos_platform_timer.h"
#import <Foundation/Foundation.h>
itzurabhi marked this conversation as resolved.
Show resolved Hide resolved
#import <AppKit/AppKit.h>

#include <limits>

using namespace KDFoundation;
#include <memory>

constexpr auto KDFoundationCocoaEventSubTypeWakeup = std::numeric_limits<short>::max();

namespace KDFoundation {

MacOSPlatformEventLoop::MacOSPlatformEventLoop()
{
@autoreleasepool {
Expand Down Expand Up @@ -78,9 +79,9 @@
// TODO
return false;
}

std::unique_ptr<AbstractPlatformTimer> MacOSPlatformEventLoop::createPlatformTimerImpl(Timer *timer)
{
// TODO
return {};
return std::make_unique<MacOSPlatformTimer>(timer);
}

} // namespace KDFoundation
39 changes: 39 additions & 0 deletions src/KDFoundation/platform/macos/macos_platform_timer.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
This file is part of KDUtils.

SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
Author: Paul Lemire <[email protected]>

SPDX-License-Identifier: MIT

Contact KDAB at <[email protected]> for commercial licensing options.
*/

#pragma once

#include <CoreFoundation/CoreFoundation.h>

#include <chrono>

#include <KDFoundation/platform/abstract_platform_timer.h>
#include <KDFoundation/file_descriptor_notifier.h>

namespace KDFoundation {

class Timer;

class KDFOUNDATION_API MacOSPlatformTimer : public AbstractPlatformTimer
{
public:
explicit MacOSPlatformTimer(Timer *timer);
~MacOSPlatformTimer() override;

private:
void arm(std::chrono::microseconds us);
void disarm();
static void timerFired(CFRunLoopTimerRef timer, void *info);
Timer *m_handler;
itzurabhi marked this conversation as resolved.
Show resolved Hide resolved
CFRunLoopTimerRef cfTimer;
};

} // namespace KDFoundation
98 changes: 98 additions & 0 deletions src/KDFoundation/platform/macos/macos_platform_timer.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
This file is part of KDUtils.

SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
Author: Paul Lemire <[email protected]>

SPDX-License-Identifier: MIT

Contact KDAB at <[email protected]> for commercial licensing options.
*/

#include "macos_platform_timer.h"
#include "macos_platform_event_loop.h"
#include <Foundation/Foundation.h>
#include <algorithm>
itzurabhi marked this conversation as resolved.
Show resolved Hide resolved
#include <cassert>
#include <chrono>
#include <cstddef>
#include <type_traits>
#include <unistd.h>
#include "KDFoundation/core_application.h"
#include "KDFoundation/timer.h"
#include "KDFoundation/platform/macos/macos_platform_event_loop.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 *info)
{
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, NULL, NULL, NULL, NULL };
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,7 @@ TEST_CASE("Event handling")
}
}

#ifndef KD_PLATFORM_MACOS
TEST_CASE("Timer handling")
TEST_CASE("Timer handling" * doctest::timeout(120))
{
SUBCASE("timer fires correctly")
{
Expand All @@ -205,15 +204,18 @@ TEST_CASE("Timer handling")
auto time = startTime;
timer.timeout.connect([&]() {
const auto endTime = std::chrono::steady_clock::now();
const auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - time).count();
SPDLOG_INFO("elapsedTime = {}", elapsedTime);
REQUIRE(endTime - time > 50ms);
REQUIRE(endTime - time < 150ms);
REQUIRE(endTime - time < 200ms);
time = endTime;
timeout++;
});

while (std::chrono::steady_clock::now() - startTime < 500ms) {
app.processEvents(500);
}
SPDLOG_INFO("timeout = {}", timeout);
REQUIRE(timeout > 3);
REQUIRE(timeout < 8);

Expand Down Expand Up @@ -261,7 +263,6 @@ TEST_CASE("Timer handling")
REQUIRE(fired == true);
}
}
#endif

TEST_CASE("Main event loop")
{
Expand Down
Loading