summaryrefslogtreecommitdiff
path: root/src/event_manager.hh
blob: e14468bac1109278ee6fda7cf299730081ac9ecc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef event_manager_hh_INCLUDED
#define event_manager_hh_INCLUDED

#include "utils.hh"

#include <chrono>
#include <unordered_set>

namespace Kakoune
{

class FDWatcher
{
public:
    using Callback = std::function<void (FDWatcher& watcher)>;
    FDWatcher(int fd, Callback callback);
    ~FDWatcher();

    int fd() const { return m_fd; }
    void run() { m_callback(*this); }
private:
    FDWatcher(const FDWatcher&) = delete;

    int      m_fd;
    Callback m_callback;
};

using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;

class Timer
{
public:
    using Callback = std::function<void (Timer& timer)>;

    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.
//
// The program main loop should call handle_next_events()
// until it's time to quit.
class EventManager : public Singleton<EventManager>
{
public:
    EventManager();
    ~EventManager();

    void handle_next_events();

    // force the watchers associated with fd to be executed
    // on next handle_next_events call.
    void force_signal(int fd);

private:
    friend class FDWatcher;
    friend class Timer;
    std::unordered_set<FDWatcher*>  m_fd_watchers;
    std::unordered_set<Timer*>      m_timers;
    std::vector<int> m_forced_fd;

    TimePoint        m_last;
};

}

#endif // event_manager_hh_INCLUDED