CEventLoop.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #include <LibCore/CObject.h>
  2. #include <LibCore/CEventLoop.h>
  3. #include <LibCore/CEvent.h>
  4. #include <LibCore/CNotifier.h>
  5. #include <LibC/unistd.h>
  6. #include <LibC/stdio.h>
  7. #include <LibC/fcntl.h>
  8. #include <LibC/string.h>
  9. #include <LibC/time.h>
  10. #include <LibC/sys/select.h>
  11. #include <LibC/sys/socket.h>
  12. #include <LibC/sys/time.h>
  13. #include <LibC/errno.h>
  14. #include <LibC/string.h>
  15. #include <LibC/stdlib.h>
  16. //#define CEVENTLOOP_DEBUG
  17. //#define DEFERRED_INVOKE_DEBUG
  18. static CEventLoop* s_main_event_loop;
  19. static Vector<CEventLoop*>* s_event_loop_stack;
  20. HashMap<int, OwnPtr<CEventLoop::EventLoopTimer>>* CEventLoop::s_timers;
  21. HashTable<CNotifier*>* CEventLoop::s_notifiers;
  22. int CEventLoop::s_next_timer_id = 1;
  23. CEventLoop::CEventLoop()
  24. {
  25. if (!s_event_loop_stack) {
  26. s_event_loop_stack = new Vector<CEventLoop*>;
  27. s_timers = new HashMap<int, OwnPtr<CEventLoop::EventLoopTimer>>;
  28. s_notifiers = new HashTable<CNotifier*>;
  29. }
  30. if (!s_main_event_loop) {
  31. s_main_event_loop = this;
  32. s_event_loop_stack->append(this);
  33. }
  34. #ifdef CEVENTLOOP_DEBUG
  35. dbgprintf("(%u) CEventLoop constructed :)\n", getpid());
  36. #endif
  37. }
  38. CEventLoop::~CEventLoop()
  39. {
  40. }
  41. CEventLoop& CEventLoop::main()
  42. {
  43. ASSERT(s_main_event_loop);
  44. return *s_main_event_loop;
  45. }
  46. CEventLoop& CEventLoop::current()
  47. {
  48. return *s_event_loop_stack->last();
  49. }
  50. void CEventLoop::quit(int code)
  51. {
  52. m_exit_requested = true;
  53. m_exit_code = code;
  54. }
  55. struct CEventLoopPusher {
  56. public:
  57. CEventLoopPusher(CEventLoop& event_loop) : m_event_loop(event_loop)
  58. {
  59. if (&m_event_loop != s_main_event_loop) {
  60. m_event_loop.take_pending_events_from(CEventLoop::current());
  61. s_event_loop_stack->append(&event_loop);
  62. }
  63. }
  64. ~CEventLoopPusher()
  65. {
  66. if (&m_event_loop != s_main_event_loop) {
  67. s_event_loop_stack->take_last();
  68. CEventLoop::current().take_pending_events_from(m_event_loop);
  69. }
  70. }
  71. private:
  72. CEventLoop& m_event_loop;
  73. };
  74. int CEventLoop::exec()
  75. {
  76. CEventLoopPusher pusher(*this);
  77. m_running = true;
  78. for (;;) {
  79. if (m_exit_requested)
  80. return m_exit_code;
  81. do_processing();
  82. if (m_queued_events.is_empty()) {
  83. wait_for_event();
  84. do_processing();
  85. }
  86. auto events = move(m_queued_events);
  87. for (auto& queued_event : events) {
  88. auto* receiver = queued_event.receiver.ptr();
  89. auto& event = *queued_event.event;
  90. #ifdef CEVENTLOOP_DEBUG
  91. dbgprintf("CEventLoop: %s{%p} event %u\n", receiver->class_name(), receiver, (unsigned)event.type());
  92. #endif
  93. if (!receiver) {
  94. switch (event.type()) {
  95. case CEvent::Quit:
  96. ASSERT_NOT_REACHED();
  97. return 0;
  98. default:
  99. dbgprintf("Event type %u with no receiver :(\n", event.type());
  100. }
  101. } else if (event.type() == CEvent::Type::DeferredInvoke) {
  102. #ifdef DEFERRED_INVOKE_DEBUG
  103. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  104. #endif
  105. static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver);
  106. } else {
  107. receiver->event(event);
  108. }
  109. if (m_exit_requested) {
  110. auto rejigged_event_queue = move(events);
  111. rejigged_event_queue.append(move(m_queued_events));
  112. m_queued_events = move(rejigged_event_queue);
  113. return m_exit_code;
  114. }
  115. }
  116. }
  117. ASSERT_NOT_REACHED();
  118. }
  119. void CEventLoop::post_event(CObject& receiver, OwnPtr<CEvent>&& event)
  120. {
  121. #ifdef CEVENTLOOP_DEBUG
  122. dbgprintf("CEventLoop::post_event: {%u} << receiver=%p, event=%p\n", m_queued_events.size(), &receiver, event.ptr());
  123. #endif
  124. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  125. }
  126. void CEventLoop::wait_for_event()
  127. {
  128. fd_set rfds;
  129. fd_set wfds;
  130. FD_ZERO(&rfds);
  131. FD_ZERO(&wfds);
  132. int max_fd = 0;
  133. auto add_fd_to_set = [&max_fd] (int fd, fd_set& set){
  134. FD_SET(fd, &set);
  135. if (fd > max_fd)
  136. max_fd = fd;
  137. };
  138. int max_fd_added = -1;
  139. add_file_descriptors_for_select(rfds, max_fd_added);
  140. max_fd = max(max_fd, max_fd_added);
  141. for (auto& notifier : *s_notifiers) {
  142. if (notifier->event_mask() & CNotifier::Read)
  143. add_fd_to_set(notifier->fd(), rfds);
  144. if (notifier->event_mask() & CNotifier::Write)
  145. add_fd_to_set(notifier->fd(), wfds);
  146. if (notifier->event_mask() & CNotifier::Exceptional)
  147. ASSERT_NOT_REACHED();
  148. }
  149. struct timeval timeout = { 0, 0 };
  150. if (!s_timers->is_empty() && m_queued_events.is_empty())
  151. get_next_timer_expiration(timeout);
  152. int rc = select(max_fd + 1, &rfds, &wfds, nullptr, (m_queued_events.is_empty() && s_timers->is_empty()) ? nullptr : &timeout);
  153. if (rc < 0) {
  154. ASSERT_NOT_REACHED();
  155. }
  156. timeval now;
  157. if (!s_timers->is_empty())
  158. gettimeofday(&now, nullptr);
  159. for (auto& it : *s_timers) {
  160. auto& timer = *it.value;
  161. if (!timer.has_expired(now))
  162. continue;
  163. #ifdef CEVENTLOOP_DEBUG
  164. dbgprintf("CEventLoop: Timer %d has expired, sending CTimerEvent to %p\n", timer.timer_id, timer.owner);
  165. #endif
  166. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  167. if (timer.should_reload) {
  168. timer.reload(now);
  169. } else {
  170. // FIXME: Support removing expired timers that don't want to reload.
  171. ASSERT_NOT_REACHED();
  172. }
  173. }
  174. for (auto& notifier : *s_notifiers) {
  175. if (FD_ISSET(notifier->fd(), &rfds)) {
  176. if (notifier->on_ready_to_read)
  177. notifier->on_ready_to_read();
  178. }
  179. if (FD_ISSET(notifier->fd(), &wfds)) {
  180. if (notifier->on_ready_to_write)
  181. notifier->on_ready_to_write();
  182. }
  183. }
  184. process_file_descriptors_after_select(rfds);
  185. }
  186. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  187. {
  188. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  189. }
  190. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  191. {
  192. fire_time = now;
  193. fire_time.tv_sec += interval / 1000;
  194. fire_time.tv_usec += (interval % 1000) * 1000;
  195. }
  196. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  197. {
  198. ASSERT(!s_timers->is_empty());
  199. bool has_checked_any = false;
  200. for (auto& it : *s_timers) {
  201. auto& fire_time = it.value->fire_time;
  202. if (!has_checked_any || fire_time.tv_sec < soonest.tv_sec || (fire_time.tv_sec == soonest.tv_sec && fire_time.tv_usec < soonest.tv_usec))
  203. soonest = fire_time;
  204. has_checked_any = true;
  205. }
  206. }
  207. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  208. {
  209. ASSERT(milliseconds >= 0);
  210. auto timer = make<EventLoopTimer>();
  211. timer->owner = object.make_weak_ptr();
  212. timer->interval = milliseconds;
  213. timeval now;
  214. gettimeofday(&now, nullptr);
  215. timer->reload(now);
  216. timer->should_reload = should_reload;
  217. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  218. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  219. timer->timer_id = timer_id;
  220. s_timers->set(timer->timer_id, move(timer));
  221. return timer_id;
  222. }
  223. bool CEventLoop::unregister_timer(int timer_id)
  224. {
  225. auto it = s_timers->find(timer_id);
  226. if (it == s_timers->end())
  227. return false;
  228. s_timers->remove(it);
  229. return true;
  230. }
  231. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  232. {
  233. s_notifiers->set(&notifier);
  234. }
  235. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  236. {
  237. s_notifiers->remove(&notifier);
  238. }