summaryrefslogtreecommitdiffstats
path: root/xbmc/games/controllers/windows/GUIConfigurationWizard.cpp
blob: ff5f8d8e9dbd18653d4dd155e7e8d23ec90132ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
 *  Copyright (C) 2014-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "GUIConfigurationWizard.h"

#include "ServiceBroker.h"
#include "games/controllers/Controller.h"
#include "games/controllers/dialogs/GUIDialogAxisDetection.h"
#include "games/controllers/guicontrols/GUIFeatureButton.h"
#include "games/controllers/input/PhysicalFeature.h"
#include "input/IKeymap.h"
#include "input/InputManager.h"
#include "input/joysticks/JoystickUtils.h"
#include "input/joysticks/interfaces/IButtonMap.h"
#include "input/joysticks/interfaces/IButtonMapCallback.h"
#include "input/keyboard/KeymapActionMap.h"
#include "peripherals/Peripherals.h"
#include "threads/SingleLock.h"
#include "utils/log.h"

#include <mutex>

using namespace KODI;
using namespace GAME;
using namespace std::chrono_literals;

namespace
{

#define ESC_KEY_CODE 27
#define SKIPPING_DETECTION_MS 200

// Duration to wait for axes to neutralize after mapping is finished
constexpr auto POST_MAPPING_WAIT_TIME_MS = 5000ms;

} // namespace

CGUIConfigurationWizard::CGUIConfigurationWizard()
  : CThread("GUIConfigurationWizard"), m_actionMap(new KEYBOARD::CKeymapActionMap)
{
  InitializeState();
}

CGUIConfigurationWizard::~CGUIConfigurationWizard(void) = default;

void CGUIConfigurationWizard::InitializeState(void)
{
  m_currentButton = nullptr;
  m_cardinalDirection = INPUT::CARDINAL_DIRECTION::NONE;
  m_wheelDirection = JOYSTICK::WHEEL_DIRECTION::NONE;
  m_throttleDirection = JOYSTICK::THROTTLE_DIRECTION::NONE;
  m_history.clear();
  m_lateAxisDetected = false;
  m_location.clear();
}

void CGUIConfigurationWizard::Run(const std::string& strControllerId,
                                  const std::vector<IFeatureButton*>& buttons)
{
  Abort();

  {
    std::unique_lock<CCriticalSection> lock(m_stateMutex);

    // Set Run() parameters
    m_strControllerId = strControllerId;
    m_buttons = buttons;

    // Reset synchronization variables
    m_inputEvent.Reset();
    m_motionlessEvent.Reset();
    m_bInMotion.clear();

    // Initialize state variables
    InitializeState();
  }

  Create();
}

void CGUIConfigurationWizard::OnUnfocus(IFeatureButton* button)
{
  std::unique_lock<CCriticalSection> lock(m_stateMutex);

  if (button == m_currentButton)
    Abort(false);
}

bool CGUIConfigurationWizard::Abort(bool bWait /* = true */)
{
  bool bWasRunning = !m_bStop;

  StopThread(false);

  m_inputEvent.Set();
  m_motionlessEvent.Set();

  if (bWait)
    StopThread(true);

  return bWasRunning;
}

void CGUIConfigurationWizard::RegisterKey(const CPhysicalFeature& key)
{
  if (key.Keycode() != XBMCK_UNKNOWN)
    m_keyMap[key.Keycode()] = key;
}

void CGUIConfigurationWizard::UnregisterKeys()
{
  m_keyMap.clear();
}

void CGUIConfigurationWizard::Process(void)
{
  CLog::Log(LOGDEBUG, "Starting configuration wizard");

  InstallHooks();

  bool bLateAxisDetected = false;

  {
    std::unique_lock<CCriticalSection> lock(m_stateMutex);
    for (IFeatureButton* button : m_buttons)
    {
      // Allow other threads to access the button we're using
      m_currentButton = button;

      while (!button->IsFinished())
      {
        // Allow other threads to access which direction the prompt is on
        m_cardinalDirection = button->GetCardinalDirection();
        m_wheelDirection = button->GetWheelDirection();
        m_throttleDirection = button->GetThrottleDirection();

        // Wait for input
        {
          using namespace JOYSTICK;

          CSingleExit exit(m_stateMutex);

          if (button->Feature().Type() == FEATURE_TYPE::UNKNOWN)
            CLog::Log(LOGDEBUG, "{}: Waiting for input", m_strControllerId);
          else
            CLog::Log(LOGDEBUG, "{}: Waiting for input for feature \"{}\"", m_strControllerId,
                      button->Feature().Name());

          if (!button->PromptForInput(m_inputEvent))
            Abort(false);
        }

        if (m_bStop)
          break;
      }

      button->Reset();

      if (m_bStop)
        break;
    }

    bLateAxisDetected = m_lateAxisDetected;

    // Finished mapping
    InitializeState();
  }

  for (auto callback : ButtonMapCallbacks())
    callback.second->SaveButtonMap();

  if (bLateAxisDetected)
  {
    CGUIDialogAxisDetection dialog;
    dialog.Show();
  }
  else
  {
    // Wait for motion to stop to avoid sending analog actions for the button
    // that is pressed immediately after button mapping finishes.
    bool bInMotion;

    {
      std::unique_lock<CCriticalSection> lock(m_motionMutex);
      bInMotion = !m_bInMotion.empty();
    }

    if (bInMotion)
    {
      CLog::Log(LOGDEBUG, "Configuration wizard: waiting {}ms for axes to neutralize",
                POST_MAPPING_WAIT_TIME_MS.count());
      m_motionlessEvent.Wait(POST_MAPPING_WAIT_TIME_MS);
    }
  }

  RemoveHooks();

  CLog::Log(LOGDEBUG, "Configuration wizard ended");
}

bool CGUIConfigurationWizard::MapPrimitive(JOYSTICK::IButtonMap* buttonMap,
                                           IKeymap* keymap,
                                           const JOYSTICK::CDriverPrimitive& primitive)
{
  using namespace INPUT;
  using namespace JOYSTICK;

  bool bHandled = false;

  // Abort if another controller cancels the prompt
  if (IsMapping() && !IsMapping(buttonMap->Location()))
  {
    //! @todo This only succeeds for game.controller.default; no actions are
    //        currently defined for other controllers
    if (keymap)
    {
      std::string feature;
      if (buttonMap->GetFeature(primitive, feature))
      {
        const auto& actions = keymap->GetActions(CJoystickUtils::MakeKeyName(feature)).actions;
        if (!actions.empty())
        {
          //! @todo Handle multiple actions mapped to the same key
          OnAction(actions.begin()->actionId);
        }
      }
    }

    // Discard input
    bHandled = true;
  }
  else if (m_history.find(primitive) != m_history.end())
  {
    // Primitive has already been mapped this round, ignore it
    bHandled = true;
  }
  else if (buttonMap->IsIgnored(primitive))
  {
    bHandled = true;
  }
  else
  {
    // Get the current state of the thread
    IFeatureButton* currentButton;
    CARDINAL_DIRECTION cardinalDirection;
    WHEEL_DIRECTION wheelDirection;
    THROTTLE_DIRECTION throttleDirection;
    {
      std::unique_lock<CCriticalSection> lock(m_stateMutex);
      currentButton = m_currentButton;
      cardinalDirection = m_cardinalDirection;
      wheelDirection = m_wheelDirection;
      throttleDirection = m_throttleDirection;
    }

    if (currentButton)
    {
      // Check if we were expecting a keyboard key
      if (currentButton->NeedsKey())
      {
        if (primitive.Type() == PRIMITIVE_TYPE::KEY)
        {
          auto it = m_keyMap.find(primitive.Keycode());
          if (it != m_keyMap.end())
          {
            const CPhysicalFeature& key = it->second;
            currentButton->SetKey(key);
            m_inputEvent.Set();
          }
        }
        else
        {
          //! @todo Check if primitive is a cancel or motion action
        }
        bHandled = true;
      }
      else
      {
        const CPhysicalFeature& feature = currentButton->Feature();

        if (primitive.Type() == PRIMITIVE_TYPE::RELATIVE_POINTER &&
            feature.Type() != FEATURE_TYPE::RELPOINTER)
        {
          // Don't allow relative pointers to map to other features
        }
        else
        {
          CLog::Log(LOGDEBUG, "{}: mapping feature \"{}\" for device {}", m_strControllerId,
                    feature.Name(), buttonMap->Location());

          switch (feature.Type())
          {
            case FEATURE_TYPE::SCALAR:
            {
              buttonMap->AddScalar(feature.Name(), primitive);
              bHandled = true;
              break;
            }
            case FEATURE_TYPE::ANALOG_STICK:
            {
              buttonMap->AddAnalogStick(feature.Name(), cardinalDirection, primitive);
              bHandled = true;
              break;
            }
            case FEATURE_TYPE::RELPOINTER:
            {
              buttonMap->AddRelativePointer(feature.Name(), cardinalDirection, primitive);
              bHandled = true;
              break;
            }
            case FEATURE_TYPE::WHEEL:
            {
              buttonMap->AddWheel(feature.Name(), wheelDirection, primitive);
              bHandled = true;
              break;
            }
            case FEATURE_TYPE::THROTTLE:
            {
              buttonMap->AddThrottle(feature.Name(), throttleDirection, primitive);
              bHandled = true;
              break;
            }
            case FEATURE_TYPE::KEY:
            {
              buttonMap->AddKey(feature.Name(), primitive);
              bHandled = true;
              break;
            }
            default:
              break;
          }
        }

        if (bHandled)
        {
          m_history.insert(primitive);

          // Don't record motion for relative pointers
          if (primitive.Type() != PRIMITIVE_TYPE::RELATIVE_POINTER)
            OnMotion(buttonMap);

          m_inputEvent.Set();

          if (m_location.empty())
          {
            m_location = buttonMap->Location();
            m_bIsKeyboard = (primitive.Type() == PRIMITIVE_TYPE::KEY);
          }
        }
      }
    }
  }

  return bHandled;
}

void CGUIConfigurationWizard::OnEventFrame(const JOYSTICK::IButtonMap* buttonMap, bool bMotion)
{
  std::unique_lock<CCriticalSection> lock(m_motionMutex);

  if (m_bInMotion.find(buttonMap) != m_bInMotion.end() && !bMotion)
    OnMotionless(buttonMap);
}

void CGUIConfigurationWizard::OnLateAxis(const JOYSTICK::IButtonMap* buttonMap,
                                         unsigned int axisIndex)
{
  std::unique_lock<CCriticalSection> lock(m_stateMutex);

  m_lateAxisDetected = true;
  Abort(false);
}

void CGUIConfigurationWizard::OnMotion(const JOYSTICK::IButtonMap* buttonMap)
{
  std::unique_lock<CCriticalSection> lock(m_motionMutex);

  m_motionlessEvent.Reset();
  m_bInMotion.insert(buttonMap);
}

void CGUIConfigurationWizard::OnMotionless(const JOYSTICK::IButtonMap* buttonMap)
{
  m_bInMotion.erase(buttonMap);
  if (m_bInMotion.empty())
    m_motionlessEvent.Set();
}

bool CGUIConfigurationWizard::OnKeyPress(const CKey& key)
{
  bool bHandled = false;

  if (!m_bStop)
  {
    // Only allow key to abort the prompt if we know for sure that we're mapping
    // a controller
    const bool bIsMappingController = (IsMapping() && !m_bIsKeyboard);

    if (bIsMappingController)
    {
      bHandled = OnAction(m_actionMap->GetActionID(key));
    }
    else
    {
      // Allow key press to fall through to the button mapper
    }
  }

  return bHandled;
}

bool CGUIConfigurationWizard::OnAction(unsigned int actionId)
{
  bool bHandled = false;

  switch (actionId)
  {
    case ACTION_MOVE_LEFT:
    case ACTION_MOVE_RIGHT:
    case ACTION_MOVE_UP:
    case ACTION_MOVE_DOWN:
    case ACTION_PAGE_UP:
    case ACTION_PAGE_DOWN:
      // Abort and allow motion
      Abort(false);
      bHandled = false;
      break;

    case ACTION_PARENT_DIR:
    case ACTION_PREVIOUS_MENU:
    case ACTION_STOP:
    case ACTION_NAV_BACK:
      // Abort and prevent action
      Abort(false);
      bHandled = true;
      break;

    default:
      // Absorb keypress
      bHandled = true;
      break;
  }

  return bHandled;
}

bool CGUIConfigurationWizard::IsMapping() const
{
  return !m_location.empty();
}

bool CGUIConfigurationWizard::IsMapping(const std::string& location) const
{
  return m_location == location;
}

void CGUIConfigurationWizard::InstallHooks(void)
{
  // Install button mapper with lowest priority
  CServiceBroker::GetPeripherals().RegisterJoystickButtonMapper(this);

  // Install hook to reattach button mapper when peripherals change
  CServiceBroker::GetPeripherals().RegisterObserver(this);

  // Install hook to cancel the button mapper
  CServiceBroker::GetInputManager().RegisterKeyboardDriverHandler(this);
}

void CGUIConfigurationWizard::RemoveHooks(void)
{
  CServiceBroker::GetInputManager().UnregisterKeyboardDriverHandler(this);
  CServiceBroker::GetPeripherals().UnregisterObserver(this);
  CServiceBroker::GetPeripherals().UnregisterJoystickButtonMapper(this);
}

void CGUIConfigurationWizard::Notify(const Observable& obs, const ObservableMessage msg)
{
  switch (msg)
  {
    case ObservableMessagePeripheralsChanged:
    {
      CServiceBroker::GetPeripherals().UnregisterJoystickButtonMapper(this);
      CServiceBroker::GetPeripherals().RegisterJoystickButtonMapper(this);
      break;
    }
    default:
      break;
  }
}