OpenTTD Source 20261112-master-gbcbec5e63f
hotkeys.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "core/backup_type.hpp"
12#include "gfx_func.h"
13#include "hotkeys.h"
14#include "ini_type.h"
15#include "string_func.h"
16#include "window_gui.h"
18
19#include "safeguards.h"
20
21std::string _hotkeys_file;
22
27static std::vector<HotkeyList*> *_hotkey_lists = nullptr;
28
31 const std::string_view name;
33};
34
36static const std::initializer_list<KeycodeNames> _keycode_to_name = {
37 {"SHIFT", WKC_SHIFT},
38 {"CTRL", WKC_CTRL},
39 {"ALT", WKC_ALT},
40 {"META", WKC_META},
41 {"GLOBAL", WKC_GLOBAL_HOTKEY},
42 {"ESC", WKC_ESC},
43 {"BACKSPACE", WKC_BACKSPACE},
44 {"INS", WKC_INSERT},
45 {"DEL", WKC_DELETE},
46 {"PAGEUP", WKC_PAGEUP},
47 {"PAGEDOWN", WKC_PAGEDOWN},
48 {"END", WKC_END},
49 {"HOME", WKC_HOME},
50 {"RETURN", WKC_RETURN},
51 {"SPACE", WKC_SPACE},
52 {"F1", WKC_F1},
53 {"F2", WKC_F2},
54 {"F3", WKC_F3},
55 {"F4", WKC_F4},
56 {"F5", WKC_F5},
57 {"F6", WKC_F6},
58 {"F7", WKC_F7},
59 {"F8", WKC_F8},
60 {"F9", WKC_F9},
61 {"F10", WKC_F10},
62 {"F11", WKC_F11},
63 {"F12", WKC_F12},
64 {"BACKQUOTE", WKC_BACKQUOTE},
65 {"PAUSE", WKC_PAUSE},
66 {"NUM_DIV", WKC_NUM_DIV},
67 {"NUM_MUL", WKC_NUM_MUL},
68 {"NUM_MINUS", WKC_NUM_MINUS},
69 {"NUM_PLUS", WKC_NUM_PLUS},
70 {"NUM_ENTER", WKC_NUM_ENTER},
71 {"NUM_DOT", WKC_NUM_DECIMAL},
72 {"SLASH", WKC_SLASH},
73 {"/", WKC_SLASH}, /* deprecated, use SLASH */
74 {"SEMICOLON", WKC_SEMICOLON},
75 {";", WKC_SEMICOLON}, /* deprecated, use SEMICOLON */
76 {"EQUALS", WKC_EQUALS},
77 {"=", WKC_EQUALS}, /* deprecated, use EQUALS */
78 {"L_BRACKET", WKC_L_BRACKET},
79 {"[", WKC_L_BRACKET}, /* deprecated, use L_BRACKET */
80 {"BACKSLASH", WKC_BACKSLASH},
81 {"\\", WKC_BACKSLASH}, /* deprecated, use BACKSLASH */
82 {"R_BRACKET", WKC_R_BRACKET},
83 {"]", WKC_R_BRACKET}, /* deprecated, use R_BRACKET */
84 {"SINGLEQUOTE", WKC_SINGLEQUOTE},
85 {"'", WKC_SINGLEQUOTE}, /* deprecated, use SINGLEQUOTE */
86 {"COMMA", WKC_COMMA},
87 {"PERIOD", WKC_PERIOD},
88 {".", WKC_PERIOD}, /* deprecated, use PERIOD */
89 {"MINUS", WKC_MINUS},
90 {"-", WKC_MINUS}, /* deprecated, use MINUS */
91};
92
98static std::optional<uint16_t> ParseCode(std::string_view keystr)
99{
100 keystr = StrTrimView(keystr, StringConsumer::WHITESPACE_NO_NEWLINE);
101 for (const auto &kn : _keycode_to_name) {
102 if (StrEqualsIgnoreCase(keystr, kn.name)) {
103 return kn.keycode;
104 }
105 }
106 if (keystr.size() == 1) {
107 auto c = keystr[0];
108 if (c >= 'a' && c <= 'z') return c - ('a'-'A');
109 /* Ignore invalid keycodes */
110 if (static_cast<uint8_t>(c) < 128) return c;
111 }
112 return std::nullopt;
113}
114
120static std::optional<uint16_t> ParseKeycode(std::string_view keystr)
121{
122 if (keystr.empty()) return std::nullopt;
123 StringConsumer consumer{keystr};
124 uint16_t keycode = 0;
125 while (consumer.AnyBytesLeft()) {
126 auto cur = consumer.ReadUntilChar('+', StringConsumer::SKIP_ONE_SEPARATOR);
127 auto code = ParseCode(cur);
128 if (!code.has_value()) return std::nullopt;
129 if (*code & WKC_SPECIAL_KEYS) {
130 /* Some completely wrong keycode we don't support. */
131 if (*code & ~WKC_SPECIAL_KEYS) return std::nullopt;
132 keycode |= *code;
133 } else {
134 /* Ignore the code if it has more then 1 letter. */
135 if (keycode & ~WKC_SPECIAL_KEYS) return std::nullopt;
136 keycode |= *code;
137 }
138 }
139 return keycode;
140}
141
147static void ParseHotkeys(Hotkey &hotkey, std::string_view value)
148{
149 StringConsumer consumer{value};
150 while (consumer.AnyBytesLeft()) {
151 auto keystr = consumer.ReadUntilChar(',', StringConsumer::SKIP_ONE_SEPARATOR);
152 auto keycode = ParseKeycode(keystr);
153 if (keycode.has_value()) hotkey.AddKeycode(*keycode);
154 }
155}
156
164static std::string KeycodeToString(uint16_t keycode)
165{
166 std::string str;
167 if (keycode & WKC_GLOBAL_HOTKEY) {
168 str += "GLOBAL";
169 }
170 if (keycode & WKC_SHIFT) {
171 if (!str.empty()) str += "+";
172 str += "SHIFT";
173 }
174 if (keycode & WKC_CTRL) {
175 if (!str.empty()) str += "+";
176 str += "CTRL";
177 }
178 if (keycode & WKC_ALT) {
179 if (!str.empty()) str += "+";
180 str += "ALT";
181 }
182 if (keycode & WKC_META) {
183 if (!str.empty()) str += "+";
184 str += "META";
185 }
186 if (!str.empty()) str += "+";
187 keycode = keycode & ~WKC_SPECIAL_KEYS;
188
189 for (const auto &kn : _keycode_to_name) {
190 if (kn.keycode == keycode) {
191 str += kn.name;
192 return str;
193 }
194 }
195 assert(keycode < 128);
196 str.push_back(keycode);
197 return str;
198}
199
206std::string SaveKeycodes(const Hotkey &hotkey)
207{
208 std::string str;
209 for (auto keycode : hotkey.keycodes) {
210 if (!str.empty()) str += ",";
211 str += KeycodeToString(keycode);
212 }
213 return str;
214}
215
222Hotkey::Hotkey(uint16_t default_keycode, const std::string &name, int num) :
223 name(name),
224 num(num)
225{
226 if (default_keycode != 0) this->AddKeycode(default_keycode);
227}
228
235Hotkey::Hotkey(const std::vector<uint16_t> &default_keycodes, const std::string &name, int num) :
236 name(name),
237 num(num)
238{
239 for (uint16_t keycode : default_keycodes) {
240 this->AddKeycode(keycode);
241 }
242}
243
249void Hotkey::AddKeycode(uint16_t keycode)
250{
251 this->keycodes.insert(keycode);
252}
253
254HotkeyList::HotkeyList(const std::string &ini_group, const std::vector<Hotkey> &items, GlobalHotkeyHandlerFunc global_hotkey_handler) :
255 global_hotkey_handler(global_hotkey_handler), ini_group(ini_group), items(items)
256{
257 if (_hotkey_lists == nullptr) _hotkey_lists = new std::vector<HotkeyList*>();
258 _hotkey_lists->push_back(this);
259}
260
263{
264 _hotkey_lists->erase(std::ranges::find(*_hotkey_lists, this));
265}
266
271void HotkeyList::Load(const IniFile &ini)
272{
273 const IniGroup *group = ini.GetGroup(this->ini_group);
274 if (group == nullptr) return;
275 for (Hotkey &hotkey : this->items) {
276 const IniItem *item = group->GetItem(hotkey.name);
277 if (item != nullptr) {
278 hotkey.keycodes.clear();
279 if (item->value.has_value()) ParseHotkeys(hotkey, *item->value);
280 }
281 }
282}
283
288void HotkeyList::Save(IniFile &ini) const
289{
290 IniGroup &group = ini.GetOrCreateGroup(this->ini_group);
291 for (const Hotkey &hotkey : this->items) {
292 IniItem &item = group.GetOrCreateItem(hotkey.name);
293 item.SetValue(SaveKeycodes(hotkey));
294 }
295}
296
303int HotkeyList::CheckMatch(uint16_t keycode, bool global_only) const
304{
305 for (const Hotkey &hotkey : this->items) {
306 auto begin = hotkey.keycodes.begin();
307 auto end = hotkey.keycodes.end();
308 if (std::find(begin, end, keycode | WKC_GLOBAL_HOTKEY) != end || (!global_only && std::find(begin, end, keycode) != end)) {
309 return hotkey.num;
310 }
311 }
312 return -1;
313}
314
315
316static void SaveLoadHotkeys(bool save)
317{
318 IniFile ini{};
319 ini.LoadFromDisk(_hotkeys_file, Subdirectory::None);
320
321 for (HotkeyList *list : *_hotkey_lists) {
322 if (save) {
323 list->Save(ini);
324 } else {
325 list->Load(ini);
326 }
327 }
328
329 if (save) ini.SaveToDisk(_hotkeys_file);
330}
331
332
335{
336 SaveLoadHotkeys(false);
337}
338
341{
342 SaveLoadHotkeys(true);
343}
344
352static EventState HandleGlobalHotkey(HotkeyList::GlobalHotkeyHandlerFunc func, int hotkey)
353{
354 /* Clear global modifier keys so they do not interfere with modifiers assigned to hotkeys. */
355 AutoRestoreBackup pressed_backup{_input_pressed, {}};
356
357 return func(hotkey);
358}
359
360void HandleGlobalHotkeys([[maybe_unused]] char32_t key, uint16_t keycode)
361{
362 for (HotkeyList *list : *_hotkey_lists) {
363 if (list->global_hotkey_handler == nullptr) continue;
364
365 int hotkey = list->CheckMatch(keycode, true);
366 if (hotkey >= 0 && HandleGlobalHotkey(list->global_hotkey_handler, hotkey) == EventState::Handled) return;
367 }
368}
369
Class for backupping variables and making sure they are restored later.
Parse data from a string / buffer.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
static const std::string_view WHITESPACE_NO_NEWLINE
ASCII whitespace characters, excluding new-line.
@ None
A path without any base directory.
ControlInputs _input_pressed
Control inputs that are currently pressed.
Definition gfx.cpp:34
Functions related to the gfx engine.
WindowKeyCodes
Definition gfx_type.h:29
@ WKC_BACKSLASH
\ Backslash
Definition gfx_type.h:101
@ WKC_MINUS
Definition gfx_type.h:106
@ WKC_COMMA
, Comma
Definition gfx_type.h:104
@ WKC_PERIOD
. Period
Definition gfx_type.h:105
@ WKC_EQUALS
= Equals
Definition gfx_type.h:99
@ WKC_SLASH
/ Forward slash
Definition gfx_type.h:97
@ WKC_SINGLEQUOTE
' Single quote
Definition gfx_type.h:103
@ WKC_R_BRACKET
] Right square bracket
Definition gfx_type.h:102
@ WKC_L_BRACKET
[ Left square bracket
Definition gfx_type.h:100
@ WKC_GLOBAL_HOTKEY
Fake keycode bit to indicate global hotkeys.
Definition gfx_type.h:35
@ WKC_SEMICOLON
; Semicolon
Definition gfx_type.h:98
static EventState HandleGlobalHotkey(HotkeyList::GlobalHotkeyHandlerFunc func, int hotkey)
Call the global handler for a hotkey.
Definition hotkeys.cpp:352
static std::vector< HotkeyList * > * _hotkey_lists
List of all HotkeyLists.
Definition hotkeys.cpp:27
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
Definition hotkeys.cpp:334
static std::optional< uint16_t > ParseCode(std::string_view keystr)
Try to parse a single part of a keycode.
Definition hotkeys.cpp:98
static void ParseHotkeys(Hotkey &hotkey, std::string_view value)
Parse a string to the keycodes it represents.
Definition hotkeys.cpp:147
std::string SaveKeycodes(const Hotkey &hotkey)
Convert all keycodes attached to a hotkey to a single string.
Definition hotkeys.cpp:206
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition hotkeys.cpp:340
static std::optional< uint16_t > ParseKeycode(std::string_view keystr)
Parse a string representation of a keycode.
Definition hotkeys.cpp:120
static std::string KeycodeToString(uint16_t keycode)
Convert a hotkey to it's string representation so it can be written to the config file.
Definition hotkeys.cpp:164
static const std::initializer_list< KeycodeNames > _keycode_to_name
Array of non-standard keycodes that can be used in the hotkeys config file.
Definition hotkeys.cpp:36
Hotkey related functions.
Types related to reading/writing '*.ini' files.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
Definition string.cpp:324
Parse strings.
Functions related to low-level strings.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
List of hotkeys for a window.
Definition hotkeys.h:44
void Save(IniFile &ini) const
Save HotkeyList to IniFile.
Definition hotkeys.cpp:288
int CheckMatch(uint16_t keycode, bool global_only=false) const
Check if a keycode is bound to something.
Definition hotkeys.cpp:303
void Load(const IniFile &ini)
Load HotkeyList from IniFile.
Definition hotkeys.cpp:271
~HotkeyList()
Remove ourselves from the global hotkey list.
Definition hotkeys.cpp:262
All data for a single hotkey.
Definition hotkeys.h:20
Hotkey(uint16_t default_keycode, const std::string &name, int num)
Create a new Hotkey object with a single default keycode.
Definition hotkeys.cpp:222
void AddKeycode(uint16_t keycode)
Add a keycode to this hotkey, from now that keycode will be matched in addition to any previously add...
Definition hotkeys.cpp:249
Ini file that supports both loading and saving.
Definition ini_type.h:87
bool SaveToDisk(const std::string &filename)
Save the Ini file's data to the disk.
Definition ini.cpp:41
A group within an ini file.
Definition ini_type.h:34
const IniItem * GetItem(std::string_view name) const
Get the item with the given name.
Definition ini_load.cpp:50
IniItem & GetOrCreateItem(std::string_view name)
Get the item with the given name, and if it doesn't exist create a new item.
Definition ini_load.cpp:64
A single "line" in an ini file.
Definition ini_type.h:23
std::optional< std::string > value
The value of this item.
Definition ini_type.h:25
void SetValue(std::string_view value)
Replace the current value with another value.
Definition ini_load.cpp:30
const IniGroup * GetGroup(std::string_view name) const
Get the group with the given name.
Definition ini_load.cpp:117
void LoadFromDisk(std::string_view filename, Subdirectory subdir)
Load the Ini file's data from the disk.
Definition ini_load.cpp:184
IniGroup & GetOrCreateGroup(std::string_view name)
Get the group with the given name, and if it doesn't exist create a new group.
Definition ini_load.cpp:145
String representation of a keycode.
Definition hotkeys.cpp:30
WindowKeyCodes keycode
The keycode.
Definition hotkeys.cpp:32
const std::string_view name
Name of the keycode.
Definition hotkeys.cpp:31
Functions, definitions and such used only by the GUI.
EventState
State of handling an event.
@ Handled
The passed event is handled.