From 1f2a241688fe890845809008a5f4bd6fff8c4dbf Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Mon, 16 May 2022 09:02:35 -0700 Subject: [PATCH] Add new virtual joysticks to the end of the list This guarantees that the device index that's returned is stable, as long as no joystick hotplug events occur. --- src/joystick/virtual/SDL_virtualjoystick.c | 12 ++++++++++-- test/testgamecontroller.c | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/joystick/virtual/SDL_virtualjoystick.c b/src/joystick/virtual/SDL_virtualjoystick.c index b557d0c67..c54d27307 100644 --- a/src/joystick/virtual/SDL_virtualjoystick.c +++ b/src/joystick/virtual/SDL_virtualjoystick.c @@ -245,8 +245,16 @@ SDL_JoystickAttachVirtualInner(const SDL_VirtualJoystickDesc *desc) hwdata->instance_id = SDL_GetNextJoystickInstanceID(); /* Add virtual joystick to SDL-global lists */ - hwdata->next = g_VJoys; - g_VJoys = hwdata; + if (g_VJoys) { + joystick_hwdata *last; + + for (last = g_VJoys; last->next; last = last->next) { + continue; + } + last->next = hwdata; + } else { + g_VJoys = hwdata; + } SDL_PrivateJoystickAdded(hwdata->instance_id); /* Return the new virtual-device's index */ diff --git a/test/testgamecontroller.c b/test/testgamecontroller.c index 45560c5da..6ccf3b661 100644 --- a/test/testgamecontroller.c +++ b/test/testgamecontroller.c @@ -365,7 +365,7 @@ static void CloseVirtualController() { int i; - for (i = 0; i < SDL_NumJoysticks(); ++i) { + for (i = SDL_NumJoysticks(); i--; ) { if (SDL_JoystickIsVirtual(i)) { SDL_JoystickDetachVirtual(i); }