CEventLoop.cpp 7.6 KB

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