CEventLoop.cpp 8.9 KB

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