ladybird/LibCore/CObject.cpp

113 lines
2.5 KiB
C++
Raw Normal View History

#include <LibCore/CObject.h>
#include <LibCore/CEvent.h>
#include <LibCore/CEventLoop.h>
2018-10-10 16:12:38 +03:00
#include <AK/Assertions.h>
#include <stdio.h>
2018-10-10 16:12:38 +03:00
CObject::CObject(CObject* parent, bool is_widget)
2018-10-10 16:12:38 +03:00
: m_parent(parent)
, m_widget(is_widget)
2018-10-10 16:12:38 +03:00
{
2018-10-10 17:49:36 +03:00
if (m_parent)
m_parent->add_child(*this);
2018-10-10 16:12:38 +03:00
}
CObject::~CObject()
2018-10-10 16:12:38 +03:00
{
stop_timer();
2018-10-10 17:49:36 +03: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 17:49:36 +03:00
delete child;
2018-10-10 16:12:38 +03:00
}
void CObject::event(CEvent& event)
2018-10-10 16:12:38 +03:00
{
switch (event.type()) {
case CEvent::Timer:
return timer_event(static_cast<CTimerEvent&>(event));
case CEvent::DeferredDestroy:
delete this;
break;
case CEvent::ChildAdded:
case CEvent::ChildRemoved:
return child_event(static_cast<CChildEvent&>(event));
case CEvent::Invalid:
2018-10-10 16:12:38 +03:00
ASSERT_NOT_REACHED();
break;
default:
break;
}
}
2018-10-10 17:49:36 +03:00
void CObject::add_child(CObject& object)
2018-10-10 17:49:36 +03:00
{
// FIXME: Should we support reparenting objects?
ASSERT(!object.parent() || object.parent() == this);
object.m_parent = this;
2018-10-10 17:49:36 +03:00
m_children.append(&object);
event(*make<CChildEvent>(CEvent::ChildAdded, object));
2018-10-10 17:49:36 +03:00
}
void CObject::remove_child(CObject& object)
2018-10-10 17:49:36 +03:00
{
for (ssize_t i = 0; i < m_children.size(); ++i) {
if (m_children[i] == &object) {
m_children.remove(i);
event(*make<CChildEvent>(CEvent::ChildRemoved, object));
return;
}
2018-10-10 17:49:36 +03:00
}
}
2018-10-12 13:18:59 +03:00
void CObject::timer_event(CTimerEvent&)
2018-10-12 13:18:59 +03:00
{
}
void CObject::child_event(CChildEvent&)
{
}
void CObject::start_timer(int ms)
2018-10-12 13:18:59 +03:00
{
if (m_timer_id) {
dbgprintf("CObject{%p} already has a timer!\n", this);
2018-10-12 13:18:59 +03:00
ASSERT_NOT_REACHED();
}
m_timer_id = CEventLoop::register_timer(*this, ms, true);
2018-10-12 13:18:59 +03:00
}
void CObject::stop_timer()
2018-10-12 13:18:59 +03:00
{
if (!m_timer_id)
2018-10-12 13:18:59 +03:00
return;
bool success = CEventLoop::unregister_timer(m_timer_id);
ASSERT(success);
m_timer_id = 0;
2018-10-12 13:18:59 +03:00
}
void CObject::delete_later()
{
CEventLoop::current().post_event(*this, make<CEvent>(CEvent::DeferredDestroy));
}
void CObject::dump_tree(int indent)
{
for (int i = 0; i < indent; ++i) {
printf(" ");
}
printf("%s{%p}\n", class_name(), this);
for_each_child([&] (auto& child) {
child.dump_tree(indent + 2);
return IterationDecision::Continue;
});
}
void CObject::deferred_invoke(Function<void(CObject&)> invokee)
{
CEventLoop::current().post_event(*this, make<CDeferredInvocationEvent>(move(invokee)));
}