Update in-flight SDL_CONTROLLERDEVICEADDED messages when a device is removed This fixes the application trying to open the wrong device index when a device is removed and another has just been added
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c
index 931aa9e..78ac096 100644
--- a/src/joystick/SDL_joystick.c
+++ b/src/joystick/SDL_joystick.c
@@ -1331,13 +1331,13 @@ void SDL_PrivateJoystickAdded(SDL_JoystickID device_instance)
* to have the right value for which, because the number of controllers in
* the system is now one less.
*/
-static void UpdateEventsForDeviceRemoval(int device_index)
+static void UpdateEventsForDeviceRemoval(int device_index, Uint32 type)
{
int i, num_events;
SDL_Event *events;
SDL_bool isstack;
- num_events = SDL_PeepEvents(NULL, 0, SDL_PEEKEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEADDED);
+ num_events = SDL_PeepEvents(NULL, 0, SDL_PEEKEVENT, type, type);
if (num_events <= 0) {
return;
}
@@ -1347,20 +1347,38 @@ static void UpdateEventsForDeviceRemoval(int device_index)
return;
}
- num_events = SDL_PeepEvents(events, num_events, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEADDED);
+ num_events = SDL_PeepEvents(events, num_events, SDL_GETEVENT, type, type);
for (i = 0; i < num_events; ++i) {
- if (events[i].cdevice.which < device_index) {
- /* No change for index values lower than the removed device */
+ Sint32 which = -1;
+ switch (type) {
+ case SDL_JOYDEVICEADDED:
+ which = events[i].jdevice.which;
+ break;
+ case SDL_CONTROLLERDEVICEADDED:
+ which = events[i].cdevice.which;
+ break;
+ default:
+ break;
}
- else if (events[i].cdevice.which == device_index) {
+ if (which < device_index) {
+ /* No change for index values lower than the removed device */
+ } else if (which == device_index) {
/* Drop this event entirely */
SDL_memmove(&events[i], &events[i + 1], sizeof(*events) * (num_events - (i + 1)));
--num_events;
--i;
- }
- else {
+ } else {
/* Fix up the device index if greater than the removed device */
- --events[i].cdevice.which;
+ switch (type) {
+ case SDL_JOYDEVICEADDED:
+ --events[i].jdevice.which;
+ break;
+ case SDL_CONTROLLERDEVICEADDED:
+ --events[i].cdevice.which;
+ break;
+ default:
+ break;
+ }
}
}
SDL_PeepEvents(events, num_events, SDL_ADDEVENT, 0, 0);
@@ -1427,7 +1445,8 @@ void SDL_PrivateJoystickRemoved(SDL_JoystickID device_instance)
SDL_PushEvent(&event);
}
- UpdateEventsForDeviceRemoval(device_index);
+ UpdateEventsForDeviceRemoval(device_index, SDL_JOYDEVICEADDED);
+ UpdateEventsForDeviceRemoval(device_index, SDL_CONTROLLERDEVICEADDED);
#endif /* !SDL_EVENTS_DISABLED */
SDL_LockJoysticks();