#include "core/Timer.hpp" #include #include #include #include "core/Log.hpp" #include "core/UiQueue.hpp" #include "spec/MockSpec.hpp" namespace dp { namespace { struct Slot { std::function fn; CancelPtr cancel; }; std::atomic g_pending{0}; Uint32 onTimer(void* userdata, SDL_TimerID, Uint32) { auto* holder = static_cast*>(userdata); std::shared_ptr slot = *holder; delete holder; UiQueue::instance().post([slot] { g_pending.fetch_sub(1); if (!slot->cancel->cancelled()) slot->fn(); }); return 0; } } // namespace unsigned Timer::pending() { return g_pending.load(); } CancelPtr Timer::after(unsigned delayMs, std::function fn) { auto cancel = std::make_shared(); if (g_pending.load() >= spec::TimerLimits::kMaxPending) { Log::warn("timer refused: pending cap reached"); cancel->cancel(); return cancel; } if (delayMs > spec::TimerLimits::kMaxDelayMs) delayMs = spec::TimerLimits::kMaxDelayMs; auto slot = std::make_shared(Slot{std::move(fn), cancel}); g_pending.fetch_add(1); auto* holder = new std::shared_ptr(slot); if (SDL_AddTimer(delayMs == 0 ? 1 : delayMs, onTimer, holder) == 0) { Log::error(std::string("SDL_AddTimer failed: ") + SDL_GetError()); delete holder; UiQueue::instance().post([slot] { g_pending.fetch_sub(1); if (!slot->cancel->cancelled()) slot->fn(); }); } return cancel; } } // namespace dp