CEventLoop.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 <sys/select.h>
  8. #include <time.h>
  9. class CEvent;
  10. class CObject;
  11. class CNotifier;
  12. class CEventLoop {
  13. public:
  14. CEventLoop();
  15. virtual ~CEventLoop();
  16. int exec();
  17. void post_event(CObject& receiver, OwnPtr<CEvent>&&);
  18. static CEventLoop& main();
  19. static CEventLoop& current();
  20. bool running() const { return m_running; }
  21. static int register_timer(CObject&, int milliseconds, bool should_reload);
  22. static bool unregister_timer(int timer_id);
  23. static void register_notifier(Badge<CNotifier>, CNotifier&);
  24. static void unregister_notifier(Badge<CNotifier>, CNotifier&);
  25. void quit(int);
  26. virtual void take_pending_events_from(CEventLoop& other)
  27. {
  28. m_queued_events.append(move(other.m_queued_events));
  29. }
  30. protected:
  31. virtual void add_file_descriptors_for_select(fd_set&, int& max_fd) { UNUSED_PARAM(max_fd); }
  32. virtual void process_file_descriptors_after_select(const fd_set&) { }
  33. virtual void do_processing() { }
  34. private:
  35. void wait_for_event();
  36. void get_next_timer_expiration(timeval&);
  37. struct QueuedEvent {
  38. WeakPtr<CObject> receiver;
  39. OwnPtr<CEvent> event;
  40. };
  41. Vector<QueuedEvent, 64> m_queued_events;
  42. bool m_running { false };
  43. bool m_exit_requested { false };
  44. int m_exit_code { 0 };
  45. struct EventLoopTimer {
  46. int timer_id { 0 };
  47. int interval { 0 };
  48. timeval fire_time;
  49. bool should_reload { false };
  50. WeakPtr<CObject> owner;
  51. void reload(const timeval& now);
  52. bool has_expired(const timeval& now) const;
  53. };
  54. static HashMap<int, OwnPtr<EventLoopTimer>>* s_timers;
  55. static int s_next_timer_id;
  56. static HashTable<CNotifier*>* s_notifiers;
  57. };