-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyboard.cpp
More file actions
637 lines (559 loc) · 14.1 KB
/
Copy pathkeyboard.cpp
File metadata and controls
637 lines (559 loc) · 14.1 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#include "keyboard.h"
#include <cctype>
#include <format>
#include <mutex>
#include <processthreadsapi.h>
#include <stdexcept>
#include <thread>
#include <unordered_map>
#include <iostream>
std::vector<std::string> split(const std::string& str, char split)
{
std::string curr = "";
std::vector<std::string> out;
for (const char& c : str)
{
if (c == split)
{
out.push_back(curr);
curr.clear();
continue;
}
curr += c;
}
out.push_back(curr);
return out;
}
std::string trim(const std::string& str)
{
size_t first = str.find_first_not_of(" \t\n\r");
if (first == std::string::npos)
{
return "";
}
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, last - first + 1);
}
Hotkey::Hotkey(const std::string& hotkey)
{
fromString(hotkey);
}
Hotkey::Hotkey(const std::vector<std::string>& keys)
{
fromArray(keys);
}
Hotkey::Hotkey(
uint8_t vkCode,
bool rwindows, bool lwindows,
bool rctrl, bool lctrl,
bool ralt, bool lalt,
bool rshift, bool lshift
)
{
this->vkCode = vkCode;
this->mods =
(rwindows?Hotkey::rwindows:0) | (lwindows?Hotkey::lwindows:0) |
(rctrl?Hotkey::rctrl:0) | (lctrl?Hotkey::lctrl:0) |
(ralt?Hotkey::ralt:0) | (lalt?Hotkey::lalt:0) |
(rshift?Hotkey::rshift:0) | (lshift?Hotkey::lshift:0);
}
void Hotkey::fromString(const std::string& hotkey)
{
std::vector<std::string> combo = split(hotkey, '-');
for (auto& str : combo)
{
str = trim(str);
}
fromArray(combo);
}
void Hotkey::fromArray(const std::vector<std::string>& keys)
{
uint16_t mod = 0;
for (const auto& curr : keys)
{
uint16_t currMod = stringToModifier(curr);
if (currMod == 0)
{
this->vkCode = stringToVkCode(curr);
break;
}
mod |= currMod;
}
this->mods = mod;
}
std::string Hotkey::toString()
{
std::string windows = "";
std::string ctrl = "";
std::string alt = "";
std::string shift = "";
switch (this->mods & 0b11)
{
case 0b11:
windows = "windows-";
break;
case 0b10:
windows = "lwindows-";
break;
case 0b01:
windows = "rwindows-";
break;
}
switch (this->mods & 0b1100)
{
case 0b1100:
ctrl= "ctrl-";
break;
case 0b1000:
ctrl= "lctrl-";
break;
case 0b0100:
ctrl= "rctrl-";
break;
}
switch (this->mods & 0b110000)
{
case 0b110000:
alt = "alt-";
break;
case 0b100000:
alt = "lalt-";
break;
case 0b010000:
alt = "ralt-";
break;
}
switch (this->mods & 0b11000000)
{
case 0b11000000:
shift = "shift-";
break;
case 0b10000000:
shift = "lshift-";
break;
case 0b01000000:
shift = "rshift-";
break;
}
std::string key = Hotkey::vkCodeToString(this->vkCode);
for (auto& c : key)
{
c = static_cast<uint8_t>(static_cast<uint8_t>(tolower(c)));
}
return std::format("{}{}{}{}{}",windows, ctrl, alt, shift, key);
}
size_t HotkeyHash::operator()(const Hotkey& k) const
{
size_t windows = ((k.mods & 0b11) != 0);
size_t ctrl = ((k.mods & 0b1100) != 0) << 2;
size_t alt = ((k.mods & 0b110000) != 0) << 4;
size_t shift = ((k.mods & 0b11000000) != 0) << 6;
size_t hash = std::hash<int>{}((int)k.vkCode);
return hash ^ (windows | ctrl | alt | shift);
}
bool HotkeyEqual::operator()(const Hotkey& a, const Hotkey& b) const
{
auto compare = [&](uint16_t mask) {
uint16_t m1 = a.mods & mask;
uint16_t m2 = b.mods & mask;
// keys are the same or they match in at least one place (which allows windows/lwindows but disallows rwindows/lwindows)
return m1 == m2 || (m1 & m2) != 0;
};
bool windows = compare(0b11);
bool ctrl = compare(0b1100);
bool alt = compare(0b110000);
bool shift = compare(0b11000000);
return (a.vkCode==b.vkCode) && (windows && ctrl && alt && shift);
}
uint8_t Hotkey::stringToVkCode(std::string key)
{
for (auto& c : key) c = std::toupper(c);
// single letter
if (key.size() == 1 && key[0] >= 'A' && key[0] <= 'Z')
return key[0];
// single digit
if (key.size() == 1 && key[0] >= '0' && key[0] <= '9')
return key[0];
// function keys (F1-F24)
if (key.size() >= 2 && key[0] == 'F')
{
try
{
int n = std::stoi(key.substr(1));
if (n >= 1 && n <= 24)
return VK_F1 + (n - 1);
}
catch (...)
{
}
}
static const std::unordered_map<std::string, int> vkMap = {
{"BACKSPACE", VK_BACK},
{"BS", VK_BACK},
{"TAB", VK_TAB},
{"ENTER", VK_RETURN},
{"RETURN", VK_RETURN},
{"SHIFT", VK_SHIFT},
{"CTRL", VK_CONTROL},
{"CONTROL", VK_CONTROL},
{"ALT", VK_MENU},
{"PAUSE", VK_PAUSE},
{"CAPSLOCK", VK_CAPITAL},
{"ESC", VK_ESCAPE},
{"ESCAPE", VK_ESCAPE},
{"SPACE", VK_SPACE},
{"PAGEUP", VK_PRIOR},
{"PGUP", VK_PRIOR},
{"PAGEDOWN", VK_NEXT},
{"PGDN", VK_NEXT},
{"END", VK_END},
{"HOME", VK_HOME},
{"LEFT", VK_LEFT},
{"UP", VK_UP},
{"RIGHT", VK_RIGHT},
{"DOWN", VK_DOWN},
{"SELECT", VK_SELECT},
{"PRINT", VK_PRINT},
{"EXECUTE", VK_EXECUTE},
{"PRINTSCREEN", VK_SNAPSHOT},
{"PRTSC", VK_SNAPSHOT},
{"INSERT", VK_INSERT},
{"INS", VK_INSERT},
{"DELETE", VK_DELETE},
{"DEL", VK_DELETE},
{"HELP", VK_HELP},
{"LWIN", VK_LWIN},
{"RWIN", VK_RWIN},
{"WIN", VK_LWIN},
{"NUMLOCK", VK_NUMLOCK},
{"SCROLLLOCK", VK_SCROLL},
{"LSHIFT", VK_LSHIFT},
{"RSHIFT", VK_RSHIFT},
{"LCTRL", VK_LCONTROL},
{"RCTRL", VK_RCONTROL},
{"LALT", VK_LMENU},
{"RALT", VK_RMENU},
{"APPS", VK_APPS},
{"SLEEP", VK_SLEEP},
{"NUMPAD0", VK_NUMPAD0},
{"NUMPAD1", VK_NUMPAD1},
{"NUMPAD2", VK_NUMPAD2},
{"NUMPAD3", VK_NUMPAD3},
{"NUMPAD4", VK_NUMPAD4},
{"NUMPAD5", VK_NUMPAD5},
{"NUMPAD6", VK_NUMPAD6},
{"NUMPAD7", VK_NUMPAD7},
{"NUMPAD8", VK_NUMPAD8},
{"NUMPAD9", VK_NUMPAD9},
{"MULTIPLY", VK_MULTIPLY},
{"ADD", VK_ADD},
{"SEPARATOR", VK_SEPARATOR},
{"SUBTRACT", VK_SUBTRACT},
{"DECIMAL", VK_DECIMAL},
{"DIVIDE", VK_DIVIDE},
{"SEMICOLON", VK_OEM_1},
{"PLUS", VK_OEM_PLUS},
{"COMMA", VK_OEM_COMMA},
{"MINUS", VK_OEM_MINUS},
{"PERIOD", VK_OEM_PERIOD},
{"SLASH", VK_OEM_2},
{"GRAVE", VK_OEM_3},
{"LBRACKET", VK_OEM_4},
{"BACKSLASH", VK_OEM_5},
{"RBRACKET", VK_OEM_6},
{"QUOTE", VK_OEM_7},
};
auto it = vkMap.find(key);
if (it != vkMap.end())
return it->second;
return 0;
}
uint16_t Hotkey::stringToModifier(std::string key)
{
enum Side
{
Either,
Left,
Right
};
for (auto& c : key)
{
c = static_cast<uint8_t>(std::tolower(static_cast<uint8_t>(c)));
}
Side side = Either;
if (key.size() > 1)
{
if (key[0] == 'l')
{
side = Left;
key.erase(0, 1);
}
else if (key[0] == 'r')
{
side = Right;
key.erase(0, 1);
}
}
uint16_t mod = 0;
if (key == "windows" || key == "meta" || key == "super" || key == "cmd" || key == "command")
{
mod = Hotkey::rwindows | Hotkey::lwindows;
}
else if (key == "ctrl" || key == "control")
{
mod = Hotkey::rctrl | Hotkey::lctrl;
}
else if (key == "alt" || key == "option")
{
mod = Hotkey::ralt | Hotkey::lalt;
}
else if (key == "shift")
{
mod = Hotkey::rshift | Hotkey::lshift;
}
// 1100
// 0110
// 1000
if (side == Left)
{
mod = (mod ^ (mod >> 1)) & mod;
}
else if (side == Right)
{
mod = (mod ^ (mod << 1)) & mod;
}
return mod;
}
bool Hotkey::isModKey(uint8_t vkCode)
{
return vkCode == VK_LCONTROL || vkCode == VK_RCONTROL || vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_LMENU || vkCode == VK_RMENU || vkCode == VK_LWIN || vkCode == VK_RWIN;
}
std::string Hotkey::vkCodeToString(uint8_t vkCode)
{
UINT scanCode = MapVirtualKeyA(vkCode, MAPVK_VK_TO_VSC);
switch (vkCode)
{
case VK_LEFT:
case VK_RIGHT:
case VK_UP:
case VK_DOWN:
case VK_RCONTROL:
case VK_RMENU:
case VK_INSERT:
case VK_DELETE:
case VK_HOME:
case VK_END:
case VK_PRIOR:
case VK_NEXT:
scanCode |= 0x100;
break;
}
char keyName[128] = {};
LONG lParam = (scanCode << 16);
if (GetKeyNameTextA(lParam, keyName, sizeof(keyName)))
return std::string(keyName);
char buffer[32];
sprintf_s(buffer, "VK_%u", vkCode);
return std::string(buffer);
}
Keyboard& Keyboard::instance()
{
static Keyboard instance;
return instance;
}
Keyboard::Keyboard()
:_keysDown(0xFF, false), _running(false)
{}
Keyboard::~Keyboard()
{
stop();
join();
}
void Keyboard::echoKeyPresses(bool val)
{
this->_echoKeyPresses = val;
}
bool Keyboard::runAsync(std::string stop)
{
if (_running)
{
return false;
}
if (!stop.empty())
{
registerHotkey(stop, [](){
Keyboard::instance().stop();
});
}
_running = true;
_thread = std::thread(&Keyboard::listen, this);
return true;
}
bool Keyboard::wait(std::string stop)
{
if (_running)
{
return false;
}
if (!stop.empty())
{
registerHotkey(stop, [](){
Keyboard::instance().stop();
});
}
_running = true;
listen();
return true;
}
bool Keyboard::stop()
{
if (!_running)
{
return false;
}
PostThreadMessage(_threadId, WM_QUIT, 0, 0);
// cant join here because the thread would be trying to join itself
_running = false;
return true;
}
void Keyboard::join()
{
if (!_thread.joinable())
{
return;
}
if (_thread.get_id() == std::this_thread::get_id())
{
throw std::runtime_error("Cannot join thread from the same thread");
}
_thread.join();
}
DWORD WINAPI Keyboard::listen()
{
_threadId = GetCurrentThreadId();
_hook = SetWindowsHookEx(
WH_KEYBOARD_LL,
keyboardProc,
GetModuleHandle(nullptr),
0
);
if (!_hook)
{
return 1;
}
if (!_running)
{
UnhookWindowsHookEx(_hook);
_hook = nullptr;
return 0;
}
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!_running)
{
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(_hook);
_hook = nullptr;
return 0;
}
void Keyboard::registerHotkey(const std::string& hotkey, const std::function<void()>& callback)
{
std::lock_guard<std::mutex> lock(_hotkeysMutex);
std::lock_guard<std::mutex> lock2(_callbacksMutex);
Hotkey internalHotkey(hotkey);
if (_hotkeyMap.find(internalHotkey) != _hotkeyMap.end())
{
throw std::runtime_error("Hotkey already registered: " + hotkey);
return;
}
_hotkeys.push_back(internalHotkey);
_callbacks.push_back(callback);
_hotkeyMap[internalHotkey] = _hotkeys.size() - 1;
}
void Keyboard::removeHotkey(const std::string& hotkey)
{
std::lock_guard<std::mutex> lock(_hotkeysMutex);
std::lock_guard<std::mutex> lock2(_callbacksMutex);
Hotkey key(hotkey);
const auto& it = _hotkeyMap.find(key);
if (it == _hotkeyMap.end())
{
return;
}
size_t index = it->second;
size_t last = _hotkeys.size() - 1;
auto& vec1 = _hotkeys;
auto& vec2 = _callbacks;
auto& map = _hotkeyMap;
if (index != last)
{
vec1[index] = std::move(vec1[last]);
vec2[index] = std::move(vec2[last]);
map[vec1[index]] = index;
}
vec1.pop_back();
vec2.pop_back();
map.erase(key);
}
void Keyboard::_handleKey(int code, WPARAM wParam, LPARAM lParam)
{
if (code != HC_ACTION)
{
return;
}
auto* key = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
switch (wParam)
{
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
std::lock_guard<std::mutex> lock(_keyDownMutex);
if (_keysDown[key->vkCode])
{
return;
}
_keysDown[key->vkCode] = true;
if (Hotkey::isModKey(key->vkCode))
{
return;
}
Hotkey pressed(key->vkCode,
_keysDown[VK_RWIN], _keysDown[VK_LWIN],
_keysDown[VK_RCONTROL], _keysDown[VK_LCONTROL],
_keysDown[VK_RMENU], _keysDown[VK_LMENU],
_keysDown[VK_RSHIFT], _keysDown[VK_LSHIFT]
);
if (_echoKeyPresses)
{
std::cout << pressed.toString() << '\n';
}
{
std::lock_guard<std::mutex> lock1(_hotkeysMutex);
const auto& it = _hotkeyMap.find(pressed);
if (it != _hotkeyMap.end())
{
std::lock_guard<std::mutex> lock2(_callbacksMutex);
_callbacks[it->second]();
}
}
break;
}
case WM_KEYUP:
case WM_SYSKEYUP:
{
std::lock_guard<std::mutex> lock(_keyDownMutex);
_keysDown[key->vkCode] = false;
break;
}
}
}
LRESULT CALLBACK keyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
Keyboard::instance()._handleKey(code, wParam, lParam);
return CallNextHookEx(nullptr, code, wParam, lParam);
}