EventLoop.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "EventLoop.h"
  2. #include "Event.h"
  3. #include "Object.h"
  4. static EventLoop* s_mainEventLoop;
  5. EventLoop::EventLoop()
  6. {
  7. if (!s_mainEventLoop)
  8. s_mainEventLoop = this;
  9. }
  10. EventLoop::~EventLoop()
  11. {
  12. }
  13. EventLoop& EventLoop::main()
  14. {
  15. ASSERT(s_mainEventLoop);
  16. return *s_mainEventLoop;
  17. }
  18. int EventLoop::exec()
  19. {
  20. for (;;) {
  21. if (m_queuedEvents.is_empty())
  22. waitForEvent();
  23. auto events = std::move(m_queuedEvents);
  24. for (auto& queuedEvent : events) {
  25. auto* receiver = queuedEvent.receiver;
  26. auto& event = *queuedEvent.event;
  27. //printf("EventLoop: Object{%p} event %u (%s)\n", receiver, (unsigned)event.type(), event.name());
  28. if (!receiver) {
  29. switch (event.type()) {
  30. case Event::Quit:
  31. return 0;
  32. default:
  33. printf("event type %u with no receiver :(\n", event.type());
  34. return 1;
  35. }
  36. } else {
  37. receiver->event(event);
  38. }
  39. }
  40. }
  41. }
  42. void EventLoop::postEvent(Object* receiver, OwnPtr<Event>&& event)
  43. {
  44. m_queuedEvents.append({ receiver, std::move(event) });
  45. }