OpenTTD Source: src/hotkeys.cpp Source File

OpenTTD Source 15.0-RC2

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
10#include "stdafx.h"
11#include "openttd.h"
12#include "hotkeys.h"
13#include "ini_type.h"
14#include "string_func.h"
15#include "window_gui.h"
16#include "core/string_consumer.hpp"
17
18#include "safeguards.h"
19
20std::string _hotkeys_file;
21
26 static std::vector<HotkeyList*> *_hotkey_lists = nullptr;
27
29 struct KeycodeNames {
30 const std::string_view name;
31 WindowKeyCodes keycode;
32};
33
35 static const std::initializer_list<KeycodeNames> _keycode_to_name = {
36 {"SHIFT", WKC_SHIFT},
37 {"CTRL", WKC_CTRL},
38 {"ALT", WKC_ALT},
39 {"META", WKC_META},
40 {"GLOBAL", WKC_GLOBAL_HOTKEY},
41 {"ESC", WKC_ESC},
42 {"BACKSPACE", WKC_BACKSPACE},
43 {"INS", WKC_INSERT},
44 {"DEL", WKC_DELETE},
45 {"PAGEUP", WKC_PAGEUP},
46 {"PAGEDOWN", WKC_PAGEDOWN},
47 {"END", WKC_END},
48 {"HOME", WKC_HOME},
49 {"RETURN", WKC_RETURN},
50 {"SPACE", WKC_SPACE},
51 {"F1", WKC_F1},
52 {"F2", WKC_F2},
53 {"F3", WKC_F3},
54 {"F4", WKC_F4},
55 {"F5", WKC_F5},
56 {"F6", WKC_F6},
57 {"F7", WKC_F7},
58 {"F8", WKC_F8},
59 {"F9", WKC_F9},
60 {"F10", WKC_F10},
61 {"F11", WKC_F11},
62 {"F12", WKC_F12},
63 {"BACKQUOTE", WKC_BACKQUOTE},
64 {"PAUSE", WKC_PAUSE},
65 {"NUM_DIV", WKC_NUM_DIV},
66 {"NUM_MUL", WKC_NUM_MUL},
67 {"NUM_MINUS", WKC_NUM_MINUS},
68 {"NUM_PLUS", WKC_NUM_PLUS},
69 {"NUM_ENTER", WKC_NUM_ENTER},
70 {"NUM_DOT", WKC_NUM_DECIMAL},
71 {"SLASH", WKC_SLASH},
72 {"/", WKC_SLASH}, /* deprecated, use SLASH */
73 {"SEMICOLON", WKC_SEMICOLON},
74 {";", WKC_SEMICOLON}, /* deprecated, use SEMICOLON */
75 {"EQUALS", WKC_EQUALS},
76 {"=", WKC_EQUALS}, /* deprecated, use EQUALS */
77 {"L_BRACKET", WKC_L_BRACKET},
78 {"[", WKC_L_BRACKET}, /* deprecated, use L_BRACKET */
79 {"BACKSLASH", WKC_BACKSLASH},
80 {"\\", WKC_BACKSLASH}, /* deprecated, use BACKSLASH */
81 {"R_BRACKET", WKC_R_BRACKET},
82 {"]", WKC_R_BRACKET}, /* deprecated, use R_BRACKET */
83 {"SINGLEQUOTE", WKC_SINGLEQUOTE},
84 {"'", WKC_SINGLEQUOTE}, /* deprecated, use SINGLEQUOTE */
85 {"COMMA", WKC_COMMA},
86 {"PERIOD", WKC_PERIOD},
87 {".", WKC_PERIOD}, /* deprecated, use PERIOD */
88 {"MINUS", WKC_MINUS},
89 {"-", WKC_MINUS}, /* deprecated, use MINUS */
90};
91
97 static std::optional<uint16_t> ParseCode(std::string_view keystr)
98{
99 keystr = StrTrimView(keystr, StringConsumer::WHITESPACE_NO_NEWLINE);
100 for (const auto &kn : _keycode_to_name) {
101 if (StrEqualsIgnoreCase(keystr, kn.name)) {
102 return kn.keycode;
103 }
104 }
105 if (keystr.size() == 1) {
106 auto c = keystr[0];
107 if (c >= 'a' && c <= 'z') return c - ('a'-'A');
108 /* Ignore invalid keycodes */
109 if (static_cast<uint8_t>(c) < 128) return c;
110 }
111 return std::nullopt;
112}
113
119 static std::optional<uint16_t> ParseKeycode(std::string_view keystr)
120{
121 if (keystr.empty()) return std::nullopt;
122 StringConsumer consumer{keystr};
123 uint16_t keycode = 0;
124 while (consumer.AnyBytesLeft()) {
125 auto cur = consumer.ReadUntilChar('+', StringConsumer::SKIP_ONE_SEPARATOR);
126 auto code = ParseCode(cur);
127 if (!code.has_value()) return std::nullopt;
128 if (*code & WKC_SPECIAL_KEYS) {
129 /* Some completely wrong keycode we don't support. */
130 if (*code & ~WKC_SPECIAL_KEYS) return std::nullopt;
131 keycode |= *code;
132 } else {
133 /* Ignore the code if it has more then 1 letter. */
134 if (keycode & ~WKC_SPECIAL_KEYS) return std::nullopt;
135 keycode |= *code;
136 }
137 }
138 return keycode;
139}
140
146 static void ParseHotkeys(Hotkey &hotkey, std::string_view value)
147{
148 StringConsumer consumer{value};
149 while (consumer.AnyBytesLeft()) {
150 auto keystr = consumer.ReadUntilChar(',', StringConsumer::SKIP_ONE_SEPARATOR);
151 auto keycode = ParseKeycode(keystr);
152 if (keycode.has_value()) hotkey.AddKeycode(*keycode);
153 }
154}
155
163 static std::string KeycodeToString(uint16_t keycode)
164{
165 std::string str;
166 if (keycode & WKC_GLOBAL_HOTKEY) {
167 str += "GLOBAL";
168 }
169 if (keycode & WKC_SHIFT) {
170 if (!str.empty()) str += "+";
171 str += "SHIFT";
172 }
173 if (keycode & WKC_CTRL) {
174 if (!str.empty()) str += "+";
175 str += "CTRL";
176 }
177 if (keycode & WKC_ALT) {
178 if (!str.empty()) str += "+";
179 str += "ALT";
180 }
181 if (keycode & WKC_META) {
182 if (!str.empty()) str += "+";
183 str += "META";
184 }
185 if (!str.empty()) str += "+";
186 keycode = keycode & ~WKC_SPECIAL_KEYS;
187
188 for (const auto &kn : _keycode_to_name) {
189 if (kn.keycode == keycode) {
190 str += kn.name;
191 return str;
192 }
193 }
194 assert(keycode < 128);
195 str.push_back(keycode);
196 return str;
197}
198
205std::string SaveKeycodes(const Hotkey &hotkey)
206{
207 std::string str;
208 for (auto keycode : hotkey.keycodes) {
209 if (!str.empty()) str += ",";
210 str += KeycodeToString(keycode);
211 }
212 return str;
213}
214
221Hotkey::Hotkey(uint16_t default_keycode, const std::string &name, int num) :
222 name(name),
223 num(num)
224{
225 if (default_keycode != 0) this->AddKeycode(default_keycode);
226}
227
234 Hotkey::Hotkey(const std::vector<uint16_t> &default_keycodes, const std::string &name, int num) :
235 name(name),
236 num(num)
237{
238 for (uint16_t keycode : default_keycodes) {
239 this->AddKeycode(keycode);
240 }
241}
242
248 void Hotkey::AddKeycode(uint16_t keycode)
249{
250 this->keycodes.insert(keycode);
251}
252
253HotkeyList::HotkeyList(const std::string &ini_group, const std::vector<Hotkey> &items, GlobalHotkeyHandlerFunc global_hotkey_handler) :
254 global_hotkey_handler(global_hotkey_handler), ini_group(ini_group), items(items)
255{
256 if (_hotkey_lists == nullptr) _hotkey_lists = new std::vector<HotkeyList*>();
257 _hotkey_lists->push_back(this);
258}
259
260HotkeyList::~HotkeyList()
261{
262 _hotkey_lists->erase(std::ranges::find(*_hotkey_lists, this));
263}
264
269 void HotkeyList::Load(const IniFile &ini)
270{
271 const IniGroup *group = ini.GetGroup(this->ini_group);
272 if (group == nullptr) return;
273 for (Hotkey &hotkey : this->items) {
274 const IniItem *item = group->GetItem(hotkey.name);
275 if (item != nullptr) {
276 hotkey.keycodes.clear();
277 if (item->value.has_value()) ParseHotkeys(hotkey, *item->value);
278 }
279 }
280}
281
286 void HotkeyList::Save(IniFile &ini) const
287{
288 IniGroup &group = ini.GetOrCreateGroup(this->ini_group);
289 for (const Hotkey &hotkey : this->items) {
290 IniItem &item = group.GetOrCreateItem(hotkey.name);
291 item.SetValue(SaveKeycodes(hotkey));
292 }
293}
294
301 int HotkeyList::CheckMatch(uint16_t keycode, bool global_only) const
302{
303 for (const Hotkey &hotkey : this->items) {
304 auto begin = hotkey.keycodes.begin();
305 auto end = hotkey.keycodes.end();
306 if (std::find(begin, end, keycode | WKC_GLOBAL_HOTKEY) != end || (!global_only && std::find(begin, end, keycode) != end)) {
307 return hotkey.num;
308 }
309 }
310 return -1;
311}
312
313
314static void SaveLoadHotkeys(bool save)
315{
316 IniFile ini{};
317 ini.LoadFromDisk(_hotkeys_file, NO_DIRECTORY);
318
319 for (HotkeyList *list : *_hotkey_lists) {
320 if (save) {
321 list->Save(ini);
322 } else {
323 list->Load(ini);
324 }
325 }
326
327 if (save) ini.SaveToDisk(_hotkeys_file);
328}
329
330
332 void LoadHotkeysFromConfig()
333{
334 SaveLoadHotkeys(false);
335}
336
338 void SaveHotkeysToConfig()
339{
340 SaveLoadHotkeys(true);
341}
342
343void HandleGlobalHotkeys([[maybe_unused]] char32_t key, uint16_t keycode)
344{
345 for (HotkeyList *list : *_hotkey_lists) {
346 if (list->global_hotkey_handler == nullptr) continue;
347
348 int hotkey = list->CheckMatch(keycode, true);
349 if (hotkey >= 0 && (list->global_hotkey_handler(hotkey) == ES_HANDLED)) return;
350 }
351}
352
StringConsumer
Parse data from a string / buffer.
Definition string_consumer.hpp:27
StringConsumer::ReadUntilChar
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
Definition string_consumer.hpp:765
StringConsumer::SKIP_ONE_SEPARATOR
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
Definition string_consumer.hpp:696
StringConsumer::WHITESPACE_NO_NEWLINE
static const std::string_view WHITESPACE_NO_NEWLINE
ASCII whitespace characters, excluding new-line.
Definition string_consumer.hpp:40
NO_DIRECTORY
@ NO_DIRECTORY
A path without any base directory.
Definition fileio_type.h:107
WindowKeyCodes
WindowKeyCodes
Definition gfx_type.h:29
WKC_BACKSLASH
@ WKC_BACKSLASH
\ Backslash
Definition gfx_type.h:101
WKC_MINUS
@ WKC_MINUS
Definition gfx_type.h:106
WKC_COMMA
@ WKC_COMMA
, Comma
Definition gfx_type.h:104
WKC_PERIOD
@ WKC_PERIOD
. Period
Definition gfx_type.h:105
WKC_EQUALS
@ WKC_EQUALS
= Equals
Definition gfx_type.h:99
WKC_SLASH
@ WKC_SLASH
/ Forward slash
Definition gfx_type.h:97
WKC_SINGLEQUOTE
@ WKC_SINGLEQUOTE
' Single quote
Definition gfx_type.h:103
WKC_R_BRACKET
@ WKC_R_BRACKET
] Right square bracket
Definition gfx_type.h:102
WKC_L_BRACKET
@ WKC_L_BRACKET
[ Left square bracket
Definition gfx_type.h:100
WKC_GLOBAL_HOTKEY
@ WKC_GLOBAL_HOTKEY
Fake keycode bit to indicate global hotkeys.
Definition gfx_type.h:35
WKC_SEMICOLON
@ WKC_SEMICOLON
; Semicolon
Definition gfx_type.h:98
_hotkey_lists
static std::vector< HotkeyList * > * _hotkey_lists
List of all HotkeyLists.
Definition hotkeys.cpp:26
LoadHotkeysFromConfig
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
Definition hotkeys.cpp:332
ParseCode
static std::optional< uint16_t > ParseCode(std::string_view keystr)
Try to parse a single part of a keycode.
Definition hotkeys.cpp:97
ParseHotkeys
static void ParseHotkeys(Hotkey &hotkey, std::string_view value)
Parse a string to the keycodes it represents.
Definition hotkeys.cpp:146
SaveKeycodes
std::string SaveKeycodes(const Hotkey &hotkey)
Convert all keycodes attached to a hotkey to a single string.
Definition hotkeys.cpp:205
SaveHotkeysToConfig
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition hotkeys.cpp:338
ParseKeycode
static std::optional< uint16_t > ParseKeycode(std::string_view keystr)
Parse a string representation of a keycode.
Definition hotkeys.cpp:119
KeycodeToString
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:163
_keycode_to_name
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:35
hotkeys.h
Hotkey related functions.
ini_type.h
Types related to reading/writing '*.ini' files.
openttd.h
Some generic types.
safeguards.h
A number of safeguards to prevent using unsafe methods.
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
StrEqualsIgnoreCase
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:323
string_consumer.hpp
Parse strings.
string_func.h
Functions related to low-level strings.
HotkeyList
List of hotkeys for a window.
Definition hotkeys.h:37
HotkeyList::Save
void Save(IniFile &ini) const
Save HotkeyList to IniFile.
Definition hotkeys.cpp:286
HotkeyList::CheckMatch
int CheckMatch(uint16_t keycode, bool global_only=false) const
Check if a keycode is bound to something.
Definition hotkeys.cpp:301
HotkeyList::Load
void Load(const IniFile &ini)
Load HotkeyList from IniFile.
Definition hotkeys.cpp:269
Hotkey
All data for a single hotkey.
Definition hotkeys.h:21
Hotkey::Hotkey
Hotkey(uint16_t default_keycode, const std::string &name, int num)
Create a new Hotkey object with a single default keycode.
Definition hotkeys.cpp:221
Hotkey::AddKeycode
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:248
IniFile
Ini file that supports both loading and saving.
Definition ini_type.h:86
IniGroup
A group within an ini file.
Definition ini_type.h:34
IniGroup::GetItem
const IniItem * GetItem(std::string_view name) const
Get the item with the given name.
Definition ini_load.cpp:51
IniGroup::GetOrCreateItem
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:65
IniItem
A single "line" in an ini file.
Definition ini_type.h:23
IniItem::value
std::optional< std::string > value
The value of this item.
Definition ini_type.h:25
IniItem::SetValue
void SetValue(std::string_view value)
Replace the current value with another value.
Definition ini_load.cpp:31
IniLoadFile::GetGroup
const IniGroup * GetGroup(std::string_view name) const
Get the group with the given name.
Definition ini_load.cpp:118
IniLoadFile::LoadFromDisk
void LoadFromDisk(std::string_view filename, Subdirectory subdir)
Load the Ini file's data from the disk.
Definition ini_load.cpp:185
IniLoadFile::GetOrCreateGroup
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:146
KeycodeNames
String representation of a keycode.
Definition hotkeys.cpp:29
KeycodeNames::keycode
WindowKeyCodes keycode
The keycode.
Definition hotkeys.cpp:31
KeycodeNames::name
const std::string_view name
Name of the keycode.
Definition hotkeys.cpp:30
window_gui.h
Functions, definitions and such used only by the GUI.
ES_HANDLED
@ ES_HANDLED
The passed event is handled.
Definition window_type.h:781