GEventLoop.cpp 13 KB

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