2012-08-28 22:32:15 +02:00
|
|
|
#include "event_manager.hh"
|
|
|
|
|
|
|
|
#include <algorithm>
|
|
|
|
|
|
|
|
namespace Kakoune
|
|
|
|
{
|
|
|
|
|
|
|
|
void EventManager::watch(int fd, EventHandler handler)
|
|
|
|
{
|
|
|
|
auto event = std::find_if(m_events.begin(), m_events.end(),
|
|
|
|
[&](const pollfd& pfd) { return pfd.fd == fd; });
|
|
|
|
if (event != m_events.end())
|
|
|
|
throw runtime_error("fd already watched");
|
|
|
|
|
2012-11-27 13:57:03 +01:00
|
|
|
m_events.emplace_back(pollfd{ fd, POLLIN | POLLPRI, 0 });
|
|
|
|
m_handlers.emplace_back(new EventHandler(std::move(handler)));
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void EventManager::unwatch(int fd)
|
|
|
|
{
|
2012-11-27 13:57:03 +01:00
|
|
|
auto event = std::find_if(m_events.begin(), m_events.end(),
|
|
|
|
[&](const pollfd& pfd) { return pfd.fd == fd; });
|
|
|
|
assert(event != m_events.end());
|
|
|
|
auto handler = m_handlers.begin() + (event - m_events.begin());
|
|
|
|
|
|
|
|
// keep handler in m_handlers_trash so that it does not die now,
|
|
|
|
// but at the end of handle_next_events. We do this as handler might
|
|
|
|
// be our caller.
|
|
|
|
m_handlers_trash.emplace_back(std::move(*handler));
|
|
|
|
m_handlers.erase(handler);
|
|
|
|
m_events.erase(event);
|
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;
|
2012-11-26 14:08:27 +01:00
|
|
|
poll(m_events.data(), m_events.size(), timeout_ms);
|
2012-11-27 13:57:03 +01:00
|
|
|
for (size_t i = 0; i < m_events.size(); ++i)
|
2012-11-26 14:08:27 +01:00
|
|
|
{
|
2012-11-27 13:57:03 +01:00
|
|
|
auto& event = m_events[i];
|
2012-11-26 14:08:27 +01:00
|
|
|
const int fd = event.fd;
|
2012-11-27 13:57:03 +01:00
|
|
|
if (event.revents or contains(m_forced, fd))
|
|
|
|
(*m_handlers[i])(fd);
|
2012-11-26 14:08:27 +01:00
|
|
|
}
|
|
|
|
|
2012-11-27 13:57:03 +01:00
|
|
|
m_handlers_trash.clear();
|
2012-10-27 15:15:34 +02:00
|
|
|
m_forced.clear();
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2012-10-27 15:01:13 +02:00
|
|
|
void EventManager::force_signal(int fd)
|
|
|
|
{
|
|
|
|
m_forced.push_back(fd);
|
|
|
|
}
|
|
|
|
|
2012-08-28 22:32:15 +02:00
|
|
|
}
|