Debian Codegraph @

xbmc/peripherals/addons/PeripheralAddon.cpp

raw
1 /*
2 * Copyright (C) 2014-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 "PeripheralAddon.h"
10
11 #include "FileItem.h"
12 #include "PeripheralAddonTranslator.h"
13 #include "addons/addoninfo/AddonInfo.h"
14 #include "addons/addoninfo/AddonType.h"
15 #include "filesystem/Directory.h"
16 #include "filesystem/SpecialProtocol.h"
17 #include "games/controllers/Controller.h"
18 #include "games/controllers/ControllerManager.h"
19 #include "input/joysticks/DriverPrimitive.h"
20 #include "input/joysticks/interfaces/IButtonMap.h"
21 #include "peripherals/Peripherals.h"
22 #include "peripherals/bus/virtual/PeripheralBusAddon.h"
23 #include "peripherals/devices/PeripheralJoystick.h"
24 #include "utils/StringUtils.h"
25 #include "utils/log.h"
26
27 #include <algorithm>
28 #include <mutex>
29 #include <shared_mutex>
30 #include <string.h>
31 #include <utility>
32
33 using namespace KODI;
34 using namespace JOYSTICK;
35 using namespace PERIPHERALS;
36 using namespace XFILE;
37
38 #define KEYBOARD_BUTTON_MAP_NAME "Keyboard"
39 #define KEYBOARD_PROVIDER "application"
40
41 #define MOUSE_BUTTON_MAP_NAME "Mouse"
42 #define MOUSE_PROVIDER "application"
43
44 #ifndef SAFE_DELETE
45 #define SAFE_DELETE(p) \
46 do \
47 { \
48 delete (p); \
49 (p) = NULL; \
50 } while (0)
51 #endif
52
53 CPeripheralAddon::CPeripheralAddon(const ADDON::AddonInfoPtr& addonInfo, CPeripherals& manager)
54 : IAddonInstanceHandler(ADDON_INSTANCE_PERIPHERAL, addonInfo), m_manager(manager)
55 {
56 m_bProvidesJoysticks =
57 addonInfo->Type(ADDON::AddonType::PERIPHERALDLL)->GetValue("@provides_joysticks").asBoolean();
58 m_bProvidesButtonMaps = addonInfo->Type(ADDON::AddonType::PERIPHERALDLL)
59 ->GetValue("@provides_buttonmaps")
60 .asBoolean();
61
62 // Create "C" interface structures, used as own parts to prevent API problems on update
63 m_ifc.peripheral = new AddonInstance_Peripheral;
64 m_ifc.peripheral->props = new AddonProps_Peripheral();
65 m_ifc.peripheral->toAddon = new KodiToAddonFuncTable_Peripheral();
66 m_ifc.peripheral->toKodi = new AddonToKodiFuncTable_Peripheral();
67
68 ResetProperties();
69 }
70
71 CPeripheralAddon::~CPeripheralAddon(void)
72 {
73 DestroyAddon();
74
75 if (m_ifc.peripheral)
76 {
77 delete m_ifc.peripheral->toAddon;
78 delete m_ifc.peripheral->toKodi;
79 delete m_ifc.peripheral->props;
80 }
81 delete m_ifc.peripheral;
82 }
83
84 void CPeripheralAddon::ResetProperties(void)
85 {
86 // Initialise members
87 m_strUserPath = CSpecialProtocol::TranslatePath(Profile());
88 m_strClientPath = CSpecialProtocol::TranslatePath(Path());
89
90 m_ifc.peripheral->props->user_path = m_strUserPath.c_str();
91 m_ifc.peripheral->props->addon_path = m_strClientPath.c_str();
92
93 m_ifc.peripheral->toKodi->kodiInstance = this;
94 m_ifc.peripheral->toKodi->feature_count = cb_feature_count;
95 m_ifc.peripheral->toKodi->feature_type = cb_feature_type;
96 m_ifc.peripheral->toKodi->refresh_button_maps = cb_refresh_button_maps;
97 m_ifc.peripheral->toKodi->trigger_scan = cb_trigger_scan;
98
99 memset(m_ifc.peripheral->toAddon, 0, sizeof(KodiToAddonFuncTable_Peripheral));
100 }
101
102 bool CPeripheralAddon::CreateAddon(void)
103 {
104 std::unique_lock<CSharedSection> lock(m_dllSection);
105
106 // Reset all properties to defaults
107 ResetProperties();
108
109 // Create directory for user data
110 if (!CDirectory::Exists(m_strUserPath))
111 CDirectory::Create(m_strUserPath);
112
113 // Initialise the add-on
114 CLog::Log(LOGDEBUG, "PERIPHERAL - {} - creating peripheral add-on instance '{}'", __FUNCTION__,
115 Name());
116
117 if (CreateInstance() != ADDON_STATUS_OK)
118 return false;
119
120 if (!GetAddonProperties())
121 {
122 DestroyInstance();
123 return false;
124 }
125
126 return true;
127 }
128
129 void CPeripheralAddon::DestroyAddon()
130 {
131 {
132 std::unique_lock<CCriticalSection> lock(m_critSection);
133 m_peripherals.clear();
134 }
135
136 {
137 std::unique_lock<CCriticalSection> lock(m_buttonMapMutex);
138 // only clear buttonMaps but don't delete them as they are owned by a
139 // CAddonJoystickInputHandling instance
140 m_buttonMaps.clear();
141 }
142
143 {
144 std::unique_lock<CSharedSection> lock(m_dllSection);
145 DestroyInstance();
146 }
147 }
148
149 bool CPeripheralAddon::GetAddonProperties(void)
150 {
151 PERIPHERAL_CAPABILITIES addonCapabilities = {};
152
153 // Get the capabilities
154 m_ifc.peripheral->toAddon->get_capabilities(m_ifc.peripheral, &addonCapabilities);
155
156 // Verify capabilities against addon.xml
157 if (m_bProvidesJoysticks != addonCapabilities.provides_joysticks)
158 {
159 CLog::Log(
160 LOGERROR,
161 "PERIPHERAL - Add-on '{}': provides_joysticks'({}) in add-on DLL doesn't match "
162 "'provides_joysticks'({}) in addon.xml. Please contact the developer of this add-on: {}",
163 Name(), addonCapabilities.provides_joysticks ? "true" : "false",
164 m_bProvidesJoysticks ? "true" : "false", Author());
165 return false;
166 }
167 if (m_bProvidesButtonMaps != addonCapabilities.provides_buttonmaps)
168 {
169 CLog::Log(
170 LOGERROR,
171 "PERIPHERAL - Add-on '{}': provides_buttonmaps' ({}) in add-on DLL doesn't match "
172 "'provides_buttonmaps' ({}) in addon.xml. Please contact the developer of this add-on: {}",
173 Name(), addonCapabilities.provides_buttonmaps ? "true" : "false",
174 m_bProvidesButtonMaps ? "true" : "false", Author());
175 return false;
176 }
177
178 // Read properties that depend on underlying driver
179 m_bSupportsJoystickRumble = addonCapabilities.provides_joystick_rumble;
180 m_bSupportsJoystickPowerOff = addonCapabilities.provides_joystick_power_off;
181
182 return true;
183 }
184
185 bool CPeripheralAddon::Register(unsigned int peripheralIndex, const PeripheralPtr& peripheral)
186 {
187 if (!peripheral)
188 return false;
189
190 std::unique_lock<CCriticalSection> lock(m_critSection);
191 if (m_peripherals.find(peripheralIndex) == m_peripherals.end())
192 {
193 if (peripheral->Type() == PERIPHERAL_JOYSTICK)
194 {
195 m_peripherals[peripheralIndex] = std::static_pointer_cast<CPeripheralJoystick>(peripheral);
196
197 CLog::Log(LOGINFO, "{} - new {} device registered on {}->{}: {}", __FUNCTION__,
198 PeripheralTypeTranslator::TypeToString(peripheral->Type()),
199 PeripheralTypeTranslator::BusTypeToString(PERIPHERAL_BUS_ADDON),
200 peripheral->Location(), peripheral->DeviceName());
201
202 return true;
203 }
204 }
205 return false;
206 }
207
208 void CPeripheralAddon::UnregisterRemovedDevices(const PeripheralScanResults& results,
209 PeripheralVector& removedPeripherals)
210 {
211 std::vector<unsigned int> removedIndexes;
212
213 {
214 std::unique_lock<CCriticalSection> lock(m_critSection);
215 for (auto& it : m_peripherals)
216 {
217 const PeripheralPtr& peripheral = it.second;
218 PeripheralScanResult updatedDevice(PERIPHERAL_BUS_ADDON);
219 if (!results.GetDeviceOnLocation(peripheral->Location(), &updatedDevice) ||
220 *peripheral != updatedDevice)
221 {
222 // Device removed
223 removedIndexes.push_back(it.first);
224 }
225 }
226 }
227
228 for (auto index : removedIndexes)
229 {
230 auto it = m_peripherals.find(index);
231 const PeripheralPtr& peripheral = it->second;
232 CLog::Log(LOGINFO, "{} - device removed from {}/{}: {} ({}:{})", __FUNCTION__,
233 PeripheralTypeTranslator::TypeToString(peripheral->Type()), peripheral->Location(),
234 peripheral->DeviceName(), peripheral->VendorIdAsString(),
235 peripheral->ProductIdAsString());
236 UnregisterButtonMap(peripheral.get());
237 peripheral->OnDeviceRemoved();
238 removedPeripherals.push_back(peripheral);
239 m_peripherals.erase(it);
240 }
241 }
242
243 bool CPeripheralAddon::HasFeature(const PeripheralFeature feature) const
244 {
245 if (feature == FEATURE_JOYSTICK)
246 return m_bProvidesJoysticks;
247
248 return false;
249 }
250
251 void CPeripheralAddon::GetFeatures(std::vector<PeripheralFeature>& features) const
252 {
253 if (m_bProvidesJoysticks &&
254 std::find(features.begin(), features.end(), FEATURE_JOYSTICK) == features.end())
255 features.push_back(FEATURE_JOYSTICK);
256 }
257
258 PeripheralPtr CPeripheralAddon::GetPeripheral(unsigned int index) const
259 {
260 PeripheralPtr peripheral;
261 std::unique_lock<CCriticalSection> lock(m_critSection);
262 auto it = m_peripherals.find(index);
263 if (it != m_peripherals.end())
264 peripheral = it->second;
265 return peripheral;
266 }
267
268 PeripheralPtr CPeripheralAddon::GetByPath(const std::string& strPath) const
269 {
270 PeripheralPtr result;
271
272 std::unique_lock<CCriticalSection> lock(m_critSection);
273 for (const auto& it : m_peripherals)
274 {
275 if (StringUtils::EqualsNoCase(strPath, it.second->FileLocation()))
276 {
277 result = it.second;
278 break;
279 }
280 }
281
282 return result;
283 }
284
285 bool CPeripheralAddon::SupportsFeature(PeripheralFeature feature) const
286 {
287 switch (feature)
288 {
289 case FEATURE_RUMBLE:
290 return m_bSupportsJoystickRumble;
291 case FEATURE_POWER_OFF:
292 return m_bSupportsJoystickPowerOff;
293 default:
294 break;
295 }
296
297 return false;
298 }
299
300 unsigned int CPeripheralAddon::GetPeripheralsWithFeature(PeripheralVector& results,
301 const PeripheralFeature feature) const
302 {
303 unsigned int iReturn = 0;
304 std::unique_lock<CCriticalSection> lock(m_critSection);
305 for (const auto& it : m_peripherals)
306 {
307 if (it.second->HasFeature(feature))
308 {
309 results.push_back(it.second);
310 ++iReturn;
311 }
312 }
313 return iReturn;
314 }
315
316 unsigned int CPeripheralAddon::GetNumberOfPeripherals(void) const
317 {
318 std::unique_lock<CCriticalSection> lock(m_critSection);
319 return static_cast<unsigned int>(m_peripherals.size());
320 }
321
322 unsigned int CPeripheralAddon::GetNumberOfPeripheralsWithId(const int iVendorId,
323 const int iProductId) const
324 {
325 unsigned int iReturn = 0;
326 std::unique_lock<CCriticalSection> lock(m_critSection);
327 for (const auto& it : m_peripherals)
328 {
329 if (it.second->VendorId() == iVendorId && it.second->ProductId() == iProductId)
330 iReturn++;
331 }
332
333 return iReturn;
334 }
335
336 void CPeripheralAddon::GetDirectory(const std::string& strPath, CFileItemList& items) const
337 {
338 std::unique_lock<CCriticalSection> lock(m_critSection);
339 for (const auto& it : m_peripherals)
340 {
341 const PeripheralPtr& peripheral = it.second;
342 if (peripheral->IsHidden())
343 continue;
344
345 CFileItemPtr peripheralFile(new CFileItem(peripheral->DeviceName()));
346 peripheralFile->SetPath(peripheral->FileLocation());
347 peripheralFile->SetProperty("vendor", peripheral->VendorIdAsString());
348 peripheralFile->SetProperty("product", peripheral->ProductIdAsString());
349 peripheralFile->SetProperty(
350 "bus", PeripheralTypeTranslator::BusTypeToString(peripheral->GetBusType()));
351 peripheralFile->SetProperty("location", peripheral->Location());
352 peripheralFile->SetProperty("class",
353 PeripheralTypeTranslator::TypeToString(peripheral->Type()));
354 peripheralFile->SetProperty("version", peripheral->GetVersionInfo());
355 peripheralFile->SetArt("icon", peripheral->GetIcon());
356 items.Add(peripheralFile);
357 }
358 }
359
360 bool CPeripheralAddon::PerformDeviceScan(PeripheralScanResults& results)
361 {
362 unsigned int peripheralCount;
363 PERIPHERAL_INFO* pScanResults;
364 PERIPHERAL_ERROR retVal;
365
366 std::shared_lock<CSharedSection> lock(m_dllSection);
367
368 if (!m_ifc.peripheral->toAddon->perform_device_scan)
369 return false;
370
371 LogError(retVal = m_ifc.peripheral->toAddon->perform_device_scan(m_ifc.peripheral,
372 &peripheralCount, &pScanResults),
373 "PerformDeviceScan()");
374
375 if (retVal == PERIPHERAL_NO_ERROR)
376 {
377 for (unsigned int i = 0; i < peripheralCount; i++)
378 {
379 kodi::addon::Peripheral peripheral(pScanResults[i]);
380 PeripheralScanResult result(PERIPHERAL_BUS_ADDON);
381 switch (peripheral.Type())
382 {
383 case PERIPHERAL_TYPE_JOYSTICK:
384 result.m_type = PERIPHERAL_JOYSTICK;
385 break;
386 default:
387 continue;
388 }
389
390 result.m_strDeviceName = peripheral.Name();
391 result.m_strLocation = StringUtils::Format("{}/{}", ID(), peripheral.Index());
392 result.m_iVendorId = peripheral.VendorID();
393 result.m_iProductId = peripheral.ProductID();
394 result.m_mappedType = PERIPHERAL_JOYSTICK;
395 result.m_mappedBusType = PERIPHERAL_BUS_ADDON;
396 result.m_iSequence = 0;
397
398 if (!results.ContainsResult(result))
399 results.m_results.push_back(result);
400 }
401
402 m_ifc.peripheral->toAddon->free_scan_results(m_ifc.peripheral, peripheralCount, pScanResults);
403
404 return true;
405 }
406
407 return false;
408 }
409
410 bool CPeripheralAddon::ProcessEvents(void)
411 {
412 if (!m_bProvidesJoysticks)
413 return false;
414
415 std::shared_lock<CSharedSection> lock(m_dllSection);
416
417 if (!m_ifc.peripheral->toAddon->get_events)
418 return false;
419
420 PERIPHERAL_ERROR retVal;
421
422 unsigned int eventCount = 0;
423 PERIPHERAL_EVENT* pEvents = nullptr;
424
425 LogError(retVal = m_ifc.peripheral->toAddon->get_events(m_ifc.peripheral, &eventCount, &pEvents),
426 "GetEvents()");
427 if (retVal == PERIPHERAL_NO_ERROR)
428 {
429 for (unsigned int i = 0; i < eventCount; i++)
430 {
431 kodi::addon::PeripheralEvent event(pEvents[i]);
432 PeripheralPtr device = GetPeripheral(event.PeripheralIndex());
433 if (!device)
434 continue;
435
436 switch (device->Type())
437 {
438 case PERIPHERAL_JOYSTICK:
439 {
440 std::shared_ptr<CPeripheralJoystick> joystickDevice =
441 std::static_pointer_cast<CPeripheralJoystick>(device);
442
443 switch (event.Type())
444 {
445 case PERIPHERAL_EVENT_TYPE_DRIVER_BUTTON:
446 {
447 const bool bPressed = (event.ButtonState() == JOYSTICK_STATE_BUTTON_PRESSED);
448 joystickDevice->OnButtonMotion(event.DriverIndex(), bPressed);
449 break;
450 }
451 case PERIPHERAL_EVENT_TYPE_DRIVER_HAT:
452 {
453 const HAT_STATE state =
454 CPeripheralAddonTranslator::TranslateHatState(event.HatState());
455 joystickDevice->OnHatMotion(event.DriverIndex(), state);
456 break;
457 }
458 case PERIPHERAL_EVENT_TYPE_DRIVER_AXIS:
459 {
460 joystickDevice->OnAxisMotion(event.DriverIndex(), event.AxisState());
461 break;
462 }
463 default:
464 break;
465 }
466 break;
467 }
468 default:
469 break;
470 }
471 }
472
473 for (const auto& it : m_peripherals)
474 {
475 if (it.second->Type() == PERIPHERAL_JOYSTICK)
476 std::static_pointer_cast<CPeripheralJoystick>(it.second)->OnInputFrame();
477 }
478
479 m_ifc.peripheral->toAddon->free_events(m_ifc.peripheral, eventCount, pEvents);
480
481 return true;
482 }
483
484 return false;
485 }
486
487 bool CPeripheralAddon::SendRumbleEvent(unsigned int peripheralIndex,
488 unsigned int driverIndex,
489 float magnitude)
490 {
491 if (!m_bProvidesJoysticks)
492 return false;
493
494 std::shared_lock<CSharedSection> lock(m_dllSection);
495
496 if (!m_ifc.peripheral->toAddon->send_event)
497 return false;
498
499 PERIPHERAL_EVENT eventStruct = {};
500
501 eventStruct.peripheral_index = peripheralIndex;
502 eventStruct.type = PERIPHERAL_EVENT_TYPE_SET_MOTOR;
503 eventStruct.driver_index = driverIndex;
504 eventStruct.motor_state = magnitude;
505
506 return m_ifc.peripheral->toAddon->send_event(m_ifc.peripheral, &eventStruct);
507 }
508
509 bool CPeripheralAddon::GetJoystickProperties(unsigned int index, CPeripheralJoystick& joystick)
510 {
511 if (!m_bProvidesJoysticks)
512 return false;
513
514 std::shared_lock<CSharedSection> lock(m_dllSection);
515
516 if (!m_ifc.peripheral->toAddon->get_joystick_info)
517 return false;
518
519 PERIPHERAL_ERROR retVal;
520
521 JOYSTICK_INFO joystickStruct;
522
523 LogError(retVal = m_ifc.peripheral->toAddon->get_joystick_info(m_ifc.peripheral, index,
524 &joystickStruct),
525 "GetJoystickInfo()");
526 if (retVal == PERIPHERAL_NO_ERROR)
527 {
528 kodi::addon::Joystick addonJoystick(joystickStruct);
529 SetJoystickInfo(joystick, addonJoystick);
530
531 m_ifc.peripheral->toAddon->free_joystick_info(m_ifc.peripheral, &joystickStruct);
532
533 return true;
534 }
535
536 return false;
537 }
538
539 bool CPeripheralAddon::GetAppearance(const CPeripheral* device, std::string& controllerId)
540 {
541 if (!m_bProvidesButtonMaps)
542 return false;
543
544 std::shared_lock<CSharedSection> lock(m_dllSection);
545
546 if (!m_ifc.peripheral->toAddon->get_appearance)
547 return false;
548
549 PERIPHERAL_ERROR retVal;
550
551 kodi::addon::Joystick joystickInfo;
552 GetJoystickInfo(device, joystickInfo);
553
554 JOYSTICK_INFO joystickStruct;
555 joystickInfo.ToStruct(joystickStruct);
556
557 char strControllerId[1024]{};
558
559 LogError(retVal = m_ifc.peripheral->toAddon->get_appearance(
560 m_ifc.peripheral, &joystickStruct, strControllerId, sizeof(strControllerId)),
561 "GetAppearance()");
562
563 kodi::addon::Joystick::FreeStruct(joystickStruct);
564
565 if (retVal == PERIPHERAL_NO_ERROR)
566 {
567 controllerId = strControllerId;
568 return true;
569 }
570
571 return false;
572 }
573
574 bool CPeripheralAddon::SetAppearance(const CPeripheral* device, const std::string& controllerId)
575 {
576 if (!m_bProvidesButtonMaps)
577 return false;
578
579 std::shared_lock<CSharedSection> lock(m_dllSection);
580
581 if (!m_ifc.peripheral->toAddon->set_appearance)
582 return false;
583
584 PERIPHERAL_ERROR retVal;
585
586 kodi::addon::Joystick joystickInfo;
587 GetJoystickInfo(device, joystickInfo);
588
589 JOYSTICK_INFO joystickStruct;
590 joystickInfo.ToStruct(joystickStruct);
591
592 LogError(retVal = m_ifc.peripheral->toAddon->set_appearance(m_ifc.peripheral, &joystickStruct,
593 controllerId.c_str()),
594 "SetAppearance()");
595
596 kodi::addon::Joystick::FreeStruct(joystickStruct);
597
598 return retVal == PERIPHERAL_NO_ERROR;
599 }
600
601 bool CPeripheralAddon::GetFeatures(const CPeripheral* device,
602 const std::string& strControllerId,
603 FeatureMap& features)
604 {
605 if (!m_bProvidesButtonMaps)
606 return false;
607
608 std::shared_lock<CSharedSection> lock(m_dllSection);
609
610 if (!m_ifc.peripheral->toAddon->get_features)
611 return false;
612
613 PERIPHERAL_ERROR retVal;
614
615 kodi::addon::Joystick joystickInfo;
616 GetJoystickInfo(device, joystickInfo);
617
618 JOYSTICK_INFO joystickStruct;
619 joystickInfo.ToStruct(joystickStruct);
620
621 unsigned int featureCount = 0;
622 JOYSTICK_FEATURE* pFeatures = nullptr;
623
624 LogError(retVal = m_ifc.peripheral->toAddon->get_features(m_ifc.peripheral, &joystickStruct,
625 strControllerId.c_str(), &featureCount,
626 &pFeatures),
627 "GetFeatures()");
628
629 kodi::addon::Joystick::FreeStruct(joystickStruct);
630
631 if (retVal == PERIPHERAL_NO_ERROR)
632 {
633 for (unsigned int i = 0; i < featureCount; i++)
634 {
635 kodi::addon::JoystickFeature feature(pFeatures[i]);
636 if (feature.Type() != JOYSTICK_FEATURE_TYPE_UNKNOWN)
637 features[feature.Name()] = feature;
638 }
639
640 m_ifc.peripheral->toAddon->free_features(m_ifc.peripheral, featureCount, pFeatures);
641
642 return true;
643 }
644
645 return false;
646 }
647
648 bool CPeripheralAddon::MapFeature(const CPeripheral* device,
649 const std::string& strControllerId,
650 const kodi::addon::JoystickFeature& feature)
651 {
652 if (!m_bProvidesButtonMaps)
653 return false;
654
655 std::shared_lock<CSharedSection> lock(m_dllSection);
656
657 if (!m_ifc.peripheral->toAddon->map_features)
658 return false;
659
660 PERIPHERAL_ERROR retVal;
661
662 kodi::addon::Joystick joystickInfo;
663 GetJoystickInfo(device, joystickInfo);
664
665 JOYSTICK_INFO joystickStruct;
666 joystickInfo.ToStruct(joystickStruct);
667
668 JOYSTICK_FEATURE addonFeature;
669 feature.ToStruct(addonFeature);
670
671 LogError(retVal = m_ifc.peripheral->toAddon->map_features(
672 m_ifc.peripheral, &joystickStruct, strControllerId.c_str(), 1, &addonFeature),
673 "MapFeatures()");
674
675 kodi::addon::Joystick::FreeStruct(joystickStruct);
676 kodi::addon::JoystickFeature::FreeStruct(addonFeature);
677
678 return retVal == PERIPHERAL_NO_ERROR;
679 }
680
681 bool CPeripheralAddon::GetIgnoredPrimitives(const CPeripheral* device, PrimitiveVector& primitives)
682 {
683 if (!m_bProvidesButtonMaps)
684 return false;
685
686 std::shared_lock<CSharedSection> lock(m_dllSection);
687
688 if (!m_ifc.peripheral->toAddon->get_ignored_primitives)
689 return false;
690
691 PERIPHERAL_ERROR retVal;
692
693 kodi::addon::Joystick joystickInfo;
694 GetJoystickInfo(device, joystickInfo);
695
696 JOYSTICK_INFO joystickStruct;
697 joystickInfo.ToStruct(joystickStruct);
698
699 unsigned int primitiveCount = 0;
700 JOYSTICK_DRIVER_PRIMITIVE* pPrimitives = nullptr;
701
702 LogError(retVal = m_ifc.peripheral->toAddon->get_ignored_primitives(
703 m_ifc.peripheral, &joystickStruct, &primitiveCount, &pPrimitives),
704 "GetIgnoredPrimitives()");
705
706 kodi::addon::Joystick::FreeStruct(joystickStruct);
707
708 if (retVal == PERIPHERAL_NO_ERROR)
709 {
710 for (unsigned int i = 0; i < primitiveCount; i++)
711 primitives.emplace_back(pPrimitives[i]);
712
713 m_ifc.peripheral->toAddon->free_primitives(m_ifc.peripheral, primitiveCount, pPrimitives);
714
715 return true;
716 }
717
718 return false;
719 }
720
721 bool CPeripheralAddon::SetIgnoredPrimitives(const CPeripheral* device,
722 const PrimitiveVector& primitives)
723 {
724 if (!m_bProvidesButtonMaps)
725 return false;
726
727 std::shared_lock<CSharedSection> lock(m_dllSection);
728
729 if (!m_ifc.peripheral->toAddon->set_ignored_primitives)
730 return false;
731
732 PERIPHERAL_ERROR retVal;
733
734 kodi::addon::Joystick joystickInfo;
735 GetJoystickInfo(device, joystickInfo);
736
737 JOYSTICK_INFO joystickStruct;
738 joystickInfo.ToStruct(joystickStruct);
739
740 JOYSTICK_DRIVER_PRIMITIVE* addonPrimitives = nullptr;
741 kodi::addon::DriverPrimitives::ToStructs(primitives, &addonPrimitives);
742 const unsigned int primitiveCount = static_cast<unsigned int>(primitives.size());
743
744 LogError(retVal = m_ifc.peripheral->toAddon->set_ignored_primitives(
745 m_ifc.peripheral, &joystickStruct, primitiveCount, addonPrimitives),
746 "SetIgnoredPrimitives()");
747
748 kodi::addon::Joystick::FreeStruct(joystickStruct);
749 kodi::addon::DriverPrimitives::FreeStructs(primitiveCount, addonPrimitives);
750
751 return retVal == PERIPHERAL_NO_ERROR;
752 }
753
754 void CPeripheralAddon::SaveButtonMap(const CPeripheral* device)
755 {
756 if (!m_bProvidesButtonMaps)
757 return;
758
759 std::shared_lock<CSharedSection> lock(m_dllSection);
760
761 if (!m_ifc.peripheral->toAddon->save_button_map)
762 return;
763
764 kodi::addon::Joystick joystickInfo;
765 GetJoystickInfo(device, joystickInfo);
766
767 JOYSTICK_INFO joystickStruct;
768 joystickInfo.ToStruct(joystickStruct);
769
770 m_ifc.peripheral->toAddon->save_button_map(m_ifc.peripheral, &joystickStruct);
771
772 kodi::addon::Joystick::FreeStruct(joystickStruct);
773
774 // Notify observing button maps
775 RefreshButtonMaps(device->DeviceName());
776 }
777
778 void CPeripheralAddon::RevertButtonMap(const CPeripheral* device)
779 {
780 if (!m_bProvidesButtonMaps)
781 return;
782
783 std::shared_lock<CSharedSection> lock(m_dllSection);
784
785 if (!m_ifc.peripheral->toAddon->revert_button_map)
786 return;
787
788 kodi::addon::Joystick joystickInfo;
789 GetJoystickInfo(device, joystickInfo);
790
791 JOYSTICK_INFO joystickStruct;
792 joystickInfo.ToStruct(joystickStruct);
793
794 m_ifc.peripheral->toAddon->revert_button_map(m_ifc.peripheral, &joystickStruct);
795
796 kodi::addon::Joystick::FreeStruct(joystickStruct);
797 }
798
799 void CPeripheralAddon::ResetButtonMap(const CPeripheral* device, const std::string& strControllerId)
800 {
801 if (!m_bProvidesButtonMaps)
802 return;
803
804 kodi::addon::Joystick joystickInfo;
805 GetJoystickInfo(device, joystickInfo);
806
807 JOYSTICK_INFO joystickStruct;
808 joystickInfo.ToStruct(joystickStruct);
809
810 m_ifc.peripheral->toAddon->reset_button_map(m_ifc.peripheral, &joystickStruct,
811 strControllerId.c_str());
812
813 kodi::addon::Joystick::FreeStruct(joystickStruct);
814
815 // Notify observing button maps
816 RefreshButtonMaps(device->DeviceName());
817 }
818
819 void CPeripheralAddon::PowerOffJoystick(unsigned int index)
820 {
821 if (!HasFeature(FEATURE_JOYSTICK))
822 return;
823
824 if (!SupportsFeature(FEATURE_POWER_OFF))
825 return;
826
827 std::shared_lock<CSharedSection> lock(m_dllSection);
828
829 if (!m_ifc.peripheral->toAddon->power_off_joystick)
830 return;
831
832 m_ifc.peripheral->toAddon->power_off_joystick(m_ifc.peripheral, index);
833 }
834
835 void CPeripheralAddon::RegisterButtonMap(CPeripheral* device, IButtonMap* buttonMap)
836 {
837 std::unique_lock<CCriticalSection> lock(m_buttonMapMutex);
838
839 UnregisterButtonMap(buttonMap);
840 m_buttonMaps.emplace_back(device, buttonMap);
841 }
842
843 void CPeripheralAddon::UnregisterButtonMap(IButtonMap* buttonMap)
844 {
845 std::unique_lock<CCriticalSection> lock(m_buttonMapMutex);
846
847 for (auto it = m_buttonMaps.begin(); it != m_buttonMaps.end(); ++it)
848 {
849 if (it->second == buttonMap)
850 {
851 m_buttonMaps.erase(it);
852 break;
853 }
854 }
855 }
856
857 void CPeripheralAddon::UnregisterButtonMap(CPeripheral* device)
858 {
859 std::unique_lock<CCriticalSection> lock(m_buttonMapMutex);
860
861 m_buttonMaps.erase(
862 std::remove_if(m_buttonMaps.begin(), m_buttonMaps.end(),
863 [device](const std::pair<CPeripheral*, JOYSTICK::IButtonMap*>& buttonMap)
864 { return buttonMap.first == device; }),
865 m_buttonMaps.end());
866 }
867
868 void CPeripheralAddon::RefreshButtonMaps(const std::string& strDeviceName /* = "" */)
869 {
870 std::unique_lock<CCriticalSection> lock(m_buttonMapMutex);
871
872 for (auto it = m_buttonMaps.begin(); it != m_buttonMaps.end(); ++it)
873 {
874 if (strDeviceName.empty() || strDeviceName == it->first->DeviceName())
875 it->second->Load();
876 }
877 }
878
879 bool CPeripheralAddon::ProvidesJoysticks(const ADDON::AddonInfoPtr& addonInfo)
880 {
881 return addonInfo->Type(ADDON::AddonType::PERIPHERALDLL)
882 ->GetValue("@provides_joysticks")
883 .asBoolean();
884 }
885
886 bool CPeripheralAddon::ProvidesButtonMaps(const ADDON::AddonInfoPtr& addonInfo)
887 {
888 return addonInfo->Type(ADDON::AddonType::PERIPHERALDLL)
889 ->GetValue("@provides_buttonmaps")
890 .asBoolean();
891 }
892
893 void CPeripheralAddon::TriggerDeviceScan()
894 {
895 m_manager.TriggerDeviceScan(PERIPHERAL_BUS_ADDON);
896 }
897
898 unsigned int CPeripheralAddon::FeatureCount(const std::string& controllerId,
899 JOYSTICK_FEATURE_TYPE type) const
900 {
901 using namespace GAME;
902
903 unsigned int count = 0;
904
905 CControllerManager& controllerProfiles = m_manager.GetControllerProfiles();
906 ControllerPtr controller = controllerProfiles.GetController(controllerId);
907 if (controller)
908 count = controller->FeatureCount(CPeripheralAddonTranslator::TranslateFeatureType(type));
909
910 return count;
911 }
912
913 JOYSTICK_FEATURE_TYPE CPeripheralAddon::FeatureType(const std::string& controllerId,
914 const std::string& featureName) const
915 {
916 using namespace GAME;
917
918 JOYSTICK_FEATURE_TYPE type = JOYSTICK_FEATURE_TYPE_UNKNOWN;
919
920 CControllerManager& controllerProfiles = m_manager.GetControllerProfiles();
921 ControllerPtr controller = controllerProfiles.GetController(controllerId);
922 if (controller)
923 type = CPeripheralAddonTranslator::TranslateFeatureType(controller->FeatureType(featureName));
924
925 return type;
926 }
927
928 void CPeripheralAddon::GetPeripheralInfo(const CPeripheral* device,
929 kodi::addon::Peripheral& peripheralInfo)
930 {
931 peripheralInfo.SetType(CPeripheralAddonTranslator::TranslateType(device->Type()));
932 peripheralInfo.SetName(device->DeviceName());
933 peripheralInfo.SetVendorID(device->VendorId());
934 peripheralInfo.SetProductID(device->ProductId());
935 }
936
937 void CPeripheralAddon::GetJoystickInfo(const CPeripheral* device,
938 kodi::addon::Joystick& joystickInfo)
939 {
940 GetPeripheralInfo(device, joystickInfo);
941
942 if (device->Type() == PERIPHERAL_JOYSTICK)
943 {
944 const CPeripheralJoystick* joystick = static_cast<const CPeripheralJoystick*>(device);
945 joystickInfo.SetProvider(joystick->Provider());
946 joystickInfo.SetButtonCount(joystick->ButtonCount());
947 joystickInfo.SetHatCount(joystick->HatCount());
948 joystickInfo.SetAxisCount(joystick->AxisCount());
949 joystickInfo.SetMotorCount(joystick->MotorCount());
950 joystickInfo.SetSupportsPowerOff(joystick->SupportsPowerOff());
951 }
952 else if (device->Type() == PERIPHERAL_KEYBOARD || device->Type() == PERIPHERAL_MOUSE)
953 {
954 joystickInfo.SetName(GetDeviceName(device->Type())); // Override name with non-localized version
955 joystickInfo.SetProvider(GetProvider(device->Type()));
956 }
957 }
958
959 void CPeripheralAddon::SetJoystickInfo(CPeripheralJoystick& joystick,
960 const kodi::addon::Joystick& joystickInfo)
961 {
962 joystick.SetProvider(joystickInfo.Provider());
963 joystick.SetRequestedPort(joystickInfo.RequestedPort());
964 joystick.SetButtonCount(joystickInfo.ButtonCount());
965 joystick.SetHatCount(joystickInfo.HatCount());
966 joystick.SetAxisCount(joystickInfo.AxisCount());
967 joystick.SetMotorCount(joystickInfo.MotorCount());
968 joystick.SetSupportsPowerOff(joystickInfo.SupportsPowerOff());
969 }
970
971 bool CPeripheralAddon::LogError(const PERIPHERAL_ERROR error, const char* strMethod) const
972 {
973 if (error != PERIPHERAL_NO_ERROR)
974 {
975 CLog::Log(LOGERROR, "PERIPHERAL - {} - addon '{}' returned an error: {}", strMethod, Name(),
976 CPeripheralAddonTranslator::TranslateError(error));
977 return false;
978 }
979 return true;
980 }
981
982 std::string CPeripheralAddon::GetDeviceName(PeripheralType type)
983 {
984 switch (type)
985 {
986 case PERIPHERAL_KEYBOARD:
987 return KEYBOARD_BUTTON_MAP_NAME;
988 case PERIPHERAL_MOUSE:
989 return MOUSE_BUTTON_MAP_NAME;
990 default:
991 break;
992 }
993
994 return "";
995 }
996
997 std::string CPeripheralAddon::GetProvider(PeripheralType type)
998 {
999 switch (type)
1000 {
1001 case PERIPHERAL_KEYBOARD:
1002 return KEYBOARD_PROVIDER;
1003 case PERIPHERAL_MOUSE:
1004 return MOUSE_PROVIDER;
1005 default:
1006 break;
1007 }
1008
1009 return "";
1010 }
1011
1012 void CPeripheralAddon::cb_trigger_scan(void* kodiInstance)
1013 {
1014 if (kodiInstance == nullptr)
1015 return;
1016
1017 static_cast<CPeripheralAddon*>(kodiInstance)->TriggerDeviceScan();
1018 }
1019
1020 void CPeripheralAddon::cb_refresh_button_maps(void* kodiInstance,
1021 const char* deviceName,
1022 const char* controllerId)
1023 {
1024 if (!kodiInstance)
1025 return;
1026
1027 static_cast<CPeripheralAddon*>(kodiInstance)->RefreshButtonMaps(deviceName ? deviceName : "");
1028 }
1029
1030 unsigned int CPeripheralAddon::cb_feature_count(void* kodiInstance,
1031 const char* controllerId,
1032 JOYSTICK_FEATURE_TYPE type)
1033 {
1034 if (kodiInstance == nullptr || controllerId == nullptr)
1035 return 0;
1036
1037 return static_cast<CPeripheralAddon*>(kodiInstance)->FeatureCount(controllerId, type);
1038 }
1039
1040 JOYSTICK_FEATURE_TYPE CPeripheralAddon::cb_feature_type(void* kodiInstance,
1041 const char* controllerId,
1042 const char* featureName)
1043 {
1044 if (kodiInstance == nullptr || controllerId == nullptr || featureName == nullptr)
1045 return JOYSTICK_FEATURE_TYPE_UNKNOWN;
1046
1047 return static_cast<CPeripheralAddon*>(kodiInstance)->FeatureType(controllerId, featureName);
1048 }