Fixed some subtle bugs with SDL2 joystick changes.

Removed platform-specific input device list polling.
Now we use SDL2's handy SDL_JOYDEVICEADDED event.
This commit is contained in:
Aloshi 2013-08-19 09:05:30 -05:00
parent 5b1cd8fbf8
commit 1418f85ba7
6 changed files with 77 additions and 247 deletions

View file

@ -6,29 +6,11 @@
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include "platform.h" #include "platform.h"
#if defined(WIN32) || defined(_WIN32)
#include <Windows.h>
#endif
namespace fs = boost::filesystem; namespace fs = boost::filesystem;
//----- InputDevice ----------------------------------------------------------------------------
InputDevice::InputDevice(const std::string & deviceName, unsigned long vendorId, unsigned long productId)
: name(deviceName), vendor(vendorId), product(productId)
{
}
bool InputDevice::operator==(const InputDevice & b) const
{
return (name == b.name && vendor == b.vendor && product == b.product);
}
//----- InputManager ---------------------------------------------------------------------------
InputManager::InputManager(Window* window) : mWindow(window), InputManager::InputManager(Window* window) : mWindow(window),
mJoysticks(NULL), mInputConfigs(NULL), mKeyboardInputConfig(NULL), mPrevAxisValues(NULL), mKeyboardInputConfig(NULL),
mNumJoysticks(0), mNumPlayers(0), devicePollingTimer(NULL) mNumJoysticks(0), mNumPlayers(0)
{ {
} }
@ -37,188 +19,69 @@ InputManager::~InputManager()
deinit(); deinit();
} }
std::vector<InputDevice> InputManager::getInputDevices() const
{
std::vector<InputDevice> currentDevices;
//retrieve all input devices from system
#if defined (__APPLE__)
#error TODO: Not implemented for MacOS yet!!!
#elif defined(__linux__)
//open linux input devices file system
const std::string inputPath("/dev/input");
fs::directory_iterator dirIt(inputPath);
while (dirIt != fs::directory_iterator()) {
//get directory entry
std::string deviceName = (*dirIt).path().string();
//remove parent path
deviceName.erase(0, inputPath.length() + 1);
//check if it start with "js"
if (deviceName.length() >= 3 && deviceName.find("js") == 0) {
//looks like a joystick. add to devices.
currentDevices.push_back(InputDevice(deviceName, 0, 0));
}
++dirIt;
}
//or dump /proc/bus/input/devices anbd search for a Handler=..."js"... entry
#elif defined(WIN32) || defined(_WIN32)
RAWINPUTDEVICELIST * deviceList = nullptr;
UINT nrOfDevices = 0;
//get number of input devices
if (GetRawInputDeviceList(deviceList, &nrOfDevices, sizeof(RAWINPUTDEVICELIST)) != -1 && nrOfDevices > 0)
{
//get list of input devices
deviceList = new RAWINPUTDEVICELIST[nrOfDevices];
if (GetRawInputDeviceList(deviceList, &nrOfDevices, sizeof(RAWINPUTDEVICELIST)) != -1)
{
//loop through input devices
for (unsigned int i = 0; i < nrOfDevices; i++)
{
//get device name
char * rawName = new char[2048];
UINT rawNameSize = 2047;
GetRawInputDeviceInfo(deviceList[i].hDevice, RIDI_DEVICENAME, (void *)rawName, &rawNameSize);
//null-terminate string
rawName[rawNameSize] = '\0';
//convert to string
std::string deviceName = rawName;
delete [] rawName;
//get deviceType
RID_DEVICE_INFO deviceInfo;
UINT deviceInfoSize = sizeof(RID_DEVICE_INFO);
GetRawInputDeviceInfo(deviceList[i].hDevice, RIDI_DEVICEINFO, (void *)&deviceInfo, &deviceInfoSize);
//check if it is a HID. we ignore keyboards and mice...
if (deviceInfo.dwType == RIM_TYPEHID)
{
//check if the vendor/product already exists in list. yes. could be more elegant...
std::vector<InputDevice>::const_iterator cdIt = currentDevices.cbegin();
while (cdIt != currentDevices.cend())
{
if (cdIt->name == deviceName && cdIt->product == deviceInfo.hid.dwProductId && cdIt->vendor == deviceInfo.hid.dwVendorId)
{
//device already there
break;
}
++cdIt;
}
//was the device found?
if (cdIt == currentDevices.cend())
{
//no. add it.
currentDevices.push_back(InputDevice(deviceName, deviceInfo.hid.dwProductId, deviceInfo.hid.dwVendorId));
}
}
}
}
delete [] deviceList;
}
#endif
return currentDevices;
}
Uint32 InputManager::devicePollingCallback(Uint32 interval, void* param)
{
//this thing my be running in a different thread, so we're not allowed to call
//any functions or change/allocate/delete stuff, but can send a user event
SDL_Event event;
event.user.type = SDL_USEREVENT;
event.user.code = SDL_USEREVENT_POLLDEVICES;
event.user.data1 = nullptr;
event.user.data2 = nullptr;
if (!SDL_PushEvent(&event)) {
LOG(LogError) << "InputManager::devicePollingCallback - SDL event queue is full!";
}
return interval;
}
void InputManager::init() void InputManager::init()
{ {
if(mJoysticks != NULL) if(initialized())
deinit(); deinit();
//get current input devices from system SDL_InitSubSystem(SDL_INIT_JOYSTICK);
inputDevices = getInputDevices();
SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_TIMER);
mNumJoysticks = SDL_NumJoysticks(); mNumJoysticks = SDL_NumJoysticks();
mJoysticks = new SDL_Joystick*[mNumJoysticks];
mInputConfigs = new InputConfig*[mNumJoysticks];
mPrevAxisValues = new std::map<int, int>[mNumJoysticks];
for(int i = 0; i < mNumJoysticks; i++) for(int i = 0; i < mNumJoysticks; i++)
{ {
mJoysticks[i] = SDL_JoystickOpen(i); SDL_Joystick* joy = SDL_JoystickOpen(i);
mInputConfigs[i] = new InputConfig(i, SDL_JoystickName(mJoysticks[i])); SDL_JoystickID joyId = SDL_JoystickInstanceID(joy);
mJoysticks.push_back(joy);
mInputConfigs[joyId] = new InputConfig(i, SDL_JoystickName(joy));
for(int k = 0; k < SDL_JoystickNumAxes(mJoysticks[i]); k++) int numAxes = SDL_JoystickNumAxes(joy);
{ mPrevAxisValues[joyId] = new int[numAxes];
mPrevAxisValues[i][k] = 0; std::fill(mPrevAxisValues[joyId], mPrevAxisValues[joyId] + numAxes, 0); //initialize array to 0
}
} }
mKeyboardInputConfig = new InputConfig(DEVICE_KEYBOARD, "Keyboard"); mKeyboardInputConfig = new InputConfig(DEVICE_KEYBOARD, "Keyboard");
SDL_JoystickEventState(SDL_ENABLE);
//start timer for input device polling
startPolling();
loadConfig(); loadConfig();
}
void InputManager::startPolling() SDL_JoystickEventState(SDL_ENABLE);
{
if(devicePollingTimer != NULL)
return;
devicePollingTimer = SDL_AddTimer(POLLING_INTERVAL, devicePollingCallback, (void *)this);
}
void InputManager::stopPolling()
{
if(devicePollingTimer == NULL)
return;
SDL_RemoveTimer(devicePollingTimer);
devicePollingTimer = NULL;
} }
void InputManager::deinit() void InputManager::deinit()
{ {
stopPolling();
SDL_JoystickEventState(SDL_DISABLE); SDL_JoystickEventState(SDL_DISABLE);
if(!SDL_WasInit(SDL_INIT_JOYSTICK)) if(!initialized())
return; return;
if(mJoysticks != NULL) for(auto iter = mJoysticks.begin(); iter != mJoysticks.end(); iter++)
{ {
for(int i = 0; i < mNumJoysticks; i++) SDL_JoystickClose(*iter);
{
SDL_JoystickClose(mJoysticks[i]);
delete mInputConfigs[i];
} }
delete[] mInputConfigs; mJoysticks.clear();
mInputConfigs = NULL;
delete[] mJoysticks; for(auto iter = mInputConfigs.begin(); iter != mInputConfigs.end(); iter++)
mJoysticks = NULL; {
delete iter->second;
}
mInputConfigs.clear();
for(auto iter = mPrevAxisValues.begin(); iter != mPrevAxisValues.end(); iter++)
{
delete[] iter->second;
}
mPrevAxisValues.clear();
if(mKeyboardInputConfig != NULL)
{
delete mKeyboardInputConfig; delete mKeyboardInputConfig;
mKeyboardInputConfig = NULL; mKeyboardInputConfig = NULL;
delete[] mPrevAxisValues;
mPrevAxisValues = NULL;
} }
SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_TIMER); SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
inputDevices.clear();
} }
int InputManager::getNumJoysticks() { return mNumJoysticks; } int InputManager::getNumJoysticks() { return mNumJoysticks; }
@ -233,7 +96,7 @@ int InputManager::getButtonCountByDevice(int id)
int InputManager::getNumPlayers() { return mNumPlayers; } int InputManager::getNumPlayers() { return mNumPlayers; }
void InputManager::setNumPlayers(int num) { mNumPlayers = num; } void InputManager::setNumPlayers(int num) { mNumPlayers = num; }
InputConfig* InputManager::getInputConfigByDevice(int device) InputConfig* InputManager::getInputConfigByDevice(SDL_JoystickID device)
{ {
if(device == DEVICE_KEYBOARD) if(device == DEVICE_KEYBOARD)
return mKeyboardInputConfig; return mKeyboardInputConfig;
@ -246,10 +109,12 @@ InputConfig* InputManager::getInputConfigByPlayer(int player)
if(mKeyboardInputConfig->getPlayerNum() == player) if(mKeyboardInputConfig->getPlayerNum() == player)
return mKeyboardInputConfig; return mKeyboardInputConfig;
for(int i = 0; i < mNumJoysticks; i++) for(auto iter = mInputConfigs.begin(); iter != mInputConfigs.end(); iter++)
{ {
if(mInputConfigs[i]->getPlayerNum() == player) if(iter->second->getPlayerNum() == player)
return mInputConfigs[i]; {
return iter->second;
}
} }
LOG(LogError) << "Could not find input config for player number " << player << "!"; LOG(LogError) << "Could not find input config for player number " << player << "!";
@ -306,28 +171,18 @@ bool InputManager::parseEvent(const SDL_Event& ev)
mWindow->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 0, false)); mWindow->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 0, false));
return true; return true;
case SDL_USEREVENT: case SDL_JOYDEVICEADDED:
if (ev.user.code == SDL_USEREVENT_POLLDEVICES) {
//poll joystick / HID again
std::vector<InputDevice> currentDevices = getInputDevices();
//compare device lists to see if devices were added/deleted
if (currentDevices != inputDevices) {
LOG(LogInfo) << "Device configuration changed!";
inputDevices = currentDevices;
//deinit and reinit InputManager
deinit(); deinit();
init(); init();
}
return true; return true;
} }
}
return false; return false;
} }
void InputManager::loadConfig() void InputManager::loadConfig()
{ {
if(!mJoysticks) if(!initialized())
{ {
LOG(LogError) << "ERROR - cannot load InputManager config without being initialized!"; LOG(LogError) << "ERROR - cannot load InputManager config without being initialized!";
} }
@ -348,10 +203,11 @@ void InputManager::loadConfig()
mNumPlayers = 0; mNumPlayers = 0;
bool* configuredDevice = new bool[mNumJoysticks]; bool* configuredDevice = new bool[mNumJoysticks];
for(int i = 0; i < mNumJoysticks; i++) std::fill(configuredDevice, configuredDevice + mNumJoysticks, false);
for(auto iter = mInputConfigs.begin(); iter != mInputConfigs.end(); iter++)
{ {
mInputConfigs[i]->setPlayerNum(-1); iter->second->setPlayerNum(-1);
configuredDevice[i] = false;
} }
pugi::xml_node root = doc.child("inputList"); pugi::xml_node root = doc.child("inputList");
@ -372,7 +228,8 @@ void InputManager::loadConfig()
{ {
if(!configuredDevice[i] && SDL_JoystickName(mJoysticks[i]) == devName) if(!configuredDevice[i] && SDL_JoystickName(mJoysticks[i]) == devName)
{ {
mInputConfigs[i]->loadFromXML(node, mNumPlayers); SDL_JoystickID joyId = SDL_JoystickInstanceID(mJoysticks[i]);
mInputConfigs[joyId]->loadFromXML(node, mNumPlayers);
mNumPlayers++; mNumPlayers++;
found = true; found = true;
configuredDevice[i] = true; configuredDevice[i] = true;
@ -423,14 +280,11 @@ void InputManager::loadDefaultConfig()
cfg->mapInput("mastervolup", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_PLUS, 1, true)); cfg->mapInput("mastervolup", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_PLUS, 1, true));
cfg->mapInput("mastervoldown", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_MINUS, 1, true)); cfg->mapInput("mastervoldown", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_MINUS, 1, true));
cfg->mapInput("sortordernext", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F7, 1, true));
cfg->mapInput("sortorderprevious", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F8, 1, true));
} }
void InputManager::writeConfig() void InputManager::writeConfig()
{ {
if(!mJoysticks) if(!initialized())
{ {
LOG(LogError) << "ERROR - cannot write config without being initialized!"; LOG(LogError) << "ERROR - cannot write config without being initialized!";
return; return;
@ -457,3 +311,8 @@ std::string InputManager::getConfigPath()
path += "/.emulationstation/es_input.cfg"; path += "/.emulationstation/es_input.cfg";
return path; return path;
} }
bool InputManager::initialized() const
{
return mKeyboardInputConfig != NULL;
}

View file

@ -9,16 +9,6 @@
class InputConfig; class InputConfig;
class Window; class Window;
struct InputDevice
{
std::string name;
unsigned long vendor;
unsigned long product;
InputDevice(const std::string & deviceName, unsigned long vendorId, unsigned long productId);
bool operator==(const InputDevice & b) const;
};
//you should only ever instantiate one of these, by the way //you should only ever instantiate one of these, by the way
class InputManager class InputManager
{ {
@ -26,38 +16,23 @@ class InputManager
Window* mWindow; Window* mWindow;
//non-InputManager classes shouldn't use this, as you can easily miss the keyboard //non-InputManager classes shouldn't use this, as you can easily miss the keyboard and don't have SDL_JoystickIDs
InputConfig* getInputConfigByDevice(int device); InputConfig* getInputConfigByDevice(SDL_JoystickID device);
void loadDefaultConfig(); void loadDefaultConfig();
int mNumJoysticks; int mNumJoysticks;
int mNumPlayers; int mNumPlayers;
SDL_Joystick** mJoysticks;
InputConfig** mInputConfigs; std::vector<SDL_Joystick*> mJoysticks;
std::map<SDL_JoystickID, InputConfig*> mInputConfigs;
InputConfig* mKeyboardInputConfig; InputConfig* mKeyboardInputConfig;
std::map<int, int>* mPrevAxisValues;
std::vector<InputDevice> inputDevices; std::map<SDL_JoystickID, int*> mPrevAxisValues;
/*! bool initialized() const;
Retrieve joysticks/ HID devices from system.
\return Returns a list of InputDevices that can be compared to the current /inputDevices to check if the configuration has changed.
\note This currently reads the content of the /dev/input on linux, searches for "js**" names and stores those. On Windows it uses GetRawInputDeviceInfo to find devices of type RIM_TYPEHID and stores those.
*/
std::vector<InputDevice> getInputDevices() const;
static const int POLLING_INTERVAL = 5000;
SDL_TimerID devicePollingTimer;
/*!
Called when devicePollingTimer runs out. Sends a SDL_UserEvent with type SDL_USEREVENT_POLLDEVICES to the event queue.
*/
static Uint32 devicePollingCallback(Uint32 interval, void * param);
public: public:
static const int SDL_USEREVENT_POLLDEVICES = SDL_USEREVENT + 100; //This event is issued when the input devices should be rescanned.
InputManager(Window* window); InputManager(Window* window);
~InputManager(); ~InputManager();
@ -77,9 +52,6 @@ public:
bool parseEvent(const SDL_Event& ev); bool parseEvent(const SDL_Event& ev);
InputConfig* getInputConfigByPlayer(int player); InputConfig* getInputConfigByPlayer(int player);
void startPolling();
void stopPolling();
}; };
#endif #endif

View file

@ -44,10 +44,6 @@ bool GuiDetectDevice::input(InputConfig* config, Input input)
if(!input.value) if(!input.value)
return false; return false;
//don't allow device list to change once the first player has registered
if(mCurrentPlayer == 0)
mWindow->getInputManager()->stopPolling();
config->setPlayerNum(mCurrentPlayer); config->setPlayerNum(mCurrentPlayer);
mWindow->getInputManager()->setNumPlayers(mWindow->getInputManager()->getNumPlayers() + 1); //inc total number of players mWindow->getInputManager()->setNumPlayers(mWindow->getInputManager()->getNumPlayers() + 1); //inc total number of players
mCurrentPlayer++; mCurrentPlayer++;

View file

@ -38,7 +38,6 @@ bool GuiInputConfig::input(InputConfig* config, Input input)
mWindow->pushGui(new GuiInputConfig(mWindow, mWindow->getInputManager()->getInputConfigByPlayer(mTargetConfig->getPlayerNum() + 1))); mWindow->pushGui(new GuiInputConfig(mWindow, mWindow->getInputManager()->getInputConfigByPlayer(mTargetConfig->getPlayerNum() + 1)));
}else{ }else{
mWindow->getInputManager()->writeConfig(); mWindow->getInputManager()->writeConfig();
mWindow->getInputManager()->startPolling(); //enable polling again since we're done
GuiGameList::create(mWindow); GuiGameList::create(mWindow);
} }
delete this; delete this;

View file

@ -16,6 +16,8 @@ void TextEditComponent::onFocusGained()
mBox.setHorizontalImage(":/glow_hor.png"); mBox.setHorizontalImage(":/glow_hor.png");
mBox.setVerticalImage(":/glow_vert.png"); mBox.setVerticalImage(":/glow_vert.png");
mBox.setBorderColor(0x51CCFFFF); mBox.setBorderColor(0x51CCFFFF);
SDL_StartTextInput();
} }
void TextEditComponent::onFocusLost() void TextEditComponent::onFocusLost()
@ -23,6 +25,8 @@ void TextEditComponent::onFocusLost()
mBox.setHorizontalImage(":/glow_off_hor.png"); mBox.setHorizontalImage(":/glow_off_hor.png");
mBox.setVerticalImage(":/glow_off_vert.png"); mBox.setVerticalImage(":/glow_off_vert.png");
mBox.setBorderColor(0xFFFFFFFF); mBox.setBorderColor(0xFFFFFFFF);
SDL_StopTextInput();
} }
void TextEditComponent::onSizeChanged() void TextEditComponent::onSizeChanged()

View file

@ -193,16 +193,16 @@ int main(int argc, char* argv[])
case SDL_KEYDOWN: case SDL_KEYDOWN:
case SDL_KEYUP: case SDL_KEYUP:
case SDL_JOYAXISMOTION: case SDL_JOYAXISMOTION:
case SDL_TEXTINPUT:
case SDL_TEXTEDITING:
case SDL_JOYDEVICEADDED:
case SDL_JOYDEVICEREMOVED:
if(window.getInputManager()->parseEvent(event)) if(window.getInputManager()->parseEvent(event))
{ {
sleeping = false; sleeping = false;
timeSinceLastEvent = 0; timeSinceLastEvent = 0;
} }
break; break;
case SDL_USEREVENT:
//try to poll input devices, but do not necessarily wake up...
window.getInputManager()->parseEvent(event);
break;
case SDL_QUIT: case SDL_QUIT:
running = false; running = false;
break; break;
@ -243,7 +243,7 @@ int main(int argc, char* argv[])
Log::flush(); Log::flush();
} }
Renderer::deinit(); window.deinit();
SystemData::deleteSystems(); SystemData::deleteSystems();
std::cout << "EmulationStation cleanly shutting down...\n"; std::cout << "EmulationStation cleanly shutting down...\n";