GEventLoop.cpp 14 KB

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