Object.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "Object.h"
  2. #include "Event.h"
  3. #include "EventLoop.h"
  4. #include <AK/Assertions.h>
  5. #ifdef USE_SDL
  6. #include <SDL.h>
  7. #endif
  8. Object::Object(Object* parent)
  9. : m_parent(parent)
  10. {
  11. if (m_parent)
  12. m_parent->addChild(*this);
  13. }
  14. Object::~Object()
  15. {
  16. if (m_parent)
  17. m_parent->removeChild(*this);
  18. auto childrenToDelete = move(m_children);
  19. for (auto* child : childrenToDelete)
  20. delete child;
  21. }
  22. void Object::event(Event& event)
  23. {
  24. switch (event.type()) {
  25. case Event::Timer:
  26. return timerEvent(static_cast<TimerEvent&>(event));
  27. case Event::DeferredDestroy:
  28. delete this;
  29. break;
  30. case Event::Invalid:
  31. ASSERT_NOT_REACHED();
  32. break;
  33. default:
  34. break;
  35. }
  36. }
  37. void Object::addChild(Object& object)
  38. {
  39. m_children.append(&object);
  40. }
  41. void Object::removeChild(Object& object)
  42. {
  43. for (unsigned i = 0; i < m_children.size(); ++i) {
  44. if (m_children[i] == &object) {
  45. m_children.remove(i);
  46. return;
  47. }
  48. }
  49. }
  50. void Object::timerEvent(TimerEvent&)
  51. {
  52. }
  53. #ifdef USE_SDL
  54. static dword sdlTimerCallback(dword interval, void* param)
  55. {
  56. EventLoop::main().postEvent(static_cast<Object*>(param), make<TimerEvent>());
  57. return interval;
  58. }
  59. #endif
  60. void Object::startTimer(int ms)
  61. {
  62. if (m_timerID) {
  63. printf("Object{%p} already has a timer!\n", this);
  64. ASSERT_NOT_REACHED();
  65. }
  66. #ifdef USE_SDL
  67. m_timerID = SDL_AddTimer(ms, sdlTimerCallback, this);
  68. #endif
  69. }
  70. void Object::stopTimer()
  71. {
  72. if (!m_timerID)
  73. return;
  74. #ifdef USE_SDL
  75. SDL_RemoveTimer(m_timerID);
  76. #endif
  77. m_timerID = 0;
  78. }
  79. void Object::deleteLater()
  80. {
  81. EventLoop::main().postEvent(this, make<DeferredDestroyEvent>());
  82. }