spacebox/src/Delegate.cpp

105 lines
3.0 KiB
C++

/* +------------------------------------------------------+
____/ \____ /| - Open source game framework licensed to freely use, |
\ / / | copy, modify and sell without restriction |
+--\ ^__^ /--+ | |
| ~/ \~ | | - created for <https://foam.shampoo.ooo> |
| ~~~~~~~~~~~~ | +------------------------------------------------------+
| SPACE ~~~~~ | /
| ~~~~~~~ BOX |/
+-------------*/
#include "Delegate.hpp"
using namespace sb;
Delegate::Delegate(Node* parent) : Node(parent) {}
void Delegate::add_subscriber(Subscriber s, std::uint32_t type)
{
if (subscribers.count(type) == 0)
{
subscribers[type] = {};
}
subscribers[type].push_back(s);
}
void Delegate::dispatch()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
/* Don't even notify subscribers of the event if input is suppressed and the input is a key or mouse click. */
if (get_input().is_suppressed() && (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP ||
event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP))
{
continue;
}
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)
{
return *static_cast<std::string*>(event.user.data1);
}
bool Delegate::get_event_cancel_state(SDL_Event& event)
{
return *static_cast<bool*>(event.user.data2);
}