forked from microsoft/PowerToys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
centralized_hotkeys.cpp
121 lines (104 loc) · 3.34 KB
/
centralized_hotkeys.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
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
#include "pch.h"
#include "centralized_hotkeys.h"
#include <map>
#include <common/logger/logger.h>
#include <common/utils/winapi_error.h>
#include <common/SettingsAPI/settings_objects.h>
namespace CentralizedHotkeys
{
std::map<Shortcut, std::vector<Action>> actions;
std::map<Shortcut, int> ids;
HWND runnerWindow;
std::wstring ToWstring(const Shortcut& shortcut)
{
std::wstring res = L"";
if (shortcut.modifiersMask & MOD_SHIFT)
{
res += L"shift+";
}
if (shortcut.modifiersMask & MOD_CONTROL)
{
res += L"ctrl+";
}
if (shortcut.modifiersMask & MOD_WIN)
{
res += L"win+";
}
if (shortcut.modifiersMask & MOD_ALT)
{
res += L"alt+";
}
res += PowerToysSettings::HotkeyObject::key_from_code(shortcut.vkCode);
return res;
}
bool AddHotkeyAction(Shortcut shortcut, Action action)
{
if (!actions[shortcut].empty())
{
// It will only work if previous one is rewritten
Logger::warn(L"{} shortcut is already registered", ToWstring(shortcut));
}
actions[shortcut].push_back(action);
// Register hotkey if it is the first shortcut
if (actions[shortcut].size() == 1)
{
if (ids.find(shortcut) == ids.end())
{
static int nextId = 0;
ids[shortcut] = nextId++;
}
if (!RegisterHotKey(runnerWindow, ids[shortcut], shortcut.modifiersMask, shortcut.vkCode))
{
Logger::warn(L"Failed to add {} shortcut. {}", ToWstring(shortcut), get_last_error_or_default(GetLastError()));
return false;
}
Logger::trace(L"{} shortcut registered", ToWstring(shortcut));
return true;
}
return true;
}
void UnregisterHotkeysForModule(std::wstring moduleName)
{
for (auto it = actions.begin(); it != actions.end(); it++)
{
auto val = std::find_if(it->second.begin(), it->second.end(), [moduleName](Action a) { return a.moduleName == moduleName; });
if (val != it->second.end())
{
it->second.erase(val);
if (it->second.empty())
{
if (!UnregisterHotKey(runnerWindow, ids[it->first]))
{
Logger::warn(L"Failed to unregister {} shortcut. {}", ToWstring(it->first), get_last_error_or_default(GetLastError()));
}
else
{
Logger::trace(L"{} shortcut unregistered", ToWstring(it->first));
}
}
}
}
}
void PopulateHotkey(Shortcut shortcut)
{
if (!actions.empty())
{
try
{
actions[shortcut].begin()->action(shortcut.modifiersMask, shortcut.vkCode);
}
catch(std::exception& ex)
{
Logger::error("Failed to execute hotkey's action. {}", ex.what());
}
catch(...)
{
Logger::error(L"Failed to execute hotkey's action");
}
}
}
void RegisterWindow(HWND hwnd)
{
runnerWindow = hwnd;
}
}