Debian Codegraph @

xbmc/input/joysticks/generic/ButtonMapping.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 "ButtonMapping.h"
10
11 #include "ServiceBroker.h"
12 #include "games/controllers/Controller.h"
13 #include "games/controllers/ControllerManager.h"
14 #include "games/controllers/input/PhysicalFeature.h"
15 #include "input/InputTranslator.h"
16 #include "input/actions/ActionIDs.h"
17 #include "input/joysticks/DriverPrimitive.h"
18 #include "input/joysticks/JoystickTranslator.h"
19 #include "input/joysticks/JoystickUtils.h"
20 #include "input/joysticks/interfaces/IButtonMap.h"
21 #include "input/joysticks/interfaces/IButtonMapper.h"
22 #include "input/keyboard/Key.h"
23 #include "input/keymaps/interfaces/IKeymap.h"
24 #include "peripherals/PeripheralTypes.h"
25 #include "peripherals/Peripherals.h"
26 #include "peripherals/devices/Peripheral.h"
27 #include "utils/log.h"
28
29 #include <algorithm>
30 #include <assert.h>
31 #include <cmath>
32 #include <memory>
33
34 using namespace KODI;
35 using namespace JOYSTICK;
36
37 #define MAPPING_COOLDOWN_MS 50 // Guard against repeated input
38 #define AXIS_THRESHOLD 0.75f // Axis must exceed this value to be mapped
39 #define TRIGGER_DELAY_MS \
40 200 // Delay trigger detection to handle anomalous triggers with non-zero center
41
42 // --- CPrimitiveDetector ------------------------------------------------------
43
44 CPrimitiveDetector::CPrimitiveDetector(CButtonMapping* buttonMapping)
45 : m_buttonMapping(buttonMapping)
46 {
47 }
48
49 bool CPrimitiveDetector::MapPrimitive(const CDriverPrimitive& primitive)
50 {
51 if (primitive.IsValid())
52 return m_buttonMapping->MapPrimitive(primitive);
53
54 return false;
55 }
56
57 // --- CButtonDetector ---------------------------------------------------------
58
59 CButtonDetector::CButtonDetector(CButtonMapping* buttonMapping, unsigned int buttonIndex)
60 : CPrimitiveDetector(buttonMapping), m_buttonIndex(buttonIndex)
61 {
62 }
63
64 bool CButtonDetector::OnMotion(bool bPressed)
65 {
66 if (bPressed)
67 return MapPrimitive(CDriverPrimitive(PRIMITIVE_TYPE::BUTTON, m_buttonIndex));
68
69 return false;
70 }
71
72 // --- CHatDetector ------------------------------------------------------------
73
74 CHatDetector::CHatDetector(CButtonMapping* buttonMapping, unsigned int hatIndex)
75 : CPrimitiveDetector(buttonMapping), m_hatIndex(hatIndex)
76 {
77 }
78
79 bool CHatDetector::OnMotion(HAT_STATE state)
80 {
81 return MapPrimitive(CDriverPrimitive(m_hatIndex, static_cast<HAT_DIRECTION>(state)));
82 }
83
84 // --- CAxisDetector -----------------------------------------------------------
85
86 CAxisDetector::CAxisDetector(CButtonMapping* buttonMapping,
87 unsigned int axisIndex,
88 const AxisConfiguration& config)
89 : CPrimitiveDetector(buttonMapping), m_axisIndex(axisIndex), m_config(config)
90 {
91 }
92
93 bool CAxisDetector::OnMotion(float position)
94 {
95 DetectType(position);
96
97 if (m_type != AXIS_TYPE::UNKNOWN)
98 {
99 // Update position if this axis is an anomalous trigger
100 if (m_type == AXIS_TYPE::OFFSET)
101 position = (position - m_config.center) / m_config.range;
102
103 // Reset state if position crosses zero
104 if (m_state == AXIS_STATE::MAPPED)
105 {
106 SEMIAXIS_DIRECTION activatedDir = m_activatedPrimitive.SemiAxisDirection();
107 SEMIAXIS_DIRECTION newDir = CJoystickTranslator::PositionToSemiAxisDirection(position);
108
109 if (activatedDir != newDir)
110 m_state = AXIS_STATE::INACTIVE;
111 }
112
113 // Check if axis has become activated
114 if (m_state == AXIS_STATE::INACTIVE)
115 {
116 if (std::abs(position) >= AXIS_THRESHOLD)
117 m_state = AXIS_STATE::ACTIVATED;
118
119 if (m_state == AXIS_STATE::ACTIVATED)
120 {
121 // Range is set later for anomalous triggers
122 m_activatedPrimitive =
123 CDriverPrimitive(m_axisIndex, m_config.center,
124 CJoystickTranslator::PositionToSemiAxisDirection(position), 1);
125 m_activationTimeMs = std::chrono::steady_clock::now();
126 }
127 }
128 }
129
130 return true;
131 }
132
133 void CAxisDetector::ProcessMotion()
134 {
135 // Process newly-activated axis
136 if (m_state == AXIS_STATE::ACTIVATED)
137 {
138 // Ignore anomalous triggers for a bit so we can detect the full range
139 bool bIgnore = false;
140 if (m_type == AXIS_TYPE::OFFSET)
141 {
142 auto now = std::chrono::steady_clock::now();
143 auto duration =
144 std::chrono::duration_cast<std::chrono::milliseconds>(now - m_activationTimeMs);
145
146 if (duration.count() < TRIGGER_DELAY_MS)
147 bIgnore = true;
148 }
149
150 if (!bIgnore)
151 {
152 // Update driver primitive's range if we're mapping an anomalous trigger
153 if (m_type == AXIS_TYPE::OFFSET)
154 {
155 m_activatedPrimitive =
156 CDriverPrimitive(m_activatedPrimitive.Index(), m_activatedPrimitive.Center(),
157 m_activatedPrimitive.SemiAxisDirection(), m_config.range);
158 }
159
160 // Map primitive
161 if (!MapPrimitive(m_activatedPrimitive))
162 {
163 if (m_type == AXIS_TYPE::OFFSET)
164 CLog::Log(LOGDEBUG, "Mapping offset axis {} failed", m_axisIndex);
165 else
166 CLog::Log(LOGDEBUG, "Mapping normal axis {} failed", m_axisIndex);
167 }
168
169 m_state = AXIS_STATE::MAPPED;
170 }
171 }
172 }
173
174 void CAxisDetector::SetEmitted(const CDriverPrimitive& activePrimitive)
175 {
176 m_state = AXIS_STATE::MAPPED;
177 m_activatedPrimitive = activePrimitive;
178 }
179
180 void CAxisDetector::DetectType(float position)
181 {
182 // Some platforms don't report a value until the axis is first changed.
183 // Detection relies on an initial value, so this axis will be disabled until
184 // the user begins button mapping again.
185 if (m_config.bLateDiscovery)
186 return;
187
188 // Update range if a range of > 1 is observed
189 if (std::abs(position - m_config.center) > 1.0f)
190 m_config.range = 2;
191
192 if (m_type != AXIS_TYPE::UNKNOWN)
193 return;
194
195 if (m_config.bKnown)
196 {
197 if (m_config.center == 0)
198 m_type = AXIS_TYPE::NORMAL;
199 else
200 m_type = AXIS_TYPE::OFFSET;
201 }
202
203 if (m_type != AXIS_TYPE::UNKNOWN)
204 return;
205
206 if (!m_initialPositionKnown)
207 {
208 m_initialPositionKnown = true;
209 m_initialPosition = position;
210 }
211
212 if (position != m_initialPosition)
213 m_initialPositionChanged = true;
214
215 if (m_initialPositionChanged)
216 {
217 // Calculate center based on initial position.
218 if (m_initialPosition < -0.5f)
219 {
220 m_config.center = -1;
221 m_type = AXIS_TYPE::OFFSET;
222 CLog::Log(LOGDEBUG, "Anomalous trigger detected on axis {} with center {}", m_axisIndex,
223 m_config.center);
224 }
225 else if (m_initialPosition > 0.5f)
226 {
227 m_config.center = 1;
228 m_type = AXIS_TYPE::OFFSET;
229 CLog::Log(LOGDEBUG, "Anomalous trigger detected on axis {} with center {}", m_axisIndex,
230 m_config.center);
231 }
232 else
233 {
234 m_type = AXIS_TYPE::NORMAL;
235 CLog::Log(LOGDEBUG, "Normal axis detected on axis {}", m_axisIndex);
236 }
237 }
238 }
239
240 // --- CKeyDetector ---------------------------------------------------------
241
242 CKeyDetector::CKeyDetector(CButtonMapping* buttonMapping, XBMCKey keycode)
243 : CPrimitiveDetector(buttonMapping), m_keycode(keycode)
244 {
245 }
246
247 bool CKeyDetector::OnMotion(bool bPressed)
248 {
249 if (bPressed)
250 return MapPrimitive(CDriverPrimitive(m_keycode));
251
252 return false;
253 }
254
255 // --- CMouseButtonDetector ----------------------------------------------------
256
257 CMouseButtonDetector::CMouseButtonDetector(CButtonMapping* buttonMapping,
258 MOUSE::BUTTON_ID buttonIndex)
259 : CPrimitiveDetector(buttonMapping), m_buttonIndex(buttonIndex)
260 {
261 }
262
263 bool CMouseButtonDetector::OnMotion(bool bPressed)
264 {
265 if (bPressed)
266 return MapPrimitive(CDriverPrimitive(m_buttonIndex));
267
268 return false;
269 }
270
271 // --- CPointerDetector --------------------------------------------------------
272
273 CPointerDetector::CPointerDetector(CButtonMapping* buttonMapping)
274 : CPrimitiveDetector(buttonMapping)
275 {
276 }
277
278 bool CPointerDetector::OnMotion(int x, int y)
279 {
280 if (!m_bStarted)
281 {
282 m_bStarted = true;
283 m_startX = x;
284 m_startY = y;
285 m_frameCount = 0;
286 }
287
288 if (m_frameCount++ >= MIN_FRAME_COUNT)
289 {
290 int dx = x - m_startX;
291 int dy = y - m_startY;
292
293 INPUT::INTERCARDINAL_DIRECTION dir = GetPointerDirection(dx, dy);
294
295 CDriverPrimitive primitive(static_cast<RELATIVE_POINTER_DIRECTION>(dir));
296 if (primitive.IsValid())
297 {
298 if (MapPrimitive(primitive))
299 m_bStarted = false;
300 }
301 }
302
303 return true;
304 }
305
306 KODI::INPUT::INTERCARDINAL_DIRECTION CPointerDetector::GetPointerDirection(int x, int y)
307 {
308 using namespace INPUT;
309
310 // Translate from left-handed coordinate system to right-handed coordinate system
311 y *= -1;
312
313 return CInputTranslator::VectorToIntercardinalDirection(static_cast<float>(x),
314 static_cast<float>(y));
315 }
316
317 // --- CButtonMapping ----------------------------------------------------------
318
319 CButtonMapping::CButtonMapping(IButtonMapper* buttonMapper,
320 IButtonMap* buttonMap,
321 KEYMAP::IKeymap* keymap)
322 : m_buttonMapper(buttonMapper), m_buttonMap(buttonMap), m_keymap(keymap)
323 {
324 assert(m_buttonMapper != nullptr);
325 assert(m_buttonMap != nullptr);
326
327 // Make sure axes mapped to Select are centered before they can be mapped.
328 // This ensures that they are not immediately mapped to the first button.
329 if (m_keymap)
330 {
331 using namespace GAME;
332
333 CControllerManager& controllerManager = CServiceBroker::GetGameControllerManager();
334 ControllerPtr controller = controllerManager.GetController(m_keymap->ControllerID());
335
336 const auto& features = controller->Features();
337 for (const auto& feature : features)
338 {
339 bool bIsSelectAction = false;
340
341 const auto& actions =
342 m_keymap->GetActions(CJoystickUtils::MakeKeyName(feature.Name())).actions;
343 if (!actions.empty() && actions.begin()->actionId == ACTION_SELECT_ITEM)
344 bIsSelectAction = true;
345
346 if (!bIsSelectAction)
347 continue;
348
349 CDriverPrimitive primitive;
350 if (!m_buttonMap->GetScalar(feature.Name(), primitive))
351 continue;
352
353 if (primitive.Type() != PRIMITIVE_TYPE::SEMIAXIS)
354 continue;
355
356 // Set initial config, as detection will fail because axis is already activated
357 AxisConfiguration axisConfig;
358 axisConfig.bKnown = true;
359 axisConfig.center = primitive.Center();
360 axisConfig.range = primitive.Range();
361
362 GetAxis(primitive.Index(), static_cast<float>(primitive.Center()), axisConfig)
363 .SetEmitted(primitive);
364 }
365 }
366 }
367
368 bool CButtonMapping::OnButtonMotion(unsigned int buttonIndex, bool bPressed)
369 {
370 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::BUTTON))
371 return false;
372
373 return GetButton(buttonIndex).OnMotion(bPressed);
374 }
375
376 bool CButtonMapping::OnHatMotion(unsigned int hatIndex, HAT_STATE state)
377 {
378 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::HAT))
379 return false;
380
381 return GetHat(hatIndex).OnMotion(state);
382 }
383
384 bool CButtonMapping::OnAxisMotion(unsigned int axisIndex,
385 float position,
386 int center,
387 unsigned int range)
388 {
389 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::SEMIAXIS))
390 return false;
391
392 return GetAxis(axisIndex, position).OnMotion(position);
393 }
394
395 void CButtonMapping::OnInputFrame(void)
396 {
397 for (auto& axis : m_axes)
398 axis.second.ProcessMotion();
399
400 m_buttonMapper->OnEventFrame(m_buttonMap, IsMapping());
401
402 m_frameCount++;
403 }
404
405 bool CButtonMapping::OnKeyPress(const CKey& key)
406 {
407 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::KEY))
408 return false;
409
410 return GetKey(static_cast<XBMCKey>(key.GetKeycode())).OnMotion(true);
411 }
412
413 bool CButtonMapping::OnPosition(int x, int y)
414 {
415 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::RELATIVE_POINTER))
416 return false;
417
418 return GetPointer().OnMotion(x, y);
419 }
420
421 bool CButtonMapping::OnButtonPress(MOUSE::BUTTON_ID button)
422 {
423 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::MOUSE_BUTTON))
424 return false;
425
426 return GetMouseButton(button).OnMotion(true);
427 }
428
429 void CButtonMapping::OnButtonRelease(MOUSE::BUTTON_ID button)
430 {
431 if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::MOUSE_BUTTON))
432 return;
433
434 GetMouseButton(button).OnMotion(false);
435 }
436
437 void CButtonMapping::SaveButtonMap()
438 {
439 m_buttonMap->SaveButtonMap();
440 }
441
442 void CButtonMapping::ResetIgnoredPrimitives()
443 {
444 std::vector<CDriverPrimitive> empty;
445 m_buttonMap->SetIgnoredPrimitives(empty);
446 }
447
448 void CButtonMapping::RevertButtonMap()
449 {
450 m_buttonMap->RevertButtonMap();
451 }
452
453 bool CButtonMapping::MapPrimitive(const CDriverPrimitive& primitive)
454 {
455 bool bHandled = false;
456
457 if (m_buttonMap->IsIgnored(primitive))
458 {
459 bHandled = true;
460 }
461 else
462 {
463 auto now = std::chrono::steady_clock::now();
464
465 bool bTimeoutElapsed = true;
466
467 if (m_buttonMapper->NeedsCooldown())
468 bTimeoutElapsed = (now >= m_lastAction + std::chrono::milliseconds(MAPPING_COOLDOWN_MS));
469
470 if (bTimeoutElapsed)
471 {
472 bHandled = m_buttonMapper->MapPrimitive(m_buttonMap, m_keymap, primitive);
473
474 if (bHandled)
475 m_lastAction = std::chrono::steady_clock::now();
476 }
477 else
478 {
479 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastAction);
480
481 CLog::Log(LOGDEBUG, "Button mapping: rapid input after {}ms dropped for profile \"{}\"",
482 duration.count(), m_buttonMapper->ControllerID());
483 bHandled = true;
484 }
485 }
486
487 return bHandled;
488 }
489
490 bool CButtonMapping::IsMapping() const
491 {
492 for (auto itAxis : m_axes)
493 {
494 if (itAxis.second.IsMapping())
495 return true;
496 }
497
498 return false;
499 }
500
501 CButtonDetector& CButtonMapping::GetButton(unsigned int buttonIndex)
502 {
503 auto itButton = m_buttons.find(buttonIndex);
504
505 if (itButton == m_buttons.end())
506 {
507 m_buttons.insert(std::make_pair(buttonIndex, CButtonDetector(this, buttonIndex)));
508 itButton = m_buttons.find(buttonIndex);
509 }
510
511 return itButton->second;
512 }
513
514 CHatDetector& CButtonMapping::GetHat(unsigned int hatIndex)
515 {
516 auto itHat = m_hats.find(hatIndex);
517
518 if (itHat == m_hats.end())
519 {
520 m_hats.insert(std::make_pair(hatIndex, CHatDetector(this, hatIndex)));
521 itHat = m_hats.find(hatIndex);
522 }
523
524 return itHat->second;
525 }
526
527 CAxisDetector& CButtonMapping::GetAxis(
528 unsigned int axisIndex,
529 float position,
530 const AxisConfiguration& initialConfig /* = AxisConfiguration() */)
531 {
532 auto itAxis = m_axes.find(axisIndex);
533
534 if (itAxis == m_axes.end())
535 {
536 AxisConfiguration config(initialConfig);
537
538 bool isGcController = false;
539
540 // Avoid showing the "capture input" dialog for the GCController driver, as
541 // analog stick axes are always late due to zeroed events not always being
542 // sent
543 #if defined(TARGET_DARWIN)
544 const std::string peripheralLocation = m_buttonMap->Location();
545
546 PERIPHERALS::CPeripherals& peripheralManager = CServiceBroker::GetPeripherals();
547
548 const PERIPHERALS::PeripheralPtr peripheral =
549 peripheralManager.GetPeripheralAtLocation(peripheralLocation);
550
551 if (peripheral &&
552 peripheral->GetBusType() == PERIPHERALS::PeripheralBusType::PERIPHERAL_BUS_GCCONTROLLER)
553 isGcController = true;
554 #endif
555
556 if (m_frameCount >= 2 && !isGcController)
557 {
558 config.bLateDiscovery = true;
559 OnLateDiscovery(axisIndex);
560 }
561
562 // Report axis
563 CLog::Log(LOGDEBUG, "Axis {} discovered at position {:.4f} after {} frames", axisIndex,
564 position, static_cast<unsigned long>(m_frameCount));
565
566 m_axes.insert(std::make_pair(axisIndex, CAxisDetector(this, axisIndex, config)));
567 itAxis = m_axes.find(axisIndex);
568 }
569
570 return itAxis->second;
571 }
572
573 CKeyDetector& CButtonMapping::GetKey(XBMCKey keycode)
574 {
575 auto itKey = m_keys.find(keycode);
576
577 if (itKey == m_keys.end())
578 {
579 m_keys.insert(std::make_pair(keycode, CKeyDetector(this, keycode)));
580 itKey = m_keys.find(keycode);
581 }
582
583 return itKey->second;
584 }
585
586 CMouseButtonDetector& CButtonMapping::GetMouseButton(MOUSE::BUTTON_ID buttonIndex)
587 {
588 auto itButton = m_mouseButtons.find(buttonIndex);
589
590 if (itButton == m_mouseButtons.end())
591 {
592 m_mouseButtons.insert(std::make_pair(buttonIndex, CMouseButtonDetector(this, buttonIndex)));
593 itButton = m_mouseButtons.find(buttonIndex);
594 }
595
596 return itButton->second;
597 }
598
599 CPointerDetector& CButtonMapping::GetPointer()
600 {
601 if (!m_pointer)
602 m_pointer = std::make_unique<CPointerDetector>(this);
603
604 return *m_pointer;
605 }
606
607 void CButtonMapping::OnLateDiscovery(unsigned int axisIndex)
608 {
609 m_buttonMapper->OnLateAxis(m_buttonMap, axisIndex);
610 }