TermOx
event_loop.hpp
1 #ifndef TERMOX_SYSTEM_EVENT_LOOP_HPP
2 #define TERMOX_SYSTEM_EVENT_LOOP_HPP
3 #include <atomic>
4 #include <cassert>
5 #include <future>
6 #include <utility>
7 
8 #include <termox/system/event_queue.hpp>
9 
10 namespace ox {
11 
13 
17 class Event_loop {
18  public:
20 
22  template <typename F>
23  auto run(F loop_function) -> int
24  {
25  if (running_)
26  return -1;
27  running_ = true;
28  if (!exit_)
29  queue_.send_all();
30  while (!exit_) {
31  loop_function(queue_);
32  queue_.send_all();
33  }
34  running_ = false;
35  exit_ = false;
36  return return_code_;
37  }
38 
40 
42  template <typename F>
43  void run_async(F&& loop_function)
44  {
45  if (fut_.valid())
46  return;
47  fut_ = std::async(std::launch::async, [this, loop_function] {
48  return this->run(std::move(loop_function));
49  });
50  assert(fut_.valid());
51  }
52 
54 
59  void exit(int return_code);
60 
62 
64  // wait, then if valid, get it
65  auto wait() -> int;
66 
68  [[nodiscard]] auto is_running() const -> bool;
69 
71  [[nodiscard]] auto exit_flag() const -> bool;
72 
74  [[nodiscard]] auto event_queue() -> Event_queue&;
75 
77  [[nodiscard]] auto event_queue() const -> Event_queue const&;
78 
79  private:
80  std::future<int> fut_;
81  int return_code_ = 0;
82  std::atomic<bool> running_ = false;
83  std::atomic<bool> exit_ = false;
84  Event_queue queue_;
85 };
86 
87 } // namespace ox
88 #endif // TERMOX_SYSTEM_EVENT_LOOP_HPP
Calls on loop_function(), and then processes the Event_queue.
Definition: event_loop.hpp:17
auto run(F loop_function) -> int
Start the event loop, calling loop_function on each iteration.
Definition: event_loop.hpp:23
void run_async(F &&loop_function)
Start the event loop in a separate thread.
Definition: event_loop.hpp:43
auto exit_flag() const -> bool
Return true if the exit flag has been set.
Definition: event_loop.cpp:20
auto event_queue() -> Event_queue &
Return a reference to the Event_queue of this loop.
Definition: event_loop.cpp:22
auto wait() -> int
Block until the async event loop returns.
Definition: event_loop.cpp:11
auto is_running() const -> bool
Return true if the event loop is currently running.
Definition: event_loop.cpp:18
void exit(int return_code)
Call on the loop to exit at the next exit point.
Definition: event_loop.cpp:5
Definition: event_queue.hpp:63
void send_all()
Send all events, then flush the screen if any events were actually sent.
Definition: event_queue.cpp:84