forked from BellCrow/GettingInShapes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Keyboard.cpp
85 lines (73 loc) · 1.83 KB
/
Keyboard.cpp
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
82
83
84
85
#include "Keyboard.h"
#include <functional>
Keyboard::Keyboard(sp<MessageSource> messageSource)
{
m_messageSource = messageSource;
std::function<void(WindowMessage)> function = std::bind(&Keyboard::Handlemessage, this, std::placeholders::_1);
m_messageSource->Subscribe(function);
Reset();
}
Keyboard::~Keyboard(){}
void Keyboard::KeyDown(int keyCode)
{
CheckKeyCode(keyCode);
m_keys[keyCode] = true;
KeyboardMessage message = KeyboardMessage(KeyboardEventType::KeyDownEvent, keyCode);
FireEvent(message);
}
void Keyboard::CheckKeyCode(int keyCode) const
{
if (MaxKeys <= keyCode)
{
throw std::exception("Illegal keycode detected");
}
}
void Keyboard::FireEvent(const KeyboardMessage& keyboardEvent)
{
for (auto eventSubscriber : m_keyboardEventSubscriber)
{
eventSubscriber->HandleKeyboardEvent(keyboardEvent);
}
for (auto eventSubscriber : m_keyboardEventLambdas)
{
eventSubscriber(keyboardEvent);
}
}
void Keyboard::Handlemessage(WindowMessage windowMessage)
{
if (windowMessage.GetMessageType() == WM_KEYDOWN)
{
KeyDown(((int)windowMessage.GetWParam()));
}
else if (windowMessage.GetMessageType() == WM_KEYUP)
{
KeyUp(((int)windowMessage.GetWParam()));
}
}
void Keyboard::KeyUp(int keyCode)
{
CheckKeyCode(keyCode);
m_keys[keyCode] = false;
KeyboardMessage message = KeyboardMessage(KeyboardEventType::KeyUpEvent, keyCode);
FireEvent(message);
}
bool Keyboard::IsKeyDown(int keyCode) const
{
CheckKeyCode(keyCode);
return m_keys[keyCode];
}
void Keyboard::Reset() noexcept
{
for (size_t i = 0; i < MaxKeys; i++)
{
m_keys[i] = false;
}
}
void Keyboard::Subscribe(const std::shared_ptr<IKeyboardEventReceiver> eventReceiver)
{
m_keyboardEventSubscriber.push_back(eventReceiver);
}
void Keyboard::Subscribe(std::function<void(KeyboardMessage)> eventReceiver)
{
m_keyboardEventLambdas.push_back(eventReceiver);
}