#include "input.hpp" #include #include #include "engine/keycodes.hpp" const std::unordered_map special_keys_map = { {'A', keycodes::UP_ARROW}, {'B', keycodes::DOWN_ARROW}, {'C', keycodes::RIGHT_ARROW}, {'D', keycodes::LEFT_ARROW}}; void UserInputObserver::listen() noexcept { while (true) { char character = 0; if (std::cin.read(&character, 1).fail()) { continue; } _input_buffer_mutex.lock(); _input_buffer += character; _input_buffer_mutex.unlock(); } } auto UserInputObserver::get_currently_pressed_key() noexcept -> Key { auto input_buffer = _get_input_buffer(); if (input_buffer.empty()) { return 0; } auto character = input_buffer.front(); // Special treatment for arrow keys if (input_buffer.length() == 3 && character == keycodes::ESCAPE) { const auto arrow_key_code = input_buffer.at(2); if (arrow_key_code >= 'A' && arrow_key_code <= 'D') { character = special_keys_map.at(arrow_key_code); } input_buffer = input_buffer.substr(2); } input_buffer = input_buffer.substr(1); _set_input_buffer(input_buffer); return character; } auto UserInputObserver::_get_input_buffer() const noexcept -> std::string { _input_buffer_mutex.lock(); auto input_buffer = _input_buffer; _input_buffer_mutex.unlock(); return input_buffer; } void UserInputObserver::_set_input_buffer(const std::string &input_buffer) noexcept { _input_buffer_mutex.lock(); _input_buffer = input_buffer; _input_buffer_mutex.unlock(); }