summaryrefslogtreecommitdiff
path: root/LibGUI/GObject.cpp
blob: d50e7bdcd984ed8ac93000d4a4fc083b72a7d194 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "GObject.h"
#include "GEvent.h"
#include "GEventLoop.h"
#include <AK/Assertions.h>

GObject::GObject(GObject* parent)
    : m_parent(parent)
{
    if (m_parent)
        m_parent->add_child(*this);
}

GObject::~GObject()
{
    stop_timer();
    if (m_parent)
        m_parent->remove_child(*this);
    auto children_to_delete = move(m_children);
    for (auto* child : children_to_delete)
        delete child;
}

void GObject::event(GEvent& event)
{
    switch (event.type()) {
    case GEvent::Timer:
        return timer_event(static_cast<GTimerEvent&>(event));
    case GEvent::DeferredDestroy:
        delete this;
        break;
    case GEvent::Invalid:
        ASSERT_NOT_REACHED();
        break;
    default:
        break;
    }
}

void GObject::add_child(GObject& object)
{
    m_children.append(&object);
}

void GObject::remove_child(GObject& object)
{
    for (ssize_t i = 0; i < m_children.size(); ++i) {
        if (m_children[i] == &object) {
            m_children.remove(i);
            return;
        }
    }
}

void GObject::timer_event(GTimerEvent&)
{
}

void GObject::start_timer(int ms)
{
    if (m_timer_id) {
        dbgprintf("GObject{%p} already has a timer!\n", this);
        ASSERT_NOT_REACHED();
    }

    m_timer_id = GEventLoop::main().register_timer(*this, ms, true);
}

void GObject::stop_timer()
{
    if (!m_timer_id)
        return;
    bool success = GEventLoop::main().unregister_timer(m_timer_id);
    ASSERT(success);
    m_timer_id = 0;
}

void GObject::delete_later()
{
    GEventLoop::main().post_event(*this, make<GEvent>(GEvent::DeferredDestroy));
}