summaryrefslogtreecommitdiff
path: root/Widgets/Object.cpp
blob: 19c48ce1efa22fcd87e8f37edafa2041d64f26b0 (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
82
83
84
#include "Object.h"
#include "Event.h"
#include "EventLoop.h"
#include <AK/Assertions.h>

#ifdef USE_SDL
#include <SDL.h>
#endif

Object::Object(Object* parent)
    : m_parent(parent)
{
    if (m_parent)
        m_parent->addChild(*this);
}

Object::~Object()
{
    if (m_parent)
        m_parent->removeChild(*this);
    auto childrenToDelete = std::move(m_children);
    for (auto* child : childrenToDelete)
        delete child;
}

void Object::event(Event& event)
{
    switch (event.type()) {
    case Event::Timer:
        return onTimer(static_cast<TimerEvent&>(event));
    case Event::Invalid:
        ASSERT_NOT_REACHED();
        break;
    default:
        break;
    }
}

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;
        }
    }
}

void Object::onTimer(TimerEvent&)
{
}

#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;
}