Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "Hotkey.h"
21 :
22 : #include "lib/external_libraries/libsdl.h"
23 : #include "ps/CLogger.h"
24 : #include "ps/CStr.h"
25 : #include "ps/ConfigDB.h"
26 : #include "ps/Globals.h"
27 : #include "ps/KeyName.h"
28 : #include "ps/Profiler2.h"
29 : #include "ps/VideoMode.h"
30 :
31 : #include <SDL_events.h>
32 : #include <SDL_mouse.h>
33 : #include <SDL_scancode.h>
34 : #include <algorithm>
35 : #include <boost/iterator/iterator_categories.hpp>
36 : #include <boost/iterator/iterator_facade.hpp>
37 : #include <boost/token_functions.hpp>
38 : #include <boost/tokenizer.hpp>
39 : #include <cstddef>
40 : #include <map>
41 : #include <string>
42 : #include <type_traits>
43 : #include <utility>
44 :
45 : static bool unified[UNIFIED_LAST - UNIFIED_SHIFT];
46 :
47 : std::unordered_map<int, KeyMapping> g_HotkeyMap;
48 :
49 : namespace {
50 : std::unordered_map<std::string, bool> g_HotkeyStatus;
51 :
52 : struct PressedHotkey
53 : {
54 40 : PressedHotkey(const SHotkeyMapping* m, bool t) : mapping(m), retriggered(t) {};
55 : // NB: this points to one of g_HotkeyMap's mappings. It works because that std::unordered_map is stable once constructed.
56 : const SHotkeyMapping* mapping;
57 : // Whether the hotkey was triggered by a key release (silences "press" and "up" events).
58 : bool retriggered;
59 : };
60 :
61 : struct ReleasedHotkey
62 : {
63 19 : ReleasedHotkey(const char* n, bool t) : name(n), wasRetriggered(t) {};
64 : const char* name;
65 : bool wasRetriggered;
66 : };
67 :
68 : // 'In-flight' state used because the hotkey triggering process is split in two phase.
69 : // These hotkeys may still be stopped if the event responsible for triggering them is handled
70 : // before it can be used to generate the hotkeys.
71 : std::vector<PressedHotkey> newPressedHotkeys;
72 : // Stores the 'specificity' of the newly pressed hotkeys.
73 : size_t closestMapMatch = 0;
74 : // This is merely used to ensure consistency in EventWillFireHotkey.
75 : const SDL_Event* currentEvent;
76 :
77 : // List of currently pressed hotkeys. This is used to quickly reset hotkeys.
78 : // This is an unsorted vector because there will generally be very few elements,
79 : // so it's presumably faster than std::set.
80 : std::vector<PressedHotkey> pressedHotkeys;
81 :
82 : // List of active keys relevant for hotkeys.
83 : std::vector<SDL_Scancode_> activeScancodes;
84 : }
85 :
86 : static_assert(std::is_integral<std::underlying_type<SDL_Scancode>::type>::value, "SDL_Scancode is not an integral enum.");
87 : static_assert(SDL_USEREVENT_ == SDL_USEREVENT, "SDL_USEREVENT_ is not the same type as the real SDL_USEREVENT");
88 :
89 : // Look up each key binding in the config file and set the mappings for
90 : // all key combinations that trigger it.
91 4 : static void LoadConfigBindings(CConfigDB& configDB)
92 : {
93 16 : for (const std::pair<const CStr, CConfigValueSet>& configPair : configDB.GetValuesWithPrefix(CFG_COMMAND, "hotkey."))
94 : {
95 12 : std::string hotkeyName = configPair.first.substr(7); // strip the "hotkey." prefix
96 :
97 : // "unused" is kept or the A23->24 migration, this can likely be removed in A25.
98 12 : if (configPair.second.empty() || (configPair.second.size() == 1 && configPair.second.front() == "unused"))
99 : {
100 : // Unused hotkeys must still be registered in the map to appear in the hotkey editor.
101 0 : SHotkeyMapping unusedCode;
102 0 : unusedCode.name = hotkeyName;
103 0 : unusedCode.primary = SKey{ UNUSED_HOTKEY_CODE };
104 0 : g_HotkeyMap[UNUSED_HOTKEY_CODE].push_back(unusedCode);
105 0 : continue;
106 0 : }
107 :
108 27 : for (const CStr& hotkey : configPair.second)
109 : {
110 15 : PS::StaticVector<SKey, 8> keyCombination;
111 :
112 : // Iterate through multiple-key bindings (e.g. Ctrl+I)
113 15 : boost::char_separator<char> sep("+");
114 15 : typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
115 15 : tokenizer tok(hotkey, sep);
116 105 : for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
117 : {
118 : // Attempt decode as key name
119 25 : SDL_Scancode scancode = FindScancode(it->c_str());
120 25 : if (!scancode)
121 : {
122 0 : LOGWARNING("Hotkey mapping used invalid key '{}'", hotkey);
123 0 : continue;
124 0 : }
125 :
126 25 : SKey key = { scancode };
127 50 : keyCombination.push_back(key);
128 15 : }
129 :
130 15 : PS::StaticVector<SKey, 8>::iterator itKey, itKey2;
131 40 : for (itKey = keyCombination.begin(); itKey != keyCombination.end(); ++itKey)
132 : {
133 25 : SHotkeyMapping bindCode;
134 :
135 50 : bindCode.name = hotkeyName;
136 25 : bindCode.primary = SKey{ itKey->code };
137 :
138 99 : for (itKey2 = keyCombination.begin(); itKey2 != keyCombination.end(); ++itKey2)
139 49 : if (itKey != itKey2) // Push any auxiliary keys
140 73 : bindCode.required.push_back(*itKey2);
141 :
142 25 : g_HotkeyMap[itKey->code].push_back(bindCode);
143 25 : }
144 30 : }
145 12 : }
146 4 : }
147 :
148 4 : void LoadHotkeys(CConfigDB& configDB)
149 : {
150 4 : PROFILE2("LoadHotkeys");
151 4 : pressedHotkeys.clear();
152 4 : LoadConfigBindings(configDB);
153 4 : }
154 :
155 5 : void UnloadHotkeys()
156 : {
157 5 : pressedHotkeys.clear();
158 5 : g_HotkeyMap.clear();
159 5 : g_HotkeyStatus.clear();
160 5 : }
161 :
162 85 : bool isPressed(const SKey& key)
163 : {
164 : // Normal keycodes are below EXTRA_KEYS_BASE
165 85 : if ((int)key.code < EXTRA_KEYS_BASE)
166 85 : return g_scancodes[key.code];
167 : // Mouse 'keycodes' are after the modifier keys
168 0 : else if ((int)key.code < MOUSE_LAST && (int)key.code > MOUSE_BASE)
169 0 : return g_mouse_buttons[key.code - MOUSE_BASE];
170 : // Modifier keycodes are between the normal keys and the mouse 'keys'
171 0 : else if ((int)key.code < UNIFIED_LAST && (int)key.code > SDL_NUM_SCANCODES)
172 0 : return unified[key.code - UNIFIED_SHIFT];
173 : // This codepath shouldn't be taken, but not having it triggers warnings.
174 : else
175 : return false;
176 : }
177 :
178 78 : Input::Reaction HotkeyStateChange(const SDL_Event& ev)
179 : {
180 78 : if (ev.type == SDL_HOTKEYPRESS || ev.type == SDL_HOTKEYPRESS_SILENT)
181 66 : g_HotkeyStatus[static_cast<const char*>(ev.user.data1)] = true;
182 45 : else if (ev.type == SDL_HOTKEYUP || ev.type == SDL_HOTKEYUP_SILENT)
183 38 : g_HotkeyStatus[static_cast<const char*>(ev.user.data1)] = false;
184 78 : return Input::Reaction::PASS;
185 : }
186 :
187 44 : Input::Reaction HotkeyInputPrepHandler(const SDL_Event& ev)
188 : {
189 44 : int scancode = SDL_SCANCODE_UNKNOWN;
190 :
191 : // Restore default state.
192 44 : newPressedHotkeys.clear();
193 44 : currentEvent = nullptr;
194 :
195 44 : switch(ev.type)
196 : {
197 40 : case SDL_KEYDOWN:
198 40 : case SDL_KEYUP:
199 40 : scancode = ev.key.keysym.scancode;
200 40 : break;
201 :
202 0 : case SDL_MOUSEBUTTONDOWN:
203 0 : case SDL_MOUSEBUTTONUP:
204 : // Mousewheel events are no longer buttons, but we want to maintain the order
205 : // expected by g_mouse_buttons for compatibility
206 0 : if (ev.button.button >= SDL_BUTTON_X1)
207 0 : scancode = MOUSE_BASE + static_cast<int>(ev.button.button) + 2;
208 : else
209 0 : scancode = MOUSE_BASE + static_cast<int>(ev.button.button);
210 : break;
211 :
212 0 : case SDL_MOUSEWHEEL:
213 0 : if (ev.wheel.y > 0)
214 : {
215 0 : scancode = MOUSE_WHEELUP;
216 0 : break;
217 : }
218 0 : else if (ev.wheel.y < 0)
219 : {
220 0 : scancode = MOUSE_WHEELDOWN;
221 0 : break;
222 : }
223 0 : else if (ev.wheel.x > 0)
224 : {
225 0 : scancode = MOUSE_X2;
226 0 : break;
227 : }
228 0 : else if (ev.wheel.x < 0)
229 : {
230 0 : scancode = MOUSE_X1;
231 0 : break;
232 : }
233 : return Input::Reaction::PASS;
234 :
235 :
236 : default:
237 : return Input::Reaction::PASS;
238 : }
239 :
240 : // Somewhat hackish:
241 : // Create phantom 'unified-modifier' events when left- or right- modifier keys are pressed
242 : // Just send them to this handler; don't let the imaginary event codes leak back to real SDL.
243 :
244 40 : SDL_Event phantom{};
245 40 : phantom.type = ((ev.type == SDL_KEYDOWN) || (ev.type == SDL_MOUSEBUTTONDOWN)) ? SDL_KEYDOWN : SDL_KEYUP;
246 40 : if (phantom.type == SDL_KEYDOWN)
247 22 : phantom.key.repeat = ev.type == SDL_KEYDOWN ? ev.key.repeat : 0;
248 :
249 40 : if (scancode == SDL_SCANCODE_LSHIFT || scancode == SDL_SCANCODE_RSHIFT)
250 : {
251 0 : phantom.key.keysym.scancode = static_cast<SDL_Scancode>(UNIFIED_SHIFT);
252 0 : unified[0] = (phantom.type == SDL_KEYDOWN);
253 0 : return HotkeyInputPrepHandler(phantom);
254 : }
255 : else if (scancode == SDL_SCANCODE_LCTRL || scancode == SDL_SCANCODE_RCTRL)
256 : {
257 0 : phantom.key.keysym.scancode = static_cast<SDL_Scancode>(UNIFIED_CTRL);
258 0 : unified[1] = (phantom.type == SDL_KEYDOWN);
259 0 : return HotkeyInputPrepHandler(phantom);
260 : }
261 : else if (scancode == SDL_SCANCODE_LALT || scancode == SDL_SCANCODE_RALT)
262 : {
263 0 : phantom.key.keysym.scancode = static_cast<SDL_Scancode>(UNIFIED_ALT);
264 0 : unified[2] = (phantom.type == SDL_KEYDOWN);
265 0 : return HotkeyInputPrepHandler(phantom);
266 : }
267 : else if (scancode == SDL_SCANCODE_LGUI || scancode == SDL_SCANCODE_RGUI)
268 : {
269 0 : phantom.key.keysym.scancode = static_cast<SDL_Scancode>(UNIFIED_SUPER);
270 0 : unified[3] = (phantom.type == SDL_KEYDOWN);
271 0 : return HotkeyInputPrepHandler(phantom);
272 : }
273 :
274 : // Check whether we have any hotkeys registered that include this scancode.
275 40 : if (g_HotkeyMap.find(scancode) == g_HotkeyMap.end())
276 : return Input::Reaction::PASS;
277 :
278 40 : currentEvent = &ev;
279 :
280 : /**
281 : * Hotkey behaviour spec (see also tests):
282 : * - If both 'F' and 'Ctrl+F' are hotkeys, and Ctrl & F keys are down, then the more specific one only is fired ('Ctrl+F' here).
283 : * - If 'Ctrl+F' and 'Ctrl+A' are both hotkeys, both may fire simulatenously (respectively without Ctrl).
284 : * - However, per the first point, 'Ctrl+Shift+F' would fire alone in that situation.
285 : * - "Press" is sent once, when the hotkey is initially triggered.
286 : * - "Up" is sent once, when the hotkey is released or superseded by a more specific hotkey.
287 : * - "Down" is sent repeatedly, and is also sent alongside the inital "Press".
288 : * - As a special case (see below), "Down" is not sent alongside "PressSilent".
289 : * - If 'Ctrl+F' is active, and 'Ctrl' is released, 'F' must become active again.
290 : * - However, the "Press" event is _not_ fired. Instead, "PressSilent" is.
291 : * - Likewise, once 'F' is released, the "Up" event will be a "UpSilent".
292 : * (the reason is that it is unexpected to trigger a press on key release).
293 : * - Hotkeys are allowed to fire with extra keys (e.g. Ctrl+F+A still triggers 'Ctrl+F').
294 : * - If 'F' and 'Ctrl+F' trigger the same hotkey, adding 'Ctrl' _and_ releasing 'Ctrl' will trigger new 'Press' events.
295 : * The "Up" event is only sent when both Ctrl & F are released.
296 : * - This is somewhat unexpected/buggy, but it makes the implementation easier and is easily avoidable for players.
297 : * - Wheel scrolling is 'instantaneous' behaviour and is essentially entirely separate from the above.
298 : * - It won't untrigger other hotkeys, and fires/releases on the same 'key event'.
299 : * Note that mouse buttons/wheel inputs can fire hotkeys, in combinations with keys.
300 : * ...Yes, this is all surprisingly complex.
301 : */
302 :
303 40 : bool isReleasedKey = ev.type == SDL_KEYUP || ev.type == SDL_MOUSEBUTTONUP;
304 : // Wheel events are pressed & released in the same go.
305 40 : bool isInstantaneous = ev.type == SDL_MOUSEWHEEL;
306 :
307 40 : if (!isInstantaneous)
308 : {
309 40 : std::vector<SDL_Scancode_>::iterator it = std::find(activeScancodes.begin(), activeScancodes.end(), scancode);
310 : // This prevents duplicates, assuming we might end up in a weird state - feels safer with input.
311 40 : if (isReleasedKey && it != activeScancodes.end())
312 18 : activeScancodes.erase(it);
313 22 : else if (!isReleasedKey && it == activeScancodes.end())
314 19 : activeScancodes.emplace_back(scancode);
315 : }
316 :
317 44 : std::vector<SDL_Scancode_> triggers;
318 40 : if (!isReleasedKey || isInstantaneous)
319 22 : triggers.push_back(scancode);
320 : else
321 : // If the key is released, we need to check all less precise hotkeys again, to see if we should retrigger some.
322 40 : for (SDL_Scancode_ code : activeScancodes)
323 22 : triggers.push_back(code);
324 :
325 : // Now check if we need to trigger new hotkeys / retrigger hotkeys.
326 : // We'll need the match-level and the keys in play to release currently pressed hotkeys.
327 40 : closestMapMatch = 0;
328 84 : for (SDL_Scancode_ code : triggers)
329 123 : for (const SHotkeyMapping& hotkey : g_HotkeyMap[code])
330 : {
331 : // Ensure no duplications in the new list.
332 79 : if (std::find_if(newPressedHotkeys.begin(), newPressedHotkeys.end(),
333 126 : [&hotkey](const PressedHotkey& v){ return v.mapping->name == hotkey.name; }) != newPressedHotkeys.end())
334 7 : continue;
335 :
336 72 : bool accept = true;
337 89 : for (const SKey& k : hotkey.required)
338 : {
339 54 : accept = isPressed(k);
340 54 : if (!accept)
341 : break;
342 : }
343 72 : if (!accept)
344 37 : continue;
345 :
346 : // Check if this is an equally precise or more precise match
347 35 : if (hotkey.required.size() + 1u >= closestMapMatch)
348 : {
349 : // Check if more precise
350 35 : if (hotkey.required.size() + 1u > closestMapMatch)
351 : {
352 : // Throw away the old less-precise matches
353 31 : newPressedHotkeys.clear();
354 31 : closestMapMatch = hotkey.required.size() + 1u;
355 : }
356 35 : newPressedHotkeys.emplace_back(&hotkey, isReleasedKey);
357 : }
358 : }
359 :
360 40 : return Input::Reaction::PASS;
361 18 : }
362 :
363 44 : Input::Reaction HotkeyInputActualHandler(const SDL_Event& ev)
364 : {
365 44 : if (!currentEvent)
366 : return Input::Reaction::PASS;
367 :
368 40 : bool isInstantaneous = ev.type == SDL_MOUSEWHEEL;
369 :
370 : // TODO: it's probably possible to break hotkeys somewhat if the "Up" event that would release a hotkey is handled
371 : // by a priori handler - it might be safer to do that in the 'Prep' phase.
372 40 : std::vector<ReleasedHotkey> releasedHotkeys;
373 :
374 : // For instantaneous events, we don't update the pressedHotkeys (i.e. currently active hotkeys),
375 : // we just fire/release the triggered hotkeys transiently.
376 : // Therefore, skip the whole 'check pressedHotkeys & swap with newPressedHotkeys' logic.
377 40 : if (!isInstantaneous)
378 : {
379 73 : for (PressedHotkey& hotkey : pressedHotkeys)
380 : {
381 33 : bool addingAnew = std::find_if(newPressedHotkeys.begin(), newPressedHotkeys.end(),
382 60 : [&hotkey](const PressedHotkey& v){ return v.mapping->name == hotkey.mapping->name; }) != newPressedHotkeys.end();
383 :
384 : // Update the triggered status to match our current state.
385 33 : if (addingAnew)
386 9 : std::find_if(newPressedHotkeys.begin(), newPressedHotkeys.end(),
387 19 : [&hotkey](const PressedHotkey& v){ return v.mapping->name == hotkey.mapping->name; })->retriggered = hotkey.retriggered;
388 : // If the already-pressed hotkey has a lower specificity than the new hotkey(s), de-activate it.
389 24 : else if (hotkey.mapping->required.size() + 1u < closestMapMatch)
390 : {
391 5 : releasedHotkeys.emplace_back(hotkey.mapping->name.c_str(), hotkey.retriggered);
392 5 : continue;
393 : }
394 :
395 : // Check that the hotkey still matches all active keys.
396 28 : bool accept = isPressed(hotkey.mapping->primary);
397 28 : if (accept)
398 15 : for (const SKey& k : hotkey.mapping->required)
399 : {
400 3 : accept = isPressed(k);
401 3 : if (!accept)
402 : break;
403 : }
404 28 : if (!accept && !addingAnew)
405 14 : releasedHotkeys.emplace_back(hotkey.mapping->name.c_str(), hotkey.retriggered);
406 14 : else if (accept)
407 : {
408 : // If this hotkey has higher specificity than the new hotkeys we wanted to trigger/retrigger,
409 : // then discard this new addition(s). This works because at any given time, all hotkeys
410 : // active must have the same specificity.
411 12 : if (hotkey.mapping->required.size() + 1u > closestMapMatch)
412 : {
413 3 : closestMapMatch = hotkey.mapping->required.size() + 1u;
414 3 : newPressedHotkeys.clear();
415 3 : newPressedHotkeys.emplace_back(hotkey.mapping, hotkey.retriggered);
416 : }
417 9 : else if (!addingAnew)
418 2 : newPressedHotkeys.emplace_back(hotkey.mapping, hotkey.retriggered);
419 : }
420 : }
421 :
422 40 : pressedHotkeys.swap(newPressedHotkeys);
423 : }
424 :
425 74 : for (const PressedHotkey& hotkey : isInstantaneous ? newPressedHotkeys : pressedHotkeys)
426 : {
427 : // Send a KeyPress event when a hotkey is pressed initially and on mouseButton and mouseWheel events.
428 34 : if (ev.type != SDL_KEYDOWN || ev.key.repeat == 0)
429 : {
430 33 : SDL_Event hotkeyPressNotification{};
431 33 : hotkeyPressNotification.type = hotkey.retriggered ? SDL_HOTKEYPRESS_SILENT : SDL_HOTKEYPRESS;
432 33 : hotkeyPressNotification.user.data1 = const_cast<char*>(hotkey.mapping->name.c_str());
433 33 : g_VideoMode.m_InputManager.PushPriorityEvent(hotkeyPressNotification);
434 : }
435 :
436 : // Send a HotkeyDown event on every key, mouseButton and mouseWheel event.
437 : // The exception is on the first retriggering: hotkeys may fire transiently
438 : // while a user lifts fingers off multi-key hotkeys, and listeners to "hotkeydown"
439 : // generally don't expect that to trigger then.
440 : // (It might be better to check for HotkeyIsPressed, however).
441 : // For keys the event is repeated depending on hardware and OS configured interval.
442 : // On linux, modifier keys (shift, alt, ctrl) are not repeated, see https://github.com/SFML/SFML/issues/122.
443 34 : if (ev.key.repeat == 0 && hotkey.retriggered)
444 11 : continue;
445 23 : SDL_Event hotkeyDownNotification{};
446 23 : hotkeyDownNotification.type = SDL_HOTKEYDOWN;
447 23 : hotkeyDownNotification.user.data1 = const_cast<char*>(hotkey.mapping->name.c_str());
448 23 : g_VideoMode.m_InputManager.PushPriorityEvent(hotkeyDownNotification);
449 : }
450 :
451 : // Release instantaneous events (e.g. mouse wheel) right away.
452 40 : if (isInstantaneous)
453 0 : for (const PressedHotkey& hotkey : newPressedHotkeys)
454 0 : releasedHotkeys.emplace_back(hotkey.mapping->name.c_str(), false);
455 :
456 59 : for (const ReleasedHotkey& hotkey : releasedHotkeys)
457 : {
458 19 : SDL_Event hotkeyNotification{};
459 19 : hotkeyNotification.type = hotkey.wasRetriggered ? SDL_HOTKEYUP_SILENT : SDL_HOTKEYUP;
460 19 : hotkeyNotification.user.data1 = const_cast<char*>(hotkey.name);
461 19 : g_VideoMode.m_InputManager.PushPriorityEvent(hotkeyNotification);
462 : }
463 :
464 40 : return Input::Reaction::PASS;
465 44 : }
466 :
467 0 : bool EventWillFireHotkey(const SDL_Event& ev, const CStr& keyname)
468 : {
469 : // Sanity check of sort. This parameter mostly exists because it looks right from the caller's perspective.
470 0 : if (&ev != currentEvent || !currentEvent)
471 : return false;
472 :
473 0 : return std::find_if(newPressedHotkeys.begin(), newPressedHotkeys.end(),
474 0 : [&keyname](const PressedHotkey& v){ return v.mapping->name == keyname; }) != newPressedHotkeys.end();
475 : }
476 :
477 0 : void ResetActiveHotkeys()
478 : {
479 0 : newPressedHotkeys.clear();
480 0 : for (const PressedHotkey& hotkey : pressedHotkeys)
481 : {
482 0 : SDL_Event hotkeyNotification;
483 0 : hotkeyNotification.type = hotkey.retriggered ? SDL_HOTKEYUP_SILENT : SDL_HOTKEYUP;
484 0 : hotkeyNotification.user.data1 = const_cast<char*>(hotkey.mapping->name.c_str());
485 0 : g_VideoMode.m_InputManager.PushPriorityEvent(hotkeyNotification);
486 : }
487 0 : pressedHotkeys.clear();
488 0 : activeScancodes.clear();
489 0 : currentEvent = nullptr;
490 0 : }
491 :
492 92 : bool HotkeyIsPressed(const CStr& keyname)
493 : {
494 92 : return g_HotkeyStatus[keyname];
495 : }
|