CEventLoop.cpp 8.2 KB

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