GEventLoop.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #include "GEventLoop.h"
  2. #include "GEvent.h"
  3. #include "GObject.h"
  4. #include "GWindow.h"
  5. #include <LibGUI/GAction.h>
  6. #include <LibGUI/GNotifier.h>
  7. #include <LibGUI/GMenu.h>
  8. #include <LibC/unistd.h>
  9. #include <LibC/stdio.h>
  10. #include <LibC/fcntl.h>
  11. #include <LibC/string.h>
  12. #include <LibC/time.h>
  13. #include <LibC/sys/select.h>
  14. #include <LibC/gui.h>
  15. #include <errno.h>
  16. #include <string.h>
  17. //#define GEVENTLOOP_DEBUG
  18. static GEventLoop* s_mainGEventLoop;
  19. void GEventLoop::initialize()
  20. {
  21. s_mainGEventLoop = nullptr;
  22. }
  23. GEventLoop::GEventLoop()
  24. {
  25. if (!s_mainGEventLoop)
  26. s_mainGEventLoop = this;
  27. m_event_fd = open("/dev/gui_events", O_RDWR | O_NONBLOCK | O_CLOEXEC);
  28. if (m_event_fd < 0) {
  29. perror("GEventLoop(): open");
  30. exit(1);
  31. }
  32. }
  33. GEventLoop::~GEventLoop()
  34. {
  35. }
  36. GEventLoop& GEventLoop::main()
  37. {
  38. ASSERT(s_mainGEventLoop);
  39. return *s_mainGEventLoop;
  40. }
  41. void GEventLoop::exit(int code)
  42. {
  43. m_exit_requested = true;
  44. m_exit_code = code;
  45. }
  46. int GEventLoop::exec()
  47. {
  48. m_running = true;
  49. for (;;) {
  50. if (m_exit_requested)
  51. return m_exit_code;
  52. if (m_queued_events.is_empty())
  53. wait_for_event();
  54. Vector<QueuedEvent> events = move(m_queued_events);
  55. for (auto& queued_event : events) {
  56. auto* receiver = queued_event.receiver;
  57. auto& event = *queued_event.event;
  58. #ifdef GEVENTLOOP_DEBUG
  59. dbgprintf("GEventLoop: %s{%p} event %u\n", receiver->class_name(), receiver, (unsigned)event.type());
  60. #endif
  61. if (!receiver) {
  62. switch (event.type()) {
  63. case GEvent::Quit:
  64. ASSERT_NOT_REACHED();
  65. return 0;
  66. default:
  67. dbgprintf("event type %u with no receiver :(\n", event.type());
  68. ASSERT_NOT_REACHED();
  69. return 1;
  70. }
  71. } else {
  72. receiver->event(event);
  73. }
  74. }
  75. }
  76. ASSERT_NOT_REACHED();
  77. }
  78. void GEventLoop::post_event(GObject* receiver, OwnPtr<GEvent>&& event)
  79. {
  80. #ifdef GEVENTLOOP_DEBUG
  81. dbgprintf("GEventLoop::post_event: {%u} << receiver=%p, event=%p\n", m_queued_events.size(), receiver, event.ptr());
  82. #endif
  83. m_queued_events.append({ receiver, move(event) });
  84. }
  85. void GEventLoop::handle_paint_event(const GUI_Event& event, GWindow& window)
  86. {
  87. #ifdef GEVENTLOOP_DEBUG
  88. dbgprintf("WID=%x Paint [%d,%d %dx%d]\n", event.window_id, event.paint.rect.location.x, event.paint.rect.location.y, event.paint.rect.size.width, event.paint.rect.size.height);
  89. #endif
  90. post_event(&window, make<GPaintEvent>(event.paint.rect));
  91. }
  92. void GEventLoop::handle_window_activation_event(const GUI_Event& event, GWindow& window)
  93. {
  94. #ifdef GEVENTLOOP_DEBUG
  95. dbgprintf("WID=%x WindowActivation\n", event.window_id);
  96. #endif
  97. post_event(&window, make<GEvent>(event.type == GUI_Event::Type::WindowActivated ? GEvent::WindowBecameActive : GEvent::WindowBecameInactive));
  98. }
  99. void GEventLoop::handle_window_close_request_event(const GUI_Event&, GWindow& window)
  100. {
  101. post_event(&window, make<GEvent>(GEvent::WindowCloseRequest));
  102. }
  103. void GEventLoop::handle_key_event(const GUI_Event& event, GWindow& window)
  104. {
  105. #ifdef GEVENTLOOP_DEBUG
  106. dbgprintf("WID=%x KeyEvent character=0x%b\n", event.window_id, event.key.character);
  107. #endif
  108. auto key_event = make<GKeyEvent>(event.type == GUI_Event::Type::KeyDown ? GEvent::KeyDown : GEvent::KeyUp, event.key.key);
  109. key_event->m_alt = event.key.alt;
  110. key_event->m_ctrl = event.key.ctrl;
  111. key_event->m_shift = event.key.shift;
  112. if (event.key.character != '\0')
  113. key_event->m_text = String(&event.key.character, 1);
  114. post_event(&window, move(key_event));
  115. }
  116. void GEventLoop::handle_mouse_event(const GUI_Event& event, GWindow& window)
  117. {
  118. #ifdef GEVENTLOOP_DEBUG
  119. dbgprintf("WID=%x MouseEvent %d,%d\n", event.window_id, event.mouse.position.x, event.mouse.position.y);
  120. #endif
  121. GMouseEvent::Type type;
  122. switch (event.type) {
  123. case GUI_Event::Type::MouseMove: type = GEvent::MouseMove; break;
  124. case GUI_Event::Type::MouseUp: type = GEvent::MouseUp; break;
  125. case GUI_Event::Type::MouseDown: type = GEvent::MouseDown; break;
  126. default: ASSERT_NOT_REACHED(); break;
  127. }
  128. GMouseButton button { GMouseButton::None };
  129. switch (event.mouse.button) {
  130. case GUI_MouseButton::NoButton: button = GMouseButton::None; break;
  131. case GUI_MouseButton::Left: button = GMouseButton::Left; break;
  132. case GUI_MouseButton::Right: button = GMouseButton::Right; break;
  133. case GUI_MouseButton::Middle: button = GMouseButton::Middle; break;
  134. default: ASSERT_NOT_REACHED(); break;
  135. }
  136. post_event(&window, make<GMouseEvent>(type, event.mouse.position, event.mouse.buttons, button));
  137. }
  138. void GEventLoop::handle_menu_event(const GUI_Event& event)
  139. {
  140. if (event.type == GUI_Event::Type::MenuItemActivated) {
  141. auto* menu = GMenu::from_menu_id(event.menu.menu_id);
  142. if (!menu) {
  143. dbgprintf("GEventLoop received event for invalid window ID %d\n", event.window_id);
  144. return;
  145. }
  146. if (auto* action = menu->action_at(event.menu.identifier))
  147. action->activate();
  148. return;
  149. }
  150. ASSERT_NOT_REACHED();
  151. }
  152. void GEventLoop::wait_for_event()
  153. {
  154. fd_set rfds;
  155. fd_set wfds;
  156. FD_ZERO(&rfds);
  157. FD_ZERO(&wfds);
  158. int max_fd = 0;
  159. auto add_fd_to_set = [&max_fd] (int fd, fd_set& set){
  160. FD_SET(fd, &set);
  161. if (fd > max_fd)
  162. max_fd = fd;
  163. };
  164. add_fd_to_set(m_event_fd, rfds);
  165. for (auto& notifier : m_notifiers) {
  166. if (notifier->event_mask() & GNotifier::Read)
  167. add_fd_to_set(notifier->fd(), rfds);
  168. if (notifier->event_mask() & GNotifier::Write)
  169. add_fd_to_set(notifier->fd(), wfds);
  170. if (notifier->event_mask() & GNotifier::Exceptional)
  171. ASSERT_NOT_REACHED();
  172. }
  173. struct timeval timeout = { 0, 0 };
  174. if (!m_timers.is_empty())
  175. get_next_timer_expiration(timeout);
  176. int rc = select(max_fd + 1, &rfds, &wfds, nullptr, (m_queued_events.is_empty() && m_timers.is_empty()) ? nullptr : &timeout);
  177. if (rc < 0) {
  178. ASSERT_NOT_REACHED();
  179. }
  180. for (auto& it : m_timers) {
  181. auto& timer = *it.value;
  182. if (!timer.has_expired())
  183. continue;
  184. #ifdef GEVENTLOOP_DEBUG
  185. dbgprintf("GEventLoop: Timer %d has expired, sending GTimerEvent to %p\n", timer.timer_id, timer.owner);
  186. #endif
  187. post_event(timer.owner, make<GTimerEvent>(timer.timer_id));
  188. if (timer.should_reload) {
  189. timer.reload();
  190. } else {
  191. // FIXME: Support removing expired timers that don't want to reload.
  192. ASSERT_NOT_REACHED();
  193. }
  194. }
  195. for (auto& notifier : m_notifiers) {
  196. if (FD_ISSET(notifier->fd(), &rfds)) {
  197. if (notifier->on_ready_to_read)
  198. notifier->on_ready_to_read(*notifier);
  199. }
  200. if (FD_ISSET(notifier->fd(), &wfds)) {
  201. if (notifier->on_ready_to_write)
  202. notifier->on_ready_to_write(*notifier);
  203. }
  204. }
  205. if (!FD_ISSET(m_event_fd, &rfds))
  206. return;
  207. bool success = drain_events_from_server();
  208. ASSERT(success);
  209. auto unprocessed_events = move(m_unprocessed_events);
  210. for (auto& event : unprocessed_events) {
  211. switch (event.type) {
  212. case GUI_Event::MenuItemActivated:
  213. handle_menu_event(event);
  214. continue;
  215. default:
  216. break;
  217. }
  218. auto* window = GWindow::from_window_id(event.window_id);
  219. if (!window) {
  220. dbgprintf("GEventLoop received event for invalid window ID %d\n", event.window_id);
  221. continue;
  222. }
  223. switch (event.type) {
  224. case GUI_Event::Type::Paint:
  225. handle_paint_event(event, *window);
  226. break;
  227. case GUI_Event::Type::MouseDown:
  228. case GUI_Event::Type::MouseUp:
  229. case GUI_Event::Type::MouseMove:
  230. handle_mouse_event(event, *window);
  231. break;
  232. case GUI_Event::Type::WindowActivated:
  233. case GUI_Event::Type::WindowDeactivated:
  234. handle_window_activation_event(event, *window);
  235. break;
  236. case GUI_Event::Type::WindowCloseRequest:
  237. handle_window_close_request_event(event, *window);
  238. break;
  239. case GUI_Event::Type::KeyDown:
  240. case GUI_Event::Type::KeyUp:
  241. handle_key_event(event, *window);
  242. break;
  243. default:
  244. break;
  245. }
  246. }
  247. }
  248. bool GEventLoop::drain_events_from_server()
  249. {
  250. for (;;) {
  251. GUI_Event event;
  252. ssize_t nread = read(m_event_fd, &event, sizeof(GUI_Event));
  253. if (nread < 0) {
  254. perror("read");
  255. exit(1);
  256. return false;
  257. }
  258. if (nread == 0)
  259. return true;
  260. assert(nread == sizeof(event));
  261. m_unprocessed_events.append(move(event));
  262. }
  263. }
  264. bool GEventLoop::EventLoopTimer::has_expired() const
  265. {
  266. timeval now;
  267. gettimeofday(&now, nullptr);
  268. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  269. }
  270. void GEventLoop::EventLoopTimer::reload()
  271. {
  272. gettimeofday(&fire_time, nullptr);
  273. fire_time.tv_sec += interval / 1000;
  274. fire_time.tv_usec += interval % 1000;
  275. }
  276. void GEventLoop::get_next_timer_expiration(timeval& soonest)
  277. {
  278. ASSERT(!m_timers.is_empty());
  279. bool has_checked_any = false;
  280. for (auto& it : m_timers) {
  281. auto& fire_time = it.value->fire_time;
  282. 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))
  283. soonest = fire_time;
  284. has_checked_any = true;
  285. }
  286. }
  287. int GEventLoop::register_timer(GObject& object, int milliseconds, bool should_reload)
  288. {
  289. ASSERT(milliseconds >= 0);
  290. auto timer = make<EventLoopTimer>();
  291. timer->owner = &object;
  292. timer->interval = milliseconds;
  293. timer->reload();
  294. timer->should_reload = should_reload;
  295. int timer_id = ++m_next_timer_id; // FIXME: This will eventually wrap around.
  296. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  297. timer->timer_id = timer_id;
  298. m_timers.set(timer->timer_id, move(timer));
  299. return timer_id;
  300. }
  301. bool GEventLoop::unregister_timer(int timer_id)
  302. {
  303. auto it = m_timers.find(timer_id);
  304. if (it == m_timers.end())
  305. return false;
  306. m_timers.remove(it);
  307. return true;
  308. }
  309. void GEventLoop::register_notifier(Badge<GNotifier>, GNotifier& notifier)
  310. {
  311. m_notifiers.set(&notifier);
  312. }
  313. void GEventLoop::unregister_notifier(Badge<GNotifier>, GNotifier& notifier)
  314. {
  315. m_notifiers.remove(&notifier);
  316. }
  317. bool GEventLoop::post_message_to_server(const GUI_ClientMessage& message)
  318. {
  319. int nwritten = write(m_event_fd, &message, sizeof(GUI_ClientMessage));
  320. return nwritten == sizeof(GUI_ClientMessage);
  321. }
  322. bool GEventLoop::wait_for_specific_event(GUI_Event::Type type, GUI_Event& event)
  323. {
  324. for (;;) {
  325. bool success = drain_events_from_server();
  326. if (!success)
  327. return false;
  328. for (size_t i = 0; i < m_unprocessed_events.size(); ++i) {
  329. if (m_unprocessed_events[i].type == type) {
  330. event = move(m_unprocessed_events[i]);
  331. m_unprocessed_events.remove(i);
  332. return true;
  333. }
  334. }
  335. }
  336. }
  337. GUI_Event GEventLoop::sync_request(const GUI_ClientMessage& request, GUI_Event::Type response_type)
  338. {
  339. bool success = post_message_to_server(request);
  340. ASSERT(success);
  341. GUI_Event response;
  342. success = GEventLoop::main().wait_for_specific_event(response_type, response);
  343. ASSERT(success);
  344. return response;
  345. }