Debian Codegraph @

xbmc/peripherals/Peripherals.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 "Peripherals.h"
10
11 #include "CompileInfo.h"
12 #include "addons/AddonButtonMap.h"
13 #include "addons/AddonManager.h"
14 #include "addons/addoninfo/AddonInfo.h"
15 #include "addons/addoninfo/AddonType.h"
16 #include "addons/gui/GUIDialogAddonSettings.h"
17 #include "addons/gui/GUIWindowAddonBrowser.h"
18 #include "bus/PeripheralBus.h"
19 #include "bus/PeripheralBusUSB.h"
20
21 #include <mutex>
22 #include <utility>
23 #if defined(TARGET_ANDROID)
24 #include "platform/android/peripherals/PeripheralBusAndroid.h"
25 #elif defined(TARGET_DARWIN)
26 #include "platform/darwin/peripherals/PeripheralBusGCController.h"
27 #endif
28 #include "FileItem.h"
29 #include "GUIUserMessages.h"
30 #include "ServiceBroker.h"
31 #include "bus/virtual/PeripheralBusAddon.h"
32 #include "bus/virtual/PeripheralBusApplication.h"
33 #include "devices/PeripheralBluetooth.h"
34 #include "devices/PeripheralCecAdapter.h"
35 #include "devices/PeripheralDisk.h"
36 #include "devices/PeripheralHID.h"
37 #include "devices/PeripheralImon.h"
38 #include "devices/PeripheralJoystick.h"
39 #include "devices/PeripheralKeyboard.h"
40 #include "devices/PeripheralMouse.h"
41 #include "devices/PeripheralNIC.h"
42 #include "devices/PeripheralNyxboard.h"
43 #include "devices/PeripheralTuner.h"
44 #include "filesystem/Directory.h"
45 #include "guilib/GUIComponent.h"
46 #include "guilib/GUIWindowManager.h"
47 #include "guilib/WindowIDs.h"
48 #include "input/actions/Action.h"
49 #include "input/actions/ActionIDs.h"
50 #include "input/joysticks/interfaces/IButtonMapper.h"
51 #include "input/keyboard/Key.h"
52 #include "interfaces/AnnouncementManager.h"
53 #include "messaging/ApplicationMessenger.h"
54 #include "messaging/ThreadMessage.h"
55 #include "peripherals/dialogs/GUIDialogPeripherals.h"
56 #include "peripherals/events/EventScanner.h"
57 #include "settings/SettingAddon.h"
58 #include "settings/Settings.h"
59 #include "settings/SettingsComponent.h"
60 #include "settings/lib/Setting.h"
61 #include "utils/StringUtils.h"
62 #include "utils/XBMCTinyXML2.h"
63 #include "utils/XMLUtils.h"
64 #include "utils/log.h"
65
66 #if defined(HAVE_LIBCEC)
67 #include "bus/virtual/PeripheralBusCEC.h"
68 #else
69 #include "dialogs/GUIDialogKaiToast.h"
70 #include "guilib/LocalizeStrings.h"
71 #endif
72
73 using namespace KODI;
74 using namespace JOYSTICK;
75 using namespace PERIPHERALS;
76 using namespace XFILE;
77
78 CPeripherals::CPeripherals(CInputManager& inputManager,
79 GAME::CControllerManager& controllerProfiles)
80 : m_inputManager(inputManager),
81 m_controllerProfiles(controllerProfiles),
82 m_eventScanner(new CEventScanner(*this)),
83 m_guiReadyEvent(std::make_unique<CEvent>())
84 {
85 // Register settings
86 std::set<std::string> settingSet;
87 settingSet.insert(CSettings::SETTING_INPUT_PERIPHERALS);
88 settingSet.insert(CSettings::SETTING_INPUT_PERIPHERALLIBRARIES);
89 settingSet.insert(CSettings::SETTING_INPUT_CONTROLLERCONFIG);
90 settingSet.insert(CSettings::SETTING_INPUT_TESTRUMBLE);
91 settingSet.insert(CSettings::SETTING_LOCALE_LANGUAGE);
92 CServiceBroker::GetSettingsComponent()->GetSettings()->RegisterCallback(this, settingSet);
93 }
94
95 CPeripherals::~CPeripherals()
96 {
97 // Unregister with GUI messenger
98 CGUIComponent* gui = CServiceBroker::GetGUI();
99 if (gui != nullptr)
100 gui->GetWindowManager().RemoveMsgTarget(this);
101
102 m_guiReadyEvent->Set();
103
104 // Unregister settings
105 CServiceBroker::GetSettingsComponent()->GetSettings()->UnregisterCallback(this);
106
107 Clear();
108 }
109
110 void CPeripherals::Initialise()
111 {
112 Clear();
113
114 CDirectory::Create("special://profile/peripheral_data");
115
116 /* load mappings from peripherals.xml */
117 LoadMappings();
118
119 std::vector<PeripheralBusPtr> busses;
120
121 #if defined(HAVE_PERIPHERAL_BUS_USB)
122 busses.push_back(std::make_shared<CPeripheralBusUSB>(*this));
123 #endif
124 #if defined(HAVE_LIBCEC)
125 busses.push_back(std::make_shared<CPeripheralBusCEC>(*this));
126 #endif
127 busses.push_back(std::make_shared<CPeripheralBusAddon>(*this));
128 #if defined(TARGET_ANDROID)
129 busses.push_back(std::make_shared<CPeripheralBusAndroid>(*this));
130 #elif defined(TARGET_DARWIN)
131 busses.push_back(std::make_shared<CPeripheralBusGCController>(*this));
132 #endif
133 busses.push_back(std::make_shared<CPeripheralBusApplication>(*this));
134
135 {
136 std::unique_lock<CCriticalSection> bussesLock(m_critSectionBusses);
137 m_busses = busses;
138 }
139
140 /* initialise all known busses and run an initial scan for devices */
141 for (auto& bus : busses)
142 bus->Initialise();
143
144 m_eventScanner->Start();
145
146 CServiceBroker::GetAppMessenger()->RegisterReceiver(this);
147 CServiceBroker::GetAnnouncementManager()->AddAnnouncer(this);
148
149 // Register for GUI messages
150 CGUIComponent* gui = CServiceBroker::GetGUI();
151 if (gui != nullptr)
152 gui->GetWindowManager().AddMsgTarget(this);
153 }
154
155 void CPeripherals::Clear()
156 {
157 CServiceBroker::GetAnnouncementManager()->RemoveAnnouncer(this);
158
159 m_eventScanner->Stop();
160
161 // avoid deadlocks by copying all busses into a temporary variable and destroying them from there
162 std::vector<PeripheralBusPtr> busses;
163 {
164 std::unique_lock<CCriticalSection> bussesLock(m_critSectionBusses);
165 /* delete busses and devices */
166 busses = m_busses;
167 m_busses.clear();
168 }
169
170 for (const auto& bus : busses)
171 bus->Clear();
172 busses.clear();
173
174 {
175 std::unique_lock<CCriticalSection> mappingsLock(m_critSectionMappings);
176 /* delete mappings */
177 for (auto& mapping : m_mappings)
178 mapping.m_settings.clear();
179 m_mappings.clear();
180 }
181
182 #if !defined(HAVE_LIBCEC)
183 m_bMissingLibCecWarningDisplayed = false;
184 #endif
185 }
186
187 void CPeripherals::TriggerDeviceScan(const PeripheralBusType type /* = PERIPHERAL_BUS_UNKNOWN */)
188 {
189 std::vector<PeripheralBusPtr> busses;
190 {
191 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
192 busses = m_busses;
193 }
194
195 for (auto& bus : busses)
196 {
197 bool bScan = false;
198
199 if (type == PERIPHERAL_BUS_UNKNOWN)
200 bScan = true;
201 else if (bus->Type() == PERIPHERAL_BUS_ADDON)
202 bScan = true;
203 else if (bus->Type() == type)
204 bScan = true;
205
206 if (bScan)
207 bus->TriggerDeviceScan();
208 }
209 }
210
211 PeripheralBusPtr CPeripherals::GetBusByType(const PeripheralBusType type) const
212 {
213 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
214
215 const auto& bus =
216 std::find_if(m_busses.cbegin(), m_busses.cend(),
217 [type](const PeripheralBusPtr& bus) { return bus->Type() == type; });
218 if (bus != m_busses.cend())
219 return *bus;
220
221 return nullptr;
222 }
223
224 PeripheralPtr CPeripherals::GetPeripheralAtLocation(
225 const std::string& strLocation, PeripheralBusType busType /* = PERIPHERAL_BUS_UNKNOWN */) const
226 {
227 PeripheralPtr result;
228
229 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
230 for (const auto& bus : m_busses)
231 {
232 /* check whether the bus matches if a bus type other than unknown was passed */
233 if (busType != PERIPHERAL_BUS_UNKNOWN && bus->Type() != busType)
234 continue;
235
236 /* return the first device that matches */
237 PeripheralPtr peripheral = bus->GetPeripheral(strLocation);
238 if (peripheral)
239 {
240 result = peripheral;
241 break;
242 }
243 }
244
245 return result;
246 }
247
248 bool CPeripherals::HasPeripheralAtLocation(
249 const std::string& strLocation, PeripheralBusType busType /* = PERIPHERAL_BUS_UNKNOWN */) const
250 {
251 return (GetPeripheralAtLocation(strLocation, busType) != nullptr);
252 }
253
254 PeripheralBusPtr CPeripherals::GetBusWithDevice(const std::string& strLocation) const
255 {
256 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
257
258 const auto& bus = std::find_if(m_busses.cbegin(), m_busses.cend(),
259 [&strLocation](const PeripheralBusPtr& bus)
260 { return bus->HasPeripheral(strLocation); });
261 if (bus != m_busses.cend())
262 return *bus;
263
264 return nullptr;
265 }
266
267 bool CPeripherals::SupportsFeature(PeripheralFeature feature) const
268 {
269 bool bSupportsFeature = false;
270
271 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
272 for (const auto& bus : m_busses)
273 bSupportsFeature |= bus->SupportsFeature(feature);
274
275 return bSupportsFeature;
276 }
277
278 int CPeripherals::GetPeripheralsWithFeature(
279 PeripheralVector& results,
280 const PeripheralFeature feature,
281 PeripheralBusType busType /* = PERIPHERAL_BUS_UNKNOWN */) const
282 {
283 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
284 int iReturn(0);
285 for (const auto& bus : m_busses)
286 {
287 /* check whether the bus matches if a bus type other than unknown was passed */
288 if (busType != PERIPHERAL_BUS_UNKNOWN && bus->Type() != busType)
289 continue;
290
291 iReturn += bus->GetPeripheralsWithFeature(results, feature);
292 }
293
294 return iReturn;
295 }
296
297 size_t CPeripherals::GetNumberOfPeripherals() const
298 {
299 size_t iReturn(0);
300 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
301 for (const auto& bus : m_busses)
302 iReturn += bus->GetNumberOfPeripherals();
303
304 return iReturn;
305 }
306
307 bool CPeripherals::HasPeripheralWithFeature(
308 const PeripheralFeature feature, PeripheralBusType busType /* = PERIPHERAL_BUS_UNKNOWN */) const
309 {
310 PeripheralVector dummy;
311 return (GetPeripheralsWithFeature(dummy, feature, busType) > 0);
312 }
313
314 void CPeripherals::CreatePeripheral(CPeripheralBus& bus, const PeripheralScanResult& result)
315 {
316 PeripheralPtr peripheral;
317 PeripheralScanResult mappedResult = result;
318 if (mappedResult.m_busType == PERIPHERAL_BUS_UNKNOWN)
319 mappedResult.m_busType = bus.Type();
320
321 /* check whether there's something mapped in peripherals.xml */
322 GetMappingForDevice(bus, mappedResult);
323
324 switch (mappedResult.m_mappedType)
325 {
326 case PERIPHERAL_HID:
327 peripheral = PeripheralPtr(new CPeripheralHID(*this, mappedResult, &bus));
328 break;
329
330 case PERIPHERAL_NIC:
331 peripheral = PeripheralPtr(new CPeripheralNIC(*this, mappedResult, &bus));
332 break;
333
334 case PERIPHERAL_DISK:
335 peripheral = PeripheralPtr(new CPeripheralDisk(*this, mappedResult, &bus));
336 break;
337
338 case PERIPHERAL_NYXBOARD:
339 peripheral = PeripheralPtr(new CPeripheralNyxboard(*this, mappedResult, &bus));
340 break;
341
342 case PERIPHERAL_TUNER:
343 peripheral = PeripheralPtr(new CPeripheralTuner(*this, mappedResult, &bus));
344 break;
345
346 case PERIPHERAL_BLUETOOTH:
347 peripheral = PeripheralPtr(new CPeripheralBluetooth(*this, mappedResult, &bus));
348 break;
349
350 case PERIPHERAL_CEC:
351 #if defined(HAVE_LIBCEC)
352 if (bus.Type() == PERIPHERAL_BUS_CEC)
353 peripheral = PeripheralPtr(new CPeripheralCecAdapter(*this, mappedResult, &bus));
354 #else
355 if (!m_bMissingLibCecWarningDisplayed)
356 {
357 m_bMissingLibCecWarningDisplayed = true;
358 CLog::Log(
359 LOGWARNING,
360 "{} - libCEC support has not been compiled in, so the CEC adapter cannot be used.",
361 __FUNCTION__);
362 CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Warning,
363 g_localizeStrings.Get(36000),
364 g_localizeStrings.Get(36017));
365 }
366 #endif
367 break;
368
369 case PERIPHERAL_IMON:
370 peripheral = PeripheralPtr(new CPeripheralImon(*this, mappedResult, &bus));
371 break;
372
373 case PERIPHERAL_JOYSTICK:
374 peripheral = PeripheralPtr(new CPeripheralJoystick(*this, mappedResult, &bus));
375 break;
376
377 case PERIPHERAL_KEYBOARD:
378 peripheral = PeripheralPtr(new CPeripheralKeyboard(*this, mappedResult, &bus));
379 break;
380
381 case PERIPHERAL_MOUSE:
382 peripheral = PeripheralPtr(new CPeripheralMouse(*this, mappedResult, &bus));
383 break;
384
385 default:
386 break;
387 }
388
389 if (peripheral)
390 {
391 /* try to initialise the new peripheral
392 * Initialise() will make sure that each device is only initialised once */
393 if (peripheral->Initialise())
394 bus.Register(peripheral);
395 else
396 {
397 CLog::Log(LOGDEBUG, "{} - failed to initialise peripheral on '{}'", __FUNCTION__,
398 mappedResult.m_strLocation);
399 }
400 }
401 }
402
403 void CPeripherals::OnDeviceAdded(const CPeripheralBus& bus, const CPeripheral& peripheral)
404 {
405 OnDeviceChanged();
406
407 //! @todo Improve device notifications in v18
408 #if 0
409 bool bNotify = true;
410
411 // don't show a notification for devices detected during the initial scan
412 if (!bus.IsInitialised())
413 bNotify = false;
414
415 if (bNotify)
416 CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(35005), peripheral.DeviceName());
417 #endif
418 }
419
420 void CPeripherals::OnDeviceDeleted(const CPeripheralBus& bus, const CPeripheral& peripheral)
421 {
422 OnDeviceChanged();
423
424 //! @todo Improve device notifications in v18
425 #if 0
426 bool bNotify = true;
427
428 if (bNotify)
429 CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(35006), peripheral.DeviceName());
430 #endif
431 }
432
433 void CPeripherals::OnDeviceChanged()
434 {
435 // refresh settings (peripherals manager could be enabled/disabled now)
436 CGUIMessage msgSettings(GUI_MSG_UPDATE, WINDOW_SETTINGS_SYSTEM, 0);
437 CServiceBroker::GetGUI()->GetWindowManager().SendThreadMessage(msgSettings,
438 WINDOW_SETTINGS_SYSTEM);
439
440 SetChanged();
441 }
442
443 bool CPeripherals::GetMappingForDevice(const CPeripheralBus& bus,
444 PeripheralScanResult& result) const
445 {
446 std::unique_lock<CCriticalSection> lock(m_critSectionMappings);
447
448 /* check all mappings in the order in which they are defined in peripherals.xml */
449 for (const auto& mapping : m_mappings)
450 {
451 bool bProductMatch = false;
452 if (mapping.m_PeripheralID.empty())
453 bProductMatch = true;
454 else
455 {
456 for (const auto& peripheralID : mapping.m_PeripheralID)
457 if (peripheralID.m_iVendorId == result.m_iVendorId &&
458 peripheralID.m_iProductId == result.m_iProductId)
459 bProductMatch = true;
460 }
461
462 bool bBusMatch =
463 (mapping.m_busType == PERIPHERAL_BUS_UNKNOWN || mapping.m_busType == bus.Type());
464 bool bClassMatch = (mapping.m_class == PERIPHERAL_UNKNOWN || mapping.m_class == result.m_type);
465
466 if (bProductMatch && bBusMatch && bClassMatch)
467 {
468 std::string strVendorId, strProductId;
469 PeripheralTypeTranslator::FormatHexString(result.m_iVendorId, strVendorId);
470 PeripheralTypeTranslator::FormatHexString(result.m_iProductId, strProductId);
471 CLog::Log(LOGDEBUG, "{} - device ({}:{}) mapped to {} (type = {})", __FUNCTION__, strVendorId,
472 strProductId, mapping.m_strDeviceName,
473 PeripheralTypeTranslator::TypeToString(mapping.m_mappedTo));
474 result.m_mappedType = mapping.m_mappedTo;
475 if (result.m_strDeviceName.empty() && !mapping.m_strDeviceName.empty())
476 result.m_strDeviceName = mapping.m_strDeviceName;
477 return true;
478 }
479 }
480
481 return false;
482 }
483
484 void CPeripherals::GetSettingsFromMapping(CPeripheral& peripheral) const
485 {
486 std::unique_lock<CCriticalSection> lock(m_critSectionMappings);
487
488 /* check all mappings in the order in which they are defined in peripherals.xml */
489 for (const auto& mapping : m_mappings)
490 {
491 bool bProductMatch = false;
492 if (mapping.m_PeripheralID.empty())
493 bProductMatch = true;
494 else
495 {
496 for (const auto& peripheralID : mapping.m_PeripheralID)
497 if (peripheralID.m_iVendorId == peripheral.VendorId() &&
498 peripheralID.m_iProductId == peripheral.ProductId())
499 bProductMatch = true;
500 }
501
502 bool bBusMatch = (mapping.m_busType == PERIPHERAL_BUS_UNKNOWN ||
503 mapping.m_busType == peripheral.GetBusType());
504 bool bClassMatch =
505 (mapping.m_class == PERIPHERAL_UNKNOWN || mapping.m_class == peripheral.Type());
506
507 if (bBusMatch && bProductMatch && bClassMatch)
508 {
509 for (auto itr = mapping.m_settings.begin(); itr != mapping.m_settings.end(); ++itr)
510 peripheral.AddSetting((*itr).first, (*itr).second.m_setting, (*itr).second.m_order);
511 }
512 }
513 }
514
515 #define SS(x) ((x) ? x : "")
516 bool CPeripherals::LoadMappings()
517 {
518 std::unique_lock<CCriticalSection> lock(m_critSectionMappings);
519
520 CXBMCTinyXML2 xmlDoc;
521 if (!xmlDoc.LoadFile("special://xbmc/system/peripherals.xml"))
522 {
523 CLog::LogF(LOGWARNING, "peripherals.xml does not exist");
524 return true;
525 }
526
527 auto* pRootElement = xmlDoc.RootElement();
528 if (pRootElement == nullptr ||
529 StringUtils::CompareNoCase(pRootElement->Value(), "peripherals") != 0)
530 {
531 CLog::LogF(LOGERROR, "peripherals.xml does not contain <peripherals>");
532 return false;
533 }
534
535 for (auto* currentNode = pRootElement->FirstChildElement("peripheral"); currentNode != nullptr;
536 currentNode = currentNode->NextSiblingElement("peripheral"))
537 {
538 PeripheralID id;
539 PeripheralDeviceMapping mapping;
540
541 mapping.m_strDeviceName = XMLUtils::GetAttribute(currentNode, "name");
542
543 // If there is no vendor_product attribute ignore this entry
544 if (currentNode->Attribute("vendor_product"))
545 {
546 // The vendor_product attribute is a list of comma separated vendor:product pairs
547 std::vector<std::string> vpArray =
548 StringUtils::Split(currentNode->Attribute("vendor_product"), ",");
549 for (const auto& i : vpArray)
550 {
551 std::vector<std::string> idArray = StringUtils::Split(i, ":");
552 if (idArray.size() != 2)
553 {
554 CLog::LogF(LOGERROR, "ignoring node \"{}\" with invalid vendor_product attribute",
555 mapping.m_strDeviceName);
556 continue;
557 }
558
559 id.m_iVendorId = PeripheralTypeTranslator::HexStringToInt(idArray[0].c_str());
560 id.m_iProductId = PeripheralTypeTranslator::HexStringToInt(idArray[1].c_str());
561 mapping.m_PeripheralID.push_back(id);
562 }
563 }
564
565 mapping.m_busType =
566 PeripheralTypeTranslator::GetBusTypeFromString(XMLUtils::GetAttribute(currentNode, "bus"));
567 mapping.m_class =
568 PeripheralTypeTranslator::GetTypeFromString(XMLUtils::GetAttribute(currentNode, "class"));
569 mapping.m_mappedTo =
570 PeripheralTypeTranslator::GetTypeFromString(XMLUtils::GetAttribute(currentNode, "mapTo"));
571 GetSettingsFromMappingsFile(currentNode, mapping.m_settings);
572
573 m_mappings.push_back(mapping);
574 CLog::LogF(LOGDEBUG, "loaded node \"{}\"", mapping.m_strDeviceName);
575 }
576
577 return true;
578 }
579
580 void CPeripherals::GetSettingsFromMappingsFile(
581 tinyxml2::XMLElement* xmlNode, std::map<std::string, PeripheralDeviceSetting>& settings)
582 {
583 auto* currentNode = xmlNode->FirstChildElement("setting");
584 int iMaxOrder = 0;
585
586 while (currentNode != nullptr)
587 {
588 SettingPtr setting;
589 std::string strKey = XMLUtils::GetAttribute(currentNode, "key");
590 if (strKey.empty())
591 continue;
592
593 std::string strSettingsType = XMLUtils::GetAttribute(currentNode, "type");
594 int iLabelId = currentNode->Attribute("label") ? atoi(currentNode->Attribute("label")) : -1;
595 const std::string config = XMLUtils::GetAttribute(currentNode, "configurable");
596 bool bConfigurable = (config.empty() || (config != "no" && config != "false" && config != "0"));
597 if (strSettingsType == "bool")
598 {
599 const std::string value = XMLUtils::GetAttribute(currentNode, "value");
600 bool bValue = (value != "no" && value != "false" && value != "0");
601 setting = std::make_shared<CSettingBool>(strKey, iLabelId, bValue);
602 }
603 else if (strSettingsType == "int")
604 {
605 int iValue = currentNode->Attribute("value") ? atoi(currentNode->Attribute("value")) : 0;
606 int iMin = currentNode->Attribute("min") ? atoi(currentNode->Attribute("min")) : 0;
607 int iStep = currentNode->Attribute("step") ? atoi(currentNode->Attribute("step")) : 1;
608 int iMax = currentNode->Attribute("max") ? atoi(currentNode->Attribute("max")) : 255;
609 setting = std::make_shared<CSettingInt>(strKey, iLabelId, iValue, iMin, iStep, iMax);
610 }
611 else if (strSettingsType == "float")
612 {
613 float fValue =
614 currentNode->Attribute("value") ? (float)atof(currentNode->Attribute("value")) : 0;
615 float fMin = currentNode->Attribute("min") ? (float)atof(currentNode->Attribute("min")) : 0;
616 float fStep =
617 currentNode->Attribute("step") ? (float)atof(currentNode->Attribute("step")) : 0;
618 float fMax = currentNode->Attribute("max") ? (float)atof(currentNode->Attribute("max")) : 0;
619 setting = std::make_shared<CSettingNumber>(strKey, iLabelId, fValue, fMin, fStep, fMax);
620 }
621 else if (StringUtils::EqualsNoCase(strSettingsType, "enum"))
622 {
623 std::string strEnums = XMLUtils::GetAttribute(currentNode, "lvalues");
624 if (!strEnums.empty())
625 {
626 TranslatableIntegerSettingOptions enums;
627 std::vector<std::string> valuesVec;
628 StringUtils::Tokenize(strEnums, valuesVec, "|");
629 for (unsigned int i = 0; i < valuesVec.size(); i++)
630 enums.emplace_back(atoi(valuesVec[i].c_str()), atoi(valuesVec[i].c_str()));
631 int iValue = currentNode->Attribute("value") ? atoi(currentNode->Attribute("value")) : 0;
632 setting = std::make_shared<CSettingInt>(strKey, iLabelId, iValue, enums);
633 }
634 }
635 else if (StringUtils::EqualsNoCase(strSettingsType, "addon"))
636 {
637 std::string addonFilter = XMLUtils::GetAttribute(currentNode, "addontype");
638 ADDON::AddonType addonType = ADDON::CAddonInfo::TranslateType(addonFilter);
639 std::string strValue = XMLUtils::GetAttribute(currentNode, "value");
640 setting = std::make_shared<CSettingAddon>(strKey, iLabelId, strValue);
641 static_cast<CSettingAddon&>(*setting).SetAddonType(addonType);
642 }
643 else
644 {
645 std::string strValue = XMLUtils::GetAttribute(currentNode, "value");
646 setting = std::make_shared<CSettingString>(strKey, iLabelId, strValue);
647 }
648
649 if (setting)
650 {
651 //! @todo add more types if needed
652
653 /* set the visibility */
654 setting->SetVisible(bConfigurable);
655
656 /* set the order */
657 int iOrder = 0;
658 currentNode->Attribute("order", std::to_string(iOrder).c_str());
659 /* if the order attribute is invalid or 0, then the setting will be added at the end */
660 if (iOrder < 0)
661 iOrder = 0;
662 if (iOrder > iMaxOrder)
663 iMaxOrder = iOrder;
664
665 /* and add this new setting */
666 PeripheralDeviceSetting deviceSetting = {setting, iOrder};
667 settings[strKey] = deviceSetting;
668 }
669
670 currentNode = currentNode->NextSiblingElement("setting");
671 }
672
673 /* add the settings without an order attribute or an invalid order attribute set at the end */
674 for (auto& it : settings)
675 {
676 if (it.second.m_order == 0)
677 it.second.m_order = ++iMaxOrder;
678 }
679 }
680
681 void CPeripherals::GetDirectory(const std::string& strPath, CFileItemList& items) const
682 {
683 if (!StringUtils::StartsWithNoCase(strPath, "peripherals://"))
684 return;
685
686 std::string strPathCut = strPath.substr(14);
687 std::string strBus = strPathCut.substr(0, strPathCut.find('/'));
688
689 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
690 for (const auto& bus : m_busses)
691 {
692 if (StringUtils::EqualsNoCase(strBus, "all") ||
693 StringUtils::EqualsNoCase(strBus, PeripheralTypeTranslator::BusTypeToString(bus->Type())))
694 bus->GetDirectory(strPath, items);
695 }
696 }
697
698 PeripheralPtr CPeripherals::GetByPath(const std::string& strPath) const
699 {
700 PeripheralPtr result;
701
702 if (!StringUtils::StartsWithNoCase(strPath, "peripherals://"))
703 return result;
704
705 std::string strPathCut = strPath.substr(14);
706 std::string strBus = strPathCut.substr(0, strPathCut.find('/'));
707
708 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
709 for (const auto& bus : m_busses)
710 {
711 if (StringUtils::EqualsNoCase(strBus, PeripheralTypeTranslator::BusTypeToString(bus->Type())))
712 {
713 result = bus->GetByPath(strPath);
714 break;
715 }
716 }
717
718 return result;
719 }
720
721 bool CPeripherals::OnAction(const CAction& action)
722 {
723 if (action.GetID() == ACTION_MUTE)
724 {
725 return ToggleMute();
726 }
727
728 if (SupportsCEC() && action.GetAmount() &&
729 (action.GetID() == ACTION_VOLUME_UP || action.GetID() == ACTION_VOLUME_DOWN))
730 {
731 PeripheralVector peripherals;
732 if (GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
733 {
734 for (auto& peripheral : peripherals)
735 {
736 std::shared_ptr<CPeripheralCecAdapter> cecDevice =
737 std::static_pointer_cast<CPeripheralCecAdapter>(peripheral);
738 if (cecDevice->HasAudioControl())
739 {
740 if (action.GetID() == ACTION_VOLUME_UP)
741 cecDevice->VolumeUp();
742 else
743 cecDevice->VolumeDown();
744 return true;
745 }
746 }
747 }
748 }
749
750 return false;
751 }
752
753 bool CPeripherals::OnMessage(CGUIMessage& message)
754 {
755 switch (message.GetMessage())
756 {
757 case GUI_MSG_NOTIFY_ALL:
758 {
759 if (message.GetParam1() == GUI_MSG_UI_READY)
760 {
761 m_guiReady = true;
762 m_guiReadyEvent->Set();
763 }
764 break;
765 }
766 default:
767 break;
768 }
769
770 return false;
771 }
772
773 bool CPeripherals::WaitForGUI()
774 {
775 m_guiReadyEvent->Wait();
776 return m_guiReady;
777 }
778
779 bool CPeripherals::IsMuted()
780 {
781 PeripheralVector peripherals;
782 if (SupportsCEC() && GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
783 {
784 for (const auto& peripheral : peripherals)
785 {
786 std::shared_ptr<CPeripheralCecAdapter> cecDevice =
787 std::static_pointer_cast<CPeripheralCecAdapter>(peripheral);
788 if (cecDevice->IsMuted())
789 return true;
790 }
791 }
792
793 return false;
794 }
795
796 bool CPeripherals::ToggleMute()
797 {
798 PeripheralVector peripherals;
799 if (SupportsCEC() && GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
800 {
801 for (auto& peripheral : peripherals)
802 {
803 std::shared_ptr<CPeripheralCecAdapter> cecDevice =
804 std::static_pointer_cast<CPeripheralCecAdapter>(peripheral);
805 if (cecDevice->HasAudioControl())
806 {
807 cecDevice->ToggleMute();
808 return true;
809 }
810 }
811 }
812
813 return false;
814 }
815
816 bool CPeripherals::ToggleDeviceState(CecStateChange mode /*= STATE_SWITCH_TOGGLE */)
817 {
818 bool ret(false);
819 PeripheralVector peripherals;
820
821 if (SupportsCEC() && GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
822 {
823 for (auto& peripheral : peripherals)
824 {
825 std::shared_ptr<CPeripheralCecAdapter> cecDevice =
826 std::static_pointer_cast<CPeripheralCecAdapter>(peripheral);
827 ret |= cecDevice->ToggleDeviceState(mode);
828 }
829 }
830
831 return ret;
832 }
833
834 bool CPeripherals::GetNextKeypress(float frameTime, CKey& key)
835 {
836 PeripheralVector peripherals;
837 if (SupportsCEC() && GetPeripheralsWithFeature(peripherals, FEATURE_CEC))
838 {
839 for (auto& peripheral : peripherals)
840 {
841 std::shared_ptr<CPeripheralCecAdapter> cecDevice =
842 std::static_pointer_cast<CPeripheralCecAdapter>(peripheral);
843 if (cecDevice->GetButton())
844 {
845 CKey newKey(cecDevice->GetButton(), cecDevice->GetHoldTime());
846 cecDevice->ResetButton();
847 key = newKey;
848 return true;
849 }
850 }
851 }
852
853 return false;
854 }
855
856 EventPollHandlePtr CPeripherals::RegisterEventPoller()
857 {
858 return m_eventScanner->RegisterPollHandle();
859 }
860
861 EventLockHandlePtr CPeripherals::RegisterEventLock()
862 {
863 return m_eventScanner->RegisterLock();
864 }
865
866 void CPeripherals::OnUserNotification()
867 {
868 if (!CServiceBroker::GetSettingsComponent()->GetSettings()->GetBool(
869 CSettings::SETTING_INPUT_RUMBLENOTIFY))
870 return;
871
872 PeripheralVector peripherals;
873 GetPeripheralsWithFeature(peripherals, FEATURE_RUMBLE);
874
875 for (auto& peripheral : peripherals)
876 peripheral->OnUserNotification();
877 }
878
879 void CPeripherals::TestFeature(PeripheralFeature feature)
880 {
881 PeripheralVector peripherals;
882 GetPeripheralsWithFeature(peripherals, feature);
883
884 for (auto& peripheral : peripherals)
885 {
886 if (peripheral->TestFeature(feature))
887 {
888 CLog::Log(LOGDEBUG, "PERIPHERALS: Device \"{}\" tested {} feature", peripheral->DeviceName(),
889 PeripheralTypeTranslator::FeatureToString(feature));
890 }
891 else
892 {
893 if (peripheral->HasFeature(feature))
894 CLog::Log(LOGDEBUG, "PERIPHERALS: Device \"{}\" failed to test {} feature",
895 peripheral->DeviceName(), PeripheralTypeTranslator::FeatureToString(feature));
896 else
897 CLog::Log(LOGDEBUG, "PERIPHERALS: Device \"{}\" doesn't support {} feature",
898 peripheral->DeviceName(), PeripheralTypeTranslator::FeatureToString(feature));
899 }
900 }
901 }
902
903 void CPeripherals::PowerOffDevices()
904 {
905 TestFeature(FEATURE_POWER_OFF);
906 }
907
908 void CPeripherals::ProcessEvents(void)
909 {
910 std::vector<PeripheralBusPtr> busses;
911 {
912 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
913 busses = m_busses;
914 }
915
916 for (PeripheralBusPtr& bus : busses)
917 bus->ProcessEvents();
918 }
919
920 void CPeripherals::EnableButtonMapping()
921 {
922 std::vector<PeripheralBusPtr> busses;
923 {
924 std::unique_lock<CCriticalSection> lock(m_critSectionBusses);
925 busses = m_busses;
926 }
927
928 for (PeripheralBusPtr& bus : busses)
929 bus->EnableButtonMapping();
930 }
931
932 PeripheralAddonPtr CPeripherals::GetAddonWithButtonMap(const CPeripheral* device)
933 {
934 PeripheralBusAddonPtr addonBus =
935 std::static_pointer_cast<CPeripheralBusAddon>(GetBusByType(PERIPHERAL_BUS_ADDON));
936
937 PeripheralAddonPtr addon;
938
939 PeripheralAddonPtr addonWithButtonMap;
940 if (addonBus && addonBus->GetAddonWithButtonMap(device, addonWithButtonMap))
941 addon = std::move(addonWithButtonMap);
942
943 return addon;
944 }
945
946 void CPeripherals::ResetButtonMaps(const std::string& controllerId)
947 {
948 PeripheralBusAddonPtr addonBus =
949 std::static_pointer_cast<CPeripheralBusAddon>(GetBusByType(PERIPHERAL_BUS_ADDON));
950
951 PeripheralVector peripherals;
952 GetPeripheralsWithFeature(peripherals, FEATURE_JOYSTICK);
953
954 for (auto& peripheral : peripherals)
955 {
956 PeripheralAddonPtr addon;
957 if (addonBus->GetAddonWithButtonMap(peripheral.get(), addon))
958 {
959 CAddonButtonMap buttonMap(peripheral.get(), addon, controllerId, *this);
960 buttonMap.Reset();
961 }
962 }
963 }
964
965 void CPeripherals::RegisterJoystickButtonMapper(IButtonMapper* mapper)
966 {
967 PeripheralVector peripherals;
968 GetPeripheralsWithFeature(peripherals, FEATURE_JOYSTICK);
969 GetPeripheralsWithFeature(peripherals, FEATURE_KEYBOARD);
970 GetPeripheralsWithFeature(peripherals, FEATURE_MOUSE);
971
972 for (auto& peripheral : peripherals)
973 peripheral->RegisterJoystickButtonMapper(mapper);
974 }
975
976 void CPeripherals::UnregisterJoystickButtonMapper(IButtonMapper* mapper)
977 {
978 mapper->ResetButtonMapCallbacks();
979
980 PeripheralVector peripherals;
981 GetPeripheralsWithFeature(peripherals, FEATURE_JOYSTICK);
982 GetPeripheralsWithFeature(peripherals, FEATURE_KEYBOARD);
983 GetPeripheralsWithFeature(peripherals, FEATURE_MOUSE);
984
985 for (auto& peripheral : peripherals)
986 peripheral->UnregisterJoystickButtonMapper(mapper);
987 }
988
989 void CPeripherals::OnSettingChanged(const std::shared_ptr<const CSetting>& setting)
990 {
991 if (setting == nullptr)
992 return;
993
994 const std::string& settingId = setting->GetId();
995 if (settingId == CSettings::SETTING_LOCALE_LANGUAGE)
996 {
997 // user set language, no longer use the TV's language
998 PeripheralVector cecDevices;
999 if (GetPeripheralsWithFeature(cecDevices, FEATURE_CEC) > 0)
1000 {
1001 for (auto& cecDevice : cecDevices)
1002 cecDevice->SetSetting("use_tv_menu_language", false);
1003 }
1004 }
1005 }
1006
1007 void CPeripherals::OnSettingAction(const std::shared_ptr<const CSetting>& setting)
1008 {
1009 if (setting == nullptr)
1010 return;
1011
1012 const std::string& settingId = setting->GetId();
1013 if (settingId == CSettings::SETTING_INPUT_PERIPHERALS)
1014 CGUIDialogPeripherals::Show(*this);
1015 else if (settingId == CSettings::SETTING_INPUT_CONTROLLERCONFIG)
1016 CServiceBroker::GetGUI()->GetWindowManager().ActivateWindow(WINDOW_DIALOG_GAME_CONTROLLERS);
1017 else if (settingId == CSettings::SETTING_INPUT_TESTRUMBLE)
1018 TestFeature(FEATURE_RUMBLE);
1019 else if (settingId == CSettings::SETTING_INPUT_PERIPHERALLIBRARIES)
1020 {
1021 std::string strAddonId;
1022 if (CGUIWindowAddonBrowser::SelectAddonID(ADDON::AddonType::PERIPHERALDLL, strAddonId, false,
1023 true, true, false, true) == 1 &&
1024 !strAddonId.empty())
1025 {
1026 ADDON::AddonPtr addon;
1027 if (CServiceBroker::GetAddonMgr().GetAddon(strAddonId, addon, ADDON::OnlyEnabled::CHOICE_YES))
1028 CGUIDialogAddonSettings::ShowForAddon(addon);
1029 }
1030 }
1031 }
1032
1033 void CPeripherals::OnApplicationMessage(MESSAGING::ThreadMessage* pMsg)
1034 {
1035 switch (pMsg->dwMessage)
1036 {
1037 case TMSG_CECTOGGLESTATE:
1038 *static_cast<bool*>(pMsg->lpVoid) = ToggleDeviceState(STATE_SWITCH_TOGGLE);
1039 break;
1040
1041 case TMSG_CECACTIVATESOURCE:
1042 ToggleDeviceState(STATE_ACTIVATE_SOURCE);
1043 break;
1044
1045 case TMSG_CECSTANDBY:
1046 ToggleDeviceState(STATE_STANDBY);
1047 break;
1048 }
1049 }
1050
1051 int CPeripherals::GetMessageMask()
1052 {
1053 return TMSG_MASK_PERIPHERALS;
1054 }
1055
1056 void CPeripherals::Announce(ANNOUNCEMENT::AnnouncementFlag flag,
1057 const std::string& sender,
1058 const std::string& message,
1059 const CVariant& data)
1060 {
1061 if (flag == ANNOUNCEMENT::Player &&
1062 sender == ANNOUNCEMENT::CAnnouncementManager::ANNOUNCEMENT_SENDER)
1063 {
1064 if (message == "OnQuit")
1065 {
1066 if (CServiceBroker::GetSettingsComponent()->GetSettings()->GetBool(
1067 CSettings::SETTING_INPUT_CONTROLLERPOWEROFF))
1068 PowerOffDevices();
1069 }
1070 }
1071 }