2012-08-28 22:32:15 +02:00
|
|
|
#include "event_manager.hh"
|
|
|
|
|
2013-01-10 18:54:40 +01:00
|
|
|
#include <poll.h>
|
2012-08-28 22:32:15 +02:00
|
|
|
|
|
|
|
namespace Kakoune
|
|
|
|
{
|
|
|
|
|
2013-01-10 18:54:40 +01:00
|
|
|
FDWatcher::FDWatcher(int fd, Callback callback)
|
|
|
|
: m_fd{fd}, m_callback{std::move(callback)}
|
2012-12-03 18:49:09 +01:00
|
|
|
{
|
2013-01-10 18:54:40 +01:00
|
|
|
EventManager::instance().register_fd_watcher(this);
|
2012-12-03 18:49:09 +01:00
|
|
|
}
|
|
|
|
|
2013-01-10 18:54:40 +01:00
|
|
|
FDWatcher::~FDWatcher()
|
2012-08-28 22:32:15 +02:00
|
|
|
{
|
2013-01-10 18:54:40 +01:00
|
|
|
EventManager::instance().unregister_fd_watcher(this);
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2013-01-10 18:54:40 +01:00
|
|
|
EventManager::EventManager()
|
2012-08-28 22:32:15 +02:00
|
|
|
{
|
2013-01-10 18:54:40 +01:00
|
|
|
m_forced_fd.reserve(4);
|
|
|
|
}
|
2012-11-27 13:57:03 +01:00
|
|
|
|
2013-01-10 18:54:40 +01:00
|
|
|
EventManager::~EventManager()
|
|
|
|
{
|
|
|
|
assert(m_fd_watchers.empty());
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void EventManager::handle_next_events()
|
|
|
|
{
|
2012-10-27 15:01:13 +02:00
|
|
|
const int timeout_ms = 100;
|
2013-01-10 18:54:40 +01:00
|
|
|
std::vector<pollfd> events;
|
|
|
|
events.reserve(m_fd_watchers.size());
|
|
|
|
for (auto& watcher : m_fd_watchers)
|
|
|
|
events.emplace_back(pollfd{ watcher->fd(), POLLIN | POLLPRI, 0 });
|
|
|
|
std::vector<int> forced = m_forced_fd;
|
|
|
|
m_forced_fd.clear();
|
|
|
|
poll(events.data(), events.size(), timeout_ms);
|
|
|
|
for (size_t i = 0; i < events.size(); ++i)
|
2012-11-26 14:08:27 +01:00
|
|
|
{
|
2013-01-10 18:54:40 +01:00
|
|
|
auto& event = events[i];
|
2012-11-26 14:08:27 +01:00
|
|
|
const int fd = event.fd;
|
2012-12-03 18:49:09 +01:00
|
|
|
if (event.revents or contains(forced, fd))
|
2013-01-10 18:54:40 +01:00
|
|
|
{
|
|
|
|
auto it = std::find_if(m_fd_watchers.begin(), m_fd_watchers.end(),
|
|
|
|
[fd](FDWatcher* w) { return w->fd() == fd; });
|
|
|
|
if (it != m_fd_watchers.end())
|
|
|
|
(*it)->run();
|
|
|
|
}
|
2012-11-26 14:08:27 +01:00
|
|
|
}
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2012-10-27 15:01:13 +02:00
|
|
|
void EventManager::force_signal(int fd)
|
|
|
|
{
|
2013-01-10 18:54:40 +01:00
|
|
|
m_forced_fd.push_back(fd);
|
|
|
|
|
|
|
|
}
|
|
|
|
void EventManager::register_fd_watcher(FDWatcher* event)
|
|
|
|
{
|
|
|
|
assert(not contains(m_fd_watchers, event));
|
|
|
|
m_fd_watchers.push_back(event);
|
|
|
|
}
|
|
|
|
|
|
|
|
void EventManager::unregister_fd_watcher(FDWatcher* event)
|
|
|
|
{
|
|
|
|
auto it = find(m_fd_watchers, event);
|
|
|
|
assert(it != m_fd_watchers.end());
|
|
|
|
m_fd_watchers.erase(it);
|
2012-10-27 15:01:13 +02:00
|
|
|
}
|
|
|
|
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|