From 7262f1e7e9ea88a021c14de9dc06ebe76112afd7 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Mon, 19 Sep 2016 23:39:14 +0300 Subject: [PATCH] Enumerate available game controllers Assign indices from zero to N-1 internally. This makes it easier for applications to use game controllers as the first available controller will always have index zero. --- source/input/gamecontroller.cpp | 18 ++++++++++++++ source/input/gamecontroller.h | 6 +++++ source/input/generic/gamecontroller.cpp | 6 +++++ source/input/linux/gamecontroller.cpp | 26 +++++++++++++++++++- source/input/linux/gamecontroller_platform.h | 2 ++ 5 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 source/input/gamecontroller.cpp diff --git a/source/input/gamecontroller.cpp b/source/input/gamecontroller.cpp new file mode 100644 index 0000000..1ad8757 --- /dev/null +++ b/source/input/gamecontroller.cpp @@ -0,0 +1,18 @@ +#include "gamecontroller.h" + +namespace Msp { +namespace Input { + +bool GameController::detect_done = false; +unsigned GameController::n_detected_controllers = 0; + +bool GameController::is_available(unsigned index) +{ + if(!detect_done) + detect(); + + return index #include #include +#include #include #include #include "gamecontroller.h" @@ -11,10 +12,17 @@ using namespace std; namespace Msp { namespace Input { +vector GameController::Private::detected_controllers; + GameController::GameController(unsigned index): event_disp(0) { - JsDevice *device = new JsDevice(format("/dev/input/js%d", index)); + if(!detect_done) + detect(); + if(index>=Private::detected_controllers.size()) + throw device_not_available(format("GameController(%d)", index)); + + JsDevice *device = new JsDevice(Private::detected_controllers[index]); priv = new Private; priv->dev = device; @@ -29,6 +37,22 @@ GameController::~GameController() delete priv; } +unsigned GameController::detect() +{ + Private::detected_controllers.clear(); + + FS::Path dev_input = "/dev/input"; + list devices = FS::list_filtered(dev_input, "^js[0-9]+"); + for(list::const_iterator i=devices.begin(); i!=devices.end(); ++i) + // TODO check permissions + Private::detected_controllers.push_back((dev_input / *i).str()); + + detect_done = true; + n_detected_controllers = Private::detected_controllers.size(); + + return Private::detected_controllers.size(); +} + void GameController::use_event_dispatcher(IO::EventDispatcher *ed) { if(event_disp) diff --git a/source/input/linux/gamecontroller_platform.h b/source/input/linux/gamecontroller_platform.h index cd63839..2951076 100644 --- a/source/input/linux/gamecontroller_platform.h +++ b/source/input/linux/gamecontroller_platform.h @@ -30,6 +30,8 @@ public: struct GameController::Private { JsDevice *dev; + + static std::vector detected_controllers; }; } // namespace Input -- 2.45.2