Reworked how/where SDL events are polled:
- poll_joystick_events is now a static member of JoyDevice so it can be
called from outside when needed (preference window for config and
caliration).
- S9xProcessEvents calls JoyDevice::poll_joystick_events directly so
events are polled when no joysticks are attached.
- JoyDevice::poll_joystick_events handles SDL_JOYDEVICE{ADDED,REMOVED}
events.
- Individual JoyDevice no longer call poll_joystick_events from
get_events.
Reworked how attached joysticks are maintained in Snes9xConfig:
- Use a map for joysticks keyed on SDL JoystickID (instance id in sdl
parlance), which is stable while a joystick is attached instead of
an array keyed on device_index.
The instance id is what poll_joystick_events gets with every
event (except for SDL_JOYDEVICEADDED which gets a device_index...)
Instance id is an incrementing int starting from 0, they are never reused.
i.e. each attach/dettach/attach cycle yields a new id.
Whereas device index are reused and can "move".
- On SDL_JOYDEVICEADDED the joystick is handed a "joynum", that is, an
int from 0 to NUM_JOYPADS-1. A new joystick always get the lowest
available joynum.
(joynum was already a member of JoyDevice but wasn't initialized,
this seemed like a proper way to use it.)
- On SDL_JOYDEVICEREMOVED, the joystick associated with the instance
id is simply removed from the map.
All this allows for the following behaviors.
It is possible to start without any joystick, add one joystick and it works.
(disconnect/reconnect cycles with a single joystick also work)
Joystick numbers are "stable" while they remain connected. For example:
- Start with joystick0 and joystick1 connected
- if joystick0 is disconnected, joystick1 keeps its number and keeps
working
- if joystick0 (or any new joystick) is connected at this time,
it gets to become joystick0
If all joysticks are disconnected while snes9x is running, the order of
the "reconnections" will determine the joystick number of each joystick.
I think there is room for improvement still, with regards to code
organization. For instance, there could be a "JoyDevices" class which
would handle all the attached JoyDevice. This would allow moving all the
"joystick_*" methods from Snes9xConfig to that new class, and
poll_joystick_events could also be moved there.
The functionality wouldn't change, but the intent/ownership would probably be clearer.