SDL_sysjoystick.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_JOYSTICK_LINUX
  20. #ifndef SDL_INPUT_LINUXEV
  21. #error SDL now requires a Linux 2.4+ kernel with /dev/input/event support.
  22. #endif
  23. /* This is the Linux implementation of the SDL joystick API */
  24. #include <sys/stat.h>
  25. #include <errno.h> /* errno, strerror */
  26. #include <fcntl.h>
  27. #include <limits.h> /* For the definition of PATH_MAX */
  28. #ifdef HAVE_INOTIFY
  29. #include <sys/inotify.h>
  30. #include <string.h> /* strerror */
  31. #endif
  32. #include <sys/ioctl.h>
  33. #include <unistd.h>
  34. #include <dirent.h>
  35. #include <linux/joystick.h>
  36. #include "../../events/SDL_events_c.h"
  37. #include "../../core/linux/SDL_evdev.h"
  38. #include "../SDL_sysjoystick.h"
  39. #include "../SDL_joystick_c.h"
  40. #include "../steam/SDL_steamcontroller.h"
  41. #include "SDL_sysjoystick_c.h"
  42. #include "../hidapi/SDL_hidapijoystick_c.h"
  43. /* This isn't defined in older Linux kernel headers */
  44. #ifndef SYN_DROPPED
  45. #define SYN_DROPPED 3
  46. #endif
  47. #ifndef BTN_NORTH
  48. #define BTN_NORTH 0x133
  49. #endif
  50. #ifndef BTN_WEST
  51. #define BTN_WEST 0x134
  52. #endif
  53. #ifndef BTN_DPAD_UP
  54. #define BTN_DPAD_UP 0x220
  55. #endif
  56. #ifndef BTN_DPAD_DOWN
  57. #define BTN_DPAD_DOWN 0x221
  58. #endif
  59. #ifndef BTN_DPAD_LEFT
  60. #define BTN_DPAD_LEFT 0x222
  61. #endif
  62. #ifndef BTN_DPAD_RIGHT
  63. #define BTN_DPAD_RIGHT 0x223
  64. #endif
  65. #include "../../core/linux/SDL_evdev_capabilities.h"
  66. #include "../../core/linux/SDL_udev.h"
  67. #include "../../core/linux/SDL_sandbox.h"
  68. #if 0
  69. #define DEBUG_INPUT_EVENTS 1
  70. #endif
  71. #if 0
  72. #define DEBUG_GAMEPAD_MAPPING 1
  73. #endif
  74. typedef enum
  75. {
  76. ENUMERATION_UNSET,
  77. ENUMERATION_LIBUDEV,
  78. ENUMERATION_FALLBACK
  79. } EnumerationMethod;
  80. static EnumerationMethod enumeration_method = ENUMERATION_UNSET;
  81. static SDL_bool IsJoystickJSNode(const char *node);
  82. static int MaybeAddDevice(const char *path);
  83. static int MaybeRemoveDevice(const char *path);
  84. /* A linked list of available joysticks */
  85. typedef struct SDL_joylist_item
  86. {
  87. SDL_JoystickID device_instance;
  88. char *path; /* "/dev/input/event2" or whatever */
  89. char *name; /* "SideWinder 3D Pro" or whatever */
  90. SDL_JoystickGUID guid;
  91. dev_t devnum;
  92. struct joystick_hwdata *hwdata;
  93. struct SDL_joylist_item *next;
  94. /* Steam Controller support */
  95. SDL_bool m_bSteamController;
  96. SDL_bool checked_mapping;
  97. SDL_GamepadMapping *mapping;
  98. } SDL_joylist_item;
  99. static SDL_bool SDL_classic_joysticks = SDL_FALSE;
  100. static SDL_joylist_item *SDL_joylist = NULL;
  101. static SDL_joylist_item *SDL_joylist_tail = NULL;
  102. static int numjoysticks = 0;
  103. static int inotify_fd = -1;
  104. static Uint64 last_joy_detect_time;
  105. static time_t last_input_dir_mtime;
  106. static void FixupDeviceInfoForMapping(int fd, struct input_id *inpid)
  107. {
  108. if (inpid->vendor == 0x045e && inpid->product == 0x0b05 && inpid->version == 0x0903) {
  109. /* This is a Microsoft Xbox One Elite Series 2 controller */
  110. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  111. /* The first version of the firmware duplicated all the inputs */
  112. if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) &&
  113. test_bit(0x2c0, keybit)) {
  114. /* Change the version to 0x0902, so we can map it differently */
  115. inpid->version = 0x0902;
  116. }
  117. }
  118. /* For Atari vcs modern and classic controllers have the version reflecting
  119. * firmware version, but the mapping stays stable so ignore
  120. * version information */
  121. if (inpid->vendor == 0x3250 && (inpid->product == 0x1001 || inpid->product == 0x1002)) {
  122. inpid->version = 0;
  123. }
  124. }
  125. #ifdef SDL_JOYSTICK_HIDAPI
  126. static SDL_bool IsVirtualJoystick(Uint16 vendor, Uint16 product, Uint16 version, const char *name)
  127. {
  128. if (vendor == USB_VENDOR_MICROSOFT && product == USB_PRODUCT_XBOX_ONE_S && version == 0 &&
  129. SDL_strcmp(name, "Xbox One S Controller") == 0) {
  130. /* This is the virtual device created by the xow driver */
  131. return SDL_TRUE;
  132. }
  133. return SDL_FALSE;
  134. }
  135. #endif /* SDL_JOYSTICK_HIDAPI */
  136. static int GuessIsJoystick(int fd)
  137. {
  138. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  139. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  140. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  141. unsigned long relbit[NBITS(REL_MAX)] = { 0 };
  142. int devclass;
  143. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  144. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  145. (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) < 0) ||
  146. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  147. return 0;
  148. }
  149. devclass = SDL_EVDEV_GuessDeviceClass(evbit, absbit, keybit, relbit);
  150. if (devclass & SDL_UDEV_DEVICE_JOYSTICK) {
  151. return 1;
  152. }
  153. return 0;
  154. }
  155. static int IsJoystick(const char *path, int fd, char **name_return, SDL_JoystickGUID *guid)
  156. {
  157. struct input_id inpid;
  158. char *name;
  159. char product_string[128];
  160. if (ioctl(fd, JSIOCGNAME(sizeof(product_string)), product_string) >= 0) {
  161. SDL_zero(inpid);
  162. #ifdef SDL_USE_LIBUDEV
  163. SDL_UDEV_GetProductInfo(path, &inpid.vendor, &inpid.product, &inpid.version);
  164. #endif
  165. } else {
  166. /* When udev is enabled we only get joystick devices here, so there's no need to test them */
  167. if (enumeration_method != ENUMERATION_LIBUDEV && !GuessIsJoystick(fd)) {
  168. return 0;
  169. }
  170. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  171. return 0;
  172. }
  173. if (ioctl(fd, EVIOCGNAME(sizeof(product_string)), product_string) < 0) {
  174. return 0;
  175. }
  176. }
  177. name = SDL_CreateJoystickName(inpid.vendor, inpid.product, NULL, product_string);
  178. if (name == NULL) {
  179. return 0;
  180. }
  181. #ifdef SDL_JOYSTICK_HIDAPI
  182. if (!IsVirtualJoystick(inpid.vendor, inpid.product, inpid.version, name) &&
  183. HIDAPI_IsDevicePresent(inpid.vendor, inpid.product, inpid.version, name)) {
  184. /* The HIDAPI driver is taking care of this device */
  185. SDL_free(name);
  186. return 0;
  187. }
  188. #endif
  189. FixupDeviceInfoForMapping(fd, &inpid);
  190. #ifdef DEBUG_JOYSTICK
  191. SDL_Log("Joystick: %s, bustype = %d, vendor = 0x%.4x, product = 0x%.4x, version = %d\n", name, inpid.bustype, inpid.vendor, inpid.product, inpid.version);
  192. #endif
  193. *guid = SDL_CreateJoystickGUID(inpid.bustype, inpid.vendor, inpid.product, inpid.version, name, 0, 0);
  194. if (SDL_ShouldIgnoreJoystick(name, *guid)) {
  195. SDL_free(name);
  196. return 0;
  197. }
  198. *name_return = name;
  199. return 1;
  200. }
  201. #ifdef SDL_USE_LIBUDEV
  202. static void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath)
  203. {
  204. if (devpath == NULL) {
  205. return;
  206. }
  207. switch (udev_type) {
  208. case SDL_UDEV_DEVICEADDED:
  209. if (!(udev_class & SDL_UDEV_DEVICE_JOYSTICK)) {
  210. return;
  211. }
  212. if (SDL_classic_joysticks) {
  213. if (!IsJoystickJSNode(devpath)) {
  214. return;
  215. }
  216. } else {
  217. if (IsJoystickJSNode(devpath)) {
  218. return;
  219. }
  220. }
  221. /* Wait a bit for the hidraw udev node to initialize */
  222. SDL_Delay(10);
  223. MaybeAddDevice(devpath);
  224. break;
  225. case SDL_UDEV_DEVICEREMOVED:
  226. MaybeRemoveDevice(devpath);
  227. break;
  228. default:
  229. break;
  230. }
  231. }
  232. #endif /* SDL_USE_LIBUDEV */
  233. static void FreeJoylistItem(SDL_joylist_item *item)
  234. {
  235. SDL_free(item->mapping);
  236. SDL_free(item->path);
  237. SDL_free(item->name);
  238. SDL_free(item);
  239. }
  240. static int MaybeAddDevice(const char *path)
  241. {
  242. struct stat sb;
  243. int fd = -1;
  244. int isstick = 0;
  245. char *name = NULL;
  246. SDL_JoystickGUID guid;
  247. SDL_joylist_item *item;
  248. if (path == NULL) {
  249. return -1;
  250. }
  251. if (stat(path, &sb) == -1) {
  252. return -1;
  253. }
  254. /* Check to make sure it's not already in list. */
  255. for (item = SDL_joylist; item != NULL; item = item->next) {
  256. if (sb.st_rdev == item->devnum) {
  257. return -1; /* already have this one */
  258. }
  259. }
  260. fd = open(path, O_RDONLY | O_CLOEXEC, 0);
  261. if (fd < 0) {
  262. return -1;
  263. }
  264. #ifdef DEBUG_INPUT_EVENTS
  265. SDL_Log("Checking %s\n", path);
  266. #endif
  267. isstick = IsJoystick(path, fd, &name, &guid);
  268. close(fd);
  269. if (!isstick) {
  270. return -1;
  271. }
  272. item = (SDL_joylist_item *)SDL_calloc(1, sizeof(SDL_joylist_item));
  273. if (item == NULL) {
  274. SDL_free(name);
  275. return -1;
  276. }
  277. item->devnum = sb.st_rdev;
  278. item->path = SDL_strdup(path);
  279. item->name = name;
  280. item->guid = guid;
  281. if ((item->path == NULL) || (item->name == NULL)) {
  282. FreeJoylistItem(item);
  283. return -1;
  284. }
  285. item->device_instance = SDL_GetNextJoystickInstanceID();
  286. if (SDL_joylist_tail == NULL) {
  287. SDL_joylist = SDL_joylist_tail = item;
  288. } else {
  289. SDL_joylist_tail->next = item;
  290. SDL_joylist_tail = item;
  291. }
  292. /* Need to increment the joystick count before we post the event */
  293. ++numjoysticks;
  294. SDL_PrivateJoystickAdded(item->device_instance);
  295. return numjoysticks;
  296. }
  297. static void RemoveJoylistItem(SDL_joylist_item *item, SDL_joylist_item *prev)
  298. {
  299. if (item->hwdata) {
  300. item->hwdata->item = NULL;
  301. }
  302. if (prev != NULL) {
  303. prev->next = item->next;
  304. } else {
  305. SDL_assert(SDL_joylist == item);
  306. SDL_joylist = item->next;
  307. }
  308. if (item == SDL_joylist_tail) {
  309. SDL_joylist_tail = prev;
  310. }
  311. /* Need to decrement the joystick count before we post the event */
  312. --numjoysticks;
  313. SDL_PrivateJoystickRemoved(item->device_instance);
  314. FreeJoylistItem(item);
  315. }
  316. static int MaybeRemoveDevice(const char *path)
  317. {
  318. SDL_joylist_item *item;
  319. SDL_joylist_item *prev = NULL;
  320. if (path == NULL) {
  321. return -1;
  322. }
  323. for (item = SDL_joylist; item != NULL; item = item->next) {
  324. /* found it, remove it. */
  325. if (SDL_strcmp(path, item->path) == 0) {
  326. const int retval = item->device_instance;
  327. RemoveJoylistItem(item, prev);
  328. return retval;
  329. }
  330. prev = item;
  331. }
  332. return -1;
  333. }
  334. static void HandlePendingRemovals(void)
  335. {
  336. SDL_joylist_item *prev = NULL;
  337. SDL_joylist_item *item = SDL_joylist;
  338. while (item != NULL) {
  339. if (item->hwdata && item->hwdata->gone) {
  340. RemoveJoylistItem(item, prev);
  341. if (prev != NULL) {
  342. item = prev->next;
  343. } else {
  344. item = SDL_joylist;
  345. }
  346. } else {
  347. prev = item;
  348. item = item->next;
  349. }
  350. }
  351. }
  352. static SDL_bool SteamControllerConnectedCallback(const char *name, SDL_JoystickGUID guid, SDL_JoystickID *device_instance)
  353. {
  354. SDL_joylist_item *item;
  355. item = (SDL_joylist_item *)SDL_calloc(1, sizeof(SDL_joylist_item));
  356. if (item == NULL) {
  357. return SDL_FALSE;
  358. }
  359. item->path = SDL_strdup("");
  360. item->name = SDL_strdup(name);
  361. item->guid = guid;
  362. item->m_bSteamController = SDL_TRUE;
  363. if ((item->path == NULL) || (item->name == NULL)) {
  364. FreeJoylistItem(item);
  365. return SDL_FALSE;
  366. }
  367. *device_instance = item->device_instance = SDL_GetNextJoystickInstanceID();
  368. if (SDL_joylist_tail == NULL) {
  369. SDL_joylist = SDL_joylist_tail = item;
  370. } else {
  371. SDL_joylist_tail->next = item;
  372. SDL_joylist_tail = item;
  373. }
  374. /* Need to increment the joystick count before we post the event */
  375. ++numjoysticks;
  376. SDL_PrivateJoystickAdded(item->device_instance);
  377. return SDL_TRUE;
  378. }
  379. static void SteamControllerDisconnectedCallback(SDL_JoystickID device_instance)
  380. {
  381. SDL_joylist_item *item;
  382. SDL_joylist_item *prev = NULL;
  383. for (item = SDL_joylist; item != NULL; item = item->next) {
  384. /* found it, remove it. */
  385. if (item->device_instance == device_instance) {
  386. RemoveJoylistItem(item, prev);
  387. return;
  388. }
  389. prev = item;
  390. }
  391. }
  392. static int StrHasPrefix(const char *string, const char *prefix)
  393. {
  394. return SDL_strncmp(string, prefix, SDL_strlen(prefix)) == 0;
  395. }
  396. static int StrIsInteger(const char *string)
  397. {
  398. const char *p;
  399. if (*string == '\0') {
  400. return 0;
  401. }
  402. for (p = string; *p != '\0'; p++) {
  403. if (*p < '0' || *p > '9') {
  404. return 0;
  405. }
  406. }
  407. return 1;
  408. }
  409. static SDL_bool IsJoystickJSNode(const char *node)
  410. {
  411. const char *last_slash = SDL_strrchr(node, '/');
  412. if (last_slash) {
  413. node = last_slash + 1;
  414. }
  415. return StrHasPrefix(node, "js") && StrIsInteger(node + 2);
  416. }
  417. static SDL_bool IsJoystickEventNode(const char *node)
  418. {
  419. const char *last_slash = SDL_strrchr(node, '/');
  420. if (last_slash) {
  421. node = last_slash + 1;
  422. }
  423. return StrHasPrefix(node, "event") && StrIsInteger(node + 5);
  424. }
  425. static SDL_bool IsJoystickDeviceNode(const char *node)
  426. {
  427. if (SDL_classic_joysticks) {
  428. return IsJoystickJSNode(node);
  429. } else {
  430. return IsJoystickEventNode(node);
  431. }
  432. }
  433. #ifdef HAVE_INOTIFY
  434. #ifdef HAVE_INOTIFY_INIT1
  435. static int SDL_inotify_init1(void)
  436. {
  437. return inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
  438. }
  439. #else
  440. static int SDL_inotify_init1(void)
  441. {
  442. int fd = inotify_init();
  443. if (fd < 0) {
  444. return -1;
  445. }
  446. fcntl(fd, F_SETFL, O_NONBLOCK);
  447. fcntl(fd, F_SETFD, FD_CLOEXEC);
  448. return fd;
  449. }
  450. #endif
  451. static void LINUX_InotifyJoystickDetect(void)
  452. {
  453. union
  454. {
  455. struct inotify_event event;
  456. char storage[4096];
  457. char enough_for_inotify[sizeof(struct inotify_event) + NAME_MAX + 1];
  458. } buf;
  459. ssize_t bytes;
  460. size_t remain = 0;
  461. size_t len;
  462. char path[PATH_MAX];
  463. bytes = read(inotify_fd, &buf, sizeof(buf));
  464. if (bytes > 0) {
  465. remain = (size_t)bytes;
  466. }
  467. while (remain > 0) {
  468. if (buf.event.len > 0) {
  469. if (IsJoystickDeviceNode(buf.event.name)) {
  470. (void)SDL_snprintf(path, SDL_arraysize(path), "/dev/input/%s", buf.event.name);
  471. if (buf.event.mask & (IN_CREATE | IN_MOVED_TO | IN_ATTRIB)) {
  472. MaybeAddDevice(path);
  473. } else if (buf.event.mask & (IN_DELETE | IN_MOVED_FROM)) {
  474. MaybeRemoveDevice(path);
  475. }
  476. }
  477. }
  478. len = sizeof(struct inotify_event) + buf.event.len;
  479. remain -= len;
  480. if (remain != 0) {
  481. SDL_memmove(&buf.storage[0], &buf.storage[len], remain);
  482. }
  483. }
  484. }
  485. #endif /* HAVE_INOTIFY */
  486. static int get_event_joystick_index(int event)
  487. {
  488. int joystick_index = -1;
  489. int i, count;
  490. struct dirent **entries = NULL;
  491. char path[PATH_MAX];
  492. (void)SDL_snprintf(path, SDL_arraysize(path), "/sys/class/input/event%d/device", event);
  493. count = scandir(path, &entries, NULL, alphasort);
  494. for (i = 0; i < count; ++i) {
  495. if (SDL_strncmp(entries[i]->d_name, "js", 2) == 0) {
  496. joystick_index = SDL_atoi(entries[i]->d_name + 2);
  497. }
  498. free(entries[i]); /* This should NOT be SDL_free() */
  499. }
  500. free(entries); /* This should NOT be SDL_free() */
  501. return joystick_index;
  502. }
  503. /* Detect devices by reading /dev/input. In the inotify code path we
  504. * have to do this the first time, to detect devices that already existed
  505. * before we started; in the non-inotify code path we do this repeatedly
  506. * (polling). */
  507. static int filter_entries(const struct dirent *entry)
  508. {
  509. return IsJoystickDeviceNode(entry->d_name);
  510. }
  511. static int sort_entries(const void *_a, const void *_b)
  512. {
  513. const struct dirent **a = (const struct dirent **)_a;
  514. const struct dirent **b = (const struct dirent **)_b;
  515. int numA, numB;
  516. int offset;
  517. if (SDL_classic_joysticks) {
  518. offset = 2; /* strlen("js") */
  519. numA = SDL_atoi((*a)->d_name + offset);
  520. numB = SDL_atoi((*b)->d_name + offset);
  521. } else {
  522. offset = 5; /* strlen("event") */
  523. numA = SDL_atoi((*a)->d_name + offset);
  524. numB = SDL_atoi((*b)->d_name + offset);
  525. /* See if we can get the joystick ordering */
  526. {
  527. int jsA = get_event_joystick_index(numA);
  528. int jsB = get_event_joystick_index(numB);
  529. if (jsA >= 0 && jsB >= 0) {
  530. numA = jsA;
  531. numB = jsB;
  532. } else if (jsA >= 0) {
  533. return -1;
  534. } else if (jsB >= 0) {
  535. return 1;
  536. }
  537. }
  538. }
  539. return numA - numB;
  540. }
  541. static void LINUX_FallbackJoystickDetect(void)
  542. {
  543. const Uint32 SDL_JOY_DETECT_INTERVAL_MS = 3000; /* Update every 3 seconds */
  544. Uint64 now = SDL_GetTicks();
  545. if (!last_joy_detect_time || now >= (last_joy_detect_time + SDL_JOY_DETECT_INTERVAL_MS)) {
  546. struct stat sb;
  547. /* Opening input devices can generate synchronous device I/O, so avoid it if we can */
  548. if (stat("/dev/input", &sb) == 0 && sb.st_mtime != last_input_dir_mtime) {
  549. int i, count;
  550. struct dirent **entries = NULL;
  551. char path[PATH_MAX];
  552. count = scandir("/dev/input", &entries, filter_entries, NULL);
  553. if (count > 1) {
  554. qsort(entries, count, sizeof(*entries), sort_entries);
  555. }
  556. for (i = 0; i < count; ++i) {
  557. (void)SDL_snprintf(path, SDL_arraysize(path), "/dev/input/%s", entries[i]->d_name);
  558. MaybeAddDevice(path);
  559. free(entries[i]); /* This should NOT be SDL_free() */
  560. }
  561. free(entries); /* This should NOT be SDL_free() */
  562. last_input_dir_mtime = sb.st_mtime;
  563. }
  564. last_joy_detect_time = now;
  565. }
  566. }
  567. static void LINUX_JoystickDetect(void)
  568. {
  569. #ifdef SDL_USE_LIBUDEV
  570. if (enumeration_method == ENUMERATION_LIBUDEV) {
  571. SDL_UDEV_Poll();
  572. } else
  573. #endif
  574. #ifdef HAVE_INOTIFY
  575. if (inotify_fd >= 0 && last_joy_detect_time != 0) {
  576. LINUX_InotifyJoystickDetect();
  577. } else
  578. #endif
  579. {
  580. LINUX_FallbackJoystickDetect();
  581. }
  582. HandlePendingRemovals();
  583. SDL_UpdateSteamControllers();
  584. }
  585. static int LINUX_JoystickInit(void)
  586. {
  587. const char *devices = SDL_GetHint(SDL_HINT_JOYSTICK_DEVICE);
  588. SDL_classic_joysticks = SDL_GetHintBoolean(SDL_HINT_LINUX_JOYSTICK_CLASSIC, SDL_FALSE);
  589. enumeration_method = ENUMERATION_UNSET;
  590. /* First see if the user specified one or more joysticks to use */
  591. if (devices != NULL) {
  592. char *envcopy, *envpath, *delim;
  593. envcopy = SDL_strdup(devices);
  594. envpath = envcopy;
  595. while (envpath != NULL) {
  596. delim = SDL_strchr(envpath, ':');
  597. if (delim != NULL) {
  598. *delim++ = '\0';
  599. }
  600. MaybeAddDevice(envpath);
  601. envpath = delim;
  602. }
  603. SDL_free(envcopy);
  604. }
  605. SDL_InitSteamControllers(SteamControllerConnectedCallback,
  606. SteamControllerDisconnectedCallback);
  607. /* Force immediate joystick detection if using fallback */
  608. last_joy_detect_time = 0;
  609. last_input_dir_mtime = 0;
  610. /* Manually scan first, since we sort by device number and udev doesn't */
  611. LINUX_JoystickDetect();
  612. #ifdef SDL_USE_LIBUDEV
  613. if (enumeration_method == ENUMERATION_UNSET) {
  614. if (SDL_GetHintBoolean("SDL_JOYSTICK_DISABLE_UDEV", SDL_FALSE)) {
  615. SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
  616. "udev disabled by SDL_JOYSTICK_DISABLE_UDEV");
  617. enumeration_method = ENUMERATION_FALLBACK;
  618. } else if (SDL_DetectSandbox() != SDL_SANDBOX_NONE) {
  619. SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
  620. "Container detected, disabling udev integration");
  621. enumeration_method = ENUMERATION_FALLBACK;
  622. } else {
  623. SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
  624. "Using udev for joystick device discovery");
  625. enumeration_method = ENUMERATION_LIBUDEV;
  626. }
  627. }
  628. if (enumeration_method == ENUMERATION_LIBUDEV) {
  629. if (SDL_UDEV_Init() < 0) {
  630. return SDL_SetError("Could not initialize UDEV");
  631. }
  632. /* Set up the udev callback */
  633. if (SDL_UDEV_AddCallback(joystick_udev_callback) < 0) {
  634. SDL_UDEV_Quit();
  635. return SDL_SetError("Could not set up joystick <-> udev callback");
  636. }
  637. /* Force a scan to build the initial device list */
  638. SDL_UDEV_Scan();
  639. } else
  640. #endif
  641. {
  642. #ifdef HAVE_INOTIFY
  643. inotify_fd = SDL_inotify_init1();
  644. if (inotify_fd < 0) {
  645. SDL_LogWarn(SDL_LOG_CATEGORY_INPUT,
  646. "Unable to initialize inotify, falling back to polling: %s",
  647. strerror(errno));
  648. } else {
  649. /* We need to watch for attribute changes in addition to
  650. * creation, because when a device is first created, it has
  651. * permissions that we can't read. When udev chmods it to
  652. * something that we maybe *can* read, we'll get an
  653. * IN_ATTRIB event to tell us. */
  654. if (inotify_add_watch(inotify_fd, "/dev/input",
  655. IN_CREATE | IN_DELETE | IN_MOVE | IN_ATTRIB) < 0) {
  656. close(inotify_fd);
  657. inotify_fd = -1;
  658. SDL_LogWarn(SDL_LOG_CATEGORY_INPUT,
  659. "Unable to add inotify watch, falling back to polling: %s",
  660. strerror(errno));
  661. }
  662. }
  663. #endif /* HAVE_INOTIFY */
  664. }
  665. return 0;
  666. }
  667. static int LINUX_JoystickGetCount(void)
  668. {
  669. return numjoysticks;
  670. }
  671. static SDL_joylist_item *GetJoystickByDevIndex(int device_index)
  672. {
  673. SDL_joylist_item *item = SDL_joylist;
  674. if ((device_index < 0) || (device_index >= numjoysticks)) {
  675. return NULL;
  676. }
  677. while (device_index > 0) {
  678. SDL_assert(item != NULL);
  679. device_index--;
  680. item = item->next;
  681. }
  682. return item;
  683. }
  684. static const char *LINUX_JoystickGetDeviceName(int device_index)
  685. {
  686. return GetJoystickByDevIndex(device_index)->name;
  687. }
  688. static const char *LINUX_JoystickGetDevicePath(int device_index)
  689. {
  690. return GetJoystickByDevIndex(device_index)->path;
  691. }
  692. static int LINUX_JoystickGetDevicePlayerIndex(int device_index)
  693. {
  694. return -1;
  695. }
  696. static void LINUX_JoystickSetDevicePlayerIndex(int device_index, int player_index)
  697. {
  698. }
  699. static SDL_JoystickGUID LINUX_JoystickGetDeviceGUID(int device_index)
  700. {
  701. return GetJoystickByDevIndex(device_index)->guid;
  702. }
  703. /* Function to perform the mapping from device index to the instance id for this index */
  704. static SDL_JoystickID LINUX_JoystickGetDeviceInstanceID(int device_index)
  705. {
  706. return GetJoystickByDevIndex(device_index)->device_instance;
  707. }
  708. static int allocate_hatdata(SDL_Joystick *joystick)
  709. {
  710. int i;
  711. SDL_AssertJoysticksLocked();
  712. joystick->hwdata->hats =
  713. (struct hwdata_hat *)SDL_malloc(joystick->nhats *
  714. sizeof(struct hwdata_hat));
  715. if (joystick->hwdata->hats == NULL) {
  716. return -1;
  717. }
  718. for (i = 0; i < joystick->nhats; ++i) {
  719. joystick->hwdata->hats[i].axis[0] = 1;
  720. joystick->hwdata->hats[i].axis[1] = 1;
  721. }
  722. return 0;
  723. }
  724. static SDL_bool GuessIfAxesAreDigitalHat(struct input_absinfo *absinfo_x, struct input_absinfo *absinfo_y)
  725. {
  726. /* A "hat" is assumed to be a digital input with at most 9 possible states
  727. * (3 per axis: negative/zero/positive), as opposed to a true "axis" which
  728. * can report a continuous range of possible values. Unfortunately the Linux
  729. * joystick interface makes no distinction between digital hat axes and any
  730. * other continuous analog axis, so we have to guess. */
  731. /* If both axes are missing, they're not anything. */
  732. if (absinfo_x == NULL && absinfo_y == NULL) {
  733. return SDL_FALSE;
  734. }
  735. /* If the hint says so, treat all hats as digital. */
  736. if (SDL_GetHintBoolean(SDL_HINT_LINUX_DIGITAL_HATS, SDL_FALSE)) {
  737. return SDL_TRUE;
  738. }
  739. /* If both axes have ranges constrained between -1 and 1, they're definitely digital. */
  740. if ((absinfo_x == NULL || (absinfo_x->minimum == -1 && absinfo_x->maximum == 1)) && (absinfo_y == NULL || (absinfo_y->minimum == -1 && absinfo_y->maximum == 1))) {
  741. return SDL_TRUE;
  742. }
  743. /* If both axes lack fuzz, flat, and resolution values, they're probably digital. */
  744. if ((absinfo_x == NULL || (!absinfo_x->fuzz && !absinfo_x->flat && !absinfo_x->resolution)) && (absinfo_y == NULL || (!absinfo_y->fuzz && !absinfo_y->flat && !absinfo_y->resolution))) {
  745. return SDL_TRUE;
  746. }
  747. /* Otherwise, treat them as analog. */
  748. return SDL_FALSE;
  749. }
  750. static void ConfigJoystick(SDL_Joystick *joystick, int fd)
  751. {
  752. int i, t;
  753. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  754. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  755. unsigned long relbit[NBITS(REL_MAX)] = { 0 };
  756. unsigned long ffbit[NBITS(FF_MAX)] = { 0 };
  757. Uint8 key_pam_size, abs_pam_size;
  758. SDL_bool use_deadzones = SDL_GetHintBoolean(SDL_HINT_LINUX_JOYSTICK_DEADZONES, SDL_FALSE);
  759. SDL_bool use_hat_deadzones = SDL_GetHintBoolean(SDL_HINT_LINUX_HAT_DEADZONES, SDL_TRUE);
  760. SDL_AssertJoysticksLocked();
  761. /* See if this device uses the new unified event API */
  762. if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) &&
  763. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) &&
  764. (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0)) {
  765. /* Get the number of buttons, axes, and other thingamajigs */
  766. for (i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  767. if (test_bit(i, keybit)) {
  768. #ifdef DEBUG_INPUT_EVENTS
  769. SDL_Log("Joystick has button: 0x%x\n", i);
  770. #endif
  771. joystick->hwdata->key_map[i] = joystick->nbuttons;
  772. joystick->hwdata->has_key[i] = SDL_TRUE;
  773. ++joystick->nbuttons;
  774. }
  775. }
  776. for (i = 0; i < BTN_JOYSTICK; ++i) {
  777. if (test_bit(i, keybit)) {
  778. #ifdef DEBUG_INPUT_EVENTS
  779. SDL_Log("Joystick has button: 0x%x\n", i);
  780. #endif
  781. joystick->hwdata->key_map[i] = joystick->nbuttons;
  782. joystick->hwdata->has_key[i] = SDL_TRUE;
  783. ++joystick->nbuttons;
  784. }
  785. }
  786. for (i = ABS_HAT0X; i <= ABS_HAT3Y; i += 2) {
  787. int hat_x = -1;
  788. int hat_y = -1;
  789. struct input_absinfo absinfo_x;
  790. struct input_absinfo absinfo_y;
  791. if (test_bit(i, absbit)) {
  792. hat_x = ioctl(fd, EVIOCGABS(i), &absinfo_x);
  793. }
  794. if (test_bit(i + 1, absbit)) {
  795. hat_y = ioctl(fd, EVIOCGABS(i + 1), &absinfo_y);
  796. }
  797. if (GuessIfAxesAreDigitalHat((hat_x < 0 ? (void *)0 : &absinfo_x),
  798. (hat_y < 0 ? (void *)0 : &absinfo_y))) {
  799. const int hat_index = (i - ABS_HAT0X) / 2;
  800. struct hat_axis_correct *correct = &joystick->hwdata->hat_correct[hat_index];
  801. #ifdef DEBUG_INPUT_EVENTS
  802. SDL_Log("Joystick has digital hat: #%d\n", hat_index);
  803. if (hat_x >= 0) {
  804. SDL_Log("X Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }\n",
  805. absinfo_x.value, absinfo_x.minimum, absinfo_x.maximum,
  806. absinfo_x.fuzz, absinfo_x.flat, absinfo_x.resolution);
  807. }
  808. if (hat_y >= 0) {
  809. SDL_Log("Y Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }\n",
  810. absinfo_y.value, absinfo_y.minimum, absinfo_y.maximum,
  811. absinfo_y.fuzz, absinfo_y.flat, absinfo_y.resolution);
  812. }
  813. #endif /* DEBUG_INPUT_EVENTS */
  814. joystick->hwdata->hats_indices[hat_index] = joystick->nhats;
  815. joystick->hwdata->has_hat[hat_index] = SDL_TRUE;
  816. correct->use_deadzones = use_hat_deadzones;
  817. correct->minimum[0] = (hat_x < 0) ? -1 : absinfo_x.minimum;
  818. correct->maximum[0] = (hat_x < 0) ? 1 : absinfo_x.maximum;
  819. correct->minimum[1] = (hat_y < 0) ? -1 : absinfo_y.minimum;
  820. correct->maximum[1] = (hat_y < 0) ? 1 : absinfo_y.maximum;
  821. ++joystick->nhats;
  822. }
  823. }
  824. for (i = 0; i < ABS_MAX; ++i) {
  825. /* Skip digital hats */
  826. if (joystick->hwdata->has_hat[(i - ABS_HAT0X) / 2]) {
  827. continue;
  828. }
  829. if (test_bit(i, absbit)) {
  830. struct input_absinfo absinfo;
  831. struct axis_correct *correct = &joystick->hwdata->abs_correct[i];
  832. if (ioctl(fd, EVIOCGABS(i), &absinfo) < 0) {
  833. continue;
  834. }
  835. #ifdef DEBUG_INPUT_EVENTS
  836. SDL_Log("Joystick has absolute axis: 0x%.2x\n", i);
  837. SDL_Log("Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }\n",
  838. absinfo.value, absinfo.minimum, absinfo.maximum,
  839. absinfo.fuzz, absinfo.flat, absinfo.resolution);
  840. #endif /* DEBUG_INPUT_EVENTS */
  841. joystick->hwdata->abs_map[i] = joystick->naxes;
  842. joystick->hwdata->has_abs[i] = SDL_TRUE;
  843. correct->minimum = absinfo.minimum;
  844. correct->maximum = absinfo.maximum;
  845. if (correct->minimum != correct->maximum) {
  846. if (use_deadzones) {
  847. correct->use_deadzones = SDL_TRUE;
  848. correct->coef[0] = (absinfo.maximum + absinfo.minimum) - 2 * absinfo.flat;
  849. correct->coef[1] = (absinfo.maximum + absinfo.minimum) + 2 * absinfo.flat;
  850. t = ((absinfo.maximum - absinfo.minimum) - 4 * absinfo.flat);
  851. if (t != 0) {
  852. correct->coef[2] = (1 << 28) / t;
  853. } else {
  854. correct->coef[2] = 0;
  855. }
  856. } else {
  857. float value_range = (correct->maximum - correct->minimum);
  858. float output_range = (SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN);
  859. correct->scale = (output_range / value_range);
  860. }
  861. }
  862. ++joystick->naxes;
  863. }
  864. }
  865. } else if ((ioctl(fd, JSIOCGBUTTONS, &key_pam_size, sizeof(key_pam_size)) >= 0) &&
  866. (ioctl(fd, JSIOCGAXES, &abs_pam_size, sizeof(abs_pam_size)) >= 0)) {
  867. size_t len;
  868. joystick->hwdata->classic = SDL_TRUE;
  869. len = (KEY_MAX - BTN_MISC + 1) * sizeof(*joystick->hwdata->key_pam);
  870. joystick->hwdata->key_pam = (Uint16 *)SDL_calloc(1, len);
  871. if (joystick->hwdata->key_pam) {
  872. if (ioctl(fd, JSIOCGBTNMAP, joystick->hwdata->key_pam, len) < 0) {
  873. SDL_free(joystick->hwdata->key_pam);
  874. joystick->hwdata->key_pam = NULL;
  875. key_pam_size = 0;
  876. }
  877. } else {
  878. key_pam_size = 0;
  879. }
  880. for (i = 0; i < key_pam_size; ++i) {
  881. Uint16 code = joystick->hwdata->key_pam[i];
  882. #ifdef DEBUG_INPUT_EVENTS
  883. SDL_Log("Joystick has button: 0x%x\n", code);
  884. #endif
  885. joystick->hwdata->key_map[code] = joystick->nbuttons;
  886. joystick->hwdata->has_key[code] = SDL_TRUE;
  887. ++joystick->nbuttons;
  888. }
  889. len = ABS_CNT * sizeof(*joystick->hwdata->abs_pam);
  890. joystick->hwdata->abs_pam = (Uint8 *)SDL_calloc(1, len);
  891. if (joystick->hwdata->abs_pam) {
  892. if (ioctl(fd, JSIOCGAXMAP, joystick->hwdata->abs_pam, len) < 0) {
  893. SDL_free(joystick->hwdata->abs_pam);
  894. joystick->hwdata->abs_pam = NULL;
  895. abs_pam_size = 0;
  896. }
  897. } else {
  898. abs_pam_size = 0;
  899. }
  900. for (i = 0; i < abs_pam_size; ++i) {
  901. Uint8 code = joystick->hwdata->abs_pam[i];
  902. // TODO: is there any way to detect analog hats in advance via this API?
  903. if (code >= ABS_HAT0X && code <= ABS_HAT3Y) {
  904. int hat_index = (code - ABS_HAT0X) / 2;
  905. if (!joystick->hwdata->has_hat[hat_index]) {
  906. #ifdef DEBUG_INPUT_EVENTS
  907. SDL_Log("Joystick has digital hat: #%d\n", hat_index);
  908. #endif
  909. joystick->hwdata->hats_indices[hat_index] = joystick->nhats++;
  910. joystick->hwdata->has_hat[hat_index] = SDL_TRUE;
  911. joystick->hwdata->hat_correct[hat_index].minimum[0] = -1;
  912. joystick->hwdata->hat_correct[hat_index].maximum[0] = 1;
  913. joystick->hwdata->hat_correct[hat_index].minimum[1] = -1;
  914. joystick->hwdata->hat_correct[hat_index].maximum[1] = 1;
  915. }
  916. } else {
  917. #ifdef DEBUG_INPUT_EVENTS
  918. SDL_Log("Joystick has absolute axis: 0x%.2x\n", code);
  919. #endif
  920. joystick->hwdata->abs_map[code] = joystick->naxes;
  921. joystick->hwdata->has_abs[code] = SDL_TRUE;
  922. ++joystick->naxes;
  923. }
  924. }
  925. }
  926. /* Allocate data to keep track of these thingamajigs */
  927. if (joystick->nhats > 0) {
  928. if (allocate_hatdata(joystick) < 0) {
  929. joystick->nhats = 0;
  930. }
  931. }
  932. if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) >= 0) {
  933. if (test_bit(FF_RUMBLE, ffbit)) {
  934. joystick->hwdata->ff_rumble = SDL_TRUE;
  935. }
  936. if (test_bit(FF_SINE, ffbit)) {
  937. joystick->hwdata->ff_sine = SDL_TRUE;
  938. }
  939. }
  940. }
  941. /* This is used to do the heavy lifting for LINUX_JoystickOpen and
  942. also LINUX_JoystickGetGamepadMapping, so we can query the hardware
  943. without adding an opened SDL_Joystick object to the system.
  944. This expects `joystick->hwdata` to be allocated and will not free it
  945. on error. Returns -1 on error, 0 on success. */
  946. static int PrepareJoystickHwdata(SDL_Joystick *joystick, SDL_joylist_item *item)
  947. {
  948. SDL_AssertJoysticksLocked();
  949. joystick->hwdata->item = item;
  950. joystick->hwdata->guid = item->guid;
  951. joystick->hwdata->effect.id = -1;
  952. joystick->hwdata->m_bSteamController = item->m_bSteamController;
  953. SDL_memset(joystick->hwdata->key_map, 0xFF, sizeof(joystick->hwdata->key_map));
  954. SDL_memset(joystick->hwdata->abs_map, 0xFF, sizeof(joystick->hwdata->abs_map));
  955. if (item->m_bSteamController) {
  956. joystick->hwdata->fd = -1;
  957. SDL_GetSteamControllerInputs(&joystick->nbuttons,
  958. &joystick->naxes,
  959. &joystick->nhats);
  960. } else {
  961. /* Try read-write first, so we can do rumble */
  962. int fd = open(item->path, O_RDWR | O_CLOEXEC, 0);
  963. if (fd < 0) {
  964. /* Try read-only again, at least we'll get events in this case */
  965. fd = open(item->path, O_RDONLY | O_CLOEXEC, 0);
  966. }
  967. if (fd < 0) {
  968. return SDL_SetError("Unable to open %s", item->path);
  969. }
  970. joystick->hwdata->fd = fd;
  971. joystick->hwdata->fname = SDL_strdup(item->path);
  972. if (joystick->hwdata->fname == NULL) {
  973. close(fd);
  974. return SDL_OutOfMemory();
  975. }
  976. /* Set the joystick to non-blocking read mode */
  977. fcntl(fd, F_SETFL, O_NONBLOCK);
  978. /* Get the number of buttons and axes on the joystick */
  979. ConfigJoystick(joystick, fd);
  980. }
  981. return 0;
  982. }
  983. /* Function to open a joystick for use.
  984. The joystick to open is specified by the device index.
  985. This should fill the nbuttons and naxes fields of the joystick structure.
  986. It returns 0, or -1 if there is an error.
  987. */
  988. static int LINUX_JoystickOpen(SDL_Joystick *joystick, int device_index)
  989. {
  990. SDL_joylist_item *item = GetJoystickByDevIndex(device_index);
  991. SDL_AssertJoysticksLocked();
  992. if (item == NULL) {
  993. return SDL_SetError("No such device");
  994. }
  995. joystick->instance_id = item->device_instance;
  996. joystick->hwdata = (struct joystick_hwdata *)
  997. SDL_calloc(1, sizeof(*joystick->hwdata));
  998. if (joystick->hwdata == NULL) {
  999. return SDL_OutOfMemory();
  1000. }
  1001. if (PrepareJoystickHwdata(joystick, item) == -1) {
  1002. SDL_free(joystick->hwdata);
  1003. joystick->hwdata = NULL;
  1004. return -1; /* SDL_SetError will already have been called */
  1005. }
  1006. SDL_assert(item->hwdata == NULL);
  1007. item->hwdata = joystick->hwdata;
  1008. /* mark joystick as fresh and ready */
  1009. joystick->hwdata->fresh = SDL_TRUE;
  1010. return 0;
  1011. }
  1012. static int LINUX_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  1013. {
  1014. struct input_event event;
  1015. SDL_AssertJoysticksLocked();
  1016. if (joystick->hwdata->ff_rumble) {
  1017. struct ff_effect *effect = &joystick->hwdata->effect;
  1018. effect->type = FF_RUMBLE;
  1019. effect->replay.length = SDL_MAX_RUMBLE_DURATION_MS;
  1020. effect->u.rumble.strong_magnitude = low_frequency_rumble;
  1021. effect->u.rumble.weak_magnitude = high_frequency_rumble;
  1022. } else if (joystick->hwdata->ff_sine) {
  1023. /* Scale and average the two rumble strengths */
  1024. Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2);
  1025. struct ff_effect *effect = &joystick->hwdata->effect;
  1026. effect->type = FF_PERIODIC;
  1027. effect->replay.length = SDL_MAX_RUMBLE_DURATION_MS;
  1028. effect->u.periodic.waveform = FF_SINE;
  1029. effect->u.periodic.magnitude = magnitude;
  1030. } else {
  1031. return SDL_Unsupported();
  1032. }
  1033. if (ioctl(joystick->hwdata->fd, EVIOCSFF, &joystick->hwdata->effect) < 0) {
  1034. /* The kernel may have lost this effect, try to allocate a new one */
  1035. joystick->hwdata->effect.id = -1;
  1036. if (ioctl(joystick->hwdata->fd, EVIOCSFF, &joystick->hwdata->effect) < 0) {
  1037. return SDL_SetError("Couldn't update rumble effect: %s", strerror(errno));
  1038. }
  1039. }
  1040. event.type = EV_FF;
  1041. event.code = joystick->hwdata->effect.id;
  1042. event.value = 1;
  1043. if (write(joystick->hwdata->fd, &event, sizeof(event)) < 0) {
  1044. return SDL_SetError("Couldn't start rumble effect: %s", strerror(errno));
  1045. }
  1046. return 0;
  1047. }
  1048. static int LINUX_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  1049. {
  1050. return SDL_Unsupported();
  1051. }
  1052. static Uint32 LINUX_JoystickGetCapabilities(SDL_Joystick *joystick)
  1053. {
  1054. Uint32 result = 0;
  1055. SDL_AssertJoysticksLocked();
  1056. if (joystick->hwdata->ff_rumble || joystick->hwdata->ff_sine) {
  1057. result |= SDL_JOYCAP_RUMBLE;
  1058. }
  1059. return result;
  1060. }
  1061. static int LINUX_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  1062. {
  1063. return SDL_Unsupported();
  1064. }
  1065. static int LINUX_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size)
  1066. {
  1067. return SDL_Unsupported();
  1068. }
  1069. static int LINUX_JoystickSetSensorsEnabled(SDL_Joystick *joystick, SDL_bool enabled)
  1070. {
  1071. return SDL_Unsupported();
  1072. }
  1073. static void HandleHat(Uint64 timestamp, SDL_Joystick *stick, int hatidx, int axis, int value)
  1074. {
  1075. int hatnum;
  1076. struct hwdata_hat *the_hat;
  1077. struct hat_axis_correct *correct;
  1078. const Uint8 position_map[3][3] = {
  1079. { SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP },
  1080. { SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT },
  1081. { SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN }
  1082. };
  1083. SDL_AssertJoysticksLocked();
  1084. hatnum = stick->hwdata->hats_indices[hatidx];
  1085. the_hat = &stick->hwdata->hats[hatnum];
  1086. correct = &stick->hwdata->hat_correct[hatidx];
  1087. /* Hopefully we detected any analog axes and left them as is rather than trying
  1088. * to use them as digital hats, but just in case, the deadzones here will
  1089. * prevent the slightest of twitches on an analog axis from registering as a hat
  1090. * movement. If the axes really are digital, this won't hurt since they should
  1091. * only ever be sending min, 0, or max anyway. */
  1092. if (value < 0) {
  1093. if (value <= correct->minimum[axis]) {
  1094. correct->minimum[axis] = value;
  1095. value = 0;
  1096. } else if (!correct->use_deadzones || value < correct->minimum[axis] / 3) {
  1097. value = 0;
  1098. } else {
  1099. value = 1;
  1100. }
  1101. } else if (value > 0) {
  1102. if (value >= correct->maximum[axis]) {
  1103. correct->maximum[axis] = value;
  1104. value = 2;
  1105. } else if (!correct->use_deadzones || value > correct->maximum[axis] / 3) {
  1106. value = 2;
  1107. } else {
  1108. value = 1;
  1109. }
  1110. } else { // value == 0
  1111. value = 1;
  1112. }
  1113. if (value != the_hat->axis[axis]) {
  1114. the_hat->axis[axis] = value;
  1115. SDL_SendJoystickHat(timestamp, stick, hatnum,
  1116. position_map[the_hat->axis[1]][the_hat->axis[0]]);
  1117. }
  1118. }
  1119. static int AxisCorrect(SDL_Joystick *joystick, int which, int value)
  1120. {
  1121. struct axis_correct *correct;
  1122. SDL_AssertJoysticksLocked();
  1123. correct = &joystick->hwdata->abs_correct[which];
  1124. if (correct->minimum != correct->maximum) {
  1125. if (correct->use_deadzones) {
  1126. value *= 2;
  1127. if (value > correct->coef[0]) {
  1128. if (value < correct->coef[1]) {
  1129. return 0;
  1130. }
  1131. value -= correct->coef[1];
  1132. } else {
  1133. value -= correct->coef[0];
  1134. }
  1135. value *= correct->coef[2];
  1136. value >>= 13;
  1137. } else {
  1138. value = (int)SDL_floorf((value - correct->minimum) * correct->scale + SDL_JOYSTICK_AXIS_MIN + 0.5f);
  1139. }
  1140. }
  1141. /* Clamp and return */
  1142. if (value < SDL_JOYSTICK_AXIS_MIN) {
  1143. return SDL_JOYSTICK_AXIS_MIN;
  1144. }
  1145. if (value > SDL_JOYSTICK_AXIS_MAX) {
  1146. return SDL_JOYSTICK_AXIS_MAX;
  1147. }
  1148. return value;
  1149. }
  1150. static void PollAllValues(Uint64 timestamp, SDL_Joystick *joystick)
  1151. {
  1152. struct input_absinfo absinfo;
  1153. unsigned long keyinfo[NBITS(KEY_MAX)];
  1154. int i;
  1155. SDL_AssertJoysticksLocked();
  1156. /* Poll all axis */
  1157. for (i = ABS_X; i < ABS_MAX; i++) {
  1158. /* We don't need to test for digital hats here, they won't have has_abs[] set */
  1159. if (joystick->hwdata->has_abs[i]) {
  1160. if (ioctl(joystick->hwdata->fd, EVIOCGABS(i), &absinfo) >= 0) {
  1161. absinfo.value = AxisCorrect(joystick, i, absinfo.value);
  1162. #ifdef DEBUG_INPUT_EVENTS
  1163. SDL_Log("Joystick : Re-read Axis %d (%d) val= %d\n",
  1164. joystick->hwdata->abs_map[i], i, absinfo.value);
  1165. #endif
  1166. SDL_SendJoystickAxis(timestamp, joystick,
  1167. joystick->hwdata->abs_map[i],
  1168. absinfo.value);
  1169. }
  1170. }
  1171. }
  1172. /* Poll all digital hats */
  1173. for (i = ABS_HAT0X; i <= ABS_HAT3Y; i++) {
  1174. const int baseaxis = i - ABS_HAT0X;
  1175. const int hatidx = baseaxis / 2;
  1176. SDL_assert(hatidx < SDL_arraysize(joystick->hwdata->has_hat));
  1177. /* We don't need to test for analog axes here, they won't have has_hat[] set */
  1178. if (joystick->hwdata->has_hat[hatidx]) {
  1179. if (ioctl(joystick->hwdata->fd, EVIOCGABS(i), &absinfo) >= 0) {
  1180. const int hataxis = baseaxis % 2;
  1181. HandleHat(timestamp, joystick, hatidx, hataxis, absinfo.value);
  1182. }
  1183. }
  1184. }
  1185. /* Poll all buttons */
  1186. SDL_zeroa(keyinfo);
  1187. if (ioctl(joystick->hwdata->fd, EVIOCGKEY(sizeof(keyinfo)), keyinfo) >= 0) {
  1188. for (i = 0; i < KEY_MAX; i++) {
  1189. if (joystick->hwdata->has_key[i]) {
  1190. const Uint8 value = test_bit(i, keyinfo) ? SDL_PRESSED : SDL_RELEASED;
  1191. #ifdef DEBUG_INPUT_EVENTS
  1192. SDL_Log("Joystick : Re-read Button %d (%d) val= %d\n",
  1193. joystick->hwdata->key_map[i], i, value);
  1194. #endif
  1195. SDL_SendJoystickButton(timestamp, joystick,
  1196. joystick->hwdata->key_map[i], value);
  1197. }
  1198. }
  1199. }
  1200. }
  1201. static void HandleInputEvents(SDL_Joystick *joystick)
  1202. {
  1203. struct input_event events[32];
  1204. int i, len, code, hat_index;
  1205. SDL_AssertJoysticksLocked();
  1206. if (joystick->hwdata->fresh) {
  1207. PollAllValues(SDL_GetTicksNS(), joystick);
  1208. joystick->hwdata->fresh = SDL_FALSE;
  1209. }
  1210. while ((len = read(joystick->hwdata->fd, events, sizeof(events))) > 0) {
  1211. len /= sizeof(events[0]);
  1212. for (i = 0; i < len; ++i) {
  1213. struct input_event *event = &events[i];
  1214. code = event->code;
  1215. /* If the kernel sent a SYN_DROPPED, we are supposed to ignore the
  1216. rest of the packet (the end of it signified by a SYN_REPORT) */
  1217. if (joystick->hwdata->recovering_from_dropped &&
  1218. ((event->type != EV_SYN) || (code != SYN_REPORT))) {
  1219. continue;
  1220. }
  1221. switch (event->type) {
  1222. case EV_KEY:
  1223. SDL_SendJoystickButton(SDL_EVDEV_GetEventTimestamp(event), joystick,
  1224. joystick->hwdata->key_map[code],
  1225. event->value);
  1226. break;
  1227. case EV_ABS:
  1228. switch (code) {
  1229. case ABS_HAT0X:
  1230. case ABS_HAT0Y:
  1231. case ABS_HAT1X:
  1232. case ABS_HAT1Y:
  1233. case ABS_HAT2X:
  1234. case ABS_HAT2Y:
  1235. case ABS_HAT3X:
  1236. case ABS_HAT3Y:
  1237. hat_index = (code - ABS_HAT0X) / 2;
  1238. if (joystick->hwdata->has_hat[hat_index]) {
  1239. HandleHat(SDL_EVDEV_GetEventTimestamp(event), joystick, hat_index, code % 2, event->value);
  1240. break;
  1241. }
  1242. SDL_FALLTHROUGH;
  1243. default:
  1244. event->value = AxisCorrect(joystick, code, event->value);
  1245. SDL_SendJoystickAxis(SDL_EVDEV_GetEventTimestamp(event), joystick,
  1246. joystick->hwdata->abs_map[code],
  1247. event->value);
  1248. break;
  1249. }
  1250. break;
  1251. case EV_SYN:
  1252. switch (code) {
  1253. case SYN_DROPPED:
  1254. #ifdef DEBUG_INPUT_EVENTS
  1255. SDL_Log("Event SYN_DROPPED detected\n");
  1256. #endif
  1257. joystick->hwdata->recovering_from_dropped = SDL_TRUE;
  1258. break;
  1259. case SYN_REPORT:
  1260. if (joystick->hwdata->recovering_from_dropped) {
  1261. joystick->hwdata->recovering_from_dropped = SDL_FALSE;
  1262. PollAllValues(SDL_GetTicksNS(), joystick); /* try to sync up to current state now */
  1263. }
  1264. break;
  1265. default:
  1266. break;
  1267. }
  1268. default:
  1269. break;
  1270. }
  1271. }
  1272. }
  1273. if (errno == ENODEV) {
  1274. /* We have to wait until the JoystickDetect callback to remove this */
  1275. joystick->hwdata->gone = SDL_TRUE;
  1276. }
  1277. }
  1278. static void HandleClassicEvents(SDL_Joystick *joystick)
  1279. {
  1280. struct js_event events[32];
  1281. int i, len, code, hat_index;
  1282. Uint64 timestamp = SDL_GetTicksNS();
  1283. SDL_AssertJoysticksLocked();
  1284. joystick->hwdata->fresh = SDL_FALSE;
  1285. while ((len = read(joystick->hwdata->fd, events, sizeof(events))) > 0) {
  1286. len /= sizeof(events[0]);
  1287. for (i = 0; i < len; ++i) {
  1288. switch (events[i].type) {
  1289. case JS_EVENT_BUTTON:
  1290. code = joystick->hwdata->key_pam[events[i].number];
  1291. SDL_SendJoystickButton(timestamp, joystick,
  1292. joystick->hwdata->key_map[code],
  1293. events[i].value);
  1294. break;
  1295. case JS_EVENT_AXIS:
  1296. code = joystick->hwdata->abs_pam[events[i].number];
  1297. switch (code) {
  1298. case ABS_HAT0X:
  1299. case ABS_HAT0Y:
  1300. case ABS_HAT1X:
  1301. case ABS_HAT1Y:
  1302. case ABS_HAT2X:
  1303. case ABS_HAT2Y:
  1304. case ABS_HAT3X:
  1305. case ABS_HAT3Y:
  1306. hat_index = (code - ABS_HAT0X) / 2;
  1307. if (joystick->hwdata->has_hat[hat_index]) {
  1308. HandleHat(timestamp, joystick, hat_index, code % 2, events[i].value);
  1309. break;
  1310. }
  1311. SDL_FALLTHROUGH;
  1312. default:
  1313. SDL_SendJoystickAxis(timestamp, joystick,
  1314. joystick->hwdata->abs_map[code],
  1315. events[i].value);
  1316. break;
  1317. }
  1318. }
  1319. }
  1320. }
  1321. }
  1322. static void LINUX_JoystickUpdate(SDL_Joystick *joystick)
  1323. {
  1324. SDL_AssertJoysticksLocked();
  1325. if (joystick->hwdata->m_bSteamController) {
  1326. SDL_UpdateSteamController(joystick);
  1327. return;
  1328. }
  1329. if (joystick->hwdata->classic) {
  1330. HandleClassicEvents(joystick);
  1331. } else {
  1332. HandleInputEvents(joystick);
  1333. }
  1334. }
  1335. /* Function to close a joystick after use */
  1336. static void LINUX_JoystickClose(SDL_Joystick *joystick)
  1337. {
  1338. SDL_AssertJoysticksLocked();
  1339. if (joystick->hwdata) {
  1340. if (joystick->hwdata->effect.id >= 0) {
  1341. ioctl(joystick->hwdata->fd, EVIOCRMFF, joystick->hwdata->effect.id);
  1342. joystick->hwdata->effect.id = -1;
  1343. }
  1344. if (joystick->hwdata->fd >= 0) {
  1345. close(joystick->hwdata->fd);
  1346. }
  1347. if (joystick->hwdata->item) {
  1348. joystick->hwdata->item->hwdata = NULL;
  1349. }
  1350. SDL_free(joystick->hwdata->key_pam);
  1351. SDL_free(joystick->hwdata->abs_pam);
  1352. SDL_free(joystick->hwdata->hats);
  1353. SDL_free(joystick->hwdata->fname);
  1354. SDL_free(joystick->hwdata);
  1355. }
  1356. }
  1357. /* Function to perform any system-specific joystick related cleanup */
  1358. static void LINUX_JoystickQuit(void)
  1359. {
  1360. SDL_joylist_item *item = NULL;
  1361. SDL_joylist_item *next = NULL;
  1362. if (inotify_fd >= 0) {
  1363. close(inotify_fd);
  1364. inotify_fd = -1;
  1365. }
  1366. for (item = SDL_joylist; item; item = next) {
  1367. next = item->next;
  1368. FreeJoylistItem(item);
  1369. }
  1370. SDL_joylist = SDL_joylist_tail = NULL;
  1371. numjoysticks = 0;
  1372. #ifdef SDL_USE_LIBUDEV
  1373. if (enumeration_method == ENUMERATION_LIBUDEV) {
  1374. SDL_UDEV_DelCallback(joystick_udev_callback);
  1375. SDL_UDEV_Quit();
  1376. }
  1377. #endif
  1378. SDL_QuitSteamControllers();
  1379. }
  1380. /*
  1381. This is based on the Linux Gamepad Specification
  1382. available at: https://www.kernel.org/doc/html/v4.15/input/gamepad.html
  1383. */
  1384. static SDL_bool LINUX_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out)
  1385. {
  1386. SDL_Joystick *joystick;
  1387. SDL_joylist_item *item = GetJoystickByDevIndex(device_index);
  1388. enum {
  1389. MAPPED_TRIGGER_LEFT = 0x1,
  1390. MAPPED_TRIGGER_RIGHT = 0x2,
  1391. MAPPED_TRIGGER_BOTH = 0x3,
  1392. MAPPED_DPAD_UP = 0x1,
  1393. MAPPED_DPAD_DOWN = 0x2,
  1394. MAPPED_DPAD_LEFT = 0x4,
  1395. MAPPED_DPAD_RIGHT = 0x8,
  1396. MAPPED_DPAD_ALL = 0xF,
  1397. };
  1398. unsigned int mapped;
  1399. SDL_AssertJoysticksLocked();
  1400. if (item->checked_mapping) {
  1401. if (item->mapping) {
  1402. SDL_memcpy(out, item->mapping, sizeof(*out));
  1403. #ifdef DEBUG_GAMEPAD_MAPPING
  1404. SDL_Log("Prior mapping for device %d", device_index);
  1405. #endif
  1406. return SDL_TRUE;
  1407. } else {
  1408. return SDL_FALSE;
  1409. }
  1410. }
  1411. /* We temporarily open the device to check how it's configured. Make
  1412. a fake SDL_Joystick object to do so. */
  1413. joystick = (SDL_Joystick *)SDL_calloc(sizeof(*joystick), 1);
  1414. if (joystick == NULL) {
  1415. SDL_OutOfMemory();
  1416. return SDL_FALSE;
  1417. }
  1418. SDL_memcpy(&joystick->guid, &item->guid, sizeof(item->guid));
  1419. joystick->hwdata = (struct joystick_hwdata *)
  1420. SDL_calloc(1, sizeof(*joystick->hwdata));
  1421. if (joystick->hwdata == NULL) {
  1422. SDL_free(joystick);
  1423. SDL_OutOfMemory();
  1424. return SDL_FALSE;
  1425. }
  1426. item->checked_mapping = SDL_TRUE;
  1427. if (PrepareJoystickHwdata(joystick, item) == -1) {
  1428. SDL_free(joystick->hwdata);
  1429. SDL_free(joystick);
  1430. return SDL_FALSE; /* SDL_SetError will already have been called */
  1431. }
  1432. /* don't assign `item->hwdata` so it's not in any global state. */
  1433. /* it is now safe to call LINUX_JoystickClose on this fake joystick. */
  1434. if (!joystick->hwdata->has_key[BTN_GAMEPAD]) {
  1435. /* Not a gamepad according to the specs. */
  1436. LINUX_JoystickClose(joystick);
  1437. SDL_free(joystick);
  1438. return SDL_FALSE;
  1439. }
  1440. /* We have a gamepad, start filling out the mappings */
  1441. if (joystick->hwdata->has_key[BTN_A]) {
  1442. out->a.kind = EMappingKind_Button;
  1443. out->a.target = joystick->hwdata->key_map[BTN_A];
  1444. #ifdef DEBUG_GAMEPAD_MAPPING
  1445. SDL_Log("Mapped A to button %d (BTN_A)", out->a.target);
  1446. #endif
  1447. }
  1448. if (joystick->hwdata->has_key[BTN_B]) {
  1449. out->b.kind = EMappingKind_Button;
  1450. out->b.target = joystick->hwdata->key_map[BTN_B];
  1451. #ifdef DEBUG_GAMEPAD_MAPPING
  1452. SDL_Log("Mapped B to button %d (BTN_B)", out->b.target);
  1453. #endif
  1454. }
  1455. /* Xbox controllers use BTN_X and BTN_Y, and PS4 controllers use BTN_WEST and BTN_NORTH */
  1456. if (SDL_GetJoystickVendor(joystick) == USB_VENDOR_SONY) {
  1457. if (joystick->hwdata->has_key[BTN_WEST]) {
  1458. out->x.kind = EMappingKind_Button;
  1459. out->x.target = joystick->hwdata->key_map[BTN_WEST];
  1460. #ifdef DEBUG_GAMEPAD_MAPPING
  1461. SDL_Log("Mapped X to button %d (BTN_WEST)", out->x.target);
  1462. #endif
  1463. }
  1464. if (joystick->hwdata->has_key[BTN_NORTH]) {
  1465. out->y.kind = EMappingKind_Button;
  1466. out->y.target = joystick->hwdata->key_map[BTN_NORTH];
  1467. #ifdef DEBUG_GAMEPAD_MAPPING
  1468. SDL_Log("Mapped Y to button %d (BTN_NORTH)", out->y.target);
  1469. #endif
  1470. }
  1471. } else {
  1472. if (joystick->hwdata->has_key[BTN_X]) {
  1473. out->x.kind = EMappingKind_Button;
  1474. out->x.target = joystick->hwdata->key_map[BTN_X];
  1475. #ifdef DEBUG_GAMEPAD_MAPPING
  1476. SDL_Log("Mapped X to button %d (BTN_X)", out->x.target);
  1477. #endif
  1478. }
  1479. if (joystick->hwdata->has_key[BTN_Y]) {
  1480. out->y.kind = EMappingKind_Button;
  1481. out->y.target = joystick->hwdata->key_map[BTN_Y];
  1482. #ifdef DEBUG_GAMEPAD_MAPPING
  1483. SDL_Log("Mapped Y to button %d (BTN_Y)", out->y.target);
  1484. #endif
  1485. }
  1486. }
  1487. if (joystick->hwdata->has_key[BTN_SELECT]) {
  1488. out->back.kind = EMappingKind_Button;
  1489. out->back.target = joystick->hwdata->key_map[BTN_SELECT];
  1490. #ifdef DEBUG_GAMEPAD_MAPPING
  1491. SDL_Log("Mapped BACK to button %d (BTN_SELECT)", out->back.target);
  1492. #endif
  1493. }
  1494. if (joystick->hwdata->has_key[BTN_START]) {
  1495. out->start.kind = EMappingKind_Button;
  1496. out->start.target = joystick->hwdata->key_map[BTN_START];
  1497. #ifdef DEBUG_GAMEPAD_MAPPING
  1498. SDL_Log("Mapped START to button %d (BTN_START)", out->start.target);
  1499. #endif
  1500. }
  1501. if (joystick->hwdata->has_key[BTN_THUMBL]) {
  1502. out->leftstick.kind = EMappingKind_Button;
  1503. out->leftstick.target = joystick->hwdata->key_map[BTN_THUMBL];
  1504. #ifdef DEBUG_GAMEPAD_MAPPING
  1505. SDL_Log("Mapped LEFTSTICK to button %d (BTN_THUMBL)", out->leftstick.target);
  1506. #endif
  1507. }
  1508. if (joystick->hwdata->has_key[BTN_THUMBR]) {
  1509. out->rightstick.kind = EMappingKind_Button;
  1510. out->rightstick.target = joystick->hwdata->key_map[BTN_THUMBR];
  1511. #ifdef DEBUG_GAMEPAD_MAPPING
  1512. SDL_Log("Mapped RIGHTSTICK to button %d (BTN_THUMBR)", out->rightstick.target);
  1513. #endif
  1514. }
  1515. if (joystick->hwdata->has_key[BTN_MODE]) {
  1516. out->guide.kind = EMappingKind_Button;
  1517. out->guide.target = joystick->hwdata->key_map[BTN_MODE];
  1518. #ifdef DEBUG_GAMEPAD_MAPPING
  1519. SDL_Log("Mapped GUIDE to button %d (BTN_MODE)", out->guide.target);
  1520. #endif
  1521. }
  1522. /*
  1523. According to the specs the D-Pad, the shoulder buttons and the triggers
  1524. can be digital, or analog, or both at the same time.
  1525. */
  1526. /* Prefer digital shoulder buttons, but settle for digital or analog hat. */
  1527. mapped = 0;
  1528. if (joystick->hwdata->has_key[BTN_TL]) {
  1529. out->leftshoulder.kind = EMappingKind_Button;
  1530. out->leftshoulder.target = joystick->hwdata->key_map[BTN_TL];
  1531. mapped |= 0x1;
  1532. #ifdef DEBUG_GAMEPAD_MAPPING
  1533. SDL_Log("Mapped LEFTSHOULDER to button %d (BTN_TL)", out->leftshoulder.target);
  1534. #endif
  1535. }
  1536. if (joystick->hwdata->has_key[BTN_TR]) {
  1537. out->rightshoulder.kind = EMappingKind_Button;
  1538. out->rightshoulder.target = joystick->hwdata->key_map[BTN_TR];
  1539. mapped |= 0x2;
  1540. #ifdef DEBUG_GAMEPAD_MAPPING
  1541. SDL_Log("Mapped RIGHTSHOULDER to button %d (BTN_TR)", out->rightshoulder.target);
  1542. #endif
  1543. }
  1544. if (mapped != 0x3 && joystick->hwdata->has_hat[1]) {
  1545. int hat = joystick->hwdata->hats_indices[1] << 4;
  1546. out->leftshoulder.kind = EMappingKind_Hat;
  1547. out->rightshoulder.kind = EMappingKind_Hat;
  1548. out->leftshoulder.target = hat | 0x4;
  1549. out->rightshoulder.target = hat | 0x2;
  1550. mapped |= 0x3;
  1551. #ifdef DEBUG_GAMEPAD_MAPPING
  1552. SDL_Log("Mapped LEFT+RIGHTSHOULDER to hat 1 (ABS_HAT1X, ABS_HAT1Y)");
  1553. #endif
  1554. }
  1555. if (!(mapped & 0x1) && joystick->hwdata->has_abs[ABS_HAT1Y]) {
  1556. out->leftshoulder.kind = EMappingKind_Axis;
  1557. out->leftshoulder.target = joystick->hwdata->abs_map[ABS_HAT1Y];
  1558. mapped |= 0x1;
  1559. #ifdef DEBUG_GAMEPAD_MAPPING
  1560. SDL_Log("Mapped LEFTSHOULDER to axis %d (ABS_HAT1Y)", out->leftshoulder.target);
  1561. #endif
  1562. }
  1563. if (!(mapped & 0x2) && joystick->hwdata->has_abs[ABS_HAT1X]) {
  1564. out->rightshoulder.kind = EMappingKind_Axis;
  1565. out->rightshoulder.target = joystick->hwdata->abs_map[ABS_HAT1X];
  1566. mapped |= 0x2;
  1567. #ifdef DEBUG_GAMEPAD_MAPPING
  1568. SDL_Log("Mapped RIGHTSHOULDER to axis %d (ABS_HAT1X)", out->rightshoulder.target);
  1569. #endif
  1570. }
  1571. /* Prefer analog triggers, but settle for digital hat or buttons. */
  1572. mapped = 0;
  1573. if (joystick->hwdata->has_abs[ABS_HAT2Y]) {
  1574. out->lefttrigger.kind = EMappingKind_Axis;
  1575. out->lefttrigger.target = joystick->hwdata->abs_map[ABS_HAT2Y];
  1576. mapped |= MAPPED_TRIGGER_LEFT;
  1577. #ifdef DEBUG_GAMEPAD_MAPPING
  1578. SDL_Log("Mapped LEFTTRIGGER to axis %d (ABS_HAT2Y)", out->lefttrigger.target);
  1579. #endif
  1580. } else if (joystick->hwdata->has_abs[ABS_Z]) {
  1581. out->lefttrigger.kind = EMappingKind_Axis;
  1582. out->lefttrigger.target = joystick->hwdata->abs_map[ABS_Z];
  1583. mapped |= MAPPED_TRIGGER_LEFT;
  1584. #ifdef DEBUG_GAMEPAD_MAPPING
  1585. SDL_Log("Mapped LEFTTRIGGER to axis %d (ABS_Z)", out->lefttrigger.target);
  1586. #endif
  1587. }
  1588. if (joystick->hwdata->has_abs[ABS_HAT2X]) {
  1589. out->righttrigger.kind = EMappingKind_Axis;
  1590. out->righttrigger.target = joystick->hwdata->abs_map[ABS_HAT2X];
  1591. mapped |= MAPPED_TRIGGER_RIGHT;
  1592. #ifdef DEBUG_GAMEPAD_MAPPING
  1593. SDL_Log("Mapped RIGHTTRIGGER to axis %d (ABS_HAT2X)", out->righttrigger.target);
  1594. #endif
  1595. } else if (joystick->hwdata->has_abs[ABS_RZ]) {
  1596. out->righttrigger.kind = EMappingKind_Axis;
  1597. out->righttrigger.target = joystick->hwdata->abs_map[ABS_RZ];
  1598. mapped |= MAPPED_TRIGGER_RIGHT;
  1599. #ifdef DEBUG_GAMEPAD_MAPPING
  1600. SDL_Log("Mapped RIGHTTRIGGER to axis %d (ABS_RZ)", out->righttrigger.target);
  1601. #endif
  1602. }
  1603. if (mapped != MAPPED_TRIGGER_BOTH && joystick->hwdata->has_hat[2]) {
  1604. int hat = joystick->hwdata->hats_indices[2] << 4;
  1605. out->lefttrigger.kind = EMappingKind_Hat;
  1606. out->righttrigger.kind = EMappingKind_Hat;
  1607. out->lefttrigger.target = hat | 0x4;
  1608. out->righttrigger.target = hat | 0x2;
  1609. mapped |= MAPPED_TRIGGER_BOTH;
  1610. #ifdef DEBUG_GAMEPAD_MAPPING
  1611. SDL_Log("Mapped LEFT+RIGHTTRIGGER to hat 2 (ABS_HAT2X, ABS_HAT2Y)");
  1612. #endif
  1613. }
  1614. if (!(mapped & MAPPED_TRIGGER_LEFT) && joystick->hwdata->has_key[BTN_TL2]) {
  1615. out->lefttrigger.kind = EMappingKind_Button;
  1616. out->lefttrigger.target = joystick->hwdata->key_map[BTN_TL2];
  1617. mapped |= MAPPED_TRIGGER_LEFT;
  1618. #ifdef DEBUG_GAMEPAD_MAPPING
  1619. SDL_Log("Mapped LEFTTRIGGER to button %d (BTN_TL2)", out->lefttrigger.target);
  1620. #endif
  1621. }
  1622. if (!(mapped & MAPPED_TRIGGER_LEFT) && joystick->hwdata->has_key[BTN_TR2]) {
  1623. out->righttrigger.kind = EMappingKind_Button;
  1624. out->righttrigger.target = joystick->hwdata->key_map[BTN_TR2];
  1625. mapped |= MAPPED_TRIGGER_RIGHT;
  1626. #ifdef DEBUG_GAMEPAD_MAPPING
  1627. SDL_Log("Mapped RIGHTTRIGGER to button %d (BTN_TR2)", out->righttrigger.target);
  1628. #endif
  1629. }
  1630. /* Prefer digital D-Pad buttons, but settle for digital or analog hat. */
  1631. mapped = 0;
  1632. if (joystick->hwdata->has_key[BTN_DPAD_UP]) {
  1633. out->dpup.kind = EMappingKind_Button;
  1634. out->dpup.target = joystick->hwdata->key_map[BTN_DPAD_UP];
  1635. mapped |= MAPPED_DPAD_UP;
  1636. #ifdef DEBUG_GAMEPAD_MAPPING
  1637. SDL_Log("Mapped DPUP to button %d (BTN_DPAD_UP)", out->dpup.target);
  1638. #endif
  1639. }
  1640. if (joystick->hwdata->has_key[BTN_DPAD_DOWN]) {
  1641. out->dpdown.kind = EMappingKind_Button;
  1642. out->dpdown.target = joystick->hwdata->key_map[BTN_DPAD_DOWN];
  1643. mapped |= MAPPED_DPAD_DOWN;
  1644. #ifdef DEBUG_GAMEPAD_MAPPING
  1645. SDL_Log("Mapped DPDOWN to button %d (BTN_DPAD_DOWN)", out->dpdown.target);
  1646. #endif
  1647. }
  1648. if (joystick->hwdata->has_key[BTN_DPAD_LEFT]) {
  1649. out->dpleft.kind = EMappingKind_Button;
  1650. out->dpleft.target = joystick->hwdata->key_map[BTN_DPAD_LEFT];
  1651. mapped |= MAPPED_DPAD_LEFT;
  1652. #ifdef DEBUG_GAMEPAD_MAPPING
  1653. SDL_Log("Mapped DPLEFT to button %d (BTN_DPAD_LEFT)", out->dpleft.target);
  1654. #endif
  1655. }
  1656. if (joystick->hwdata->has_key[BTN_DPAD_RIGHT]) {
  1657. out->dpright.kind = EMappingKind_Button;
  1658. out->dpright.target = joystick->hwdata->key_map[BTN_DPAD_RIGHT];
  1659. mapped |= MAPPED_DPAD_RIGHT;
  1660. #ifdef DEBUG_GAMEPAD_MAPPING
  1661. SDL_Log("Mapped DPRIGHT to button %d (BTN_DPAD_RIGHT)", out->dpright.target);
  1662. #endif
  1663. }
  1664. if (mapped != MAPPED_DPAD_ALL) {
  1665. if (joystick->hwdata->has_hat[0]) {
  1666. int hat = joystick->hwdata->hats_indices[0] << 4;
  1667. out->dpleft.kind = EMappingKind_Hat;
  1668. out->dpright.kind = EMappingKind_Hat;
  1669. out->dpup.kind = EMappingKind_Hat;
  1670. out->dpdown.kind = EMappingKind_Hat;
  1671. out->dpleft.target = hat | 0x8;
  1672. out->dpright.target = hat | 0x2;
  1673. out->dpup.target = hat | 0x1;
  1674. out->dpdown.target = hat | 0x4;
  1675. mapped |= MAPPED_DPAD_ALL;
  1676. #ifdef DEBUG_GAMEPAD_MAPPING
  1677. SDL_Log("Mapped DPUP+DOWN+LEFT+RIGHT to hat 0 (ABS_HAT0X, ABS_HAT0Y)");
  1678. #endif
  1679. } else if (joystick->hwdata->has_abs[ABS_HAT0X] && joystick->hwdata->has_abs[ABS_HAT0Y]) {
  1680. out->dpleft.kind = EMappingKind_Axis;
  1681. out->dpright.kind = EMappingKind_Axis;
  1682. out->dpup.kind = EMappingKind_Axis;
  1683. out->dpdown.kind = EMappingKind_Axis;
  1684. out->dpleft.target = joystick->hwdata->abs_map[ABS_HAT0X];
  1685. out->dpright.target = joystick->hwdata->abs_map[ABS_HAT0X];
  1686. out->dpup.target = joystick->hwdata->abs_map[ABS_HAT0Y];
  1687. out->dpdown.target = joystick->hwdata->abs_map[ABS_HAT0Y];
  1688. mapped |= MAPPED_DPAD_ALL;
  1689. #ifdef DEBUG_GAMEPAD_MAPPING
  1690. SDL_Log("Mapped DPUP+DOWN to axis %d (ABS_HAT0Y)", out->dpup.target);
  1691. SDL_Log("Mapped DPLEFT+RIGHT to axis %d (ABS_HAT0X)", out->dpleft.target);
  1692. #endif
  1693. }
  1694. }
  1695. if (joystick->hwdata->has_abs[ABS_X] && joystick->hwdata->has_abs[ABS_Y]) {
  1696. out->leftx.kind = EMappingKind_Axis;
  1697. out->lefty.kind = EMappingKind_Axis;
  1698. out->leftx.target = joystick->hwdata->abs_map[ABS_X];
  1699. out->lefty.target = joystick->hwdata->abs_map[ABS_Y];
  1700. #ifdef DEBUG_GAMEPAD_MAPPING
  1701. SDL_Log("Mapped LEFTX to axis %d (ABS_X)", out->leftx.target);
  1702. SDL_Log("Mapped LEFTY to axis %d (ABS_Y)", out->lefty.target);
  1703. #endif
  1704. }
  1705. if (joystick->hwdata->has_abs[ABS_RX] && joystick->hwdata->has_abs[ABS_RY]) {
  1706. out->rightx.kind = EMappingKind_Axis;
  1707. out->righty.kind = EMappingKind_Axis;
  1708. out->rightx.target = joystick->hwdata->abs_map[ABS_RX];
  1709. out->righty.target = joystick->hwdata->abs_map[ABS_RY];
  1710. #ifdef DEBUG_GAMEPAD_MAPPING
  1711. SDL_Log("Mapped RIGHTX to axis %d (ABS_RX)", out->rightx.target);
  1712. SDL_Log("Mapped RIGHTY to axis %d (ABS_RY)", out->righty.target);
  1713. #endif
  1714. }
  1715. LINUX_JoystickClose(joystick);
  1716. SDL_free(joystick);
  1717. /* Cache the mapping for later */
  1718. item->mapping = (SDL_GamepadMapping *)SDL_malloc(sizeof(*item->mapping));
  1719. if (item->mapping) {
  1720. SDL_memcpy(item->mapping, out, sizeof(*out));
  1721. }
  1722. #ifdef DEBUG_GAMEPAD_MAPPING
  1723. SDL_Log("Generated mapping for device %d", device_index);
  1724. #endif
  1725. return SDL_TRUE;
  1726. }
  1727. SDL_JoystickDriver SDL_LINUX_JoystickDriver = {
  1728. LINUX_JoystickInit,
  1729. LINUX_JoystickGetCount,
  1730. LINUX_JoystickDetect,
  1731. LINUX_JoystickGetDeviceName,
  1732. LINUX_JoystickGetDevicePath,
  1733. LINUX_JoystickGetDevicePlayerIndex,
  1734. LINUX_JoystickSetDevicePlayerIndex,
  1735. LINUX_JoystickGetDeviceGUID,
  1736. LINUX_JoystickGetDeviceInstanceID,
  1737. LINUX_JoystickOpen,
  1738. LINUX_JoystickRumble,
  1739. LINUX_JoystickRumbleTriggers,
  1740. LINUX_JoystickGetCapabilities,
  1741. LINUX_JoystickSetLED,
  1742. LINUX_JoystickSendEffect,
  1743. LINUX_JoystickSetSensorsEnabled,
  1744. LINUX_JoystickUpdate,
  1745. LINUX_JoystickClose,
  1746. LINUX_JoystickQuit,
  1747. LINUX_JoystickGetGamepadMapping
  1748. };
  1749. #endif /* SDL_JOYSTICK_LINUX */