CEventLoop.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #pragma once
  2. #include <AK/Badge.h>
  3. #include <AK/HashMap.h>
  4. #include <AK/OwnPtr.h>
  5. #include <AK/Vector.h>
  6. #include <AK/WeakPtr.h>
  7. #include <LibCore/CLock.h>
  8. #include <LibCore/CEvent.h>
  9. #include <sys/select.h>
  10. #include <sys/time.h>
  11. #include <time.h>
  12. class CObject;
  13. class CNotifier;
  14. class CEventLoop {
  15. public:
  16. CEventLoop();
  17. virtual ~CEventLoop();
  18. int exec();
  19. enum class WaitMode {
  20. WaitForEvents,
  21. PollForEvents,
  22. };
  23. // processe events, generally called by exec() in a loop.
  24. // this should really only be used for integrating with other event loops
  25. void pump(WaitMode = WaitMode::WaitForEvents);
  26. void post_event(CObject& receiver, NonnullOwnPtr<CEvent>&&);
  27. static CEventLoop& main();
  28. static CEventLoop& current();
  29. bool was_exit_requested() const { return m_exit_requested; }
  30. static int register_timer(CObject&, int milliseconds, bool should_reload);
  31. static bool unregister_timer(int timer_id);
  32. static void register_notifier(Badge<CNotifier>, CNotifier&);
  33. static void unregister_notifier(Badge<CNotifier>, CNotifier&);
  34. void quit(int);
  35. virtual void take_pending_events_from(CEventLoop& other)
  36. {
  37. m_queued_events.append(move(other.m_queued_events));
  38. }
  39. static void wake();
  40. private:
  41. void wait_for_event(WaitMode);
  42. void get_next_timer_expiration(timeval&);
  43. struct QueuedEvent {
  44. WeakPtr<CObject> receiver;
  45. NonnullOwnPtr<CEvent> event;
  46. };
  47. Vector<QueuedEvent, 64> m_queued_events;
  48. bool m_exit_requested { false };
  49. int m_exit_code { 0 };
  50. static int s_wake_pipe_fds[2];
  51. CLock m_lock;
  52. struct EventLoopTimer {
  53. int timer_id { 0 };
  54. int interval { 0 };
  55. timeval fire_time;
  56. bool should_reload { false };
  57. WeakPtr<CObject> owner;
  58. void reload(const timeval& now);
  59. bool has_expired(const timeval& now) const;
  60. };
  61. static HashMap<int, OwnPtr<EventLoopTimer>>* s_timers;
  62. static int s_next_timer_id;
  63. static HashTable<CNotifier*>* s_notifiers;
  64. };