event_manager.hh (2845B)
1 #ifndef event_manager_hh_INCLUDED 2 #define event_manager_hh_INCLUDED 3 4 #include "clock.hh" 5 #include "meta.hh" 6 #include "utils.hh" 7 #include "optional.hh" 8 #include "vector.hh" 9 #include "function.hh" 10 11 #include <sys/select.h> 12 #include <csignal> 13 14 namespace Kakoune 15 { 16 17 enum class EventMode 18 { 19 Normal, 20 Urgent, 21 }; 22 23 enum class FdEvents 24 { 25 None = 0, 26 Read = 1 << 0, 27 Write = 1 << 1, 28 Except = 1 << 2, 29 }; 30 31 constexpr bool with_bit_ops(Meta::Type<FdEvents>) { return true; } 32 33 class FDWatcher 34 { 35 public: 36 using Callback = Function<void (FDWatcher& watcher, FdEvents events, EventMode mode)>; 37 FDWatcher(int fd, FdEvents events, EventMode mode, Callback callback); 38 FDWatcher(const FDWatcher&) = delete; 39 FDWatcher& operator=(const FDWatcher&) = delete; 40 ~FDWatcher(); 41 42 int fd() const { return m_fd; } 43 FdEvents events() const { return m_events; } 44 FdEvents& events() { return m_events; } 45 EventMode mode() const { return m_mode; } 46 47 void run(FdEvents events, EventMode mode); 48 49 void reset_fd(int fd) { m_fd = fd; } 50 void close_fd(); 51 void disable() { m_fd = -1; } 52 53 private: 54 int m_fd; 55 FdEvents m_events; 56 EventMode m_mode; 57 Callback m_callback; 58 }; 59 60 class Timer 61 { 62 public: 63 using Callback = Function<void (Timer& timer)>; 64 65 Timer(TimePoint date, Callback callback, 66 EventMode mode = EventMode::Normal); 67 Timer(const Timer&) = delete; 68 Timer& operator=(const Timer&) = delete; 69 ~Timer(); 70 71 TimePoint next_date() const { return m_date; } 72 void set_next_date(TimePoint date) { m_date = date; } 73 void disable() { m_date = TimePoint::max(); } 74 void run(EventMode mode); 75 76 private: 77 TimePoint m_date; 78 EventMode m_mode; 79 Callback m_callback; 80 }; 81 82 // The EventManager provides an interface to file descriptor 83 // based event handling. 84 // 85 // The program main loop should call handle_next_events() 86 // until it's time to quit. 87 class EventManager : public Singleton<EventManager> 88 { 89 public: 90 using Nanoseconds = std::chrono::nanoseconds; 91 92 EventManager(); 93 ~EventManager(); 94 95 // blocks until next event if no timeout given 96 bool handle_next_events(EventMode mode, sigset_t* sigmask = nullptr, 97 Optional<Nanoseconds> timeout = {}); 98 99 // force the watchers associated with fd to be executed 100 // on next handle_next_events call. 101 void force_signal(int fd); 102 103 static void handle_urgent_events(); 104 105 private: 106 friend class FDWatcher; 107 friend class Timer; 108 Vector<FDWatcher*, MemoryDomain::Events> m_fd_watchers; 109 Vector<Timer*, MemoryDomain::Events> m_timers; 110 fd_set m_forced_fd; 111 bool m_has_forced_fd = false; 112 113 TimePoint m_last; 114 }; 115 116 using SignalHandler = void(*)(int); 117 118 SignalHandler set_signal_handler(int signum, SignalHandler handler); 119 120 } 121 122 #endif // event_manager_hh_INCLUDED