GObject.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "GObject.h"
  2. #include "GEvent.h"
  3. #include "GEventLoop.h"
  4. #include <AK/Assertions.h>
  5. GObject::GObject(GObject* parent)
  6. : m_parent(parent)
  7. {
  8. if (m_parent)
  9. m_parent->add_child(*this);
  10. }
  11. GObject::~GObject()
  12. {
  13. stop_timer();
  14. if (m_parent)
  15. m_parent->remove_child(*this);
  16. auto children_to_delete = move(m_children);
  17. for (auto* child : children_to_delete)
  18. delete child;
  19. }
  20. void GObject::event(GEvent& event)
  21. {
  22. switch (event.type()) {
  23. case GEvent::Timer:
  24. return timer_event(static_cast<GTimerEvent&>(event));
  25. case GEvent::DeferredDestroy:
  26. delete this;
  27. break;
  28. case GEvent::Invalid:
  29. ASSERT_NOT_REACHED();
  30. break;
  31. default:
  32. break;
  33. }
  34. }
  35. void GObject::add_child(GObject& object)
  36. {
  37. m_children.append(&object);
  38. }
  39. void GObject::remove_child(GObject& object)
  40. {
  41. for (unsigned i = 0; i < m_children.size(); ++i) {
  42. if (m_children[i] == &object) {
  43. m_children.remove(i);
  44. return;
  45. }
  46. }
  47. }
  48. void GObject::timer_event(GTimerEvent&)
  49. {
  50. }
  51. void GObject::start_timer(int ms)
  52. {
  53. if (m_timer_id) {
  54. dbgprintf("GObject{%p} already has a timer!\n", this);
  55. ASSERT_NOT_REACHED();
  56. }
  57. m_timer_id = GEventLoop::main().register_timer(*this, ms, true);
  58. }
  59. void GObject::stop_timer()
  60. {
  61. if (!m_timer_id)
  62. return;
  63. bool success = GEventLoop::main().unregister_timer(m_timer_id);
  64. ASSERT(success);
  65. m_timer_id = 0;
  66. }
  67. void GObject::delete_later()
  68. {
  69. GEventLoop::main().post_event(this, make<GEvent>(GEvent::DeferredDestroy));
  70. }