spacebox/src/Delegate.cpp

69 lines
1.7 KiB
C++

#include "Delegate.hpp"
int Delegate::command_event_type = SDL_RegisterEvents(1);
Delegate::Delegate(Node* parent) : Node(parent) {}
void Delegate::add_subscriber(Subscriber s, int type)
{
if (subscribers.count(type) == 0)
{
subscribers[type] = {};
}
subscribers[type].push_back(s);
}
void Delegate::dispatch()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
for (auto iter = subscribers.begin(); iter != subscribers.end(); iter++)
{
if (event.type == iter->first)
{
for (Subscriber s : iter->second)
{
if (s.o->is_active())
{
s.f(event);
}
}
}
}
if (event.type == command_event_type)
{
delete static_cast<bool*>(event.user.data2);
}
}
}
bool Delegate::compare(SDL_Event& event, const std::vector<std::string>& commands, bool neutral, bool cancel)
{
for (const std::string& command : commands)
{
if (compare(event, command, neutral, cancel))
{
return true;
}
}
return false;
}
bool Delegate::compare(SDL_Event& event, const std::string& command, bool neutral, bool cancel)
{
return event.type == command_event_type &&
(command == "" || command == *static_cast<std::string*>(event.user.data1)) &&
(neutral || (cancel == *static_cast<bool*>(event.user.data2)));
}
bool Delegate::compare_cancel(SDL_Event& event, const std::string& command)
{
return compare(event, command, false, true);
}
bool Delegate::compare_neutral(SDL_Event& event, const std::string& command)
{
return compare(event, command, true);
}