EventLoop.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Forward.h>
  8. #include <AK/Function.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/Noncopyable.h>
  11. #include <AK/NonnullOwnPtr.h>
  12. #include <AK/Vector.h>
  13. #include <AK/WeakPtr.h>
  14. #include <LibCore/Forward.h>
  15. #include <sys/time.h>
  16. #include <sys/types.h>
  17. namespace Core {
  18. class EventLoop {
  19. public:
  20. enum class MakeInspectable {
  21. No,
  22. Yes,
  23. };
  24. explicit EventLoop(MakeInspectable = MakeInspectable::No);
  25. ~EventLoop();
  26. int exec();
  27. enum class WaitMode {
  28. WaitForEvents,
  29. PollForEvents,
  30. };
  31. // processe events, generally called by exec() in a loop.
  32. // this should really only be used for integrating with other event loops
  33. void pump(WaitMode = WaitMode::WaitForEvents);
  34. void post_event(Object& receiver, NonnullOwnPtr<Event>&&);
  35. static EventLoop& main();
  36. static EventLoop& current();
  37. bool was_exit_requested() const { return m_exit_requested; }
  38. static int register_timer(Object&, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible);
  39. static bool unregister_timer(int timer_id);
  40. static void register_notifier(Badge<Notifier>, Notifier&);
  41. static void unregister_notifier(Badge<Notifier>, Notifier&);
  42. void quit(int);
  43. void unquit();
  44. void take_pending_events_from(EventLoop& other)
  45. {
  46. m_queued_events.extend(move(other.m_queued_events));
  47. }
  48. static void wake();
  49. static int register_signal(int signo, Function<void(int)> handler);
  50. static void unregister_signal(int handler_id);
  51. // Note: Boost uses Parent/Child/Prepare, but we don't really have anything
  52. // interesting to do in the parent or before forking.
  53. enum class ForkEvent {
  54. Child,
  55. };
  56. static void notify_forked(ForkEvent);
  57. private:
  58. void wait_for_event(WaitMode);
  59. Optional<struct timeval> get_next_timer_expiration();
  60. static void dispatch_signal(int);
  61. static void handle_signal(int);
  62. struct QueuedEvent {
  63. AK_MAKE_NONCOPYABLE(QueuedEvent);
  64. public:
  65. QueuedEvent(Object& receiver, NonnullOwnPtr<Event>);
  66. QueuedEvent(QueuedEvent&&);
  67. ~QueuedEvent();
  68. WeakPtr<Object> receiver;
  69. NonnullOwnPtr<Event> event;
  70. };
  71. Vector<QueuedEvent, 64> m_queued_events;
  72. static pid_t s_pid;
  73. bool m_exit_requested { false };
  74. int m_exit_code { 0 };
  75. static int s_wake_pipe_fds[2];
  76. struct Private;
  77. NonnullOwnPtr<Private> m_private;
  78. };
  79. }