joystick cleanups #444

Check that SDL reports any available controls for a joystick, otherwise
mark it invalid and close it.

When processing events for joysticks, check that each one is valid.

Set initial value of controls to zero initially not after getting the
initial state, previously we were getting the initial state and
overwriting it with zeroes, defeating the purpose.

Fix memory leak, `curval` array of controls not being cleared.

Signed-off-by: Rafael Kitover <rkitover@gmail.com>
This commit is contained in:
Rafael Kitover 2019-06-24 20:28:07 +00:00
parent 684b1bb7aa
commit 9fa20b49ca
No known key found for this signature in database
GPG Key ID: 08AB596679D86240
1 changed files with 21 additions and 3 deletions

View File

@ -9,16 +9,20 @@ struct wxSDLJoyState {
SDL_Joystick* dev;
int nax, nhat, nbut;
short* curval;
bool is_valid;
~wxSDLJoyState()
{
if (dev)
SDL_JoystickClose(dev);
if (curval)
delete[] curval;
}
wxSDLJoyState()
{
dev = NULL;
nax = nhat = nbut = 0;
curval = NULL;
is_valid = true;
}
};
@ -46,12 +50,26 @@ wxSDLJoy::wxSDLJoy(bool analog)
for (int i = 0; i < njoy; i++) {
SDL_Joystick* dev = joystate[i].dev = SDL_JoystickOpen(i);
int nctrl = 0;
nctrl += joystate[i].nax = SDL_JoystickNumAxes(dev);
nctrl += joystate[i].nax = SDL_JoystickNumAxes(dev);
nctrl += joystate[i].nhat = SDL_JoystickNumHats(dev);
nctrl += joystate[i].nbut = SDL_JoystickNumButtons(dev);
if (!nctrl) {
joystate[i].is_valid = false;
SDL_JoystickClose(dev);
joystate[i].dev = NULL;
continue;
}
joystate[i].curval = new short[nctrl]{0};
// clear controls
memset(joystate[i].curval, 0, sizeof(short) * nctrl);
// initialize axis previous value to initial state
#if SDL_VERSION_ATLEAST(2, 0, 6)
for (int j = 0; j < joystate[i].nax; j++) {
@ -60,8 +78,6 @@ wxSDLJoy::wxSDLJoy(bool analog)
joystate[i].curval[j] = initial_state;
}
#endif
memset(joystate[i].curval, 0, sizeof(short) * nctrl);
}
}
@ -139,6 +155,8 @@ void wxSDLJoy::Notify()
wxEvtHandler* handler = evthandler ? evthandler : wxWindow::FindFocus();
for (int i = 0; i < njoy; i++) {
if (!joystate[i].is_valid) continue;
SDL_Joystick* dev = joystate[i].dev;
if (dev) {