#include "EventManager.h" namespace crepe { template void EventManager::subscribe(EventHandler && callback, int channel) { std::type_index event_type = typeid(EventType); std::unique_ptr> handler = std::make_unique>(callback); if (channel) { std::unordered_map>> & handlers_map = this->subscribers_by_event_id[event_type]; auto handlers = handlers_map.find(channel); if (handlers != handlers_map.end()) { handlers->second.emplace_back(std::move(handler)); } else { handlers_map[channel].emplace_back(std::move(handler)); } } else { std::vector> & handlers = this->subscribers[event_type]; handlers.emplace_back(std::move(handler)); } } template void EventManager::queue_event(EventType && event, int channel) { std::type_index event_type = std::type_index(typeid(EventType)); std::unique_ptr event_ptr = std::make_unique(std::forward(event)); std::tuple, int, std::type_index> tuple( std::move(event_ptr), channel, event_type); this->events_queue.push_back(std::move(tuple)); } template void EventManager::trigger_event(const EventType & event, int channel) { std::type_index event_type = std::type_index(typeid(EventType)); if (channel > 0) { std::unordered_map>> & handlers_map = this->subscribers_by_event_id[event_type]; auto handlers_it = handlers_map.find(channel); if (handlers_it != handlers_map.end()) { std::vector> & handlers = handlers_it->second; for (auto it = handlers.begin(); it != handlers.end();++it) { // stops when callback returns true if((*it)->exec(event)){ break; } } } } else { std::vector> & handlers = this->subscribers[event_type]; for (auto it = handlers.begin(); it != handlers.end();++it) { // stops when callback returns true if((*it)->exec(event)){ break; } } } } template void EventManager::unsubscribe(const EventHandler & callback, int channel) { std::type_index event_type(typeid(EventType)); std::string handler_name = callback.target_type().name(); if (channel) { auto subscriber_list = this->subscribers_by_event_id.find(event_type); if (subscriber_list != this->subscribers_by_event_id.end()) { std::unordered_map< int, std::vector>> & handlers_map = subscriber_list->second; auto handlers = handlers_map.find(channel); if (handlers != handlers_map.end()) { std::vector> & callbacks = handlers->second; for (auto it = callbacks.begin(); it != callbacks.end(); ++it) { if ((*it)->get_type() == handler_name) { it = callbacks.erase(it); return; } } } } } else { auto handlers_it = this->subscribers.find(event_type); if (handlers_it != this->subscribers.end()) { std::vector> & handlers = handlers_it->second; for (auto it = handlers.begin(); it != handlers.end(); ++it) { if ((*it)->get_type() == handler_name) { it = handlers.erase(it); return; } } } } } } // namespace crepe