Skip to content
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ CMakeUserPresets.json
.vs/
.vscode/
.idea/
compile_commands.json
3 changes: 2 additions & 1 deletion CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"generator": "Ninja",
"cacheVariables": {
"KDUTILS_BUILD_TESTS": "OFF",
"KDUTILS_CODE_COVERAGE": "OFF"
"KDUTILS_CODE_COVERAGE": "OFF",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
}
},
{
Expand Down
2 changes: 2 additions & 0 deletions src/KDFoundation/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,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
7 changes: 7 additions & 0 deletions src/KDFoundation/platform/macos/macos_platform_event_loop.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,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 +41,9 @@ class KDFOUNDATION_API MacOSPlatformEventLoop : public AbstractPlatformEventLoop
private:
void waitForEventsImpl(int timeout) override;
std::unique_ptr<AbstractPlatformTimer> createPlatformTimerImpl(Timer *timer) override;

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

} // namespace KDFoundation
12 changes: 8 additions & 4 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,18 @@
*/

#include "macos_platform_event_loop.h"
#include "macos_platform_timer.h"

#import <Foundation/Foundation.h>
#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 @@ -81,6 +84,7 @@

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 <info@kdab.com>
Author: Paul Lemire <paul.lemire@kdab.com>

SPDX-License-Identifier: MIT

Contact KDAB at <info@kdab.com> for commercial licensing options.
*/

#pragma once

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

#include <CoreFoundation/CoreFoundation.h>

#include <chrono>

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 *const m_handler;
CFRunLoopTimerRef cfTimer;
};

} // namespace KDFoundation
100 changes: 100 additions & 0 deletions src/KDFoundation/platform/macos/macos_platform_timer.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
39 changes: 26 additions & 13 deletions tests/auto/foundation/core_application/tst_core_application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -187,32 +187,46 @@ TEST_CASE("Event handling")
}
}

#ifndef KD_PLATFORM_MACOS
TEST_CASE("Timer handling")
/// macOS on GitHub runners is super slow and timeouts
template<typename T>
inline T adjustTimeout(T timeout)
{
#ifdef DOCTEST_PLATFORM_MAC
if (std::getenv("GITHUB_JOB"))
return timeout * 10;
#endif

return timeout;
}

TEST_CASE("Timer handling" * doctest::timeout(120))
{
SUBCASE("timer fires correctly")
{
using namespace std::literals::chrono_literals;

CoreApplication app;
Timer timer;
timer.interval = 100ms;
timer.interval = adjustTimeout(100ms);
timer.running = true;

int timeout = 0;
auto startTime = std::chrono::steady_clock::now();
auto time = startTime;
std::ignore = timer.timeout.connect([&]() {
const auto endTime = std::chrono::steady_clock::now();
REQUIRE(endTime - time > 50ms);
REQUIRE(endTime - time < 150ms);
const auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - time).count();
SPDLOG_INFO("elapsedTime = {}", elapsedTime);
REQUIRE(endTime - time > adjustTimeout(50ms));
REQUIRE(endTime - time < adjustTimeout(250ms));
time = endTime;
timeout++;
});

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

Expand All @@ -234,7 +248,7 @@ TEST_CASE("Timer handling")
Timer timer;

// Set initial interval to 100ms
timer.interval = 100ms;
timer.interval = adjustTimeout(100ms);
timer.running = true;

bool fired = false;
Expand All @@ -244,23 +258,22 @@ TEST_CASE("Timer handling")
});

// After 50ms, timer shouldn't have yet fired
app.processEvents(50);
app.processEvents(adjustTimeout(50));
REQUIRE(fired == false);

// Reset interval, it should fire 150ms from now
timer.interval = 150ms;
timer.interval = adjustTimeout(150ms);

// Advance 100ms, it should _not_ yet fire because it was
// restarted to 150ms even though the original timeout passed
app.processEvents(100);
app.processEvents(adjustTimeout(100));
REQUIRE(fired == false);

// It should fire after additional 100ms
app.processEvents(100);
app.processEvents(adjustTimeout(100));
REQUIRE(fired == true);
}
}
#endif

TEST_CASE("Main event loop")
{
Expand Down