-
Notifications
You must be signed in to change notification settings - Fork 495
Expand file tree
/
Copy pathHotkey.cpp
More file actions
404 lines (334 loc) · 12 KB
/
Hotkey.cpp
File metadata and controls
404 lines (334 loc) · 12 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
#include "modules/Hotkey.h"
#include <ranges>
#include <SDL_keycode.h>
#include "Core.h"
#include "ColorText.h"
#include "MiscUtils.h"
#include "PluginManager.h"
#include "modules/DFSDL.h"
#include "modules/Gui.h"
#include "df/global_objects.h"
#include "df/viewscreen.h"
#include "df/interfacest.h"
using namespace DFHack;
using Hotkey::KeySpec;
using Hotkey::KeyBinding;
enum HotkeySignal : uint8_t {
None = 0,
CmdReady,
Shutdown,
};
static bool operator==(const KeySpec& a, const KeySpec& b) {
return a.modifiers == b.modifiers && a.sym == b.sym &&
a.focus.size() == b.focus.size() &&
std::equal(a.focus.begin(), a.focus.end(), b.focus.begin());
}
// Equality operator for key bindings
static bool operator==(const KeyBinding& a, const KeyBinding& b) {
return a.spec == b.spec &&
a.command == b.command &&
a.cmdline == b.cmdline;
}
std::string KeySpec::toString(bool include_focus) const {
std::string out;
if (modifiers & DFH_MOD_CTRL) out += "Ctrl-";
if (modifiers & DFH_MOD_ALT) out += "Alt-";
if (modifiers & DFH_MOD_SUPER) out += "Super-";
if (modifiers & DFH_MOD_SHIFT) out += "Shift-";
std::string key_name;
if (this->sym < 0) {
key_name = "MOUSE" + std::to_string(-this->sym);
} else {
key_name = DFSDL::DFSDL_GetKeyName(this->sym);
}
out += key_name;
if (include_focus && !this->focus.empty()) {
out += "@";
bool first = true;
for (const auto& fc : this->focus) {
if (first) {
first = false;
out += fc;
} else {
out += "|" + fc;
}
}
}
return out;
}
std::optional<KeySpec> KeySpec::parse(std::string spec, std::string* err) {
KeySpec out;
// Determine focus string, if present
size_t focus_idx = spec.find('@');
if (focus_idx != std::string::npos) {
split_string(&out.focus, spec.substr(focus_idx + 1), "|");
spec.erase(focus_idx);
}
// Treat remaining keyspec as lowercase for case-insensitivity.
std::transform(spec.begin(), spec.end(), spec.begin(), tolower);
// Determine modifier flags
auto match_modifier = [&out, &spec](std::string_view prefix, int mod) {
bool found = spec.starts_with(prefix);
if (found) {
out.modifiers |= mod;
spec.erase(0, prefix.size());
}
return found;
};
while (match_modifier("shift-", DFH_MOD_SHIFT)
|| match_modifier("ctrl-", DFH_MOD_CTRL)
|| match_modifier("alt-", DFH_MOD_ALT)
|| match_modifier("super-", DFH_MOD_SUPER)) {}
out.sym = DFSDL::DFSDL_GetKeyFromName(spec.c_str());
if (out.sym != SDLK_UNKNOWN)
return out;
// Attempt to parse as a mouse binding
if (spec.starts_with("mouse")) {
spec.erase(0, 5);
// Read button number, ensuring between 4 and 15 inclusive
try {
int mbutton = std::stoi(spec);
if (mbutton >= 4 && mbutton <= 15) {
out.sym = -mbutton;
return out;
}
} catch (...) {
// If integer parsing fails, it isn't valid
}
if (err)
*err = "Invalid mouse button '" + spec + "', only 4-15 are valid";
return std::nullopt;
}
if (err)
*err = "Unknown key '" + spec + "'";
// Invalid key binding
return std::nullopt;
}
bool KeySpec::isDisruptive() const {
// SDLK enum uses the actual characters for a key as its value.
// Escaped values included are Return, Escape, Backspace, and Tab
const std::string essential_key_set = "\r\x1B\b\t -=[]\\;',./";
// Letters A-Z, 0-9, and other special keys such as return/escape, and other general typing keys
bool is_essential_key = (this->sym >= SDLK_a && this->sym <= SDLK_z) // A-Z
|| (this->sym >= SDLK_0 && this->sym <= SDLK_9) // 0-9
|| (this->sym < CHAR_MAX && essential_key_set.find((char)this->sym) != std::string::npos)
|| (this->sym >= SDLK_LEFT && this->sym <= SDLK_UP); // Arrow keys
// Essential keys are safe, so long as they have a modifier that isn't Shift
if (is_essential_key && !(this->modifiers & ~DFH_MOD_SHIFT))
return true;
return false;
}
// Hotkeys actions are executed from an external thread to avoid deadlocks
// that may occur if running commands from the render or simulation threads.
void HotkeyManager::hotkey_thread_fn() {
auto& core = DFHack::Core::getInstance();
std::unique_lock<std::mutex> l(lock);
while (true) {
cond.wait(l, [this]() { return this->hotkey_sig != HotkeySignal::None; });
if (hotkey_sig == HotkeySignal::Shutdown)
return;
if (hotkey_sig != HotkeySignal::CmdReady)
continue;
// Copy and reset important data, then release the lock
this->hotkey_sig = HotkeySignal::None;
std::string cmd = this->queued_command;
this->queued_command.clear();
l.unlock();
// Attempt execution of command
DFHack::color_ostream_proxy out(core.getConsole());
auto res = core.runCommand(out, cmd);
if (res == DFHack::CR_NOT_IMPLEMENTED)
out.printerr("Invalid hotkey command: '%s'\n", cmd.c_str());
l.lock();
}
}
bool HotkeyManager::addKeybind(KeySpec spec, std::string_view cmd) {
// No point in a hotkey with no action
if (cmd.empty())
return false;
KeyBinding binding;
binding.spec = std::move(spec);
binding.cmdline = cmd;
size_t space_idx = cmd.find(' ');
binding.command = space_idx == std::string::npos ? cmd : cmd.substr(0, space_idx);
std::lock_guard<std::mutex> l(lock);
auto& bindings = this->bindings[binding.spec.sym];
for (auto& bind : bindings) {
// Don't set a keybind twice, but return true as there isn't an issue
if (bind == binding)
return true;
}
bindings.emplace_back(binding);
return true;
}
bool HotkeyManager::addKeybind(std::string keyspec, std::string_view cmd) {
std::optional<KeySpec> spec_opt = KeySpec::parse(std::move(keyspec));
if (!spec_opt.has_value())
return false;
return this->addKeybind(spec_opt.value(), cmd);
}
bool HotkeyManager::removeKeybind(const KeySpec& spec, bool match_focus, std::string_view cmdline) {
std::lock_guard<std::mutex> l(lock);
if (!bindings.contains(spec.sym))
return false;
auto& binds = bindings[spec.sym];
auto new_end = std::remove_if(binds.begin(), binds.end(), [match_focus, spec, &cmdline](const auto& v) {
return v.spec.sym == spec.sym
&& v.spec.modifiers == spec.modifiers
&& (!match_focus || v.spec.focus == spec.focus)
&& (cmdline.empty() || v.cmdline == cmdline);
});
if (new_end == binds.end())
return false; // No bindings removed
binds.erase(new_end, binds.end());
return true;
}
bool HotkeyManager::removeKeybind(std::string keyspec, bool match_focus, std::string_view cmdline) {
std::optional<KeySpec> spec_opt = KeySpec::parse(std::move(keyspec));
if (!spec_opt.has_value())
return false;
return this->removeKeybind(spec_opt.value(), match_focus, cmdline);
}
std::vector<std::string> HotkeyManager::listKeybinds(const KeySpec& spec) {
std::lock_guard<std::mutex> l(lock);
if (!bindings.contains(spec.sym))
return {};
std::vector<std::string> out;
auto& binds = bindings[spec.sym];
for (const auto& bind : binds) {
if (bind.spec.modifiers != spec.modifiers)
continue;
// If no focus is required, it is always active
if (spec.focus.empty() || bind.spec.focus.empty()) {
out.push_back(bind.cmdline);
continue;
}
// If a focus is required, determine if search spec if the same or more specific
for (const auto& requested : spec.focus) {
for (const auto& to_match : bind.spec.focus) {
if (prefix_matches(to_match, requested))
out.push_back("@" + to_match + ":" + bind.cmdline);
}
}
}
return out;
}
std::vector<std::string> HotkeyManager::listKeybinds(std::string keyspec) {
std::optional<KeySpec> spec_opt = KeySpec::parse(std::move(keyspec));
if (!spec_opt.has_value())
return {};
return this->listKeybinds(spec_opt.value());
}
std::vector<KeyBinding> HotkeyManager::listActiveKeybinds() {
std::lock_guard<std::mutex> l(lock);
std::vector<KeyBinding> out;
for(const auto& [_, bind_set] : bindings) {
for (const auto& binding : bind_set) {
if (binding.spec.focus.empty()) {
// Binding always active
out.emplace_back(binding);
continue;
}
for (const auto& focus : binding.spec.focus) {
// Determine if focus string allows this binding
if (Gui::matchFocusString(focus)) {
out.emplace_back(binding);
break;
}
}
}
}
return out;
}
std::vector<KeyBinding> HotkeyManager::listAllKeybinds() {
std::lock_guard<std::mutex> l(lock);
std::vector<KeyBinding> out;
for (const auto& [_, bind_set] : bindings) {
for (const auto& bind : bind_set) {
out.emplace_back(bind);
}
}
return out;
}
bool HotkeyManager::handleKeybind(int sym, int modifiers) {
// Ensure gamestate is ready
if (!df::global::gview || !df::global::plotinfo)
return false;
// Get topmost active screen
df::viewscreen *screen = &df::global::gview->view;
while (screen->child)
screen = screen->child;
// Map keypad return to return
if (sym == SDLK_KP_ENTER)
sym = SDLK_RETURN;
std::unique_lock<std::mutex> l(lock);
// If reading input for a keybinding screen, save the input and exit early
if (keybind_save_requested) {
KeySpec spec;
spec.sym = sym;
spec.modifiers = modifiers;
requested_keybind = spec.toString(false);
keybind_save_requested = false;
return true;
}
if (!bindings.contains(sym))
return false;
auto& binds = bindings[sym];
auto& core = Core::getInstance();
bool mortal_mode = core.getMortalMode();
// Iterate in reverse, prioritizing the last added keybinds
for (const auto& bind : binds | std::views::reverse) {
if (bind.spec.modifiers != modifiers)
continue;
if (!bind.spec.focus.empty()) {
bool matched = false;
for (const auto& focus : bind.spec.focus) {
if (Gui::matchFocusString(focus)) {
matched = true;
break;
}
}
if (!matched)
continue;
}
if (!core.getPluginManager()->CanInvokeHotkey(bind.command, screen))
continue;
if (mortal_mode && core.isArmokTool(bind.command))
continue;
queued_command = bind.cmdline;
hotkey_sig = HotkeySignal::CmdReady;
l.unlock();
cond.notify_all();
return true;
}
return false;
}
void HotkeyManager::setHotkeyCommand(std::string cmd) {
std::unique_lock<std::mutex> l(lock);
queued_command = std::move(cmd);
hotkey_sig = HotkeySignal::CmdReady;
l.unlock();
cond.notify_all();
}
void HotkeyManager::requestKeybindingInput(bool cancel) {
std::lock_guard<std::mutex> l(lock);
keybind_save_requested = !cancel;
requested_keybind.clear();
}
std::string HotkeyManager::getKeybindingInput() {
std::lock_guard<std::mutex> l(lock);
return requested_keybind;
}
HotkeyManager::HotkeyManager() {
this->hotkey_thread = std::thread(&HotkeyManager::hotkey_thread_fn, this);
}
HotkeyManager::~HotkeyManager() {
// Set shutdown signal and notify thread
{
std::lock_guard<std::mutex> l(lock);
this->hotkey_sig = HotkeySignal::Shutdown;
}
cond.notify_all();
if (this->hotkey_thread.joinable())
this->hotkey_thread.join();
}