Debian Codegraph @

xbmc/peripherals/devices/PeripheralJoystick.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 "PeripheralJoystick.h"
10
11 #include "ServiceBroker.h"
12 #include "addons/AddonInstaller.h"
13 #include "addons/AddonManager.h"
14 #include "application/Application.h"
15 #include "games/GameServices.h"
16 #include "games/controllers/Controller.h"
17 #include "games/controllers/ControllerIDs.h"
18 #include "games/controllers/ControllerManager.h"
19 #include "input/InputManager.h"
20 #include "input/joysticks/DeadzoneFilter.h"
21 #include "input/joysticks/JoystickMonitor.h"
22 #include "input/joysticks/JoystickTranslator.h"
23 #include "input/joysticks/RumbleGenerator.h"
24 #include "input/joysticks/interfaces/IDriverHandler.h"
25 #include "input/keymaps/joysticks/KeymapHandling.h"
26 #include "peripherals/Peripherals.h"
27 #include "peripherals/addons/AddonButtonMap.h"
28 #include "peripherals/bus/virtual/PeripheralBusAddon.h"
29 #include "utils/log.h"
30
31 #include <algorithm>
32 #include <memory>
33 #include <mutex>
34
35 using namespace KODI;
36 using namespace JOYSTICK;
37 using namespace PERIPHERALS;
38
39 CPeripheralJoystick::CPeripheralJoystick(CPeripherals& manager,
40 const PeripheralScanResult& scanResult,
41 CPeripheralBus* bus)
42 : CPeripheral(manager, scanResult, bus), m_rumbleGenerator(new CRumbleGenerator)
43 {
44 m_features.push_back(FEATURE_JOYSTICK);
45 // FEATURE_RUMBLE conditionally added via SetMotorCount()
46 }
47
48 CPeripheralJoystick::~CPeripheralJoystick(void)
49 {
50 if (m_rumbleGenerator)
51 {
52 m_rumbleGenerator->AbortRumble();
53 m_rumbleGenerator.reset();
54 }
55
56 if (m_joystickMonitor)
57 {
58 UnregisterInputHandler(m_joystickMonitor.get());
59 m_joystickMonitor.reset();
60 }
61
62 m_appInput.reset();
63 m_deadzoneFilter.reset();
64 m_buttonMap.reset();
65
66 // Wait for remaining install tasks
67 for (std::future<void>& task : m_installTasks)
68 task.wait();
69 }
70
71 bool CPeripheralJoystick::InitialiseFeature(const PeripheralFeature feature)
72 {
73 bool bSuccess = false;
74
75 if (CPeripheral::InitialiseFeature(feature))
76 {
77 if (feature == FEATURE_JOYSTICK)
78 {
79 // Ensure an add-on is present to translate input
80 PeripheralAddonPtr addon = m_manager.GetAddonWithButtonMap(this);
81 if (!addon)
82 {
83 CLog::Log(LOGERROR, "CPeripheralJoystick: No button mapping add-on for {}", m_strLocation);
84 }
85 else
86 {
87 if (m_bus->InitializeProperties(*this))
88 bSuccess = true;
89 else
90 CLog::Log(LOGERROR, "CPeripheralJoystick: Invalid location ({})", m_strLocation);
91 }
92
93 if (bSuccess)
94 {
95 m_buttonMap =
96 std::make_unique<CAddonButtonMap>(this, addon, DEFAULT_CONTROLLER_ID, m_manager);
97 if (m_buttonMap->Load())
98 {
99 InitializeDeadzoneFiltering(*m_buttonMap);
100 InitializeControllerProfile(*m_buttonMap);
101 }
102 else
103 {
104 CLog::Log(LOGERROR, "CPeripheralJoystick: Failed to load button map for {}",
105 m_strLocation);
106 m_buttonMap.reset();
107 }
108
109 // Give joystick monitor priority over default controller
110 m_appInput = std::make_unique<KEYMAP::CKeymapHandling>(
111 this, false, m_manager.GetInputManager().KeymapEnvironment());
112 m_joystickMonitor = std::make_unique<CJoystickMonitor>();
113 RegisterInputHandler(m_joystickMonitor.get(), false);
114 }
115 }
116 else if (feature == FEATURE_RUMBLE)
117 {
118 bSuccess = true; // Nothing to do
119 }
120 else if (feature == FEATURE_POWER_OFF)
121 {
122 bSuccess = true; // Nothing to do
123 }
124 }
125
126 return bSuccess;
127 }
128
129 void CPeripheralJoystick::InitializeDeadzoneFiltering(IButtonMap& buttonMap)
130 {
131 m_deadzoneFilter = std::make_unique<CDeadzoneFilter>(&buttonMap, this);
132 }
133
134 void CPeripheralJoystick::InitializeControllerProfile(IButtonMap& buttonMap)
135 {
136 const std::string controllerId = buttonMap.GetAppearance();
137 if (controllerId.empty())
138 return;
139
140 auto controller = m_manager.GetControllerProfiles().GetController(controllerId);
141 if (controller)
142 CPeripheral::SetControllerProfile(controller);
143 else
144 {
145 std::unique_lock<CCriticalSection> lock(m_controllerInstallMutex);
146
147 // Deposit controller into queue
148 m_controllersToInstall.emplace(controllerId);
149
150 // Clean up finished install tasks
151 m_installTasks.erase(std::remove_if(m_installTasks.begin(), m_installTasks.end(),
152 [](std::future<void>& task) {
153 return task.wait_for(std::chrono::seconds(0)) ==
154 std::future_status::ready;
155 }),
156 m_installTasks.end());
157
158 // Install controller off-thread
159 std::future<void> installTask =
160 std::async(std::launch::async,
161 [this]()
162 {
163 // Withdraw controller from queue
164 std::string controllerToInstall;
165 {
166 std::unique_lock<CCriticalSection> lock(m_controllerInstallMutex);
167 if (!m_controllersToInstall.empty())
168 {
169 controllerToInstall = m_controllersToInstall.front();
170 m_controllersToInstall.pop();
171 }
172 }
173
174 // Do the install
175 GAME::ControllerPtr controller = InstallAsync(controllerToInstall);
176 if (controller)
177 CPeripheral::SetControllerProfile(controller);
178 });
179
180 // Hold the task to prevent the destructor from completing during an install
181 m_installTasks.emplace_back(std::move(installTask));
182 }
183 }
184
185 void CPeripheralJoystick::OnUserNotification()
186 {
187 IInputReceiver* inputReceiver = m_appInput->GetInputReceiver(m_rumbleGenerator->ControllerID());
188 m_rumbleGenerator->NotifyUser(inputReceiver);
189 }
190
191 bool CPeripheralJoystick::TestFeature(PeripheralFeature feature)
192 {
193 bool bSuccess = false;
194
195 switch (feature)
196 {
197 case FEATURE_RUMBLE:
198 {
199 IInputReceiver* inputReceiver =
200 m_appInput->GetInputReceiver(m_rumbleGenerator->ControllerID());
201 bSuccess = m_rumbleGenerator->DoTest(inputReceiver);
202 break;
203 }
204 case FEATURE_POWER_OFF:
205 if (m_supportsPowerOff)
206 {
207 PowerOff();
208 bSuccess = true;
209 }
210 break;
211 default:
212 break;
213 }
214
215 return bSuccess;
216 }
217
218 void CPeripheralJoystick::PowerOff()
219 {
220 m_bus->PowerOff(m_strLocation);
221 }
222
223 void CPeripheralJoystick::RegisterJoystickDriverHandler(IDriverHandler* handler, bool bPromiscuous)
224 {
225 std::unique_lock<CCriticalSection> lock(m_handlerMutex);
226
227 DriverHandler driverHandler = {handler, bPromiscuous};
228 m_driverHandlers.insert(m_driverHandlers.begin(), driverHandler);
229 }
230
231 void CPeripheralJoystick::UnregisterJoystickDriverHandler(IDriverHandler* handler)
232 {
233 std::unique_lock<CCriticalSection> lock(m_handlerMutex);
234
235 m_driverHandlers.erase(std::remove_if(m_driverHandlers.begin(), m_driverHandlers.end(),
236 [handler](const DriverHandler& driverHandler)
237 { return driverHandler.handler == handler; }),
238 m_driverHandlers.end());
239 }
240
241 KEYMAP::IKeymap* CPeripheralJoystick::GetKeymap(const std::string& controllerId)
242 {
243 return m_appInput->GetKeymap(controllerId);
244 }
245
246 void CPeripheralJoystick::SetLastActive(const CDateTime& lastActive)
247 {
248 // Update state
249 m_lastActive = lastActive;
250
251 // Update ancestor
252 CPeripheral::SetLastActive(lastActive);
253 }
254
255 GAME::ControllerPtr CPeripheralJoystick::ControllerProfile() const
256 {
257 // Button map has the freshest state
258 if (m_buttonMap)
259 {
260 const std::string controllerId = m_buttonMap->GetAppearance();
261 if (!controllerId.empty())
262 {
263 auto controller = m_manager.GetControllerProfiles().GetController(controllerId);
264 if (controller)
265 return controller;
266 }
267 }
268
269 // Fall back to last set controller profile
270 if (m_controllerProfile)
271 return m_controllerProfile;
272
273 // Fall back to default controller
274 return m_manager.GetControllerProfiles().GetDefaultController();
275 }
276
277 void CPeripheralJoystick::SetControllerProfile(const KODI::GAME::ControllerPtr& controller)
278 {
279 CPeripheral::SetControllerProfile(controller);
280
281 // Save preference to buttonmap
282 if (m_buttonMap)
283 {
284 const std::string controllerId = controller ? controller->ID() : "";
285
286 if (m_buttonMap->SetAppearance(controllerId))
287 m_buttonMap->SaveButtonMap();
288 }
289 }
290
291 bool CPeripheralJoystick::OnButtonMotion(unsigned int buttonIndex, bool bPressed)
292 {
293 // Silence debug log if controllers are not enabled
294 if (m_manager.GetInputManager().IsControllerEnabled())
295 {
296 CLog::Log(LOGDEBUG, "BUTTON [ {} ] on \"{}\" {}", buttonIndex, DeviceName(),
297 bPressed ? "pressed" : "released");
298 }
299
300 // Avoid sending activated input if the app is in the background
301 if (bPressed && !g_application.IsAppFocused())
302 return false;
303
304 std::unique_lock<CCriticalSection> lock(m_handlerMutex);
305
306 // Update state
307 SetLastActive(CDateTime::GetCurrentDateTime());
308
309 // Check GUI setting and send button release if controllers are disabled
310 if (!m_manager.GetInputManager().IsControllerEnabled())
311 {
312 for (std::vector<DriverHandler>::iterator it = m_driverHandlers.begin();
313 it != m_driverHandlers.end(); ++it)
314 it->handler->OnButtonMotion(buttonIndex, false);
315 return true;
316 }
317
318 // Process promiscuous handlers
319 for (auto& it : m_driverHandlers)
320 {
321 if (it.bPromiscuous)
322 it.handler->OnButtonMotion(buttonIndex, bPressed);
323 }
324
325 bool bHandled = false;
326
327 // Process regular handlers until one is handled
328 for (auto& it : m_driverHandlers)
329 {
330 if (!it.bPromiscuous)
331 {
332 bHandled |= it.handler->OnButtonMotion(buttonIndex, bPressed);
333
334 // If button is released, force bHandled to false to notify all handlers.
335 // This avoids "sticking".
336 if (!bPressed)
337 bHandled = false;
338
339 // Once a button is handled, we're done
340 if (bHandled)
341 break;
342 }
343 }
344
345 return bHandled;
346 }
347
348 bool CPeripheralJoystick::OnHatMotion(unsigned int hatIndex, HAT_STATE state)
349 {
350 // Silence debug log if controllers are not enabled
351 if (m_manager.GetInputManager().IsControllerEnabled())
352 {
353 CLog::Log(LOGDEBUG, "HAT [ {} ] on \"{}\" {}", hatIndex, DeviceName(),
354 CJoystickTranslator::HatStateToString(state));
355 }
356
357 // Avoid sending activated input if the app is in the background
358 if (state != HAT_STATE::NONE && !g_application.IsAppFocused())
359 return false;
360
361 // Update state
362 SetLastActive(CDateTime::GetCurrentDateTime());
363
364 std::unique_lock<CCriticalSection> lock(m_handlerMutex);
365
366 // Check GUI setting and send hat unpressed if controllers are disabled
367 if (!m_manager.GetInputManager().IsControllerEnabled())
368 {
369 for (std::vector<DriverHandler>::iterator it = m_driverHandlers.begin();
370 it != m_driverHandlers.end(); ++it)
371 it->handler->OnHatMotion(hatIndex, HAT_STATE::NONE);
372 return true;
373 }
374
375 // Process promiscuous handlers
376 for (auto& it : m_driverHandlers)
377 {
378 if (it.bPromiscuous)
379 it.handler->OnHatMotion(hatIndex, state);
380 }
381
382 bool bHandled = false;
383
384 // Process regular handlers until one is handled
385 for (auto& it : m_driverHandlers)
386 {
387 if (!it.bPromiscuous)
388 {
389 bHandled |= it.handler->OnHatMotion(hatIndex, state);
390
391 // If hat is centered, force bHandled to false to notify all handlers.
392 // This avoids "sticking".
393 if (state == HAT_STATE::NONE)
394 bHandled = false;
395
396 // Once a hat is handled, we're done
397 if (bHandled)
398 break;
399 }
400 }
401
402 return bHandled;
403 }
404
405 bool CPeripheralJoystick::OnAxisMotion(unsigned int axisIndex, float position)
406 {
407 // Get axis properties
408 int center = 0;
409 unsigned int range = 1;
410 if (m_buttonMap)
411 m_buttonMap->GetAxisProperties(axisIndex, center, range);
412
413 // Apply deadzone filtering
414 if (center == 0 && m_deadzoneFilter)
415 position = m_deadzoneFilter->FilterAxis(axisIndex, position);
416
417 // Avoid sending activated input if the app is in the background
418 if (position != static_cast<float>(center) && !g_application.IsAppFocused())
419 return false;
420
421 std::unique_lock<CCriticalSection> lock(m_handlerMutex);
422
423 // Check GUI setting and send analog axis centered if controllers are disabled
424 if (!m_manager.GetInputManager().IsControllerEnabled())
425 {
426 for (std::vector<DriverHandler>::iterator it = m_driverHandlers.begin();
427 it != m_driverHandlers.end(); ++it)
428 it->handler->OnAxisMotion(axisIndex, static_cast<float>(center), center, range);
429 return true;
430 }
431
432 // Process promiscuous handlers
433 for (auto& it : m_driverHandlers)
434 {
435 if (it.bPromiscuous)
436 it.handler->OnAxisMotion(axisIndex, position, center, range);
437 }
438
439 bool bHandled = false;
440
441 // Process regular handlers until one is handled
442 for (auto& it : m_driverHandlers)
443 {
444 if (!it.bPromiscuous)
445 {
446 bHandled |= it.handler->OnAxisMotion(axisIndex, position, center, range);
447
448 // If axis is centered, force bHandled to false to notify all handlers.
449 // This avoids "sticking".
450 if (position == static_cast<float>(center))
451 bHandled = false;
452
453 // Once an axis is handled, we're done
454 if (bHandled)
455 break;
456 }
457 }
458
459 // Update state
460 if (bHandled)
461 SetLastActive(CDateTime::GetCurrentDateTime());
462
463 return bHandled;
464 }
465
466 void CPeripheralJoystick::OnInputFrame(void)
467 {
468 std::unique_lock<CCriticalSection> lock(m_handlerMutex);
469
470 for (auto& it : m_driverHandlers)
471 it.handler->OnInputFrame();
472 }
473
474 bool CPeripheralJoystick::SetMotorState(unsigned int motorIndex, float magnitude)
475 {
476 bool bHandled = false;
477
478 if (m_mappedBusType == PERIPHERAL_BUS_ADDON)
479 {
480 CPeripheralBusAddon* addonBus = static_cast<CPeripheralBusAddon*>(m_bus);
481 if (addonBus)
482 {
483 bHandled = addonBus->SendRumbleEvent(m_strLocation, motorIndex, magnitude);
484 }
485 }
486 return bHandled;
487 }
488
489 void CPeripheralJoystick::SetMotorCount(unsigned int motorCount)
490 {
491 m_motorCount = motorCount;
492
493 if (m_motorCount == 0)
494 m_features.erase(std::remove(m_features.begin(), m_features.end(), FEATURE_RUMBLE),
495 m_features.end());
496 else if (std::find(m_features.begin(), m_features.end(), FEATURE_RUMBLE) == m_features.end())
497 m_features.push_back(FEATURE_RUMBLE);
498 }
499
500 void CPeripheralJoystick::SetSupportsPowerOff(bool bSupportsPowerOff)
501 {
502 m_supportsPowerOff = bSupportsPowerOff;
503
504 if (!m_supportsPowerOff)
505 m_features.erase(std::remove(m_features.begin(), m_features.end(), FEATURE_POWER_OFF),
506 m_features.end());
507 else if (std::find(m_features.begin(), m_features.end(), FEATURE_POWER_OFF) == m_features.end())
508 m_features.push_back(FEATURE_POWER_OFF);
509 }
510
511 GAME::ControllerPtr CPeripheralJoystick::InstallAsync(const std::string& controllerId)
512 {
513 // Installing controllers calls into the GUI, so wait for it to be ready
514 if (!m_manager.WaitForGUI())
515 return {};
516
517 GAME::ControllerPtr controller;
518
519 // Only 1 install at a time. Remaining installs will wake when this one
520 // is done.
521 std::unique_lock<CCriticalSection> lockInstall(m_manager.GetAddonInstallMutex());
522
523 CLog::LogF(LOGDEBUG, "Installing {}", controllerId);
524
525 if (InstallSync(controllerId))
526 controller = m_manager.GetControllerProfiles().GetController(controllerId);
527 else
528 CLog::LogF(LOGERROR, "Failed to install {}", controllerId);
529
530 return controller;
531 }
532
533 bool CPeripheralJoystick::InstallSync(const std::string& controllerId)
534 {
535 // If the addon isn't installed we need to install it
536 bool installed = CServiceBroker::GetAddonMgr().IsAddonInstalled(controllerId);
537 if (!installed)
538 {
539 ADDON::AddonPtr installedAddon;
540 installed = ADDON::CAddonInstaller::GetInstance().InstallModal(
541 controllerId, installedAddon, ADDON::InstallModalPrompt::CHOICE_NO);
542 }
543
544 if (installed)
545 {
546 // Make sure add-on is enabled
547 if (CServiceBroker::GetAddonMgr().IsAddonDisabled(controllerId))
548 CServiceBroker::GetAddonMgr().EnableAddon(controllerId);
549 }
550
551 return installed;
552 }