Skip to content

Commit

Permalink
joystick cleanups #444
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
rkitover committed Jun 24, 2019
1 parent 684b1bb commit 9fa20b4
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/wx/widgets/sdljoy.cpp
Expand Up @@ -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;
}
};

Expand Down Expand Up @@ -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++) {
Expand All @@ -60,8 +78,6 @@ wxSDLJoy::wxSDLJoy(bool analog)
joystate[i].curval[j] = initial_state;
}
#endif

memset(joystate[i].curval, 0, sizeof(short) * nctrl);
}
}

Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 9fa20b4

Please sign in to comment.