Fixed bug 4477 - Support more than 4 XInput-capable devices on Windows
authorSam Lantinga <slouken@libsdl.org>
Mon, 16 Mar 2020 12:23:38 -0700
changeset 13633340324c76848
parent 13632 49320151ca4d
child 13634 9a8e6854f652
Fixed bug 4477 - Support more than 4 XInput-capable devices on Windows

Jimb Esser

Add new RawInput controller API, and improved correlation with XInput/WGI

Reorder joystick init so drivers can ask the others if they handle a device reliably
Do not poll disconnected XInput devices (major perf issue)
Fix various cases where incorrect correlation could happen
Simple mechanism for propagating unhandled Guide button presses even before guaranteed correlation
Correlate by axis motion as well as button presses
Fix failing to zero other trigger
Fix SDL_HINT_JOYSTICK_HIDAPI not working if set before calling SDL_Init()
Add missing device to device names
Disable RawInput if we have a mismatch of XInput-capable but not RawInput-capable devices

Updated to SDL 2.0.13 code with the following notes:
New HID driver: xbox360w - no idea what that is, hopefully urelated
SDL_hidapijoystick.c had been refactored to couple data handling logic with device opening logic and device lists caused some problems, yields slightly uglier integration than previously when the 360 HID device driver was just handling the data.
SDL_hidapijoystick.c now often pulls the device off of the joystick_hwdata structure for some rumble logic, but it appears that code path is never reached, so probably not a problem.
Looks like joystick_hwdata was refactored to not include a mutex in other drivers, maintainers may want to do the same refactor here if that's useful for some reason.
Something changed in how devices get names, so getting generic names.
Had to fix a (new?) bug where removing an XInput controller caused existing controllers (that moved to a new XInput index) to get identified as 0x045e/0x02fd ("it's probably Bluetooth" in code), rendering the existing HIDAPI_IsDevicePresent and new RAWINPUT_IsDevicePresent unreliable.
VisualC/SDL/SDL.vcxproj
VisualC/SDL/SDL.vcxproj.filters
configure
configure.ac
include/SDL_config.h.in
include/SDL_config_windows.h
include/SDL_hints.h
src/joystick/SDL_gamecontroller.c
src/joystick/SDL_joystick.c
src/joystick/SDL_joystick_c.h
src/joystick/SDL_sysjoystick.h
src/joystick/hidapi/SDL_hidapi_gamecube.c
src/joystick/hidapi/SDL_hidapi_ps4.c
src/joystick/hidapi/SDL_hidapi_switch.c
src/joystick/hidapi/SDL_hidapi_xbox360.c
src/joystick/hidapi/SDL_hidapi_xbox360w.c
src/joystick/hidapi/SDL_hidapi_xboxone.c
src/joystick/hidapi/SDL_hidapijoystick.c
src/joystick/hidapi/SDL_hidapijoystick_c.h
src/joystick/windows/SDL_dinputjoystick.c
src/joystick/windows/SDL_xinputjoystick.c
src/video/windows/SDL_windowswindow.c
     1.1 --- a/VisualC/SDL/SDL.vcxproj	Mon Mar 16 00:21:22 2020 -0400
     1.2 +++ b/VisualC/SDL/SDL.vcxproj	Mon Mar 16 12:23:38 2020 -0700
     1.3 @@ -318,12 +318,15 @@
     1.4      <ClInclude Include="..\..\src\haptic\windows\SDL_dinputhaptic_c.h" />
     1.5      <ClInclude Include="..\..\src\haptic\windows\SDL_windowshaptic_c.h" />
     1.6      <ClInclude Include="..\..\src\haptic\windows\SDL_xinputhaptic_c.h" />
     1.7 +    <ClInclude Include="..\..\src\hidapi\hidapi\hidapi.h" />
     1.8      <ClInclude Include="..\..\src\joystick\controller_type.h" />
     1.9      <ClInclude Include="..\..\src\joystick\hidapi\SDL_hidapijoystick_c.h" />
    1.10 +    <ClInclude Include="..\..\src\joystick\SDL_gamecontrollerdb.h" />
    1.11      <ClInclude Include="..\..\src\joystick\SDL_joystick_c.h" />
    1.12      <ClInclude Include="..\..\src\joystick\SDL_sysjoystick.h" />
    1.13      <ClInclude Include="..\..\src\joystick\virtual\SDL_virtualjoystick_c.h" />
    1.14      <ClInclude Include="..\..\src\joystick\windows\SDL_dinputjoystick_c.h" />
    1.15 +    <ClInclude Include="..\..\src\joystick\windows\SDL_rawinputjoystick_c.h" />
    1.16      <ClInclude Include="..\..\src\joystick\windows\SDL_windowsjoystick_c.h" />
    1.17      <ClInclude Include="..\..\src\joystick\windows\SDL_xinputjoystick_c.h" />
    1.18      <ClInclude Include="..\..\src\libm\math_libm.h" />
    1.19 @@ -432,6 +435,7 @@
    1.20      <ClCompile Include="..\..\src\joystick\virtual\SDL_virtualjoystick.c" />
    1.21      <ClCompile Include="..\..\src\joystick\windows\SDL_dinputjoystick.c" />
    1.22      <ClCompile Include="..\..\src\joystick\windows\SDL_mmjoystick.c" />
    1.23 +    <ClCompile Include="..\..\src\joystick\windows\SDL_rawinputjoystick.c" />
    1.24      <ClCompile Include="..\..\src\joystick\windows\SDL_windowsjoystick.c" />
    1.25      <ClCompile Include="..\..\src\joystick\windows\SDL_xinputjoystick.c" />
    1.26      <ClCompile Include="..\..\src\libm\e_atan2.c" />
     2.1 --- a/VisualC/SDL/SDL.vcxproj.filters	Mon Mar 16 00:21:22 2020 -0400
     2.2 +++ b/VisualC/SDL/SDL.vcxproj.filters	Mon Mar 16 12:23:38 2020 -0700
     2.3 @@ -323,6 +323,9 @@
     2.4      <ClInclude Include="..\..\src\video\windows\SDL_windowswindow.h" />
     2.5      <ClInclude Include="..\..\src\video\windows\wmmsg.h" />
     2.6      <ClInclude Include="..\..\src\video\yuv2rgb\yuv_rgb.h" />
     2.7 +    <ClInclude Include="..\..\src\joystick\windows\SDL_rawinputjoystick_c.h" />
     2.8 +    <ClInclude Include="..\..\src\hidapi\hidapi\hidapi.h" />
     2.9 +    <ClInclude Include="..\..\src\joystick\SDL_gamecontrollerdb.h" />
    2.10    </ItemGroup>
    2.11    <ItemGroup>
    2.12      <ClCompile Include="..\..\src\atomic\SDL_atomic.c" />
    2.13 @@ -478,6 +481,7 @@
    2.14      <ClCompile Include="..\..\src\video\windows\SDL_windowsvulkan.c" />
    2.15      <ClCompile Include="..\..\src\video\windows\SDL_windowswindow.c" />
    2.16      <ClCompile Include="..\..\src\video\yuv2rgb\yuv_rgb.c" />
    2.17 +    <ClCompile Include="..\..\src\joystick\windows\SDL_rawinputjoystick.c" />
    2.18    </ItemGroup>
    2.19    <ItemGroup>
    2.20      <ResourceCompile Include="..\..\src\main\windows\version.rc" />
     3.1 --- a/configure	Mon Mar 16 00:21:22 2020 -0400
     3.2 +++ b/configure	Mon Mar 16 12:23:38 2020 -0700
     3.3 @@ -24336,6 +24336,8 @@
     3.4  
     3.5  $as_echo "#define SDL_JOYSTICK_HIDAPI 1" >>confdefs.h
     3.6  
     3.7 +$as_echo "#define SDL_JOYSTICK_RAWINPUT 1" >>confdefs.h
     3.8 +
     3.9              EXTRA_CFLAGS="$EXTRA_CFLAGS -I$srcdir/src/hidapi/hidapi"
    3.10              SOURCES="$SOURCES $srcdir/src/joystick/hidapi/*.c"
    3.11              SOURCES="$SOURCES $srcdir/src/hidapi/SDL_hidapi.c"
     4.1 --- a/configure.ac	Mon Mar 16 00:21:22 2020 -0400
     4.2 +++ b/configure.ac	Mon Mar 16 12:23:38 2020 -0700
     4.3 @@ -3316,6 +3316,7 @@
     4.4  
     4.5          if test x$hidapi_support = xyes; then
     4.6              AC_DEFINE(SDL_JOYSTICK_HIDAPI, 1, [ ])
     4.7 +            AC_DEFINE(SDL_JOYSTICK_RAWINPUT, 1, [ ])
     4.8              EXTRA_CFLAGS="$EXTRA_CFLAGS -I$srcdir/src/hidapi/hidapi"
     4.9              SOURCES="$SOURCES $srcdir/src/joystick/hidapi/*.c"
    4.10              SOURCES="$SOURCES $srcdir/src/hidapi/SDL_hidapi.c"
     5.1 --- a/include/SDL_config.h.in	Mon Mar 16 00:21:22 2020 -0400
     5.2 +++ b/include/SDL_config.h.in	Mon Mar 16 12:23:38 2020 -0700
     5.3 @@ -289,6 +289,7 @@
     5.4  #undef SDL_JOYSTICK_USBHID
     5.5  #undef SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H
     5.6  #undef SDL_JOYSTICK_HIDAPI
     5.7 +#undef SDL_JOYSTICK_RAWINPUT
     5.8  #undef SDL_JOYSTICK_EMSCRIPTEN
     5.9  #undef SDL_JOYSTICK_VIRTUAL
    5.10  #undef SDL_HAPTIC_DUMMY
     6.1 --- a/include/SDL_config_windows.h	Mon Mar 16 00:21:22 2020 -0400
     6.2 +++ b/include/SDL_config_windows.h	Mon Mar 16 12:23:38 2020 -0700
     6.3 @@ -197,6 +197,7 @@
     6.4  #define SDL_JOYSTICK_DINPUT 1
     6.5  #define SDL_JOYSTICK_XINPUT 1
     6.6  #define SDL_JOYSTICK_HIDAPI 1
     6.7 +#define SDL_JOYSTICK_RAWINPUT 1
     6.8  #define SDL_HAPTIC_DINPUT   1
     6.9  #define SDL_HAPTIC_XINPUT   1
    6.10  
     7.1 --- a/include/SDL_hints.h	Mon Mar 16 00:21:22 2020 -0400
     7.2 +++ b/include/SDL_hints.h	Mon Mar 16 12:23:38 2020 -0700
     7.3 @@ -634,10 +634,23 @@
     7.4   *    "0"       - HIDAPI driver is not used
     7.5   *    "1"       - HIDAPI driver is used
     7.6   *
     7.7 - *  The default is the value of SDL_HINT_JOYSTICK_HIDAPI
     7.8 + *  The default is "0" on Windows, otherwise the value of SDL_HINT_JOYSTICK_HIDAPI
     7.9   */
    7.10  #define SDL_HINT_JOYSTICK_HIDAPI_XBOX   "SDL_JOYSTICK_HIDAPI_XBOX"
    7.11  
    7.12 + /**
    7.13 +  *  \brief  A variable controlling whether the HIDAPI driver for XBox controllers on Windows should pull correlated
    7.14 +  *      data from XInput.
    7.15 +  *
    7.16 +  *  This variable can be set to the following values:
    7.17 +  *    "0"       - HIDAPI Xbox driver will only use HIDAPI data
    7.18 +  *    "1"       - HIDAPI Xbox driver will also pull data from XInput, providing better trigger axes, guide button
    7.19 +  *                presses, and rumble support
    7.20 +  *
    7.21 +  *  The default is "1".  This hint applies to any joysticks opened after setting the hint.
    7.22 +  */
    7.23 +#define SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT   "SDL_JOYSTICK_HIDAPI_CORRELATE_XINPUT"
    7.24 +
    7.25  /**
    7.26   *  \brief  A variable controlling whether the HIDAPI driver for Nintendo GameCube controllers should be used.
    7.27   *
    7.28 @@ -660,6 +673,15 @@
    7.29   */
    7.30  #define SDL_HINT_ENABLE_STEAM_CONTROLLERS "SDL_ENABLE_STEAM_CONTROLLERS"
    7.31  
    7.32 + /**
    7.33 +  *  \brief  A variable controlling whether the RAWINPUT joystick drivers should be used for better handling XInput-capable devices.
    7.34 +  *
    7.35 +  *  This variable can be set to the following values:
    7.36 +  *    "0"       - RAWINPUT drivers are not used
    7.37 +  *    "1"       - RAWINPUT drivers are used (the default)
    7.38 +  *
    7.39 +  */
    7.40 +#define SDL_HINT_JOYSTICK_RAWINPUT "SDL_JOYSTICK_RAWINPUT"
    7.41  
    7.42  /**
    7.43   *  \brief If set to "0" then never set the top most bit on a SDL Window, even if the video mode expects it.
     8.1 --- a/src/joystick/SDL_gamecontroller.c	Mon Mar 16 00:21:22 2020 -0400
     8.2 +++ b/src/joystick/SDL_gamecontroller.c	Mon Mar 16 12:23:38 2020 -0700
     8.3 @@ -439,6 +439,12 @@
     8.4              /* This is a HIDAPI device */
     8.5              return s_pHIDAPIMapping;
     8.6          }
     8.7 +#if SDL_JOYSTICK_RAWINPUT
     8.8 +        if (SDL_IsJoystickRAWINPUT(*guid)) {
     8.9 +            /* This is a RAWINPUT device - same data as HIDAPI */
    8.10 +            return s_pHIDAPIMapping;
    8.11 +        }
    8.12 +#endif
    8.13  #if SDL_JOYSTICK_XINPUT
    8.14          if (SDL_IsJoystickXInput(*guid)) {
    8.15              /* This is an XInput device */
     9.1 --- a/src/joystick/SDL_joystick.c	Mon Mar 16 00:21:22 2020 -0400
     9.2 +++ b/src/joystick/SDL_joystick.c	Mon Mar 16 12:23:38 2020 -0700
     9.3 @@ -51,6 +51,13 @@
     9.4  #endif
     9.5  
     9.6  static SDL_JoystickDriver *SDL_joystick_drivers[] = {
     9.7 +#ifdef SDL_JOYSTICK_RAWINPUT /* Before WINDOWS_ driver, as WINDOWS wants to check if this driver is handling things */
     9.8 +    /* Also before HIDAPI, as HIDAPI wants to check if this driver is handling things */
     9.9 +    &SDL_RAWINPUT_JoystickDriver,
    9.10 +#endif
    9.11 +#ifdef SDL_JOYSTICK_HIDAPI /* Before WINDOWS_ driver, as WINDOWS wants to check if this driver is handling things */
    9.12 +    &SDL_HIDAPI_JoystickDriver,
    9.13 +#endif
    9.14  #if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
    9.15      &SDL_WINDOWS_JoystickDriver,
    9.16  #endif
    9.17 @@ -75,9 +82,6 @@
    9.18  #ifdef SDL_JOYSTICK_USBHID  /* !!! FIXME: "USBHID" is a generic name, and doubly-confusing with HIDAPI next to it. This is the *BSD interface, rename this. */
    9.19      &SDL_BSD_JoystickDriver,
    9.20  #endif
    9.21 -#ifdef SDL_JOYSTICK_HIDAPI
    9.22 -    &SDL_HIDAPI_JoystickDriver,
    9.23 -#endif
    9.24  #ifdef SDL_JOYSTICK_VIRTUAL
    9.25      &SDL_VIRTUAL_JoystickDriver,
    9.26  #endif
    9.27 @@ -1730,6 +1734,12 @@
    9.28  }
    9.29  
    9.30  SDL_bool
    9.31 +SDL_IsJoystickRAWINPUT(SDL_JoystickGUID guid)
    9.32 +{
    9.33 +    return (guid.data[14] == 'r') ? SDL_TRUE : SDL_FALSE;
    9.34 +}
    9.35 +
    9.36 +SDL_bool
    9.37  SDL_IsJoystickVirtual(SDL_JoystickGUID guid)
    9.38  {
    9.39      return (guid.data[14] == 'v') ? SDL_TRUE : SDL_FALSE;
    10.1 --- a/src/joystick/SDL_joystick_c.h	Mon Mar 16 00:21:22 2020 -0400
    10.2 +++ b/src/joystick/SDL_joystick_c.h	Mon Mar 16 12:23:38 2020 -0700
    10.3 @@ -73,6 +73,9 @@
    10.4  /* Function to return whether a joystick guid comes from the HIDAPI driver */
    10.5  extern SDL_bool SDL_IsJoystickHIDAPI(SDL_JoystickGUID guid);
    10.6  
    10.7 +/* Function to return whether a joystick guid comes from the RAWINPUT driver */
    10.8 +extern SDL_bool SDL_IsJoystickRAWINPUT(SDL_JoystickGUID guid);
    10.9 +
   10.10  /* Function to return whether a joystick guid comes from the Virtual driver */
   10.11  extern SDL_bool SDL_IsJoystickVirtual(SDL_JoystickGUID guid);
   10.12  
    11.1 --- a/src/joystick/SDL_sysjoystick.h	Mon Mar 16 00:21:22 2020 -0400
    11.2 +++ b/src/joystick/SDL_sysjoystick.h	Mon Mar 16 12:23:38 2020 -0700
    11.3 @@ -150,6 +150,7 @@
    11.4  extern SDL_JoystickDriver SDL_EMSCRIPTEN_JoystickDriver;
    11.5  extern SDL_JoystickDriver SDL_HAIKU_JoystickDriver;
    11.6  extern SDL_JoystickDriver SDL_HIDAPI_JoystickDriver;
    11.7 +extern SDL_JoystickDriver SDL_RAWINPUT_JoystickDriver;
    11.8  extern SDL_JoystickDriver SDL_IOS_JoystickDriver;
    11.9  extern SDL_JoystickDriver SDL_LINUX_JoystickDriver;
   11.10  extern SDL_JoystickDriver SDL_VIRTUAL_JoystickDriver;
    12.1 --- a/src/joystick/hidapi/SDL_hidapi_gamecube.c	Mon Mar 16 00:21:22 2020 -0400
    12.2 +++ b/src/joystick/hidapi/SDL_hidapi_gamecube.c	Mon Mar 16 12:23:38 2020 -0700
    12.3 @@ -176,11 +176,11 @@
    12.4              if (curSlot[0] & 0x30) { /* 0x10 - Wired, 0x20 - Wireless */
    12.5                  if (ctx->joysticks[i] == -1) {
    12.6                      ResetAxisRange(ctx, i);
    12.7 -                    HIDAPI_JoystickConnected(device, &ctx->joysticks[i]);
    12.8 +                    HIDAPI_JoystickConnected(device, &ctx->joysticks[i], SDL_FALSE);
    12.9                  }
   12.10              } else {
   12.11                  if (ctx->joysticks[i] != -1) {
   12.12 -                    HIDAPI_JoystickDisconnected(device, ctx->joysticks[i]);
   12.13 +                    HIDAPI_JoystickDisconnected(device, ctx->joysticks[i], SDL_FALSE);
   12.14                      ctx->joysticks[i] = -1;
   12.15                  }
   12.16                  continue;
   12.17 @@ -252,7 +252,7 @@
   12.18              if (curSlot[0] & 0x30) { /* 0x10 - Wired, 0x20 - Wireless */
   12.19                  if (ctx->joysticks[i] == -1) {
   12.20                      ResetAxisRange(ctx, i);
   12.21 -                    HIDAPI_JoystickConnected(device, &ctx->joysticks[i]);
   12.22 +                    HIDAPI_JoystickConnected(device, &ctx->joysticks[i], SDL_FALSE);
   12.23                  }
   12.24                  joystick = SDL_JoystickFromInstanceID(ctx->joysticks[i]);
   12.25  
   12.26 @@ -262,7 +262,7 @@
   12.27                  }
   12.28              } else {
   12.29                  if (ctx->joysticks[i] != -1) {
   12.30 -                    HIDAPI_JoystickDisconnected(device, ctx->joysticks[i]);
   12.31 +                    HIDAPI_JoystickDisconnected(device, ctx->joysticks[i], SDL_FALSE);
   12.32                      ctx->joysticks[i] = -1;
   12.33                  }
   12.34                  continue;
    13.1 --- a/src/joystick/hidapi/SDL_hidapi_ps4.c	Mon Mar 16 00:21:22 2020 -0400
    13.2 +++ b/src/joystick/hidapi/SDL_hidapi_ps4.c	Mon Mar 16 12:23:38 2020 -0700
    13.3 @@ -213,7 +213,7 @@
    13.4  static SDL_bool
    13.5  HIDAPI_DriverPS4_InitDevice(SDL_HIDAPI_Device *device)
    13.6  {
    13.7 -    return HIDAPI_JoystickConnected(device, NULL);
    13.8 +    return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE);
    13.9  }
   13.10  
   13.11  static int
   13.12 @@ -496,7 +496,7 @@
   13.13  
   13.14      if (size < 0) {
   13.15          /* Read error, device is disconnected */
   13.16 -        HIDAPI_JoystickDisconnected(device, joystick->instance_id);
   13.17 +        HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE);
   13.18      }
   13.19      return (size >= 0);
   13.20  }
    14.1 --- a/src/joystick/hidapi/SDL_hidapi_switch.c	Mon Mar 16 00:21:22 2020 -0400
    14.2 +++ b/src/joystick/hidapi/SDL_hidapi_switch.c	Mon Mar 16 12:23:38 2020 -0700
    14.3 @@ -671,7 +671,7 @@
    14.4  static SDL_bool
    14.5  HIDAPI_DriverSwitch_InitDevice(SDL_HIDAPI_Device *device)
    14.6  {
    14.7 -    return HIDAPI_JoystickConnected(device, NULL);
    14.8 +    return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE);
    14.9  }
   14.10  
   14.11  static int
   14.12 @@ -1121,7 +1121,7 @@
   14.13  
   14.14      if (size < 0) {
   14.15          /* Read error, device is disconnected */
   14.16 -        HIDAPI_JoystickDisconnected(device, joystick->instance_id);
   14.17 +        HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE);
   14.18      }
   14.19      return (size >= 0);
   14.20  }
    15.1 --- a/src/joystick/hidapi/SDL_hidapi_xbox360.c	Mon Mar 16 00:21:22 2020 -0400
    15.2 +++ b/src/joystick/hidapi/SDL_hidapi_xbox360.c	Mon Mar 16 12:23:38 2020 -0700
    15.3 @@ -47,34 +47,190 @@
    15.4  
    15.5  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
    15.6  #include "../../core/windows/SDL_windows.h"
    15.7 +typedef struct WindowsGamingInputGamepadState WindowsGamingInputGamepadState;
    15.8 +#define GamepadButtons_GUIDE 0x40000000
    15.9  #define COBJMACROS
   15.10  #include "windows.gaming.input.h"
   15.11  #endif
   15.12  
   15.13 +#if defined(SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT)
   15.14 +#define SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
   15.15 +#endif
   15.16  
   15.17  typedef struct {
   15.18      Uint8 last_state[USB_PACKET_LENGTH];
   15.19 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
   15.20 +    Uint32 match_state; /* Low 16 bits for button states, high 16 for 4 4bit axes */
   15.21 +    Uint32 last_state_packet;
   15.22 +#endif
   15.23  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
   15.24      SDL_bool xinput_enabled;
   15.25 +    SDL_bool xinput_correlated;
   15.26 +    Uint8 xinput_correlation_id;
   15.27 +    Uint8 xinput_correlation_count;
   15.28 +    Uint8 xinput_uncorrelate_count;
   15.29      Uint8 xinput_slot;
   15.30  #endif
   15.31  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
   15.32 -    SDL_bool coinitialized;
   15.33 -    __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics;
   15.34 -    __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
   15.35 -    struct __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration;
   15.36 +    SDL_bool wgi_correlated;
   15.37 +    Uint8 wgi_correlation_id;
   15.38 +    Uint8 wgi_correlation_count;
   15.39 +    Uint8 wgi_uncorrelate_count;
   15.40 +    WindowsGamingInputGamepadState *wgi_slot;
   15.41  #endif
   15.42  } SDL_DriverXbox360_Context;
   15.43  
   15.44 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
   15.45 +static struct {
   15.46 +    Uint32 last_state_packet;
   15.47 +    SDL_Joystick *joystick;
   15.48 +    SDL_Joystick *last_joystick;
   15.49 +} guide_button_candidate;
   15.50 +
   15.51 +typedef struct WindowsMatchState {
   15.52 +    SHORT match_axes[4];
   15.53 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
   15.54 +    WORD xinput_buttons;
   15.55 +#endif
   15.56 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
   15.57 +    Uint32 wgi_buttons;
   15.58 +#endif
   15.59 +    SDL_bool any_data;
   15.60 +} WindowsMatchState;
   15.61 +
   15.62 +static void HIDAPI_DriverXbox360_FillMatchState(WindowsMatchState *state, Uint32 match_state)
   15.63 +{
   15.64 +    int ii;
   15.65 +    state->any_data = SDL_FALSE;
   15.66 +    /*  SHORT state->match_axes[4] = {
   15.67 +            (match_state & 0x000F0000) >> 4,
   15.68 +            (match_state & 0x00F00000) >> 8,
   15.69 +            (match_state & 0x0F000000) >> 12,
   15.70 +            (match_state & 0xF0000000) >> 16,
   15.71 +        }; */
   15.72 +    for (ii = 0; ii < 4; ii++) {
   15.73 +        state->match_axes[ii] = (match_state & (0x000F0000 << (ii * 4))) >> (4 + ii * 4);
   15.74 +        if ((Uint32)(state->match_axes[ii] + 0x1000) > 0x2000) { /* match_state bit is not 0xF, 0x1, or 0x2 */
   15.75 +            state->any_data = SDL_TRUE;
   15.76 +        }
   15.77 +    }
   15.78  
   15.79  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
   15.80 -static Uint8 xinput_slots;
   15.81 +    /* Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less */
   15.82 +#define XInputAxesMatch(gamepad) (\
   15.83 +   (Uint32)(gamepad.sThumbLX - state->match_axes[0] + 0x1000) <= 0x2fff && \
   15.84 +   (Uint32)(~gamepad.sThumbLY - state->match_axes[1] + 0x1000) <= 0x2fff && \
   15.85 +   (Uint32)(gamepad.sThumbRX - state->match_axes[2] + 0x1000) <= 0x2fff && \
   15.86 +   (Uint32)(~gamepad.sThumbRY - state->match_axes[3] + 0x1000) <= 0x2fff)
   15.87 +    /* Explicit
   15.88 +#define XInputAxesMatch(gamepad) (\
   15.89 +    SDL_abs((Sint8)((gamepad.sThumbLX & 0xF000) >> 8) - ((match_state & 0x000F0000) >> 12)) <= 0x10 && \
   15.90 +    SDL_abs((Sint8)((~gamepad.sThumbLY & 0xF000) >> 8) - ((match_state & 0x00F00000) >> 16)) <= 0x10 && \
   15.91 +    SDL_abs((Sint8)((gamepad.sThumbRX & 0xF000) >> 8) - ((match_state & 0x0F000000) >> 20)) <= 0x10 && \
   15.92 +    SDL_abs((Sint8)((~gamepad.sThumbRY & 0xF000) >> 8) - ((match_state & 0xF0000000) >> 24)) <= 0x10) */
   15.93 +
   15.94 +
   15.95 +    state->xinput_buttons =
   15.96 +        /* Bitwise map .RLDUWVQTS.KYXBA -> YXBA..WVQTKSRLDU */
   15.97 +        match_state << 12 | (match_state & 0x0780) >> 1 | (match_state & 0x0010) << 1 | (match_state & 0x0040) >> 2 | (match_state & 0x7800) >> 11;
   15.98 +    /*  Explicit
   15.99 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? XINPUT_GAMEPAD_A : 0) |
  15.100 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? XINPUT_GAMEPAD_B : 0) |
  15.101 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? XINPUT_GAMEPAD_X : 0) |
  15.102 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? XINPUT_GAMEPAD_Y : 0) |
  15.103 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? XINPUT_GAMEPAD_BACK : 0) |
  15.104 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? XINPUT_GAMEPAD_START : 0) |
  15.105 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? XINPUT_GAMEPAD_LEFT_THUMB : 0) |
  15.106 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? XINPUT_GAMEPAD_RIGHT_THUMB: 0) |
  15.107 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? XINPUT_GAMEPAD_LEFT_SHOULDER : 0) |
  15.108 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? XINPUT_GAMEPAD_RIGHT_SHOULDER : 0) |
  15.109 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? XINPUT_GAMEPAD_DPAD_UP : 0) |
  15.110 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? XINPUT_GAMEPAD_DPAD_DOWN : 0) |
  15.111 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? XINPUT_GAMEPAD_DPAD_LEFT : 0) |
  15.112 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? XINPUT_GAMEPAD_DPAD_RIGHT : 0);
  15.113 +    */
  15.114 +
  15.115 +    if (state->xinput_buttons)
  15.116 +        state->any_data = SDL_TRUE;
  15.117 +#endif
  15.118 +
  15.119 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.120 +    /* Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less */
  15.121 +#define WindowsGamingInputAxesMatch(gamepad) (\
  15.122 +    (Uint16)(((Sint16)(gamepad.LeftThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[0] + 0x1000) <= 0x2fff && \
  15.123 +    (Uint16)((~(Sint16)(gamepad.LeftThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[1] + 0x1000) <= 0x2fff && \
  15.124 +    (Uint16)(((Sint16)(gamepad.RightThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[2] + 0x1000) <= 0x2fff && \
  15.125 +    (Uint16)((~(Sint16)(gamepad.RightThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[3] + 0x1000) <= 0x2fff)
  15.126 +
  15.127 +
  15.128 +    state->wgi_buttons =
  15.129 +        /* Bitwise map .RLD UWVQ TS.K YXBA -> ..QT WVRL DUYX BAKS */
  15.130 +        /*  RStick/LStick (QT)         RShould/LShould  (WV)                 DPad R/L/D/U                          YXBA                         bac(K)                      (S)tart */
  15.131 +        (match_state & 0x0180) << 5 | (match_state & 0x0600) << 1 | (match_state & 0x7800) >> 5 | (match_state & 0x000F) << 2 | (match_state & 0x0010) >> 3 | (match_state & 0x0040) >> 6;
  15.132 +    /*  Explicit
  15.133 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? GamepadButtons_A : 0) |
  15.134 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? GamepadButtons_B : 0) |
  15.135 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? GamepadButtons_X : 0) |
  15.136 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? GamepadButtons_Y : 0) |
  15.137 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? GamepadButtons_View : 0) |
  15.138 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? GamepadButtons_Menu : 0) |
  15.139 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? GamepadButtons_LeftThumbstick : 0) |
  15.140 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? GamepadButtons_RightThumbstick: 0) |
  15.141 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? GamepadButtons_LeftShoulder: 0) |
  15.142 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? GamepadButtons_RightShoulder: 0) |
  15.143 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? GamepadButtons_DPadUp : 0) |
  15.144 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? GamepadButtons_DPadDown : 0) |
  15.145 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? GamepadButtons_DPadLeft : 0) |
  15.146 +        ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? GamepadButtons_DPadRight : 0); */
  15.147 +
  15.148 +    if (state->wgi_buttons)
  15.149 +        state->any_data = SDL_TRUE;
  15.150 +#endif
  15.151 +
  15.152 +}
  15.153 +
  15.154 +
  15.155 +#endif
  15.156 +
  15.157 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.158 +static struct {
  15.159 +    XINPUT_STATE_EX state;
  15.160 +    SDL_bool connected; /* Currently has an active XInput device */
  15.161 +    SDL_bool used; /* Is currently mapped to an SDL device */
  15.162 +    Uint8 correlation_id;
  15.163 +} xinput_state[XUSER_MAX_COUNT];
  15.164 +static SDL_bool xinput_device_change = SDL_TRUE;
  15.165 +static SDL_bool xinput_state_dirty = SDL_TRUE;
  15.166 +
  15.167 +static void
  15.168 +HIDAPI_DriverXbox360_UpdateXInput()
  15.169 +{
  15.170 +    DWORD user_index;
  15.171 +    if (xinput_device_change) {
  15.172 +        for (user_index = 0; user_index < XUSER_MAX_COUNT; user_index++) {
  15.173 +            XINPUT_CAPABILITIES capabilities;
  15.174 +            xinput_state[user_index].connected = XINPUTGETCAPABILITIES(user_index, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS;
  15.175 +        }
  15.176 +        xinput_device_change = SDL_FALSE;
  15.177 +        xinput_state_dirty = SDL_TRUE;
  15.178 +    }
  15.179 +    if (xinput_state_dirty) {
  15.180 +        xinput_state_dirty = SDL_FALSE;
  15.181 +        for (user_index = 0; user_index < SDL_arraysize(xinput_state); ++user_index) {
  15.182 +            if (xinput_state[user_index].connected) {
  15.183 +                if (!XINPUTGETSTATE(user_index, &xinput_state[user_index].state) == ERROR_SUCCESS) {
  15.184 +                    xinput_state[user_index].connected = SDL_FALSE;
  15.185 +                }
  15.186 +            }
  15.187 +        }
  15.188 +    }
  15.189 +}
  15.190  
  15.191  static void
  15.192  HIDAPI_DriverXbox360_MarkXInputSlotUsed(Uint8 xinput_slot)
  15.193  {
  15.194      if (xinput_slot != XUSER_INDEX_ANY) {
  15.195 -        xinput_slots |= (0x01 << xinput_slot);
  15.196 +        xinput_state[xinput_slot].used = SDL_TRUE;
  15.197      }
  15.198  }
  15.199  
  15.200 @@ -82,58 +238,209 @@
  15.201  HIDAPI_DriverXbox360_MarkXInputSlotFree(Uint8 xinput_slot)
  15.202  {
  15.203      if (xinput_slot != XUSER_INDEX_ANY) {
  15.204 -        xinput_slots &= ~(0x01 << xinput_slot);
  15.205 +        xinput_state[xinput_slot].used = SDL_FALSE;
  15.206      }
  15.207  }
  15.208 +static SDL_bool
  15.209 +HIDAPI_DriverXbox360_MissingXInputSlot()
  15.210 +{
  15.211 +    int ii;
  15.212 +    for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) {
  15.213 +        if (xinput_state[ii].connected && !xinput_state[ii].used) {
  15.214 +            return SDL_TRUE;
  15.215 +        }
  15.216 +    }
  15.217 +    return SDL_FALSE;
  15.218 +}
  15.219  
  15.220  static SDL_bool
  15.221 -HIDAPI_DriverXbox360_MissingXInputSlot()
  15.222 +HIDAPI_DriverXbox360_XInputSlotMatches(const WindowsMatchState *state, Uint8 slot_idx)
  15.223  {
  15.224 -    return xinput_slots != 0x0F;
  15.225 +    if (xinput_state[slot_idx].connected) {
  15.226 +        WORD xinput_buttons = xinput_state[slot_idx].state.Gamepad.wButtons;
  15.227 +        if ((xinput_buttons & ~XINPUT_GAMEPAD_GUIDE) == state->xinput_buttons && XInputAxesMatch(xinput_state[slot_idx].state.Gamepad)) {
  15.228 +            return SDL_TRUE;
  15.229 +        }
  15.230 +    }
  15.231 +    return SDL_FALSE;
  15.232  }
  15.233  
  15.234 -static Uint8
  15.235 -HIDAPI_DriverXbox360_GuessXInputSlot(WORD wButtons)
  15.236 +
  15.237 +static SDL_bool
  15.238 +HIDAPI_DriverXbox360_GuessXInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, Uint8 *slot_idx)
  15.239  {
  15.240 -    DWORD user_index;
  15.241 +    int user_index;
  15.242      int match_count;
  15.243 -    Uint8 match_slot;
  15.244 -
  15.245 -    if (!XINPUTGETSTATE) {
  15.246 -        return XUSER_INDEX_ANY;
  15.247 -    }
  15.248  
  15.249      match_count = 0;
  15.250      for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) {
  15.251 -        XINPUT_STATE_EX xinput_state;
  15.252 -
  15.253 -        if (XINPUTGETSTATE(user_index, &xinput_state) == ERROR_SUCCESS) {
  15.254 -            if (xinput_state.Gamepad.wButtons == wButtons) {
  15.255 -                ++match_count;
  15.256 -                match_slot = (Uint8)user_index;
  15.257 -            }
  15.258 +        if (!xinput_state[user_index].used && HIDAPI_DriverXbox360_XInputSlotMatches(state, user_index)) {
  15.259 +            ++match_count;
  15.260 +            *slot_idx = (Uint8)user_index;
  15.261 +            /* Incrementing correlation_id for any match, as negative evidence for others being correlated */
  15.262 +            *correlation_id = ++xinput_state[user_index].correlation_id;
  15.263          }
  15.264      }
  15.265 -    if (match_count == 1) {
  15.266 -        return match_slot;
  15.267 +    /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched.
  15.268 +       Note that we're still invalidating *other* potential correlations if we have more than one match or we have no
  15.269 +       data. */
  15.270 +    if (match_count == 1 && state->any_data) {
  15.271 +        return SDL_TRUE;
  15.272      }
  15.273 -    return XUSER_INDEX_ANY;
  15.274 +    return SDL_FALSE;
  15.275  }
  15.276  
  15.277  #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */
  15.278  
  15.279  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.280  
  15.281 +typedef struct WindowsGamingInputGamepadState {
  15.282 +    __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  15.283 +    struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state;
  15.284 +    SDL_DriverXbox360_Context *correlated_context;
  15.285 +    SDL_bool used; /* Is currently mapped to an SDL device */
  15.286 +    SDL_bool connected; /* Just used during update to track disconnected */
  15.287 +    Uint8 correlation_id;
  15.288 +    struct __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration;
  15.289 +} WindowsGamingInputGamepadState;
  15.290 +
  15.291 +static struct {
  15.292 +    WindowsGamingInputGamepadState **per_gamepad;
  15.293 +    int per_gamepad_count;
  15.294 +    SDL_bool initialized;
  15.295 +    SDL_bool dirty;
  15.296 +    SDL_bool need_device_list_update;
  15.297 +    int ref_count;
  15.298 +    __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics;
  15.299 +} wgi_state;
  15.300 +
  15.301 +static void
  15.302 +HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotUsed(WindowsGamingInputGamepadState *wgi_slot, SDL_DriverXbox360_Context *ctx)
  15.303 +{
  15.304 +    wgi_slot->used = SDL_TRUE;
  15.305 +    wgi_slot->correlated_context = ctx;
  15.306 +}
  15.307 +
  15.308 +static void
  15.309 +HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotFree(WindowsGamingInputGamepadState *wgi_slot)
  15.310 +{
  15.311 +    wgi_slot->used = SDL_FALSE;
  15.312 +    wgi_slot->correlated_context = NULL;
  15.313 +}
  15.314 +
  15.315 +static SDL_bool
  15.316 +HIDAPI_DriverXbox360_MissingWindowsGamingInputSlot()
  15.317 +{
  15.318 +    int ii;
  15.319 +    for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  15.320 +        if (!wgi_state.per_gamepad[ii]->used) {
  15.321 +            return SDL_TRUE;
  15.322 +        }
  15.323 +    }
  15.324 +    return SDL_FALSE;
  15.325 +}
  15.326 +
  15.327 +static void
  15.328 +HIDAPI_DriverXbox360_UpdateWindowsGamingInput()
  15.329 +{
  15.330 +    int ii;
  15.331 +    if (!wgi_state.gamepad_statics)
  15.332 +        return;
  15.333 +
  15.334 +    if (!wgi_state.dirty)
  15.335 +        return;
  15.336 +    wgi_state.dirty = SDL_FALSE;
  15.337 +
  15.338 +    if (wgi_state.need_device_list_update) {
  15.339 +        wgi_state.need_device_list_update = SDL_FALSE;
  15.340 +        for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  15.341 +            wgi_state.per_gamepad[ii]->connected = SDL_FALSE;
  15.342 +        }
  15.343 +        HRESULT hr;
  15.344 +        __FIVectorView_1_Windows__CGaming__CInput__CGamepad *gamepads;
  15.345 +
  15.346 +        hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_get_Gamepads(wgi_state.gamepad_statics, &gamepads);
  15.347 +        if (SUCCEEDED(hr)) {
  15.348 +            unsigned int num_gamepads;
  15.349 +
  15.350 +            hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_get_Size(gamepads, &num_gamepads);
  15.351 +            if (SUCCEEDED(hr)) {
  15.352 +                unsigned int i;
  15.353 +                for (i = 0; i < num_gamepads; ++i) {
  15.354 +                    __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  15.355 +
  15.356 +                    hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, i, &gamepad);
  15.357 +                    if (SUCCEEDED(hr)) {
  15.358 +                        SDL_bool found = SDL_FALSE;
  15.359 +                        int jj;
  15.360 +                        for (jj = 0; jj < wgi_state.per_gamepad_count ; jj++) {
  15.361 +                            if (wgi_state.per_gamepad[jj]->gamepad == gamepad) {
  15.362 +                                found = SDL_TRUE;
  15.363 +                                wgi_state.per_gamepad[jj]->connected = SDL_TRUE;
  15.364 +                                break;
  15.365 +                            }
  15.366 +                        }
  15.367 +                        if (!found) {
  15.368 +                            /* New device, add it */
  15.369 +                            wgi_state.per_gamepad_count++;
  15.370 +                            wgi_state.per_gamepad = SDL_realloc(wgi_state.per_gamepad, sizeof(wgi_state.per_gamepad[0]) * wgi_state.per_gamepad_count);
  15.371 +                            if (!wgi_state.per_gamepad) {
  15.372 +                                SDL_OutOfMemory();
  15.373 +                                return;
  15.374 +                            }
  15.375 +                            WindowsGamingInputGamepadState *gamepad_state = SDL_calloc(1, sizeof(*gamepad_state));
  15.376 +                            if (!gamepad_state) {
  15.377 +                                SDL_OutOfMemory();
  15.378 +                                return;
  15.379 +                            }
  15.380 +                            wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1] = gamepad_state;
  15.381 +                            gamepad_state->gamepad = gamepad;
  15.382 +                            gamepad_state->connected = SDL_TRUE;
  15.383 +                        } else {
  15.384 +                            /* Already tracked */
  15.385 +                            __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad);
  15.386 +                        }
  15.387 +                    }
  15.388 +                }
  15.389 +                for (ii = wgi_state.per_gamepad_count - 1; ii >= 0; ii--) {
  15.390 +                    WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii];
  15.391 +                    if (!gamepad_state->connected) {
  15.392 +                        /* Device missing, must be disconnected */
  15.393 +                        if (gamepad_state->correlated_context) {
  15.394 +                            gamepad_state->correlated_context->wgi_correlated = SDL_FALSE;
  15.395 +                            gamepad_state->correlated_context->wgi_slot = NULL;
  15.396 +                        }
  15.397 +                        __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad_state->gamepad);
  15.398 +                        SDL_free(gamepad_state);
  15.399 +                        wgi_state.per_gamepad[ii] = wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1];
  15.400 +                        --wgi_state.per_gamepad_count;
  15.401 +                    }
  15.402 +                }
  15.403 +            }
  15.404 +            __FIVectorView_1_Windows__CGaming__CInput__CGamepad_Release(gamepads);
  15.405 +        }
  15.406 +    } /* need_device_list_update */
  15.407 +
  15.408 +    for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  15.409 +        HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(wgi_state.per_gamepad[ii]->gamepad, &wgi_state.per_gamepad[ii]->state);
  15.410 +        if (!SUCCEEDED(hr)) {
  15.411 +            wgi_state.per_gamepad[ii]->connected = SDL_FALSE; /* Not used by anything, currently */
  15.412 +        }
  15.413 +    }
  15.414 +}
  15.415  static void
  15.416  HIDAPI_DriverXbox360_InitWindowsGamingInput(SDL_DriverXbox360_Context *ctx)
  15.417  {
  15.418 -    /* I think this takes care of RoInitialize() in a way that is compatible with the rest of SDL */
  15.419 -    if (FAILED(WIN_CoInitialize())) {
  15.420 -        return;
  15.421 -    }
  15.422 -    ctx->coinitialized = SDL_TRUE;
  15.423 +    wgi_state.need_device_list_update = SDL_TRUE;
  15.424 +    wgi_state.ref_count++;
  15.425 +    if (!wgi_state.initialized) {
  15.426 +        /* I think this takes care of RoInitialize() in a way that is compatible with the rest of SDL */
  15.427 +        if (FAILED(WIN_CoInitialize())) {
  15.428 +            return;
  15.429 +        }
  15.430 +        wgi_state.initialized = SDL_TRUE;
  15.431 +        wgi_state.dirty = SDL_TRUE;
  15.432  
  15.433 -    {
  15.434          static const IID SDL_IID_IGamepadStatics = { 0x8BBCE529, 0xD49C, 0x39E9, { 0x95, 0x60, 0xE4, 0x7D, 0xDE, 0x96, 0xB7, 0xC8 } };
  15.435          HRESULT hr;
  15.436          HMODULE hModule = LoadLibraryA("combase.dll");
  15.437 @@ -151,7 +458,7 @@
  15.438  
  15.439                  hr = WindowsCreateStringFunc(pNamespace, SDL_wcslen(pNamespace), &hNamespaceString);
  15.440                  if (SUCCEEDED(hr)) {
  15.441 -                    RoGetActivationFactoryFunc(hNamespaceString, &SDL_IID_IGamepadStatics, &ctx->gamepad_statics);
  15.442 +                    RoGetActivationFactoryFunc(hNamespaceString, &SDL_IID_IGamepadStatics, &wgi_state.gamepad_statics);
  15.443                      WindowsDeleteStringFunc(hNamespaceString);
  15.444                  }
  15.445              }
  15.446 @@ -160,90 +467,112 @@
  15.447      }
  15.448  }
  15.449  
  15.450 -static Uint8
  15.451 -HIDAPI_DriverXbox360_GetGamepadButtonsForMatch(__x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad)
  15.452 +static SDL_bool
  15.453 +HIDAPI_DriverXbox360_WindowsGamingInputSlotMatches(const WindowsMatchState *state, WindowsGamingInputGamepadState *slot)
  15.454  {
  15.455 -    HRESULT hr;
  15.456 -    struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state;
  15.457 -    Uint8 buttons = 0;
  15.458 +    Uint32 wgi_buttons = slot->state.Buttons;
  15.459 +    if ((wgi_buttons & 0x3FFF) == state->wgi_buttons && WindowsGamingInputAxesMatch(slot->state)) {
  15.460 +        return SDL_TRUE;
  15.461 +    }
  15.462 +    return SDL_FALSE;
  15.463 +}
  15.464  
  15.465 -    hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(gamepad, &state);
  15.466 -    if (SUCCEEDED(hr)) {
  15.467 -        if (state.Buttons & GamepadButtons_A) {
  15.468 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_A);
  15.469 -        }
  15.470 -        if (state.Buttons & GamepadButtons_B) {
  15.471 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_B);
  15.472 -        }
  15.473 -        if (state.Buttons & GamepadButtons_X) {
  15.474 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_X);
  15.475 -        }
  15.476 -        if (state.Buttons & GamepadButtons_Y) {
  15.477 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_Y);
  15.478 +static SDL_bool
  15.479 +HIDAPI_DriverXbox360_GuessWindowsGamingInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, WindowsGamingInputGamepadState **slot)
  15.480 +{
  15.481 +    int match_count;
  15.482 +
  15.483 +    match_count = 0;
  15.484 +    for (int user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) {
  15.485 +        WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[user_index];
  15.486 +        if (HIDAPI_DriverXbox360_WindowsGamingInputSlotMatches(state, gamepad_state)) {
  15.487 +            ++match_count;
  15.488 +            *slot = gamepad_state;
  15.489 +            /* Incrementing correlation_id for any match, as negative evidence for others being correlated */
  15.490 +            *correlation_id = ++gamepad_state->correlation_id;
  15.491          }
  15.492      }
  15.493 -    return buttons;
  15.494 -}
  15.495 -
  15.496 -static void
  15.497 -HIDAPI_DriverXbox360_GuessGamepad(SDL_DriverXbox360_Context *ctx, Uint8 buttons)
  15.498 -{
  15.499 -    HRESULT hr;
  15.500 -    __FIVectorView_1_Windows__CGaming__CInput__CGamepad *gamepads;
  15.501 -
  15.502 -    hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_get_Gamepads(ctx->gamepad_statics, &gamepads);
  15.503 -    if (SUCCEEDED(hr)) {
  15.504 -        unsigned int i, num_gamepads;
  15.505 -
  15.506 -        hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_get_Size(gamepads, &num_gamepads);
  15.507 -        if (SUCCEEDED(hr)) {
  15.508 -            int match_count;
  15.509 -            unsigned int match_slot;
  15.510 -
  15.511 -            match_count = 0;
  15.512 -            for (i = 0; i < num_gamepads; ++i) {
  15.513 -                __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  15.514 -
  15.515 -                hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, i, &gamepad);
  15.516 -                if (SUCCEEDED(hr)) {
  15.517 -                    Uint8 gamepad_buttons = HIDAPI_DriverXbox360_GetGamepadButtonsForMatch(gamepad);
  15.518 -                    if (buttons == gamepad_buttons) {
  15.519 -                        ++match_count;
  15.520 -                        match_slot = i;
  15.521 -                    }
  15.522 -                    __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad);
  15.523 -                }
  15.524 -            }
  15.525 -            if (match_count == 1) {
  15.526 -                hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, match_slot, &ctx->gamepad);
  15.527 -                if (SUCCEEDED(hr)) {
  15.528 -                }
  15.529 -            }
  15.530 -        }
  15.531 -        __FIVectorView_1_Windows__CGaming__CInput__CGamepad_Release(gamepads);
  15.532 +    /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched.
  15.533 +       Note that we're still invalidating *other* potential correlations if we have more than one match or we have no
  15.534 +       data. */
  15.535 +    if (match_count == 1 && state->any_data) {
  15.536 +        return SDL_TRUE;
  15.537      }
  15.538 +    return SDL_FALSE;
  15.539  }
  15.540  
  15.541  static void
  15.542  HIDAPI_DriverXbox360_QuitWindowsGamingInput(SDL_DriverXbox360_Context *ctx)
  15.543  {
  15.544 -    if (ctx->gamepad_statics) {
  15.545 -        __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(ctx->gamepad_statics);
  15.546 -        ctx->gamepad_statics = NULL;
  15.547 -    }
  15.548 -    if (ctx->gamepad) {
  15.549 -        __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(ctx->gamepad);
  15.550 -        ctx->gamepad = NULL;
  15.551 -    }
  15.552 -
  15.553 -    if (ctx->coinitialized) {
  15.554 +    wgi_state.need_device_list_update = SDL_TRUE;
  15.555 +    --wgi_state.ref_count;
  15.556 +    if (!wgi_state.ref_count && wgi_state.initialized) {
  15.557 +        for (int ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  15.558 +            __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(wgi_state.per_gamepad[ii]->gamepad);
  15.559 +        }
  15.560 +        if (wgi_state.per_gamepad) {
  15.561 +            SDL_free(wgi_state.per_gamepad);
  15.562 +            wgi_state.per_gamepad = NULL;
  15.563 +        }
  15.564 +        wgi_state.per_gamepad_count = 0;
  15.565 +        if (wgi_state.gamepad_statics) {
  15.566 +            __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(wgi_state.gamepad_statics);
  15.567 +            wgi_state.gamepad_statics = NULL;
  15.568 +        }
  15.569          WIN_CoUninitialize();
  15.570 -        ctx->coinitialized = SDL_FALSE;
  15.571 +        wgi_state.initialized = SDL_FALSE;
  15.572      }
  15.573  }
  15.574  
  15.575  #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT */
  15.576  
  15.577 +static void
  15.578 +HIDAPI_DriverXbox360_PostUpdate(void)
  15.579 +{
  15.580 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
  15.581 +    SDL_bool unmapped_guide_pressed = SDL_FALSE;
  15.582 +
  15.583 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.584 +    if (!wgi_state.dirty) {
  15.585 +        int ii;
  15.586 +        for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  15.587 +            WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii];
  15.588 +            if (!gamepad_state->used && (gamepad_state->state.Buttons & GamepadButtons_GUIDE)) {
  15.589 +                unmapped_guide_pressed = SDL_TRUE;
  15.590 +                break;
  15.591 +            }
  15.592 +        }
  15.593 +    }
  15.594 +    wgi_state.dirty = SDL_TRUE;
  15.595 +#endif
  15.596 +
  15.597 +
  15.598 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.599 +    if (!xinput_state_dirty) {
  15.600 +        int ii;
  15.601 +        for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) {
  15.602 +            if (xinput_state[ii].connected && !xinput_state[ii].used && (xinput_state[ii].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE)) {
  15.603 +                unmapped_guide_pressed = SDL_TRUE;
  15.604 +                break;
  15.605 +            }
  15.606 +        }
  15.607 +    }
  15.608 +    xinput_state_dirty = SDL_TRUE;
  15.609 +#endif
  15.610 +
  15.611 +    if (unmapped_guide_pressed) {
  15.612 +        if (guide_button_candidate.joystick && !guide_button_candidate.last_joystick) {
  15.613 +            SDL_PrivateJoystickButton(guide_button_candidate.joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_PRESSED);
  15.614 +            guide_button_candidate.last_joystick = guide_button_candidate.joystick;
  15.615 +        }
  15.616 +    } else if (guide_button_candidate.last_joystick) {
  15.617 +        SDL_PrivateJoystickButton(guide_button_candidate.last_joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED);
  15.618 +        guide_button_candidate.last_joystick = NULL;
  15.619 +    }
  15.620 +    guide_button_candidate.joystick = NULL;
  15.621 +#endif
  15.622 +}
  15.623 +
  15.624  #if defined(__MACOSX__)
  15.625  static SDL_bool
  15.626  IsBluetoothXboxOneController(Uint16 vendor_id, Uint16 product_id)
  15.627 @@ -320,7 +649,7 @@
  15.628  static SDL_bool
  15.629  HIDAPI_DriverXbox360_InitDevice(SDL_HIDAPI_Device *device)
  15.630  {
  15.631 -    return HIDAPI_JoystickConnected(device, NULL);
  15.632 +    return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE);
  15.633  }
  15.634  
  15.635  static int
  15.636 @@ -349,17 +678,20 @@
  15.637          return SDL_FALSE;
  15.638      }
  15.639  
  15.640 -    device->dev = hid_open_path(device->path, 0);
  15.641 -    if (!device->dev) {
  15.642 -        SDL_free(ctx);
  15.643 -        SDL_SetError("Couldn't open %s", device->path);
  15.644 -        return SDL_FALSE;
  15.645 +    if (device->path) { /* else opened for RAWINPUT driver */
  15.646 +        device->dev = hid_open_path(device->path, 0);
  15.647 +        if (!device->dev) {
  15.648 +            SDL_SetError("Couldn't open %s", device->path);
  15.649 +            SDL_free(ctx);
  15.650 +            return SDL_FALSE;
  15.651 +        }
  15.652      }
  15.653      device->context = ctx;
  15.654  
  15.655  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.656 -    ctx->xinput_enabled = SDL_GetHintBoolean(SDL_HINT_XINPUT_ENABLED, SDL_TRUE);
  15.657 -    if (ctx->xinput_enabled && WIN_LoadXInputDLL() < 0) {
  15.658 +    xinput_device_change = SDL_TRUE;
  15.659 +    ctx->xinput_enabled = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT, SDL_TRUE);
  15.660 +    if (ctx->xinput_enabled && (WIN_LoadXInputDLL() < 0 || !XINPUTGETSTATE)) {
  15.661          ctx->xinput_enabled = SDL_FALSE;
  15.662      }
  15.663      ctx->xinput_slot = XUSER_INDEX_ANY;
  15.664 @@ -370,7 +702,7 @@
  15.665  
  15.666      /* Set the controller LED */
  15.667      player_index = SDL_JoystickGetPlayerIndex(joystick);
  15.668 -    if (player_index >= 0) {
  15.669 +    if (player_index >= 0 && device->dev) {
  15.670          SetSlotLED(device->dev, (player_index % 4));
  15.671      }
  15.672  
  15.673 @@ -393,12 +725,12 @@
  15.674      SDL_bool rumbled = SDL_FALSE;
  15.675  
  15.676  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.677 -    if (!rumbled && ctx->gamepad) {
  15.678 +    if (!rumbled && ctx->wgi_correlated) {
  15.679 +        WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot;
  15.680          HRESULT hr;
  15.681 -
  15.682 -        ctx->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16;
  15.683 -        ctx->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16;
  15.684 -        hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(ctx->gamepad, ctx->vibration);
  15.685 +        gamepad_state->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16;
  15.686 +        gamepad_state->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16;
  15.687 +        hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, gamepad_state->vibration);
  15.688          if (SUCCEEDED(hr)) {
  15.689              rumbled = SDL_TRUE;
  15.690          }
  15.691 @@ -406,7 +738,7 @@
  15.692  #endif
  15.693  
  15.694  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.695 -    if (!rumbled && ctx->xinput_slot != XUSER_INDEX_ANY) {
  15.696 +    if (!rumbled && ctx->xinput_correlated) {
  15.697          XINPUT_VIBRATION XVibration;
  15.698  
  15.699          if (!XINPUTSETSTATE) {
  15.700 @@ -473,6 +805,13 @@
  15.701  static void
  15.702  HIDAPI_DriverXbox360_HandleStatePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXbox360_Context *ctx, Uint8 *data, int size)
  15.703  {
  15.704 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
  15.705 +    Uint32 match_state = ctx->match_state;
  15.706 +    /* Update match_state with button bit, then fall through */
  15.707 +#   define SDL_PrivateJoystickButton(joystick, button, state) if (state) match_state |= 1 << (button); else match_state &=~(1<<(button)); SDL_PrivateJoystickButton(joystick, button, state)
  15.708 +    /* Grab high 4 bits of value, then fall through */
  15.709 +#   define SDL_PrivateJoystickAxis(joystick, axis, value) if (axis < 4) match_state = (match_state & ~(0xF << (4 * axis + 16))) | ((value) & 0xF000) << (4 * axis + 4); SDL_PrivateJoystickAxis(joystick, axis, value)
  15.710 +#endif
  15.711      Sint16 axis;
  15.712      SDL_bool has_trigger_data = SDL_FALSE;
  15.713  
  15.714 @@ -543,96 +882,56 @@
  15.715      axis = (int)*(Uint16*)(&data[6]) - 0x8000;
  15.716      SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis);
  15.717  
  15.718 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
  15.719 +#undef SDL_PrivateJoystickAxis
  15.720 +#endif
  15.721 +
  15.722 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.723 +    /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */
  15.724 +    if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) {
  15.725 +        has_trigger_data = SDL_TRUE;
  15.726 +    }
  15.727 +#endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */
  15.728 +
  15.729  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.730 -    if (ctx->gamepad_statics && !ctx->gamepad) {
  15.731 -        Uint8 buttons = 0;
  15.732 -
  15.733 -        if (data[10] & 0x01) {
  15.734 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_A);
  15.735 -        }
  15.736 -        if (data[10] & 0x02) {
  15.737 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_B);
  15.738 -        }
  15.739 -        if (data[10] & 0x04) {
  15.740 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_X);
  15.741 -        }
  15.742 -        if (data[10] & 0x08) {
  15.743 -            buttons |= (1 << SDL_CONTROLLER_BUTTON_Y);
  15.744 -        }
  15.745 -        if (buttons != 0) {
  15.746 -            HIDAPI_DriverXbox360_GuessGamepad(ctx, buttons);
  15.747 -        }
  15.748 -    }
  15.749 -
  15.750 -    if (ctx->gamepad) {
  15.751 -        HRESULT hr;
  15.752 -        struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state;
  15.753 -        
  15.754 -        hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(ctx->gamepad, &state);
  15.755 -        if (SUCCEEDED(hr)) {
  15.756 -            SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (state.Buttons & 0x40000000) ? SDL_PRESSED : SDL_RELEASED);
  15.757 -            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, ((int)(state.LeftTrigger * SDL_MAX_UINT16)) - 32768);
  15.758 -            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, ((int)(state.RightTrigger * SDL_MAX_UINT16)) - 32768);
  15.759 -            has_trigger_data = SDL_TRUE;
  15.760 -        }
  15.761 +    if (!has_trigger_data && ctx->wgi_correlated) {
  15.762 +        has_trigger_data = SDL_TRUE;
  15.763      }
  15.764  #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT */
  15.765  
  15.766 -#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.767 -    if (ctx->xinput_enabled) {
  15.768 -        if (ctx->xinput_slot == XUSER_INDEX_ANY && HIDAPI_DriverXbox360_MissingXInputSlot()) {
  15.769 -            WORD wButtons = 0;
  15.770 -
  15.771 -            if (data[10] & 0x01) {
  15.772 -                wButtons |= XINPUT_GAMEPAD_A;
  15.773 -            }
  15.774 -            if (data[10] & 0x02) {
  15.775 -                wButtons |= XINPUT_GAMEPAD_B;
  15.776 -            }
  15.777 -            if (data[10] & 0x04) {
  15.778 -                wButtons |= XINPUT_GAMEPAD_X;
  15.779 -            }
  15.780 -            if (data[10] & 0x08) {
  15.781 -                wButtons |= XINPUT_GAMEPAD_Y;
  15.782 -            }
  15.783 -            if (wButtons != 0) {
  15.784 -                Uint8 xinput_slot = HIDAPI_DriverXbox360_GuessXInputSlot(wButtons);
  15.785 -                if (xinput_slot != XUSER_INDEX_ANY) {
  15.786 -                    HIDAPI_DriverXbox360_MarkXInputSlotUsed(xinput_slot);
  15.787 -                    ctx->xinput_slot = xinput_slot;
  15.788 -                }
  15.789 -            }
  15.790 -        }
  15.791 -
  15.792 -        if (!has_trigger_data && ctx->xinput_slot != XUSER_INDEX_ANY) {
  15.793 -            XINPUT_STATE_EX xinput_state;
  15.794 -
  15.795 -            if (XINPUTGETSTATE(ctx->xinput_slot, &xinput_state) == ERROR_SUCCESS) {
  15.796 -                SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  15.797 -                SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, ((int)xinput_state.Gamepad.bLeftTrigger * 257) - 32768);
  15.798 -                SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, ((int)xinput_state.Gamepad.bRightTrigger * 257) - 32768);
  15.799 -                has_trigger_data = SDL_TRUE;
  15.800 -            }
  15.801 -        }
  15.802 -    }
  15.803 -#endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */
  15.804 -
  15.805      if (!has_trigger_data) {
  15.806          axis = (data[9] * 257) - 32768;
  15.807          if (data[9] < 0x80) {
  15.808              axis = -axis * 2 - 32769;
  15.809 +            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, SDL_MIN_SINT16);
  15.810              SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis);
  15.811          } else if (data[9] > 0x80) {
  15.812              axis = axis * 2 - 32767;
  15.813              SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis);
  15.814 +            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, SDL_MIN_SINT16);
  15.815          } else {
  15.816              SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, SDL_MIN_SINT16);
  15.817              SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, SDL_MIN_SINT16);
  15.818          }
  15.819      }
  15.820  
  15.821 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
  15.822 +    ctx->match_state = match_state;
  15.823 +    ctx->last_state_packet = SDL_GetTicks();
  15.824 +#undef SDL_PrivateJoystickButton
  15.825 +#endif
  15.826      SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state)));
  15.827  }
  15.828 +
  15.829 +#ifdef SDL_JOYSTICK_RAWINPUT
  15.830 +static void
  15.831 +HIDAPI_DriverXbox360_HandleStatePacketFromRAWINPUT(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 *data, int size)
  15.832 +{
  15.833 +    SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context;
  15.834 +    HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, data, size);
  15.835 +}
  15.836 +#endif
  15.837 +
  15.838  #else
  15.839  
  15.840  static void
  15.841 @@ -689,13 +988,243 @@
  15.842  }
  15.843  #endif /* __WIN32__ */
  15.844  
  15.845 +static void
  15.846 +HIDAPI_DriverXbox360_UpdateOtherAPIs(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  15.847 +{
  15.848 +    SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context;
  15.849 +    SDL_bool has_trigger_data = SDL_FALSE;
  15.850 +    SDL_bool correlated = SDL_FALSE;
  15.851 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
  15.852 +    WindowsMatchState match_state_xinput;
  15.853 +#endif
  15.854 +
  15.855 +    /* Poll for trigger data once (not per-state-packet) */
  15.856 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.857 +    /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */
  15.858 +    if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) {
  15.859 +        HIDAPI_DriverXbox360_UpdateXInput();
  15.860 +        if (xinput_state[ctx->xinput_slot].connected) {
  15.861 +            SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (xinput_state[ctx->xinput_slot].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  15.862 +            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bLeftTrigger * 257) - 32768);
  15.863 +            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bRightTrigger * 257) - 32768);
  15.864 +            has_trigger_data = SDL_TRUE;
  15.865 +        }
  15.866 +    }
  15.867 +#endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */
  15.868 +
  15.869 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.870 +    if (!has_trigger_data && ctx->wgi_correlated) {
  15.871 +        HIDAPI_DriverXbox360_UpdateWindowsGamingInput(); /* May detect disconnect / cause uncorrelation */
  15.872 +        if (ctx->wgi_correlated) { /* Still connected */
  15.873 +            struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading *state = &ctx->wgi_slot->state;
  15.874 +            SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (state->Buttons & GamepadButtons_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  15.875 +            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, ((int)(state->LeftTrigger * SDL_MAX_UINT16)) - 32768);
  15.876 +            SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, ((int)(state->RightTrigger * SDL_MAX_UINT16)) - 32768);
  15.877 +            has_trigger_data = SDL_TRUE;
  15.878 +        }
  15.879 +    }
  15.880 +#endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT */
  15.881 +
  15.882 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
  15.883 +    HIDAPI_DriverXbox360_FillMatchState(&match_state_xinput, ctx->match_state);
  15.884 +
  15.885 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT
  15.886 +    /* Parallel logic to WINDOWS_XINPUT below */
  15.887 +    HIDAPI_DriverXbox360_UpdateWindowsGamingInput();
  15.888 +    if (ctx->wgi_correlated) {
  15.889 +        /* We have been previously correlated, ensure we are still matching, see comments in XINPUT section */
  15.890 +        if (HIDAPI_DriverXbox360_WindowsGamingInputSlotMatches(&match_state_xinput, ctx->wgi_slot)) {
  15.891 +            ctx->wgi_uncorrelate_count = 0;
  15.892 +        } else {
  15.893 +            ++ctx->wgi_uncorrelate_count;
  15.894 +            /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event
  15.895 +              pumping can easily cause this to uncorrelate for a frame.  2 seemed reliable in my testing, but
  15.896 +              let's set it to 3 to be safe.  An incorrect un-correlation will simply result in lower precision
  15.897 +              triggers for a frame. */
  15.898 +            if (ctx->wgi_uncorrelate_count >= 3) {
  15.899 +#ifdef DEBUG_JOYSTICK
  15.900 +                SDL_Log("UN-Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, ctx->wgi_slot);
  15.901 +#endif
  15.902 +                HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotFree(ctx->wgi_slot);
  15.903 +                ctx->wgi_correlated = SDL_FALSE;
  15.904 +                ctx->wgi_correlation_count = 0;
  15.905 +                /* Force immediate update of triggers */
  15.906 +                HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state));
  15.907 +                /* Force release of Guide button, it can't possibly be down on this device now. */
  15.908 +                /* It gets left down if we were actually correlated incorrectly and it was released on the WindowsGamingInput
  15.909 +                  device but we didn't get a state packet. */
  15.910 +                SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED);
  15.911 +            }
  15.912 +        }
  15.913 +    }
  15.914 +    if (!ctx->wgi_correlated) {
  15.915 +        SDL_bool new_correlation_count = 0;
  15.916 +        if (HIDAPI_DriverXbox360_MissingWindowsGamingInputSlot()) {
  15.917 +            Uint8 correlation_id;
  15.918 +            WindowsGamingInputGamepadState *slot_idx;
  15.919 +            if (HIDAPI_DriverXbox360_GuessWindowsGamingInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) {
  15.920 +                /* we match exactly one WindowsGamingInput device */
  15.921 +                /* Probably can do without wgi_correlation_count, just check and clear wgi_slot to NULL, unless we need
  15.922 +                   even more frames to be sure. */
  15.923 +                if (ctx->wgi_correlation_count && ctx->wgi_slot == slot_idx) {
  15.924 +                    /* was correlated previously, and still the same device */
  15.925 +                    if (ctx->wgi_correlation_id + 1 == correlation_id) {
  15.926 +                        /* no one else was correlated in the meantime */
  15.927 +                        new_correlation_count = ctx->wgi_correlation_count + 1;
  15.928 +                        if (new_correlation_count == 2) {
  15.929 +                            /* correlation stayed steady and uncontested across multiple frames, guaranteed match */
  15.930 +                            ctx->wgi_correlated = SDL_TRUE;
  15.931 +#ifdef DEBUG_JOYSTICK
  15.932 +                            SDL_Log("Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, slot_idx);
  15.933 +#endif
  15.934 +                            correlated = SDL_TRUE;
  15.935 +                            HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotUsed(ctx->wgi_slot, ctx);
  15.936 +                            /* If the generalized Guide button was using us, it doesn't need to anymore */
  15.937 +                            if (guide_button_candidate.joystick == joystick)
  15.938 +                                guide_button_candidate.joystick = NULL;
  15.939 +                            if (guide_button_candidate.last_joystick == joystick)
  15.940 +                                guide_button_candidate.last_joystick = NULL;
  15.941 +                            /* Force immediate update of guide button / triggers */
  15.942 +                            HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state));
  15.943 +                        }
  15.944 +                    } else {
  15.945 +                        /* someone else also possibly correlated to this device, start over */
  15.946 +                        new_correlation_count = 1;
  15.947 +                    }
  15.948 +                } else {
  15.949 +                    /* new possible correlation */
  15.950 +                    new_correlation_count = 1;
  15.951 +                    ctx->wgi_slot = slot_idx;
  15.952 +                }
  15.953 +                ctx->wgi_correlation_id = correlation_id;
  15.954 +            } else {
  15.955 +                /* Match multiple WindowsGamingInput devices, or none (possibly due to no buttons pressed) */
  15.956 +            }
  15.957 +        }
  15.958 +        ctx->wgi_correlation_count = new_correlation_count;
  15.959 +    } else {
  15.960 +        correlated = SDL_TRUE;
  15.961 +    }
  15.962 +#endif
  15.963 +
  15.964 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
  15.965 +    /* Parallel logic to WINDOWS_GAMING_INPUT above */
  15.966 +    if (ctx->xinput_enabled) {
  15.967 +        HIDAPI_DriverXbox360_UpdateXInput();
  15.968 +        if (ctx->xinput_correlated) {
  15.969 +            /* We have been previously correlated, ensure we are still matching */
  15.970 +            /* This is required to deal with two (mostly) un-preventable mis-correlation situations:
  15.971 +              A) Since the HID data stream does not provide an initial state (but polling XInput does), if we open
  15.972 +                 5 controllers (#1-4 XInput mapped, #5 is not), and controller 1 had the A button down (and we don't
  15.973 +                 know), and the user presses A on controller #5, we'll see exactly 1 controller with A down (#5) and
  15.974 +                 exactly 1 XInput device with A down (#1), and incorrectly correlate.  This code will then un-correlate
  15.975 +                 when A is released from either controller #1 or #5.
  15.976 +              B) Since the app may not open all controllers, we could have a similar situation where only controller #5
  15.977 +                 is opened, and the user holds A on controllers #1 and #5 simultaneously - again we see only 1 controller
  15.978 +                 with A down and 1 XInput device with A down, and incorrectly correlate.  This should be very unusual
  15.979 +                 (only when apps do not open all controllers, yet are listening to Guide button presses, yet
  15.980 +                 for some reason want to ignore guide button presses on the un-opened controllers, yet users are
  15.981 +                 pressing buttons on the unopened controllers), and will resolve itself when either button is released
  15.982 +                 and we un-correlate.  We could prevent this by processing the state packets for *all* controllers,
  15.983 +                 even un-opened ones, as that would allow more precise correlation.
  15.984 +            */
  15.985 +            if (HIDAPI_DriverXbox360_XInputSlotMatches(&match_state_xinput, ctx->xinput_slot)) {
  15.986 +                ctx->xinput_uncorrelate_count = 0;
  15.987 +            } else {
  15.988 +                ++ctx->xinput_uncorrelate_count;
  15.989 +                /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event
  15.990 +                  pumping can easily cause this to uncorrelate for a frame.  2 seemed reliable in my testing, but
  15.991 +                  let's set it to 3 to be safe.  An incorrect un-correlation will simply result in lower precision
  15.992 +                  triggers for a frame. */
  15.993 +                if (ctx->xinput_uncorrelate_count >= 3) {
  15.994 +#ifdef DEBUG_JOYSTICK
  15.995 +                    SDL_Log("UN-Correlated joystick %d to XInput device #%d\n", joystick->instance_id, ctx->xinput_slot);
  15.996 +#endif
  15.997 +                    HIDAPI_DriverXbox360_MarkXInputSlotFree(ctx->xinput_slot);
  15.998 +                    ctx->xinput_correlated = SDL_FALSE;
  15.999 +                    ctx->xinput_correlation_count = 0;
 15.1000 +                    /* Force immediate update of triggers */
 15.1001 +                    HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state));
 15.1002 +                    /* Force release of Guide button, it can't possibly be down on this device now. */
 15.1003 +                    /* It gets left down if we were actually correlated incorrectly and it was released on the XInput
 15.1004 +                      device but we didn't get a state packet. */
 15.1005 +                    SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED);
 15.1006 +                }
 15.1007 +            }
 15.1008 +        }
 15.1009 +        if (!ctx->xinput_correlated) {
 15.1010 +            SDL_bool new_correlation_count = 0;
 15.1011 +            if (HIDAPI_DriverXbox360_MissingXInputSlot()) {
 15.1012 +                Uint8 correlation_id;
 15.1013 +                Uint8 slot_idx;
 15.1014 +                if (HIDAPI_DriverXbox360_GuessXInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) {
 15.1015 +                    /* we match exactly one XInput device */
 15.1016 +                    /* Probably can do without xinput_correlation_count, just check and clear xinput_slot to ANY, unless
 15.1017 +                       we need even more frames to be sure */
 15.1018 +                    if (ctx->xinput_correlation_count && ctx->xinput_slot == slot_idx) {
 15.1019 +                        /* was correlated previously, and still the same device */
 15.1020 +                        if (ctx->xinput_correlation_id + 1 == correlation_id) {
 15.1021 +                            /* no one else was correlated in the meantime */
 15.1022 +                            new_correlation_count = ctx->xinput_correlation_count + 1;
 15.1023 +                            if (new_correlation_count == 2) {
 15.1024 +                                /* correlation stayed steady and uncontested across multiple frames, guaranteed match */
 15.1025 +                                ctx->xinput_correlated = SDL_TRUE;
 15.1026 +#ifdef DEBUG_JOYSTICK
 15.1027 +                                SDL_Log("Correlated joystick %d to XInput device #%d\n", joystick->instance_id, slot_idx);
 15.1028 +#endif
 15.1029 +                                correlated = SDL_TRUE;
 15.1030 +                                HIDAPI_DriverXbox360_MarkXInputSlotUsed(ctx->xinput_slot);
 15.1031 +                                /* If the generalized Guide button was using us, it doesn't need to anymore */
 15.1032 +                                if (guide_button_candidate.joystick == joystick)
 15.1033 +                                    guide_button_candidate.joystick = NULL;
 15.1034 +                                if (guide_button_candidate.last_joystick == joystick)
 15.1035 +                                    guide_button_candidate.last_joystick = NULL;
 15.1036 +                                /* Force immediate update of guide button / triggers */
 15.1037 +                                HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state));
 15.1038 +                            }
 15.1039 +                        } else {
 15.1040 +                            /* someone else also possibly correlated to this device, start over */
 15.1041 +                            new_correlation_count = 1;
 15.1042 +                        }
 15.1043 +                    } else {
 15.1044 +                        /* new possible correlation */
 15.1045 +                        new_correlation_count = 1;
 15.1046 +                        ctx->xinput_slot = slot_idx;
 15.1047 +                    }
 15.1048 +                    ctx->xinput_correlation_id = correlation_id;
 15.1049 +                } else {
 15.1050 +                    /* Match multiple XInput devices, or none (possibly due to no buttons pressed) */
 15.1051 +                }
 15.1052 +            }
 15.1053 +            ctx->xinput_correlation_count = new_correlation_count;
 15.1054 +        } else {
 15.1055 +            correlated = SDL_TRUE;
 15.1056 +        }
 15.1057 +    }
 15.1058 +#endif
 15.1059 +
 15.1060 +    if (!correlated) {
 15.1061 +        if (!guide_button_candidate.joystick ||
 15.1062 +            (ctx->last_state_packet && (
 15.1063 +                !guide_button_candidate.last_state_packet ||
 15.1064 +                SDL_TICKS_PASSED(ctx->last_state_packet, guide_button_candidate.last_state_packet)
 15.1065 +            ))
 15.1066 +        ) {
 15.1067 +            guide_button_candidate.joystick = joystick;
 15.1068 +            guide_button_candidate.last_state_packet = ctx->last_state_packet;
 15.1069 +        }
 15.1070 +    }
 15.1071 +#endif
 15.1072 +
 15.1073 +}
 15.1074 +
 15.1075  static SDL_bool
 15.1076  HIDAPI_DriverXbox360_UpdateDevice(SDL_HIDAPI_Device *device)
 15.1077  {
 15.1078      SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context;
 15.1079      SDL_Joystick *joystick = NULL;
 15.1080      Uint8 data[USB_PACKET_LENGTH];
 15.1081 -    int size;
 15.1082 +    int size = 0;
 15.1083  
 15.1084      if (device->num_joysticks > 0) {
 15.1085          joystick = SDL_JoystickFromInstanceID(device->joysticks[0]);
 15.1086 @@ -704,14 +1233,17 @@
 15.1087          return SDL_FALSE;
 15.1088      }
 15.1089  
 15.1090 -    while ((size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) {
 15.1091 +    while (device->dev && (size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) {
 15.1092          HIDAPI_DriverXbox360_HandleStatePacket(joystick, device->dev, ctx, data, size);
 15.1093      }
 15.1094  
 15.1095      if (size < 0) {
 15.1096          /* Read error, device is disconnected */
 15.1097 -        HIDAPI_JoystickDisconnected(device, joystick->instance_id);
 15.1098 +        HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE);
 15.1099 +    } else {
 15.1100 +        HIDAPI_DriverXbox360_UpdateOtherAPIs(device, joystick);
 15.1101      }
 15.1102 +    
 15.1103      return (size >= 0);
 15.1104  }
 15.1105  
 15.1106 @@ -721,10 +1253,20 @@
 15.1107  #if defined(SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT)
 15.1108      SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context;
 15.1109  #endif
 15.1110 +    
 15.1111 +#ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING
 15.1112 +    if (guide_button_candidate.joystick == joystick)
 15.1113 +        guide_button_candidate.joystick = NULL;
 15.1114 +    if (guide_button_candidate.last_joystick == joystick)
 15.1115 +        guide_button_candidate.last_joystick = NULL;
 15.1116 +#endif
 15.1117  
 15.1118  #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT
 15.1119 +    xinput_device_change = SDL_TRUE;
 15.1120      if (ctx->xinput_enabled) {
 15.1121 -        HIDAPI_DriverXbox360_MarkXInputSlotFree(ctx->xinput_slot);
 15.1122 +        if (ctx->xinput_correlated) {
 15.1123 +            HIDAPI_DriverXbox360_MarkXInputSlotFree(ctx->xinput_slot);
 15.1124 +        }
 15.1125          WIN_UnloadXInputDLL();
 15.1126      }
 15.1127  #endif
 15.1128 @@ -732,8 +1274,10 @@
 15.1129      HIDAPI_DriverXbox360_QuitWindowsGamingInput(ctx);
 15.1130  #endif
 15.1131  
 15.1132 -    hid_close(device->dev);
 15.1133 -    device->dev = NULL;
 15.1134 +    if (device->dev) {
 15.1135 +        hid_close(device->dev);
 15.1136 +        device->dev = NULL;
 15.1137 +    }
 15.1138  
 15.1139      SDL_free(device->context);
 15.1140      device->context = NULL;
 15.1141 @@ -757,7 +1301,11 @@
 15.1142      HIDAPI_DriverXbox360_OpenJoystick,
 15.1143      HIDAPI_DriverXbox360_RumbleJoystick,
 15.1144      HIDAPI_DriverXbox360_CloseJoystick,
 15.1145 -    HIDAPI_DriverXbox360_FreeDevice
 15.1146 +    HIDAPI_DriverXbox360_FreeDevice,
 15.1147 +    HIDAPI_DriverXbox360_PostUpdate,
 15.1148 +#ifdef SDL_JOYSTICK_RAWINPUT
 15.1149 +    HIDAPI_DriverXbox360_HandleStatePacketFromRAWINPUT,
 15.1150 +#endif
 15.1151  };
 15.1152  
 15.1153  #endif /* SDL_JOYSTICK_HIDAPI_XBOX360 */
    16.1 --- a/src/joystick/hidapi/SDL_hidapi_xbox360w.c	Mon Mar 16 00:21:22 2020 -0400
    16.2 +++ b/src/joystick/hidapi/SDL_hidapi_xbox360w.c	Mon Mar 16 12:23:38 2020 -0700
    16.3 @@ -231,10 +231,10 @@
    16.4                  if (connected) {
    16.5                      SDL_JoystickID joystickID;
    16.6  
    16.7 -                    HIDAPI_JoystickConnected(device, &joystickID);
    16.8 +                    HIDAPI_JoystickConnected(device, &joystickID, SDL_FALSE);
    16.9  
   16.10                  } else if (device->num_joysticks > 0) {
   16.11 -                    HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
   16.12 +                    HIDAPI_JoystickDisconnected(device, device->joysticks[0], SDL_FALSE);
   16.13                  }
   16.14              }
   16.15          } else if (size == 29 && data[0] == 0x00 && data[1] == 0x0f && data[2] == 0x00 && data[3] == 0xf0) {
   16.16 @@ -262,7 +262,7 @@
   16.17      if (joystick) {
   16.18          if (size < 0) {
   16.19              /* Read error, device is disconnected */
   16.20 -            HIDAPI_JoystickDisconnected(device, joystick->instance_id);
   16.21 +            HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE);
   16.22          }
   16.23      }
   16.24      return (size >= 0);
    17.1 --- a/src/joystick/hidapi/SDL_hidapi_xboxone.c	Mon Mar 16 00:21:22 2020 -0400
    17.2 +++ b/src/joystick/hidapi/SDL_hidapi_xboxone.c	Mon Mar 16 12:23:38 2020 -0700
    17.3 @@ -279,7 +279,7 @@
    17.4  static SDL_bool
    17.5  HIDAPI_DriverXboxOne_InitDevice(SDL_HIDAPI_Device *device)
    17.6  {
    17.7 -    return HIDAPI_JoystickConnected(device, NULL);
    17.8 +    return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE);
    17.9  }
   17.10  
   17.11  static int
   17.12 @@ -694,7 +694,7 @@
   17.13          !ControllerSendsWaitingForInit(device->vendor_id, device->product_id)) {
   17.14          if (SDL_TICKS_PASSED(SDL_GetTicks(), ctx->start_time + CONTROLLER_INIT_DELAY_MS)) {
   17.15              if (!SendControllerInit(device, ctx)) {
   17.16 -                HIDAPI_JoystickDisconnected(device, joystick->instance_id);
   17.17 +                HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE);
   17.18                  return SDL_FALSE;
   17.19              }
   17.20              ctx->initialized = SDL_TRUE;
   17.21 @@ -737,7 +737,7 @@
   17.22                      SDL_Log("Delay after init: %ums\n", SDL_GetTicks() - ctx->start_time);
   17.23  #endif
   17.24                      if (!SendControllerInit(device, ctx)) {
   17.25 -                        HIDAPI_JoystickDisconnected(device, joystick->instance_id);
   17.26 +                        HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE);
   17.27                          return SDL_FALSE;
   17.28                      }
   17.29                      ctx->initialized = SDL_TRUE;
    18.1 --- a/src/joystick/hidapi/SDL_hidapijoystick.c	Mon Mar 16 00:21:22 2020 -0400
    18.2 +++ b/src/joystick/hidapi/SDL_hidapijoystick.c	Mon Mar 16 12:23:38 2020 -0700
    18.3 @@ -37,6 +37,7 @@
    18.4  
    18.5  #if defined(__WIN32__)
    18.6  #include "../../core/windows/SDL_windows.h"
    18.7 +#include "../windows/SDL_rawinputjoystick_c.h"
    18.8  #endif
    18.9  
   18.10  #if defined(__MACOSX__)
   18.11 @@ -419,6 +420,13 @@
   18.12          return NULL;
   18.13      }
   18.14  
   18.15 +#ifdef SDL_JOYSTICK_RAWINPUT
   18.16 +    if (RAWINPUT_IsDevicePresent(device->vendor_id, device->product_id, device->version)) {
   18.17 +        /* The RAWINPUT driver is taking care of this device */
   18.18 +        return NULL;
   18.19 +    }
   18.20 +#endif
   18.21 +
   18.22      if (device->usage_page && device->usage_page != USAGE_PAGE_GENERIC_DESKTOP) {
   18.23          return NULL;
   18.24      }
   18.25 @@ -502,7 +510,7 @@
   18.26  
   18.27      /* Disconnect any joysticks */
   18.28      while (device->num_joysticks) {
   18.29 -        HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
   18.30 +        HIDAPI_JoystickDisconnected(device, device->joysticks[0], SDL_FALSE);
   18.31      }
   18.32  
   18.33      device->driver->FreeDevice(device);
   18.34 @@ -575,6 +583,11 @@
   18.35          return -1;
   18.36      }
   18.37  
   18.38 +#ifdef __WINDOWS__
   18.39 +    /* On Windows, turns out HIDAPI for Xbox controllers doesn't allow background input, so off by default */
   18.40 +    SDL_SetHintWithPriority(SDL_HINT_JOYSTICK_HIDAPI_XBOX, "0", SDL_HINT_DEFAULT);
   18.41 +#endif
   18.42 +
   18.43      for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
   18.44          SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
   18.45          SDL_AddHintCallback(driver->hint, SDL_HIDAPIDriverHintChanged, NULL);
   18.46 @@ -591,7 +604,7 @@
   18.47  }
   18.48  
   18.49  SDL_bool
   18.50 -HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID)
   18.51 +HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID, SDL_bool is_external)
   18.52  {
   18.53      SDL_JoystickID joystickID;
   18.54      SDL_JoystickID *joysticks = (SDL_JoystickID *)SDL_realloc(device->joysticks, (device->num_joysticks + 1)*sizeof(*device->joysticks));
   18.55 @@ -602,7 +615,9 @@
   18.56      joystickID = SDL_GetNextJoystickInstanceID();
   18.57      device->joysticks = joysticks;
   18.58      device->joysticks[device->num_joysticks++] = joystickID;
   18.59 -    ++SDL_HIDAPI_numjoysticks;
   18.60 +    if (!is_external) {
   18.61 +        ++SDL_HIDAPI_numjoysticks;
   18.62 +    }
   18.63  
   18.64      SDL_PrivateJoystickAdded(joystickID);
   18.65  
   18.66 @@ -613,20 +628,22 @@
   18.67  }
   18.68  
   18.69  void
   18.70 -HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID)
   18.71 +HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID, SDL_bool is_external)
   18.72  {
   18.73      int i;
   18.74  
   18.75      for (i = 0; i < device->num_joysticks; ++i) {
   18.76          if (device->joysticks[i] == joystickID) {
   18.77              SDL_Joystick *joystick = SDL_JoystickFromInstanceID(joystickID);
   18.78 -            if (joystick) {
   18.79 +            if (joystick && !is_external) {
   18.80                  HIDAPI_JoystickClose(joystick);
   18.81              }
   18.82  
   18.83              SDL_memmove(&device->joysticks[i], &device->joysticks[i+1], device->num_joysticks - i - 1);
   18.84              --device->num_joysticks;
   18.85 -            --SDL_HIDAPI_numjoysticks;
   18.86 +            if (!is_external) {
   18.87 +                --SDL_HIDAPI_numjoysticks;
   18.88 +            }
   18.89              if (device->num_joysticks == 0) {
   18.90                  SDL_free(device->joysticks);
   18.91                  device->joysticks = NULL;
   18.92 @@ -882,6 +899,7 @@
   18.93  static void
   18.94  HIDAPI_JoystickDetect(void)
   18.95  {
   18.96 +    int i;
   18.97      if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) {
   18.98          HIDAPI_UpdateDiscovery();
   18.99          if (SDL_HIDAPI_discovery.m_bHaveDevicesChanged) {
  18.100 @@ -891,6 +909,12 @@
  18.101          }
  18.102          SDL_AtomicUnlock(&SDL_HIDAPI_spinlock);
  18.103      }
  18.104 +    for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  18.105 +        SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  18.106 +        if (driver->enabled && driver->PostUpdate) {
  18.107 +            driver->PostUpdate();
  18.108 +        }
  18.109 +    }
  18.110  }
  18.111  
  18.112  void
    19.1 --- a/src/joystick/hidapi/SDL_hidapijoystick_c.h	Mon Mar 16 00:21:22 2020 -0400
    19.2 +++ b/src/joystick/hidapi/SDL_hidapijoystick_c.h	Mon Mar 16 12:23:38 2020 -0700
    19.3 @@ -40,8 +40,6 @@
    19.4  #ifdef __WINDOWS__
    19.5  /* On Windows, Xbox One controllers are handled by the Xbox 360 driver */
    19.6  #undef SDL_JOYSTICK_HIDAPI_XBOXONE
    19.7 -/* It turns out HIDAPI for Xbox controllers doesn't allow background input */
    19.8 -#undef SDL_JOYSTICK_HIDAPI_XBOX360
    19.9  #endif
   19.10  
   19.11  #ifdef __MACOSX__
   19.12 @@ -103,6 +101,10 @@
   19.13      int (*RumbleJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble);
   19.14      void (*CloseJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick);
   19.15      void (*FreeDevice)(SDL_HIDAPI_Device *device);
   19.16 +    void (*PostUpdate)(void);
   19.17 +#ifdef SDL_JOYSTICK_RAWINPUT
   19.18 +    void (*HandleStatePacketFromRAWINPUT)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 *data, int size);
   19.19 +#endif
   19.20  
   19.21  } SDL_HIDAPI_DeviceDriver;
   19.22  
   19.23 @@ -120,8 +122,8 @@
   19.24  extern SDL_bool HIDAPI_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name);
   19.25  
   19.26  extern void HIDAPI_UpdateDevices(void);
   19.27 -extern SDL_bool HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID);
   19.28 -extern void HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID);
   19.29 +extern SDL_bool HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID, SDL_bool is_external);
   19.30 +extern void HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID, SDL_bool is_external);
   19.31  
   19.32  #endif /* SDL_JOYSTICK_HIDAPI_H */
   19.33  
    20.1 --- a/src/joystick/windows/SDL_dinputjoystick.c	Mon Mar 16 00:21:22 2020 -0400
    20.2 +++ b/src/joystick/windows/SDL_dinputjoystick.c	Mon Mar 16 12:23:38 2020 -0700
    20.3 @@ -26,6 +26,7 @@
    20.4  
    20.5  #include "SDL_windowsjoystick_c.h"
    20.6  #include "SDL_dinputjoystick_c.h"
    20.7 +#include "SDL_rawinputjoystick_c.h"
    20.8  #include "SDL_xinputjoystick_c.h"
    20.9  #include "../hidapi/SDL_hidapijoystick_c.h"
   20.10  
   20.11 @@ -672,6 +673,14 @@
   20.12      }
   20.13  #endif
   20.14  
   20.15 +#ifdef SDL_JOYSTICK_RAWINPUT
   20.16 +    if (RAWINPUT_IsDevicePresent(vendor, product, 0)) {
   20.17 +        /* The RAWINPUT driver is taking care of this device */
   20.18 +        SDL_free(pNewJoystick);
   20.19 +        return DIENUM_CONTINUE;
   20.20 +    }
   20.21 +#endif
   20.22 +
   20.23      WINDOWS_AddJoystickDevice(pNewJoystick);
   20.24  
   20.25      return DIENUM_CONTINUE; /* get next device, please */
    21.1 --- a/src/joystick/windows/SDL_xinputjoystick.c	Mon Mar 16 00:21:22 2020 -0400
    21.2 +++ b/src/joystick/windows/SDL_xinputjoystick.c	Mon Mar 16 12:23:38 2020 -0700
    21.3 @@ -30,6 +30,7 @@
    21.4  #include "SDL_timer.h"
    21.5  #include "SDL_windowsjoystick_c.h"
    21.6  #include "SDL_xinputjoystick_c.h"
    21.7 +#include "SDL_rawinputjoystick_c.h"
    21.8  #include "../hidapi/SDL_hidapijoystick_c.h"
    21.9  
   21.10  /*
   21.11 @@ -292,6 +293,14 @@
   21.12      }
   21.13  #endif
   21.14  
   21.15 +#ifdef SDL_JOYSTICK_RAWINPUT
   21.16 +    if (RAWINPUT_IsDevicePresent(vendor, product, version)) {
   21.17 +        /* The RAWINPUT driver is taking care of this device */
   21.18 +        SDL_free(pNewJoystick);
   21.19 +        return;
   21.20 +    }
   21.21 +#endif
   21.22 +
   21.23      WINDOWS_AddJoystickDevice(pNewJoystick);
   21.24  }
   21.25  
   21.26 @@ -318,6 +327,18 @@
   21.27          const Uint8 userid = (Uint8)iuserid;
   21.28          XINPUT_CAPABILITIES capabilities;
   21.29          if (XINPUTGETCAPABILITIES(userid, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS) {
   21.30 +            /* Adding a new device, must handle all removes first, or GuessXInputDevice goes terribly wrong (returns
   21.31 +              a product/vendor ID that is not even attached to the system) when we get a remove and add on the same tick
   21.32 +              (e.g. when disconnecting a device and the OS reassigns which userid an already-attached controller is)
   21.33 +            */
   21.34 +            int iuserid2;
   21.35 +            for (iuserid2 = iuserid - 1; iuserid2 >= 0; iuserid2--) {
   21.36 +                const Uint8 userid2 = (Uint8)iuserid2;
   21.37 +                XINPUT_CAPABILITIES capabilities2;
   21.38 +                if (XINPUTGETCAPABILITIES(userid2, XINPUT_FLAG_GAMEPAD, &capabilities2) != ERROR_SUCCESS) {
   21.39 +                    DelXInputDevice(userid2);
   21.40 +                }
   21.41 +            }
   21.42              AddXInputDevice(userid, capabilities.SubType, pContext);
   21.43          } else {
   21.44              DelXInputDevice(userid);
    22.1 --- a/src/video/windows/SDL_windowswindow.c	Mon Mar 16 00:21:22 2020 -0400
    22.2 +++ b/src/video/windows/SDL_windowswindow.c	Mon Mar 16 12:23:38 2020 -0700
    22.3 @@ -30,6 +30,7 @@
    22.4  #include "../../events/SDL_keyboard_c.h"
    22.5  #include "../../events/SDL_mouse_c.h"
    22.6  
    22.7 +#include "../../joystick/windows/SDL_rawinputjoystick_c.h"
    22.8  #include "SDL_windowsvideo.h"
    22.9  #include "SDL_windowswindow.h"
   22.10  #include "SDL_hints.h"
   22.11 @@ -808,9 +809,18 @@
   22.12      }
   22.13  }
   22.14  
   22.15 +static LRESULT CALLBACK SDL_HelperWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
   22.16 +{
   22.17 +#if SDL_JOYSTICK_RAWINPUT
   22.18 +    if (RAWINPUT_WindowProc(hWnd, msg, wParam, lParam) == 0) {
   22.19 +        return 0;
   22.20 +    }
   22.21 +#endif
   22.22 +    return DefWindowProc(hWnd, msg, wParam, lParam);
   22.23 +}
   22.24  
   22.25  /*
   22.26 - * Creates a HelperWindow used for DirectInput events.
   22.27 + * Creates a HelperWindow used for DirectInput and RawInput events.
   22.28   */
   22.29  int
   22.30  SDL_HelperWindowCreate(void)
   22.31 @@ -825,7 +835,7 @@
   22.32  
   22.33      /* Create the class. */
   22.34      SDL_zero(wce);
   22.35 -    wce.lpfnWndProc = DefWindowProc;
   22.36 +    wce.lpfnWndProc = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT, SDL_TRUE) ? SDL_HelperWindowProc : DefWindowProc;
   22.37      wce.lpszClassName = (LPCWSTR) SDL_HelperWindowClassName;
   22.38      wce.hInstance = hInstance;
   22.39