Debian Codegraph @

xbmc/input/keymaps/ButtonTranslator.cpp

raw
1 /*
2 * Copyright (C) 2005-2024 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 #include "ButtonTranslator.h"
10
11 #include "AppTranslator.h"
12 #include "FileItem.h"
13 #include "filesystem/Directory.h"
14 #include "guilib/WindowIDs.h"
15 #include "input/WindowTranslator.h"
16 #include "input/actions/Action.h"
17 #include "input/actions/ActionIDs.h"
18 #include "input/actions/ActionTranslator.h"
19 #include "input/keyboard/Key.h"
20 #include "input/keyboard/KeyIDs.h"
21 #include "input/keymaps/interfaces/IKeyMapper.h"
22 #include "input/keymaps/joysticks/GamepadTranslator.h"
23 #include "input/keymaps/keyboard/KeyboardTranslator.h"
24 #include "input/keymaps/remote/CustomControllerTranslator.h"
25 #include "input/keymaps/remote/IRTranslator.h"
26 #include "input/mouse/MouseTranslator.h"
27 #include "utils/StringUtils.h"
28 #include "utils/XBMCTinyXML2.h"
29 #include "utils/log.h"
30
31 #include <algorithm>
32 #include <utility>
33
34 using namespace KODI;
35 using namespace KEYMAP;
36
37 // Add the supplied device name to the list of connected devices
38 bool CButtonTranslator::AddDevice(const std::string& strDevice)
39 {
40 // Only add the device if it isn't already in the list
41 if (m_deviceList.find(strDevice) != m_deviceList.end())
42 return false;
43
44 // Add the device
45 m_deviceList.insert(strDevice);
46
47 // New device added so reload the key mappings
48 Load();
49
50 return true;
51 }
52
53 bool CButtonTranslator::RemoveDevice(const std::string& strDevice)
54 {
55 // Find the device
56 auto it = m_deviceList.find(strDevice);
57 if (it == m_deviceList.end())
58 return false;
59
60 // Remove the device
61 m_deviceList.erase(it);
62
63 // Device removed so reload the key mappings
64 Load();
65
66 return true;
67 }
68
69 bool CButtonTranslator::Load()
70 {
71 Clear();
72
73 // Directories to search for keymaps. They're applied in this order,
74 // so keymaps in profile/keymaps/ override e.g. system/keymaps
75 static std::vector<std::string> DIRS_TO_CHECK = {"special://xbmc/system/keymaps/",
76 "special://masterprofile/keymaps/",
77 "special://profile/keymaps/"};
78
79 bool success = false;
80
81 for (const auto& dir : DIRS_TO_CHECK)
82 {
83 if (XFILE::CDirectory::Exists(dir))
84 {
85 CFileItemList files;
86 XFILE::CDirectory::GetDirectory(dir, files, ".xml", XFILE::DIR_FLAG_DEFAULTS);
87 // Sort the list for filesystem based priorities, e.g. 01-keymap.xml, 02-keymap-overrides.xml
88 files.Sort(SortByFile, SortOrderAscending);
89 for (int fileIndex = 0; fileIndex < files.Size(); ++fileIndex)
90 {
91 if (!files[fileIndex]->m_bIsFolder)
92 success |= LoadKeymap(files[fileIndex]->GetPath());
93 }
94
95 // Load mappings for any HID devices we have connected
96 for (const auto& device : m_deviceList)
97 {
98 std::string devicedir = dir;
99 devicedir.append(device);
100 devicedir.append("/");
101 if (XFILE::CDirectory::Exists(devicedir))
102 {
103 CFileItemList files;
104 XFILE::CDirectory::GetDirectory(devicedir, files, ".xml", XFILE::DIR_FLAG_DEFAULTS);
105 // Sort the list for filesystem based priorities, e.g. 01-keymap.xml,
106 // 02-keymap-overrides.xml
107 files.Sort(SortByFile, SortOrderAscending);
108 for (int fileIndex = 0; fileIndex < files.Size(); ++fileIndex)
109 {
110 if (!files[fileIndex]->m_bIsFolder)
111 success |= LoadKeymap(files[fileIndex]->GetPath());
112 }
113 }
114 }
115 }
116 }
117
118 if (!success)
119 {
120 CLog::Log(LOGERROR, "Error loading keymaps from: {} or {} or {}", DIRS_TO_CHECK[0],
121 DIRS_TO_CHECK[1], DIRS_TO_CHECK[2]);
122 return false;
123 }
124
125 // Done!
126 return true;
127 }
128
129 bool CButtonTranslator::LoadKeymap(const std::string& keymapPath)
130 {
131 CXBMCTinyXML2 xmlDoc;
132
133 CLog::Log(LOGINFO, "Loading {}", keymapPath);
134 if (!xmlDoc.LoadFile(keymapPath))
135 {
136 CLog::Log(LOGERROR, "Error loading keymap: {}, Line {}\n{}", keymapPath, xmlDoc.ErrorLineNum(),
137 xmlDoc.ErrorStr());
138 return false;
139 }
140
141 auto* pRoot = xmlDoc.RootElement();
142 if (pRoot == nullptr)
143 {
144 CLog::Log(LOGERROR, "Error getting keymap root: {}", keymapPath);
145 return false;
146 }
147
148 std::string strValue = pRoot->Value();
149 if (strValue != "keymap")
150 {
151 CLog::Log(LOGERROR, "{} Doesn't contain <keymap>", keymapPath);
152 return false;
153 }
154
155 // run through our window groups
156 auto* pWindow = pRoot->FirstChild();
157 while (pWindow != nullptr)
158 {
159 if (pWindow->ToElement())
160 {
161 int windowID = WINDOW_INVALID;
162 const char* szWindow = pWindow->Value();
163 if (szWindow != nullptr)
164 {
165 if (StringUtils::CompareNoCase(szWindow, "global") == 0)
166 windowID = -1;
167 else
168 windowID = CWindowTranslator::TranslateWindow(szWindow);
169 }
170 MapWindowActions(pWindow, windowID);
171 }
172 pWindow = pWindow->NextSibling();
173 }
174
175 return true;
176 }
177
178 CAction CButtonTranslator::GetAction(int window, const CKey& key, bool fallback)
179 {
180 std::string strAction;
181
182 // handle virtual windows
183 window = CWindowTranslator::GetVirtualWindow(window);
184
185 // try to get the action from the current window
186 unsigned int actionID = GetActionCode(window, key, strAction);
187
188 if (fallback)
189 {
190 // if it's invalid, try to get it from fallback windows or the global map (window == -1)
191 while (actionID == ACTION_NONE && window > -1)
192 {
193 window = CWindowTranslator::GetFallbackWindow(window);
194 actionID = GetActionCode(window, key, strAction);
195 }
196 }
197
198 return CAction(actionID, strAction, key);
199 }
200
201 bool CButtonTranslator::HasLongpressMapping(int window, const CKey& key)
202 {
203 // handle virtual windows
204 window = CWindowTranslator::GetVirtualWindow(window);
205 return HasLongpressMapping_Internal(window, key);
206 }
207
208 bool CButtonTranslator::HasLongpressMapping_Internal(int window, const CKey& key)
209 {
210 std::map<int, buttonMap>::const_iterator it = m_translatorMap.find(window);
211 if (it != m_translatorMap.end())
212 {
213 uint32_t code = key.GetButtonCode();
214 code |= CKey::MODIFIER_LONG;
215 buttonMap::const_iterator it2 = (*it).second.find(code);
216
217 if (it2 != (*it).second.end())
218 return it2->second.id != ACTION_NOOP;
219
220 #ifdef TARGET_POSIX
221 // Some buttoncodes changed in Hardy
222 if ((code & KEY_VKEY) == KEY_VKEY && (code & 0x0F00))
223 {
224 code &= ~0x0F00;
225 it2 = (*it).second.find(code);
226 if (it2 != (*it).second.end())
227 return true;
228 }
229 #endif
230 }
231
232 // no key mapping found for the current window do the fallback handling
233 if (window > -1)
234 {
235 // first check if we have a fallback for the window
236 int fallbackWindow = CWindowTranslator::GetFallbackWindow(window);
237 if (fallbackWindow > -1 && HasLongpressMapping_Internal(fallbackWindow, key))
238 return true;
239
240 // fallback to default section
241 return HasLongpressMapping_Internal(-1, key);
242 }
243
244 return false;
245 }
246
247 unsigned int CButtonTranslator::GetActionCode(int window,
248 const CKey& key,
249 std::string& strAction) const
250 {
251 uint32_t code = key.GetButtonCode();
252
253 std::map<int, buttonMap>::const_iterator it = m_translatorMap.find(window);
254 if (it == m_translatorMap.end())
255 return ACTION_NONE;
256
257 buttonMap::const_iterator it2 = (*it).second.find(code);
258 unsigned int action = ACTION_NONE;
259 if (it2 == (*it).second.end() &&
260 code & CKey::MODIFIER_LONG) // If long action not found, try short one
261 {
262 code &= ~CKey::MODIFIER_LONG;
263 it2 = (*it).second.find(code);
264 }
265
266 if (it2 != (*it).second.end())
267 {
268 action = (*it2).second.id;
269 strAction = (*it2).second.strID;
270 }
271
272 #ifdef TARGET_POSIX
273 // Some buttoncodes changed in Hardy
274 if (action == ACTION_NONE && (code & KEY_VKEY) == KEY_VKEY && (code & 0x0F00))
275 {
276 CLog::Log(LOGDEBUG, "{}: Trying Hardy keycode for {:#04x}", __FUNCTION__, code);
277 code &= ~0x0F00;
278 it2 = (*it).second.find(code);
279 if (it2 != (*it).second.end())
280 {
281 action = (*it2).second.id;
282 strAction = (*it2).second.strID;
283 }
284 }
285 #endif
286
287 return action;
288 }
289
290 void CButtonTranslator::MapAction(uint32_t buttonCode, const std::string& szAction, buttonMap& map)
291 {
292 unsigned int action = ACTION_NONE;
293 if (!ACTION::CActionTranslator::TranslateString(szAction, action) || buttonCode == 0)
294 return; // no valid action, or an invalid buttoncode
295
296 // have a valid action, and a valid button - map it.
297 // check to see if we've already got this (button,action) pair defined
298 buttonMap::iterator it = map.find(buttonCode);
299 if (it == map.end() || (*it).second.id != action || (*it).second.strID != szAction)
300 {
301 // NOTE: This multimap is only being used as a normal map at this point (no support
302 // for multiple actions per key)
303 if (it != map.end())
304 map.erase(it);
305 CButtonAction button;
306 button.id = action;
307 button.strID = szAction;
308 map.insert(std::pair<uint32_t, CButtonAction>(buttonCode, button));
309 }
310 }
311
312 void CButtonTranslator::MapWindowActions(const tinyxml2::XMLNode* pWindow, int windowID)
313 {
314 if (pWindow == nullptr || windowID == WINDOW_INVALID)
315 return;
316
317 static const std::vector<std::string> types = {"gamepad", "remote", "universalremote",
318 "keyboard", "mouse", "appcommand"};
319
320 for (const auto& type : types)
321 {
322 for (auto* pDevice = pWindow->FirstChildElement(type.c_str()); pDevice != nullptr;
323 pDevice = pDevice->NextSiblingElement(type.c_str()))
324 {
325 buttonMap map;
326 std::map<int, buttonMap>::iterator it = m_translatorMap.find(windowID);
327 if (it != m_translatorMap.end())
328 {
329 map = std::move(it->second);
330 m_translatorMap.erase(it);
331 }
332
333 const auto* pButton = pDevice->FirstChildElement();
334
335 while (pButton != nullptr)
336 {
337 uint32_t buttonCode = 0;
338
339 if (type == "gamepad")
340 buttonCode = CGamepadTranslator::TranslateString(pButton->Value());
341 else if (type == "remote")
342 buttonCode = CIRTranslator::TranslateString(pButton->Value());
343 else if (type == "universalremote")
344 buttonCode = CIRTranslator::TranslateUniversalRemoteString(pButton->Value());
345 else if (type == "keyboard")
346 buttonCode = CKeyboardTranslator::TranslateButton(pButton);
347 else if (type == "mouse")
348 buttonCode = CMouseTranslator::TranslateCommand(pButton);
349 else if (type == "appcommand")
350 buttonCode = CAppTranslator::TranslateAppCommand(pButton->Value());
351
352 if (buttonCode != 0)
353 {
354 if (pButton->FirstChild() && pButton->FirstChild()->Value()[0])
355 MapAction(buttonCode, pButton->FirstChild()->Value(), map);
356 else
357 {
358 buttonMap::iterator it = map.find(buttonCode);
359 while (it != map.end())
360 {
361 map.erase(it);
362 it = map.find(buttonCode);
363 }
364 }
365 }
366 pButton = pButton->NextSiblingElement();
367 }
368
369 // add our map to our table
370 if (!map.empty())
371 m_translatorMap.insert(std::make_pair(windowID, std::move(map)));
372 }
373 }
374
375 for (const auto& it : m_buttonMappers)
376 {
377 const std::string& device = it.first;
378 IKeyMapper* mapper = it.second;
379
380 // Map device actions
381 auto* pDevice = pWindow->FirstChildElement(device.c_str());
382 while (pDevice)
383 {
384 mapper->MapActions(windowID, pDevice);
385 pDevice = pDevice->NextSiblingElement(device.c_str());
386 }
387 }
388 }
389
390 void CButtonTranslator::Clear()
391 {
392 m_translatorMap.clear();
393
394 for (auto it : m_buttonMappers)
395 it.second->Clear();
396 }
397
398 void CButtonTranslator::RegisterMapper(const std::string& device, IKeyMapper* mapper)
399 {
400 m_buttonMappers[device] = mapper;
401 }
402
403 void CButtonTranslator::UnregisterMapper(const IKeyMapper* mapper)
404 {
405 for (auto it = m_buttonMappers.begin(); it != m_buttonMappers.end(); ++it)
406 {
407 if (it->second == mapper)
408 {
409 m_buttonMappers.erase(it);
410 break;
411 }
412 }
413 }
414
415 uint32_t CButtonTranslator::TranslateString(const std::string& strMap, const std::string& strButton)
416 {
417 if (strMap == "KB") // standard keyboard map
418 {
419 return CKeyboardTranslator::TranslateString(strButton);
420 }
421 else if (strMap == "XG") // xbox gamepad map
422 {
423 return CGamepadTranslator::TranslateString(strButton);
424 }
425 else if (strMap == "R1") // xbox remote map
426 {
427 return CIRTranslator::TranslateString(strButton);
428 }
429 else if (strMap == "R2") // xbox universal remote map
430 {
431 return CIRTranslator::TranslateUniversalRemoteString(strButton);
432 }
433 else
434 {
435 return 0;
436 }
437 }