CEventLoop.cpp 8.0 KB

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