CEventLoop.h 2.1 KB

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