aboutsummaryrefslogtreecommitdiff
path: root/src/engine/user/input.cpp
blob: 505a0fa40c007d3eaeabb2bafc0ccce2d37cddcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "input.hpp"

#include <iostream>
#include <unordered_map>

#include "engine/keycodes.hpp"

const std::unordered_map<char, char> 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();
}