aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/api/EventManager.cpp
blob: 4f88e9710dd87e79c095bde1e2e59ada29933df9 (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
#include "EventManager.h"

using namespace crepe;

EventManager & EventManager::get_instance() {
	static EventManager instance;
	return instance;
}

void EventManager::dispatch_events() {
    for (auto event_it = this->events_queue.begin(); event_it != this->events_queue.end();) {
        std::unique_ptr<Event>& event = (*event_it).event;
        int channel = (*event_it).channel;
        std::type_index event_type = (*event_it).type;

        bool event_handled = false;
        auto handlers_it = this->subscribers.find(event_type);
        if (handlers_it != this->subscribers.end()) {
            std::vector<CallbackEntry>& handlers = handlers_it->second;
            
            std::sort(handlers.begin(), handlers.end(), [](const CallbackEntry& a, const CallbackEntry& b) {
                return a.priority > b.priority;
            });

            for (auto handler_it = handlers.begin(); handler_it != handlers.end(); ++handler_it) {
                // If callback is executed and returns true, remove the event from the queue
                if ((*handler_it).callback->exec(*event)) {
                    event_it = this->events_queue.erase(event_it);
                    event_handled = true;
                    break;
                }
            }
        }

        if (!event_handled) {
            ++event_it;
        }
    }
}

void EventManager::clear(){
	this->subscribers.clear();
	this->events_queue.clear();
}