ladybird/Widgets/Object.cpp

85 lines
1.5 KiB
C++
Raw Normal View History

2018-10-10 16:12:38 +03:00
#include "Object.h"
#include "Event.h"
2018-10-12 13:18:59 +03:00
#include "EventLoop.h"
2018-10-10 16:12:38 +03:00
#include <AK/Assertions.h>
2018-10-12 13:18:59 +03:00
#ifdef USE_SDL
#include <SDL.h>
#endif
2018-10-10 16:12:38 +03:00
Object::Object(Object* parent)
: m_parent(parent)
{
2018-10-10 17:49:36 +03:00
if (m_parent)
m_parent->addChild(*this);
2018-10-10 16:12:38 +03:00
}
Object::~Object()
{
2018-10-10 17:49:36 +03:00
if (m_parent)
m_parent->removeChild(*this);
auto childrenToDelete = std::move(m_children);
for (auto* child : childrenToDelete)
2018-10-10 17:49:36 +03:00
delete child;
2018-10-10 16:12:38 +03:00
}
void Object::event(Event& event)
{
switch (event.type()) {
2018-10-12 13:18:59 +03:00
case Event::Timer:
return timerEvent(static_cast<TimerEvent&>(event));
2018-10-10 16:12:38 +03:00
case Event::Invalid:
ASSERT_NOT_REACHED();
break;
default:
break;
}
}
2018-10-10 17:49:36 +03:00
void Object::addChild(Object& object)
{
m_children.append(&object);
}
void Object::removeChild(Object& object)
{
for (unsigned i = 0; i < m_children.size(); ++i) {
if (m_children[i] == &object) {
m_children.remove(i);
return;
}
2018-10-10 17:49:36 +03:00
}
}
2018-10-12 13:18:59 +03:00
void Object::timerEvent(TimerEvent&)
2018-10-12 13:18:59 +03:00
{
}
#ifdef USE_SDL
static dword sdlTimerCallback(dword interval, void* param)
{
EventLoop::main().postEvent(static_cast<Object*>(param), make<TimerEvent>());
return interval;
}
#endif
void Object::startTimer(int ms)
{
if (m_timerID) {
printf("Object{%p} already has a timer!\n", this);
ASSERT_NOT_REACHED();
}
#if USE_SDL
m_timerID = SDL_AddTimer(ms, sdlTimerCallback, this);
#endif
}
void Object::stopTimer()
{
if (!m_timerID)
return;
SDL_RemoveTimer(m_timerID);
m_timerID = 0;
}