GObject.cpp 1.6 KB

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