diff --git a/src/event_manager.cc b/src/event_manager.cc index 9ae3e78c..295bc622 100644 --- a/src/event_manager.cc +++ b/src/event_manager.cc @@ -16,6 +16,23 @@ FDWatcher::~FDWatcher() EventManager::instance().m_fd_watchers.remove(this); } +Timer::Timer(TimePoint date, Callback callback) + : m_date{date}, m_callback{std::move(callback)} +{ + EventManager::instance().m_timers.add(this); +} + +Timer::~Timer() +{ + EventManager::instance().m_timers.remove(this); +} + +void Timer::run() +{ + m_date = TimePoint::max(); + m_callback(*this); +} + EventManager::EventManager() { m_forced_fd.reserve(4); @@ -24,6 +41,7 @@ EventManager::EventManager() EventManager::~EventManager() { assert(m_fd_watchers.empty()); + assert(m_timers.empty()); } void EventManager::handle_next_events() @@ -48,6 +66,13 @@ void EventManager::handle_next_events() (*it)->run(); } } + + TimePoint now = Clock::now(); + for (auto& timer : m_timers) + { + if (timer->next_date() <= now) + timer->run(); + } } void EventManager::force_signal(int fd) diff --git a/src/event_manager.hh b/src/event_manager.hh index ae719f06..fd304a40 100644 --- a/src/event_manager.hh +++ b/src/event_manager.hh @@ -3,6 +3,8 @@ #include "utils.hh" +#include + namespace Kakoune { @@ -20,6 +22,26 @@ private: Callback m_callback; }; +using Clock = std::chrono::steady_clock; +using TimePoint = Clock::time_point; + +class Timer +{ +public: + using Callback = std::function; + + Timer(TimePoint date, Callback callback); + ~Timer(); + + TimePoint next_date() const { return m_date; } + void set_next_date(TimePoint date) { m_date = date; } + void run(); + +private: + TimePoint m_date; + Callback m_callback; +}; + // The EventManager provides an interface to file descriptor // based event handling. // @@ -39,8 +61,12 @@ public: private: friend class FDWatcher; + friend class Timer; Set m_fd_watchers; + Set m_timers; std::vector m_forced_fd; + + TimePoint m_last; }; }