ladybird/LibGUI/GObject.cpp

91 lines
1.9 KiB
C++
Raw Normal View History

#include "GObject.h"
#include "GEvent.h"
#include "GEventLoop.h"
2018-10-10 13:12:38 +00:00
#include <AK/Assertions.h>
GObject::GObject(GObject* parent)
2018-10-10 13:12:38 +00:00
: m_parent(parent)
{
2018-10-10 14:49:36 +00:00
if (m_parent)
m_parent->add_child(*this);
2018-10-10 13:12:38 +00:00
}
GObject::~GObject()
2018-10-10 13:12:38 +00:00
{
stop_timer();
2018-10-10 14:49:36 +00:00
if (m_parent)
m_parent->remove_child(*this);
auto children_to_delete = move(m_children);
for (auto* child : children_to_delete)
2018-10-10 14:49:36 +00:00
delete child;
2018-10-10 13:12:38 +00:00
}
void GObject::event(GEvent& event)
2018-10-10 13:12:38 +00:00
{
switch (event.type()) {
case GEvent::Timer:
return timer_event(static_cast<GTimerEvent&>(event));
case GEvent::DeferredDestroy:
delete this;
break;
case GEvent::ChildAdded:
case GEvent::ChildRemoved:
return child_event(static_cast<GChildEvent&>(event));
case GEvent::Invalid:
2018-10-10 13:12:38 +00:00
ASSERT_NOT_REACHED();
break;
default:
break;
}
}
2018-10-10 14:49:36 +00:00
void GObject::add_child(GObject& object)
2018-10-10 14:49:36 +00:00
{
m_children.append(&object);
GEventLoop::main().post_event(*this, make<GChildEvent>(GEvent::ChildAdded, object));
2018-10-10 14:49:36 +00:00
}
void GObject::remove_child(GObject& object)
2018-10-10 14:49:36 +00:00
{
for (ssize_t i = 0; i < m_children.size(); ++i) {
if (m_children[i] == &object) {
m_children.remove(i);
GEventLoop::main().post_event(*this, make<GChildEvent>(GEvent::ChildRemoved, object));
return;
}
2018-10-10 14:49:36 +00:00
}
}
2018-10-12 10:18:59 +00:00
void GObject::timer_event(GTimerEvent&)
2018-10-12 10:18:59 +00:00
{
}
void GObject::child_event(GChildEvent&)
{
}
void GObject::start_timer(int ms)
2018-10-12 10:18:59 +00:00
{
if (m_timer_id) {
dbgprintf("GObject{%p} already has a timer!\n", this);
2018-10-12 10:18:59 +00:00
ASSERT_NOT_REACHED();
}
m_timer_id = GEventLoop::main().register_timer(*this, ms, true);
2018-10-12 10:18:59 +00:00
}
void GObject::stop_timer()
2018-10-12 10:18:59 +00:00
{
if (!m_timer_id)
2018-10-12 10:18:59 +00:00
return;
bool success = GEventLoop::main().unregister_timer(m_timer_id);
ASSERT(success);
m_timer_id = 0;
2018-10-12 10:18:59 +00:00
}
void GObject::delete_later()
{
GEventLoop::main().post_event(*this, make<GEvent>(GEvent::DeferredDestroy));
}