libfilezilla
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
event_handler.hpp
Go to the documentation of this file.
1 #ifndef LIBFILEZILLA_EVENT_HANDLER
2 #define LIBFILEZILLA_EVENT_HANDLER
3 
4 #include "event_loop.hpp"
5 
9 namespace fz {
10 
54 class FZ_PUBLIC_SYMBOL event_handler
55 {
56 public:
57  event_handler() = delete;
58 
59  explicit event_handler(event_loop& loop);
60  virtual ~event_handler();
61 
62  event_handler(event_handler const&) = delete;
63  event_handler& operator=(event_handler const&) = delete;
64 
73  void remove_handler();
74 
81  virtual void operator()(event_base const&) = 0;
82 
83  /* \brief Sends the passed event asynchronously to the handler.
84  *
85  * Can be called from any thread.
86  *
87  * All events are processed in the order they are sent, excluding possible races between threads.
88  */
89  template<typename T, typename... Args>
90  void send_event(Args&&... args) {
91  event_loop_.send_event(this, new T(std::forward<Args>(args)...));
92  }
93 
110  timer_id add_timer(duration const& interval, bool one_shot);
111 
116  void stop_timer(timer_id id);
117 
118  event_loop & event_loop_;
119 private:
120  friend class event_loop;
121  bool removing_{};
122 };
123 
138 template<typename T, typename F>
139 bool dispatch(event_base const& ev, F&& f)
140 {
141  bool const same = same_type<T>(ev);
142  if (same) {
143  T const* e = static_cast<T const*>(&ev);
144  apply(std::forward<F>(f), e->v_);
145  }
146  return same;
147 }
148 
164 template<typename T, typename H, typename F>
165 bool dispatch(event_base const& ev, H* h, F&& f)
166 {
167  bool const same = same_type<T>(ev);
168  if (same) {
169  T const* e = static_cast<T const*>(&ev);
170  apply(h, std::forward<F>(f), e->v_);
171  }
172  return same;
173 }
174 
193 template<typename T, typename ... Ts, typename H, typename F, typename ... Fs>
194 bool dispatch(event_base const& ev, H* h, F&& f, Fs&& ... fs)
195 {
196  if (dispatch<T>(ev, h, std::forward<F>(f))) {
197  return true;
198  }
199 
200  return dispatch<Ts...>(ev, h, std::forward<Fs>(fs)...);
201 }
202 
203 }
204 
205 #endif
auto apply(F &&f, Tuple &&args) -> decltype(apply_(std::forward< F >(f), std::forward< Tuple >(args), Seq()))
Apply tuple to ordinary functor.
Definition: apply.hpp:43
Simple handler for asynchronous event processing.
Definition: event_handler.hpp:54
bool dispatch(event_base const &ev, F &&f)
Dispatch for simple_event<> based events to simple functors.
Definition: event_handler.hpp:139
A simple threaded event loop for the typesafe event system.
A threaded event loop that supports sending events and timers.
Definition: event_loop.hpp:30
The namespace used by libfilezilla.
Definition: apply.hpp:16
The duration class represents a time interval in milliseconds.
Definition: time.hpp:236
Common base class for all events.
Definition: event.hpp:21