From fd2f0e3f0dd2573d0dc2941e2b7d161e5836b00b Mon Sep 17 00:00:00 2001 From: staphen Date: Sun, 10 Oct 2021 14:41:03 -0400 Subject: [PATCH] Validate gamepad button count --- Source/controls/devices/game_controller.cpp | 3 ++- Source/controls/devices/joystick.cpp | 5 ++++- Source/utils/sdl2_backports.h | 9 +++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Source/controls/devices/game_controller.cpp b/Source/controls/devices/game_controller.cpp index d7c5ad194..ebe5a5bc2 100644 --- a/Source/controls/devices/game_controller.cpp +++ b/Source/controls/devices/game_controller.cpp @@ -8,6 +8,7 @@ #include "controls/devices/joystick.h" #include "utils/log.hpp" #include "utils/sdl_ptrs.h" +#include "utils/sdl2_backports.h" #include "utils/stubs.h" namespace devilution { @@ -123,7 +124,7 @@ SDL_GameControllerButton GameController::ToSdlGameControllerButton(ControllerBut bool GameController::IsPressed(ControllerButton button) const { const SDL_GameControllerButton gcButton = ToSdlGameControllerButton(button); - return gcButton != SDL_CONTROLLER_BUTTON_INVALID && SDL_GameControllerGetButton(sdl_game_controller_, gcButton) != 0; + return SDL_GameControllerHasButton(sdl_game_controller_, gcButton) && SDL_GameControllerGetButton(sdl_game_controller_, gcButton) != 0; } bool GameController::ProcessAxisMotion(const SDL_Event &event) diff --git a/Source/controls/devices/joystick.cpp b/Source/controls/devices/joystick.cpp index 563be4c97..a834d727a 100644 --- a/Source/controls/devices/joystick.cpp +++ b/Source/controls/devices/joystick.cpp @@ -210,7 +210,10 @@ bool Joystick::IsPressed(ControllerButton button) const if (IsHatButtonPressed(button)) return true; const int joyButton = ToSdlJoyButton(button); - return joyButton != -1 && SDL_JoystickGetButton(sdl_joystick_, joyButton) != 0; + if (joyButton == -1) + return false; + const int numButtons = SDL_JoystickNumButtons(sdl_joystick_); + return joyButton < numButtons && SDL_JoystickGetButton(sdl_joystick_, joyButton) != 0; } bool Joystick::ProcessAxisMotion(const SDL_Event &event) diff --git a/Source/utils/sdl2_backports.h b/Source/utils/sdl2_backports.h index 2b5bd9dd2..f1c3f584d 100644 --- a/Source/utils/sdl2_backports.h +++ b/Source/utils/sdl2_backports.h @@ -49,3 +49,12 @@ SDL_CreateRGBSurfaceWithFormatFrom(void *pixels, return surface; } #endif + +#if !SDL_VERSION_ATLEAST(2, 0, 14) +inline SDL_bool +SDL_GameControllerHasButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button) +{ + SDL_GameControllerButtonBind bind = SDL_GameControllerGetBindForButton(gamecontroller, button); + return (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE) ? SDL_TRUE : SDL_FALSE; +} +#endif