spacebox/src/Input.cpp

95 lines
2.5 KiB
C++

#include "Input.hpp"
Input::Input(Node *parent) : Node(parent)
{
load_key_map();
get_delegate().subscribe(&Input::respond, this, SDL_KEYDOWN);
get_delegate().subscribe(&Input::respond, this, SDL_KEYUP);
for (KeyCombination& combination : key_map)
{
print_key_combination(combination);
}
}
void Input::print_key_combination(KeyCombination &combination)
{
std::cout << "<KeyCombination " << combination.command << ", " <<
combination.key << ", ctrl " << combination.ctrl << ", shift " <<
combination.shift << ", alt " << combination.alt << ">" << std::endl;
}
void Input::load_key_map()
{
nlohmann::json &config = get_configuration();
for (auto& entry : config.at("keys").items())
{
bool ctrl = false, alt = false, shift = false;
int key;
if (not entry.value().is_string())
{
for (std::string part : entry.value())
{
if (part == "CTRL")
{
ctrl = true;
}
else if (part == "SHIFT")
{
shift = true;
}
else if (part == "ALT")
{
alt = true;
}
else
{
key = get_key_code(part);
}
}
}
else
{
key = get_key_code(entry.value());
}
add_to_key_map(entry.key(), key, ctrl, shift, alt);
}
}
int Input::get_key_code(std::string name)
{
if (key_ids.count(name) > 0)
{
return key_ids[name];
}
else
{
return (SDL_Keycode) name[0];
}
}
void Input::add_to_key_map(
std::string command, SDL_Keycode key_code, bool ctrl, bool shift, bool alt)
{
key_map.push_back((KeyCombination){command, key_code, ctrl, shift, alt});
}
void Input::respond(SDL_Event &event)
{
SDL_Keymod mod = SDL_GetModState();
for (KeyCombination& combination : key_map)
{
if (event.key.keysym.sym == combination.key and
(not combination.ctrl || mod & KMOD_CTRL) and
(not combination.shift || mod & KMOD_SHIFT) and
(not combination.alt || mod & KMOD_ALT))
{
SDL_Event relay;
bool* cancel = new bool(event.type == SDL_KEYDOWN ? false : true);
relay.type = Delegate::command_event_type;
relay.user.data1 = &combination.command;
relay.user.data2 = cancel;
SDL_PushEvent(&relay);
}
}
}