Debian Codegraph @

xbmc/games/addons/input/GameClientInput.cpp

raw
1 /*
2 * Copyright (C) 2017-2018 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 "GameClientInput.h"
10
11 #include "GameClientController.h"
12 #include "GameClientHardware.h"
13 #include "GameClientJoystick.h"
14 #include "GameClientKeyboard.h"
15 #include "GameClientMouse.h"
16 #include "GameClientPort.h"
17 #include "GameClientTopology.h"
18 #include "ServiceBroker.h"
19 #include "addons/addoninfo/AddonInfo.h"
20 #include "addons/kodi-dev-kit/include/kodi/addon-instance/Game.h"
21 #include "games/GameServices.h"
22 #include "games/addons/GameClient.h"
23 #include "games/addons/GameClientCallbacks.h"
24 #include "games/controllers/Controller.h"
25 #include "games/controllers/ControllerLayout.h"
26 #include "games/controllers/input/PhysicalTopology.h"
27 #include "games/controllers/types/ControllerHub.h"
28 #include "games/controllers/types/ControllerNode.h"
29 #include "games/controllers/types/ControllerTree.h"
30 #include "games/ports/input/PortManager.h"
31 #include "games/ports/types/PortNode.h"
32 #include "input/joysticks/JoystickTypes.h"
33 #include "peripherals/Peripherals.h"
34 #include "peripherals/events/EventLockHandle.h"
35 #include "utils/log.h"
36
37 #include <algorithm>
38 #include <memory>
39 #include <mutex>
40
41 using namespace KODI;
42 using namespace GAME;
43
44 CGameClientInput::CGameClientInput(CGameClient& gameClient,
45 AddonInstance_Game& addonStruct,
46 CCriticalSection& clientAccess)
47 : CGameClientSubsystem(gameClient, addonStruct, clientAccess),
48 m_topology(new CGameClientTopology),
49 m_portManager(std::make_unique<CPortManager>())
50 {
51 }
52
53 CGameClientInput::~CGameClientInput()
54 {
55 Deinitialize();
56 }
57
58 void CGameClientInput::Initialize()
59 {
60 LoadTopology();
61
62 // Send controller layouts to game client
63 SetControllerLayouts(m_topology->GetControllerTree().GetControllers());
64
65 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
66
67 // Reset ports to default state (first accepted controller is connected)
68 ActivateControllers(m_topology->GetControllerTree());
69
70 // Initialize the port manager
71 m_portManager->Initialize(m_gameClient.Profile());
72 m_portManager->SetControllerTree(m_topology->GetControllerTree());
73 m_portManager->LoadXML();
74 }
75
76 void CGameClientInput::Start(IGameInputCallback* input)
77 {
78 {
79 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
80
81 m_inputCallback = input;
82
83 // Connect/disconnect active controllers
84 for (const CPortNode& port : m_portManager->GetControllerTree().GetPorts())
85 {
86 if (port.IsConnected())
87 {
88 const ControllerPtr& activeController = port.GetActiveController().GetController();
89 if (activeController)
90 ConnectController(port.GetAddress(), activeController);
91 }
92 else
93 DisconnectController(port.GetAddress());
94 }
95
96 // Ensure hardware is open to receive events
97 m_hardware = std::make_unique<CGameClientHardware>(m_gameClient);
98 }
99
100 // Notify observers of the initial port configuration
101 NotifyObservers(ObservableMessageGamePortsChanged);
102 }
103
104 void CGameClientInput::Deinitialize()
105 {
106 Stop();
107
108 m_topology->Clear();
109 m_controllerLayouts.clear();
110 m_portManager->Clear();
111 }
112
113 void CGameClientInput::Stop()
114 {
115 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
116
117 m_hardware.reset();
118
119 CloseMouse();
120
121 CloseKeyboard();
122
123 PERIPHERALS::EventLockHandlePtr inputHandlingLock;
124 CloseJoysticks(inputHandlingLock);
125
126 // If a port was closed, then this blocks until all peripheral input has
127 // been handled
128 inputHandlingLock.reset();
129
130 m_inputCallback = nullptr;
131 }
132
133 bool CGameClientInput::HasFeature(const std::string& controllerId,
134 const std::string& featureName) const
135 {
136 bool bHasFeature = false;
137
138 try
139 {
140 bHasFeature =
141 m_struct.toAddon->HasFeature(&m_struct, controllerId.c_str(), featureName.c_str());
142 }
143 catch (...)
144 {
145 CLog::Log(LOGERROR, "GAME: {}: exception caught in HasFeature()", m_gameClient.ID());
146
147 // Fail gracefully
148 bHasFeature = true;
149 }
150
151 return bHasFeature;
152 }
153
154 bool CGameClientInput::AcceptsInput() const
155 {
156 if (m_inputCallback != nullptr)
157 return m_inputCallback->AcceptsInput();
158
159 return false;
160 }
161
162 bool CGameClientInput::InputEvent(const game_input_event& event)
163 {
164 bool bHandled = false;
165
166 try
167 {
168 bHandled = m_struct.toAddon->InputEvent(&m_struct, &event);
169 }
170 catch (...)
171 {
172 CLog::Log(LOGERROR, "GAME: {}: exception caught in InputEvent()", m_gameClient.ID());
173 }
174
175 return bHandled;
176 }
177
178 float CGameClientInput::GetPortActivation(const std::string& portAddress)
179 {
180 float activation = 0.0f;
181
182 std::unique_lock<std::recursive_mutex> lock(m_portMutex, std::defer_lock);
183
184 if (lock.try_lock())
185 {
186 auto it = m_joysticks.find(portAddress);
187 if (it != m_joysticks.end())
188 activation = it->second->GetActivation();
189
190 if (portAddress == KEYBOARD_PORT_ADDRESS && m_keyboard)
191 activation = std::max(m_keyboard->GetActivation(), activation);
192 else if (portAddress == MOUSE_PORT_ADDRESS && m_mouse)
193 activation = std::max(m_mouse->GetActivation(), activation);
194 }
195
196 return activation;
197 }
198
199 void CGameClientInput::LoadTopology()
200 {
201 game_input_topology* topologyStruct = nullptr;
202
203 if (m_gameClient.Initialized())
204 {
205 try
206 {
207 topologyStruct = m_struct.toAddon->GetTopology(&m_struct);
208 }
209 catch (...)
210 {
211 m_gameClient.LogException("GetTopology()");
212 }
213 }
214
215 GameClientPortVec hardwarePorts;
216 int playerLimit = -1;
217
218 if (topologyStruct != nullptr)
219 {
220 //! @todo Guard against infinite loops provided by the game client
221
222 game_input_port* ports = topologyStruct->ports;
223 if (ports != nullptr)
224 {
225 for (unsigned int i = 0; i < topologyStruct->port_count; i++)
226 hardwarePorts.emplace_back(new CGameClientPort(ports[i]));
227 }
228
229 playerLimit = topologyStruct->player_limit;
230
231 try
232 {
233 m_struct.toAddon->FreeTopology(&m_struct, topologyStruct);
234 }
235 catch (...)
236 {
237 m_gameClient.LogException("FreeTopology()");
238 }
239 }
240
241 // If no topology is available, create a default one with a single port that
242 // accepts all controllers imported by addon.xml
243 if (hardwarePorts.empty())
244 hardwarePorts.emplace_back(new CGameClientPort(GetControllers(m_gameClient)));
245
246 m_topology = std::make_unique<CGameClientTopology>(std::move(hardwarePorts), playerLimit);
247 }
248
249 void CGameClientInput::ActivateControllers(CControllerHub& hub)
250 {
251 for (auto& port : hub.GetPorts())
252 {
253 if (port.GetCompatibleControllers().empty())
254 continue;
255
256 port.SetConnected(true);
257 port.SetActiveController(0);
258 for (auto& controller : port.GetCompatibleControllers())
259 ActivateControllers(controller.GetHub());
260 }
261 }
262
263 void CGameClientInput::SetControllerLayouts(const ControllerVector& controllers)
264 {
265 if (controllers.empty())
266 return;
267
268 for (const auto& controller : controllers)
269 {
270 const std::string controllerId = controller->ID();
271 if (m_controllerLayouts.find(controllerId) == m_controllerLayouts.end())
272 m_controllerLayouts[controllerId] =
273 std::make_unique<CGameClientController>(*this, controller);
274 }
275
276 std::vector<game_controller_layout> controllerStructs;
277 for (const auto& it : m_controllerLayouts)
278 controllerStructs.emplace_back(it.second->TranslateController());
279
280 try
281 {
282 m_struct.toAddon->SetControllerLayouts(&m_struct, controllerStructs.data(),
283 static_cast<unsigned int>(controllerStructs.size()));
284 }
285 catch (...)
286 {
287 m_gameClient.LogException("SetControllerLayouts()");
288 }
289 }
290
291 const CControllerTree& CGameClientInput::GetDefaultControllerTree() const
292 {
293 return m_topology->GetControllerTree();
294 }
295
296 CControllerTree CGameClientInput::GetActiveControllerTree() const
297 {
298 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
299
300 return m_portManager->GetControllerTree();
301 }
302
303 bool CGameClientInput::SupportsKeyboard() const
304 {
305 const CControllerTree& controllers = GetDefaultControllerTree();
306
307 auto it =
308 std::find_if(controllers.GetPorts().begin(), controllers.GetPorts().end(),
309 [](const CPortNode& port) { return port.GetPortType() == PORT_TYPE::KEYBOARD; });
310
311 return it != controllers.GetPorts().end() && !it->GetCompatibleControllers().empty();
312 }
313
314 bool CGameClientInput::SupportsMouse() const
315 {
316 const CControllerTree& controllers = GetDefaultControllerTree();
317
318 auto it =
319 std::find_if(controllers.GetPorts().begin(), controllers.GetPorts().end(),
320 [](const CPortNode& port) { return port.GetPortType() == PORT_TYPE::MOUSE; });
321
322 return it != controllers.GetPorts().end() && !it->GetCompatibleControllers().empty();
323 }
324
325 int CGameClientInput::GetPlayerLimit() const
326 {
327 return m_topology->GetPlayerLimit();
328 }
329
330 bool CGameClientInput::ConnectController(const std::string& portAddress,
331 const ControllerPtr& controller)
332 {
333 // Validate parameters
334 if (portAddress.empty() || !controller)
335 return false;
336
337 const CControllerTree& controllerTree = GetDefaultControllerTree();
338
339 // Validate controller
340 const CPortNode& port = controllerTree.GetPort(portAddress);
341 if (!port.IsControllerAccepted(portAddress, controller->ID()))
342 {
343 CLog::Log(LOGERROR, "Failed to open port: Invalid controller \"{}\" on port \"{}\"",
344 controller->ID(), portAddress);
345 return false;
346 }
347
348 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
349
350 const CPortNode& currentPort = m_portManager->GetControllerTree().GetPort(portAddress);
351
352 // Close current ports if any are open
353 PERIPHERALS::EventLockHandlePtr inputHandlingLock;
354 CloseJoysticks(currentPort, inputHandlingLock);
355 inputHandlingLock.reset();
356
357 {
358 std::unique_lock<CCriticalSection> lock(m_clientAccess);
359
360 if (!m_gameClient.Initialized())
361 return false;
362
363 try
364 {
365 if (!m_struct.toAddon->ConnectController(&m_struct, true, portAddress.c_str(),
366 controller->ID().c_str()))
367 {
368 return false;
369 }
370 }
371 catch (...)
372 {
373 m_gameClient.LogException("ConnectController()");
374 return false;
375 }
376 }
377
378 // Update port state
379 m_portManager->ConnectController(portAddress, true, controller->ID());
380 SetChanged();
381
382 // Update agent input
383 if (controller->Layout().Topology().ProvidesInput())
384 OpenJoystick(portAddress, controller);
385
386 bool bSuccess = true;
387
388 // If port is a multitap, we need to activate its children
389 const CPortNode& updatedPort = m_portManager->GetControllerTree().GetPort(portAddress);
390 const PortVec& childPorts = updatedPort.GetActiveController().GetHub().GetPorts();
391 for (const CPortNode& childPort : childPorts)
392 {
393 const ControllerPtr& childController = childPort.GetActiveController().GetController();
394 if (childController)
395 bSuccess &= ConnectController(childPort.GetAddress(), childController);
396 }
397
398 return bSuccess;
399 }
400
401 bool CGameClientInput::DisconnectController(const std::string& portAddress)
402 {
403 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
404
405 if (!DisconnectControllerRecursive(portAddress))
406 return false;
407
408 // Update port state
409 m_portManager->ConnectController(portAddress, false);
410 SetChanged();
411
412 return true;
413 }
414
415 bool CGameClientInput::DisconnectControllerRecursive(const std::string& portAddress)
416 {
417 PERIPHERALS::EventLockHandlePtr inputHandlingLock;
418
419 // If port is a multitap, we need to deactivate its children
420 const CPortNode& currentPort = m_portManager->GetControllerTree().GetPort(portAddress);
421 const PortVec& childPorts = currentPort.GetActiveController().GetHub().GetPorts();
422 for (const CPortNode& childPort : childPorts)
423 DisconnectControllerRecursive(childPort.GetAddress());
424
425 // Update agent input
426 CloseJoysticks(currentPort, inputHandlingLock);
427
428 // If a port was closed, then destroying the last lock will block until all
429 // peripheral input handling is complete to avoid invalidating the port's
430 // input handler
431 inputHandlingLock.reset();
432
433 {
434 std::unique_lock<CCriticalSection> lock(m_clientAccess);
435
436 if (!m_gameClient.Initialized())
437 return false;
438
439 try
440 {
441 if (!m_struct.toAddon->ConnectController(&m_struct, false, portAddress.c_str(), ""))
442 return false;
443 }
444 catch (...)
445 {
446 m_gameClient.LogException("ConnectController()");
447 return false;
448 }
449 }
450
451 // Update agent input
452 CloseJoystick(portAddress, inputHandlingLock);
453 inputHandlingLock.reset();
454
455 return true;
456 }
457
458 void CGameClientInput::SavePorts()
459 {
460 {
461 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
462
463 // Save port state
464 m_portManager->SaveXMLAsync();
465 }
466
467 // Let the observers know that ports have changed
468 NotifyObservers(ObservableMessageGamePortsChanged);
469 }
470
471 void CGameClientInput::ResetPorts()
472 {
473 std::lock_guard<std::recursive_mutex> lock(m_portMutex);
474
475 const CControllerTree& controllerTree = GetDefaultControllerTree();
476 ResetPorts(controllerTree.GetPorts());
477 }
478
479 bool CGameClientInput::HasAgent() const
480 {
481 if (!m_joysticks.empty())
482 return true;
483
484 if (m_keyboard)
485 return true;
486
487 if (m_mouse)
488 return true;
489
490 return false;
491 }
492
493 bool CGameClientInput::OpenKeyboard(const ControllerPtr& controller,
494 const PERIPHERALS::PeripheralPtr& keyboard)
495 {
496 using namespace JOYSTICK;
497
498 if (!controller)
499 {
500 CLog::Log(LOGERROR, "Failed to open keyboard, no controller given");
501 return false;
502 }
503
504 if (!keyboard)
505 return false;
506
507 bool bSuccess = false;
508
509 {
510 std::unique_lock<CCriticalSection> lock(m_clientAccess);
511
512 if (m_gameClient.Initialized())
513 {
514 try
515 {
516 bSuccess = m_struct.toAddon->EnableKeyboard(&m_struct, true, controller->ID().c_str());
517 }
518 catch (...)
519 {
520 m_gameClient.LogException("EnableKeyboard()");
521 }
522 }
523 }
524
525 if (bSuccess)
526 {
527 m_keyboard =
528 std::make_unique<CGameClientKeyboard>(m_gameClient, controller->ID(), keyboard.get());
529 m_keyboard->SetSource(keyboard);
530 return true;
531 }
532
533 return false;
534 }
535
536 bool CGameClientInput::IsKeyboardOpen() const
537 {
538 return static_cast<bool>(m_keyboard);
539 }
540
541 void CGameClientInput::CloseKeyboard()
542 {
543 if (m_keyboard)
544 {
545 m_keyboard.reset();
546
547 std::unique_lock<CCriticalSection> lock(m_clientAccess);
548
549 if (m_gameClient.Initialized())
550 {
551 try
552 {
553 m_struct.toAddon->EnableKeyboard(&m_struct, false, "");
554 }
555 catch (...)
556 {
557 m_gameClient.LogException("EnableKeyboard()");
558 }
559 }
560 }
561 }
562
563 bool CGameClientInput::OpenMouse(const ControllerPtr& controller,
564 const PERIPHERALS::PeripheralPtr& mouse)
565 {
566 using namespace JOYSTICK;
567
568 if (!controller)
569 {
570 CLog::Log(LOGERROR, "Failed to open mouse, no controller given");
571 return false;
572 }
573
574 if (!mouse)
575 return false;
576
577 bool bSuccess = false;
578
579 {
580 std::unique_lock<CCriticalSection> lock(m_clientAccess);
581
582 if (m_gameClient.Initialized())
583 {
584 try
585 {
586 bSuccess = m_struct.toAddon->EnableMouse(&m_struct, true, controller->ID().c_str());
587 }
588 catch (...)
589 {
590 m_gameClient.LogException("EnableMouse()");
591 }
592 }
593 }
594
595 if (bSuccess)
596 {
597 m_mouse = std::make_unique<CGameClientMouse>(m_gameClient, controller->ID(), mouse.get());
598 m_mouse->SetSource(mouse);
599 return true;
600 }
601
602 return false;
603 }
604
605 bool CGameClientInput::IsMouseOpen() const
606 {
607 return static_cast<bool>(m_mouse);
608 }
609
610 void CGameClientInput::CloseMouse()
611 {
612 if (m_mouse)
613 {
614 m_mouse.reset();
615
616 std::unique_lock<CCriticalSection> lock(m_clientAccess);
617
618 if (m_gameClient.Initialized())
619 {
620 try
621 {
622 m_struct.toAddon->EnableMouse(&m_struct, false, "");
623 }
624 catch (...)
625 {
626 m_gameClient.LogException("EnableMouse()");
627 }
628 }
629 }
630 }
631
632 bool CGameClientInput::OpenJoystick(const std::string& portAddress, const ControllerPtr& controller)
633 {
634 using namespace JOYSTICK;
635
636 if (!controller)
637 {
638 CLog::Log(LOGERROR, "Failed to open port \"{}\", no controller given", portAddress);
639 return false;
640 }
641
642 if (m_joysticks.find(portAddress) != m_joysticks.end())
643 {
644 CLog::Log(LOGERROR, "Failed to open port \"{}\", already open", portAddress);
645 return false;
646 }
647
648 m_joysticks[portAddress] =
649 std::make_shared<CGameClientJoystick>(m_gameClient, portAddress, controller);
650
651 return true;
652 }
653
654 void CGameClientInput::CloseJoysticks(PERIPHERALS::EventLockHandlePtr& inputHandlingLock)
655 {
656 std::vector<std::string> portAddresses;
657 for (const auto& it : m_joysticks)
658 portAddresses.emplace_back(it.first);
659
660 for (const std::string& portAddress : portAddresses)
661 CloseJoystick(portAddress, inputHandlingLock);
662 }
663
664 void CGameClientInput::CloseJoysticks(const CPortNode& port,
665 PERIPHERALS::EventLockHandlePtr& inputHandlingLock)
666 {
667 const PortVec& childPorts = port.GetActiveController().GetHub().GetPorts();
668 for (const CPortNode& childPort : childPorts)
669 CloseJoysticks(childPort, inputHandlingLock);
670
671 CloseJoystick(port.GetAddress(), inputHandlingLock);
672 }
673
674 void CGameClientInput::CloseJoystick(const std::string& portAddress,
675 PERIPHERALS::EventLockHandlePtr& inputHandlingLock)
676 {
677 auto it = m_joysticks.find(portAddress);
678 if (it != m_joysticks.end())
679 {
680 if (!inputHandlingLock)
681 {
682 // An input handler is being destroyed. Disable input until the lock is
683 // released. Note: acquiring the lock blocks until all peripheral input
684 // has been handled.
685 inputHandlingLock = CServiceBroker::GetPeripherals().RegisterEventLock();
686 }
687
688 m_joysticks.erase(it);
689 }
690 }
691
692 void CGameClientInput::HardwareReset()
693 {
694 if (m_hardware)
695 m_hardware->OnResetButton();
696 }
697
698 bool CGameClientInput::ReceiveInputEvent(const game_input_event& event)
699 {
700 bool bHandled = false;
701
702 switch (event.type)
703 {
704 case GAME_INPUT_EVENT_MOTOR:
705 if (event.port_address != nullptr && event.feature_name != nullptr)
706 bHandled = SetRumble(event.port_address, event.feature_name, event.motor.magnitude);
707 break;
708 default:
709 break;
710 }
711
712 return bHandled;
713 }
714
715 bool CGameClientInput::SetRumble(const std::string& portAddress,
716 const std::string& feature,
717 float magnitude)
718 {
719 bool bHandled = false;
720
721 auto it = m_joysticks.find(portAddress);
722 if (it != m_joysticks.end())
723 bHandled = it->second->SetRumble(feature, magnitude);
724
725 return bHandled;
726 }
727
728 ControllerVector CGameClientInput::GetControllers(const CGameClient& gameClient)
729 {
730 ControllerVector controllers;
731
732 CGameServices& gameServices = CServiceBroker::GetGameServices();
733
734 const auto& dependencies = gameClient.GetDependencies();
735 for (auto it = dependencies.begin(); it != dependencies.end(); ++it)
736 {
737 ControllerPtr controller = gameServices.GetController(it->id);
738 if (controller)
739 controllers.push_back(controller);
740 }
741
742 if (controllers.empty())
743 {
744 // Use the default controller
745 ControllerPtr controller = gameServices.GetDefaultController();
746 if (controller)
747 controllers.push_back(controller);
748 }
749
750 return controllers;
751 }
752
753 void CGameClientInput::ResetPorts(const PortVec& ports)
754 {
755 for (const CPortNode& port : ports)
756 {
757 // Reset port
758 const CControllerNode& activeController = port.GetActiveController();
759 ConnectController(port.GetAddress(), activeController.GetController());
760
761 // Reset child ports
762 ResetPorts(activeController.GetHub().GetPorts());
763 }
764 }