spacebox/src/Delegate.cpp

89 lines
2.2 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)
{
cancelling_propagation = false;
for (Subscriber s : iter->second)
{
if (s.o->is_active())
{
s.f(event);
if (cancelling_propagation)
{
break;
}
}
}
}
}
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 == get_event_command(event)) &&
(neutral || (cancel == get_event_cancel_state(event)));
}
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);
}
void Delegate::cancel_propagation()
{
cancelling_propagation = true;
}
const std::string& Delegate::get_event_command(SDL_Event& event) const
{
return *static_cast<std::string*>(event.user.data1);
}
bool Delegate::get_event_cancel_state(SDL_Event& event) const
{
return *static_cast<bool*>(event.user.data2);
}