CEventLoop.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. }
  127. }
  128. }
  129. void CEventLoop::post_event(CObject& receiver, OwnPtr<CEvent>&& event)
  130. {
  131. LOCKER(m_lock);
  132. #ifdef CEVENTLOOP_DEBUG
  133. dbgprintf("CEventLoop::post_event: {%u} << receiver=%p, event=%p\n", m_queued_events.size(), &receiver, event.ptr());
  134. #endif
  135. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  136. }
  137. void CEventLoop::wait_for_event(WaitMode mode)
  138. {
  139. fd_set rfds;
  140. fd_set wfds;
  141. FD_ZERO(&rfds);
  142. FD_ZERO(&wfds);
  143. int max_fd = 0;
  144. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  145. FD_SET(fd, &set);
  146. if (fd > max_fd)
  147. max_fd = fd;
  148. };
  149. int max_fd_added = -1;
  150. add_file_descriptors_for_select(rfds, max_fd_added);
  151. max_fd = max(max_fd, max_fd_added);
  152. for (auto& notifier : *s_notifiers) {
  153. if (notifier->event_mask() & CNotifier::Read)
  154. add_fd_to_set(notifier->fd(), rfds);
  155. if (notifier->event_mask() & CNotifier::Write)
  156. add_fd_to_set(notifier->fd(), wfds);
  157. if (notifier->event_mask() & CNotifier::Exceptional)
  158. ASSERT_NOT_REACHED();
  159. }
  160. bool queued_events_is_empty;
  161. {
  162. LOCKER(m_lock);
  163. queued_events_is_empty = m_queued_events.is_empty();
  164. }
  165. timeval now;
  166. struct timeval timeout = { 0, 0 };
  167. bool should_wait_forever = false;
  168. if (mode == WaitMode::WaitForEvents) {
  169. if (!s_timers->is_empty() && queued_events_is_empty) {
  170. gettimeofday(&now, nullptr);
  171. get_next_timer_expiration(timeout);
  172. timeval_sub(timeout, now, timeout);
  173. } else {
  174. should_wait_forever = true;
  175. }
  176. } else {
  177. should_wait_forever = false;
  178. }
  179. int marked_fd_count = select(max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  180. if (marked_fd_count < 0) {
  181. ASSERT_NOT_REACHED();
  182. }
  183. if (!s_timers->is_empty()) {
  184. gettimeofday(&now, nullptr);
  185. }
  186. for (auto& it : *s_timers) {
  187. auto& timer = *it.value;
  188. if (!timer.has_expired(now))
  189. continue;
  190. #ifdef CEVENTLOOP_DEBUG
  191. dbgprintf("CEventLoop: Timer %d has expired, sending CTimerEvent to %p\n", timer.timer_id, timer.owner);
  192. #endif
  193. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  194. if (timer.should_reload) {
  195. timer.reload(now);
  196. } else {
  197. // FIXME: Support removing expired timers that don't want to reload.
  198. ASSERT_NOT_REACHED();
  199. }
  200. }
  201. if (!marked_fd_count)
  202. return;
  203. for (auto& notifier : *s_notifiers) {
  204. if (FD_ISSET(notifier->fd(), &rfds)) {
  205. if (notifier->on_ready_to_read)
  206. notifier->on_ready_to_read();
  207. }
  208. if (FD_ISSET(notifier->fd(), &wfds)) {
  209. if (notifier->on_ready_to_write)
  210. notifier->on_ready_to_write();
  211. }
  212. }
  213. process_file_descriptors_after_select(rfds);
  214. }
  215. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  216. {
  217. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  218. }
  219. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  220. {
  221. fire_time = now;
  222. fire_time.tv_sec += interval / 1000;
  223. fire_time.tv_usec += (interval % 1000) * 1000;
  224. }
  225. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  226. {
  227. ASSERT(!s_timers->is_empty());
  228. bool has_checked_any = false;
  229. for (auto& it : *s_timers) {
  230. auto& fire_time = it.value->fire_time;
  231. 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))
  232. soonest = fire_time;
  233. has_checked_any = true;
  234. }
  235. }
  236. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  237. {
  238. ASSERT(milliseconds >= 0);
  239. auto timer = make<EventLoopTimer>();
  240. timer->owner = object.make_weak_ptr();
  241. timer->interval = milliseconds;
  242. timeval now;
  243. gettimeofday(&now, nullptr);
  244. timer->reload(now);
  245. timer->should_reload = should_reload;
  246. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  247. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  248. timer->timer_id = timer_id;
  249. s_timers->set(timer->timer_id, move(timer));
  250. return timer_id;
  251. }
  252. bool CEventLoop::unregister_timer(int timer_id)
  253. {
  254. auto it = s_timers->find(timer_id);
  255. if (it == s_timers->end())
  256. return false;
  257. s_timers->remove(it);
  258. return true;
  259. }
  260. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  261. {
  262. s_notifiers->set(&notifier);
  263. }
  264. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  265. {
  266. s_notifiers->remove(&notifier);
  267. }