SDL_hidapijoystick.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2021 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_HIDAPI
  20. #include "SDL_atomic.h"
  21. #include "SDL_endian.h"
  22. #include "SDL_hints.h"
  23. #include "SDL_thread.h"
  24. #include "SDL_timer.h"
  25. #include "SDL_joystick.h"
  26. #include "SDL_log.h"
  27. #include "../SDL_sysjoystick.h"
  28. #include "SDL_hidapijoystick_c.h"
  29. #include "SDL_hidapi_rumble.h"
  30. #include "../../SDL_hints_c.h"
  31. #if defined(__WIN32__)
  32. #include "../../core/windows/SDL_windows.h"
  33. #include "../windows/SDL_rawinputjoystick_c.h"
  34. #endif
  35. #if defined(__MACOSX__)
  36. #include <CoreFoundation/CoreFoundation.h>
  37. #include <mach/mach.h>
  38. #include <IOKit/IOKitLib.h>
  39. #include <IOKit/hid/IOHIDDevice.h>
  40. #include <IOKit/usb/USBSpec.h>
  41. #endif
  42. #if defined(__LINUX__)
  43. #include "../../core/linux/SDL_udev.h"
  44. #ifdef SDL_USE_LIBUDEV
  45. #include <poll.h>
  46. #endif
  47. #ifdef HAVE_INOTIFY
  48. #include <errno.h> /* errno, strerror */
  49. #include <fcntl.h>
  50. #include <limits.h> /* For the definition of NAME_MAX */
  51. #include <sys/inotify.h>
  52. #endif
  53. #include <unistd.h>
  54. #endif
  55. #if defined(SDL_USE_LIBUDEV)
  56. typedef enum
  57. {
  58. ENUMERATION_UNSET,
  59. ENUMERATION_LIBUDEV,
  60. ENUMERATION_FALLBACK
  61. } LinuxEnumerationMethod;
  62. static LinuxEnumerationMethod linux_enumeration_method = ENUMERATION_UNSET;
  63. #endif
  64. struct joystick_hwdata
  65. {
  66. SDL_HIDAPI_Device *device;
  67. };
  68. static SDL_HIDAPI_DeviceDriver *SDL_HIDAPI_drivers[] = {
  69. #ifdef SDL_JOYSTICK_HIDAPI_GAMECUBE
  70. &SDL_HIDAPI_DriverGameCube,
  71. #endif
  72. #ifdef SDL_JOYSTICK_HIDAPI_PS4
  73. &SDL_HIDAPI_DriverPS4,
  74. #endif
  75. #ifdef SDL_JOYSTICK_HIDAPI_PS5
  76. &SDL_HIDAPI_DriverPS5,
  77. #endif
  78. #ifdef SDL_JOYSTICK_HIDAPI_STADIA
  79. &SDL_HIDAPI_DriverStadia,
  80. #endif
  81. #ifdef SDL_JOYSTICK_HIDAPI_STEAM
  82. &SDL_HIDAPI_DriverSteam,
  83. #endif
  84. #ifdef SDL_JOYSTICK_HIDAPI_SWITCH
  85. &SDL_HIDAPI_DriverSwitch,
  86. #endif
  87. #ifdef SDL_JOYSTICK_HIDAPI_XBOX360
  88. &SDL_HIDAPI_DriverXbox360,
  89. &SDL_HIDAPI_DriverXbox360W,
  90. #endif
  91. #ifdef SDL_JOYSTICK_HIDAPI_XBOXONE
  92. &SDL_HIDAPI_DriverXboxOne,
  93. #endif
  94. };
  95. static int SDL_HIDAPI_numdrivers = 0;
  96. static SDL_SpinLock SDL_HIDAPI_spinlock;
  97. static SDL_HIDAPI_Device *SDL_HIDAPI_devices;
  98. static int SDL_HIDAPI_numjoysticks = 0;
  99. static SDL_bool initialized = SDL_FALSE;
  100. static SDL_bool shutting_down = SDL_FALSE;
  101. #if defined(HAVE_INOTIFY)
  102. static int inotify_fd = -1;
  103. #endif
  104. #if defined(SDL_USE_LIBUDEV)
  105. static const SDL_UDEV_Symbols * usyms = NULL;
  106. #endif
  107. static struct
  108. {
  109. SDL_bool m_bHaveDevicesChanged;
  110. SDL_bool m_bCanGetNotifications;
  111. Uint32 m_unLastDetect;
  112. #if defined(__WIN32__)
  113. SDL_threadID m_nThreadID;
  114. WNDCLASSEXA m_wndClass;
  115. HWND m_hwndMsg;
  116. HDEVNOTIFY m_hNotify;
  117. double m_flLastWin32MessageCheck;
  118. #endif
  119. #if defined(__MACOSX__)
  120. IONotificationPortRef m_notificationPort;
  121. mach_port_t m_notificationMach;
  122. #endif
  123. #if defined(SDL_USE_LIBUDEV)
  124. struct udev *m_pUdev;
  125. struct udev_monitor *m_pUdevMonitor;
  126. int m_nUdevFd;
  127. #endif
  128. } SDL_HIDAPI_discovery;
  129. #ifdef __WIN32__
  130. struct _DEV_BROADCAST_HDR
  131. {
  132. DWORD dbch_size;
  133. DWORD dbch_devicetype;
  134. DWORD dbch_reserved;
  135. };
  136. typedef struct _DEV_BROADCAST_DEVICEINTERFACE_A
  137. {
  138. DWORD dbcc_size;
  139. DWORD dbcc_devicetype;
  140. DWORD dbcc_reserved;
  141. GUID dbcc_classguid;
  142. char dbcc_name[ 1 ];
  143. } DEV_BROADCAST_DEVICEINTERFACE_A, *PDEV_BROADCAST_DEVICEINTERFACE_A;
  144. typedef struct _DEV_BROADCAST_HDR DEV_BROADCAST_HDR;
  145. #define DBT_DEVICEARRIVAL 0x8000 /* system detected a new device */
  146. #define DBT_DEVICEREMOVECOMPLETE 0x8004 /* device was removed from the system */
  147. #define DBT_DEVTYP_DEVICEINTERFACE 0x00000005 /* device interface class */
  148. #define DBT_DEVNODES_CHANGED 0x0007
  149. #define DBT_CONFIGCHANGED 0x0018
  150. #define DBT_DEVICETYPESPECIFIC 0x8005 /* type specific event */
  151. #define DBT_DEVINSTSTARTED 0x8008 /* device installed and started */
  152. #include <initguid.h>
  153. DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);
  154. static LRESULT CALLBACK ControllerWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  155. {
  156. switch (message) {
  157. case WM_DEVICECHANGE:
  158. switch (wParam) {
  159. case DBT_DEVICEARRIVAL:
  160. case DBT_DEVICEREMOVECOMPLETE:
  161. if (((DEV_BROADCAST_HDR*)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
  162. SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
  163. }
  164. break;
  165. }
  166. return TRUE;
  167. }
  168. return DefWindowProc(hwnd, message, wParam, lParam);
  169. }
  170. #endif /* __WIN32__ */
  171. #if defined(__MACOSX__)
  172. static void CallbackIOServiceFunc(void *context, io_iterator_t portIterator)
  173. {
  174. /* Must drain the iterator, or we won't receive new notifications */
  175. io_object_t entry;
  176. while ((entry = IOIteratorNext(portIterator)) != 0) {
  177. IOObjectRelease(entry);
  178. *(SDL_bool*)context = SDL_TRUE;
  179. }
  180. }
  181. #endif /* __MACOSX__ */
  182. #ifdef HAVE_INOTIFY
  183. #ifdef HAVE_INOTIFY_INIT1
  184. static int SDL_inotify_init1(void) {
  185. return inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
  186. }
  187. #else
  188. static int SDL_inotify_init1(void) {
  189. int fd = inotify_init();
  190. if (fd < 0) return -1;
  191. fcntl(fd, F_SETFL, O_NONBLOCK);
  192. fcntl(fd, F_SETFD, FD_CLOEXEC);
  193. return fd;
  194. }
  195. #endif
  196. static int
  197. StrHasPrefix(const char *string, const char *prefix)
  198. {
  199. return (SDL_strncmp(string, prefix, SDL_strlen(prefix)) == 0);
  200. }
  201. static int
  202. StrIsInteger(const char *string)
  203. {
  204. const char *p;
  205. if (*string == '\0') {
  206. return 0;
  207. }
  208. for (p = string; *p != '\0'; p++) {
  209. if (*p < '0' || *p > '9') {
  210. return 0;
  211. }
  212. }
  213. return 1;
  214. }
  215. #endif
  216. static void
  217. HIDAPI_InitializeDiscovery()
  218. {
  219. SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
  220. SDL_HIDAPI_discovery.m_bCanGetNotifications = SDL_FALSE;
  221. SDL_HIDAPI_discovery.m_unLastDetect = 0;
  222. #if defined(__WIN32__)
  223. SDL_HIDAPI_discovery.m_nThreadID = SDL_ThreadID();
  224. SDL_zero(SDL_HIDAPI_discovery.m_wndClass);
  225. SDL_HIDAPI_discovery.m_wndClass.hInstance = GetModuleHandle(NULL);
  226. SDL_HIDAPI_discovery.m_wndClass.lpszClassName = "SDL_HIDAPI_DEVICE_DETECTION";
  227. SDL_HIDAPI_discovery.m_wndClass.lpfnWndProc = ControllerWndProc; /* This function is called by windows */
  228. SDL_HIDAPI_discovery.m_wndClass.cbSize = sizeof(WNDCLASSEX);
  229. RegisterClassExA(&SDL_HIDAPI_discovery.m_wndClass);
  230. SDL_HIDAPI_discovery.m_hwndMsg = CreateWindowExA(0, "SDL_HIDAPI_DEVICE_DETECTION", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
  231. {
  232. DEV_BROADCAST_DEVICEINTERFACE_A devBroadcast;
  233. SDL_zero(devBroadcast);
  234. devBroadcast.dbcc_size = sizeof( devBroadcast );
  235. devBroadcast.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
  236. devBroadcast.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
  237. /* DEVICE_NOTIFY_ALL_INTERFACE_CLASSES is important, makes GUID_DEVINTERFACE_USB_DEVICE ignored,
  238. * but that seems to be necessary to get a notice after each individual usb input device actually
  239. * installs, rather than just as the composite device is seen.
  240. */
  241. SDL_HIDAPI_discovery.m_hNotify = RegisterDeviceNotification( SDL_HIDAPI_discovery.m_hwndMsg, &devBroadcast, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES );
  242. SDL_HIDAPI_discovery.m_bCanGetNotifications = ( SDL_HIDAPI_discovery.m_hNotify != 0 );
  243. }
  244. #endif /* __WIN32__ */
  245. #if defined(__MACOSX__)
  246. SDL_HIDAPI_discovery.m_notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
  247. if (SDL_HIDAPI_discovery.m_notificationPort) {
  248. {
  249. io_iterator_t portIterator = 0;
  250. io_object_t entry;
  251. IOReturn result = IOServiceAddMatchingNotification(
  252. SDL_HIDAPI_discovery.m_notificationPort,
  253. kIOFirstMatchNotification,
  254. IOServiceMatching(kIOHIDDeviceKey),
  255. CallbackIOServiceFunc, &SDL_HIDAPI_discovery.m_bHaveDevicesChanged, &portIterator);
  256. if (result == 0) {
  257. /* Must drain the existing iterator, or we won't receive new notifications */
  258. while ((entry = IOIteratorNext(portIterator)) != 0) {
  259. IOObjectRelease(entry);
  260. }
  261. } else {
  262. IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort);
  263. SDL_HIDAPI_discovery.m_notificationPort = nil;
  264. }
  265. }
  266. {
  267. io_iterator_t portIterator = 0;
  268. io_object_t entry;
  269. IOReturn result = IOServiceAddMatchingNotification(
  270. SDL_HIDAPI_discovery.m_notificationPort,
  271. kIOTerminatedNotification,
  272. IOServiceMatching(kIOHIDDeviceKey),
  273. CallbackIOServiceFunc, &SDL_HIDAPI_discovery.m_bHaveDevicesChanged, &portIterator);
  274. if (result == 0) {
  275. /* Must drain the existing iterator, or we won't receive new notifications */
  276. while ((entry = IOIteratorNext(portIterator)) != 0) {
  277. IOObjectRelease(entry);
  278. }
  279. } else {
  280. IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort);
  281. SDL_HIDAPI_discovery.m_notificationPort = nil;
  282. }
  283. }
  284. }
  285. SDL_HIDAPI_discovery.m_notificationMach = MACH_PORT_NULL;
  286. if (SDL_HIDAPI_discovery.m_notificationPort) {
  287. SDL_HIDAPI_discovery.m_notificationMach = IONotificationPortGetMachPort(SDL_HIDAPI_discovery.m_notificationPort);
  288. }
  289. SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_notificationMach != MACH_PORT_NULL);
  290. #endif // __MACOSX__
  291. #if defined(SDL_USE_LIBUDEV)
  292. if (linux_enumeration_method == ENUMERATION_LIBUDEV) {
  293. SDL_HIDAPI_discovery.m_pUdev = NULL;
  294. SDL_HIDAPI_discovery.m_pUdevMonitor = NULL;
  295. SDL_HIDAPI_discovery.m_nUdevFd = -1;
  296. usyms = SDL_UDEV_GetUdevSyms();
  297. if (usyms) {
  298. SDL_HIDAPI_discovery.m_pUdev = usyms->udev_new();
  299. }
  300. if (SDL_HIDAPI_discovery.m_pUdev) {
  301. SDL_HIDAPI_discovery.m_pUdevMonitor = usyms->udev_monitor_new_from_netlink(SDL_HIDAPI_discovery.m_pUdev, "udev");
  302. if (SDL_HIDAPI_discovery.m_pUdevMonitor) {
  303. usyms->udev_monitor_enable_receiving(SDL_HIDAPI_discovery.m_pUdevMonitor);
  304. SDL_HIDAPI_discovery.m_nUdevFd = usyms->udev_monitor_get_fd(SDL_HIDAPI_discovery.m_pUdevMonitor);
  305. SDL_HIDAPI_discovery.m_bCanGetNotifications = SDL_TRUE;
  306. }
  307. }
  308. }
  309. else
  310. #endif /* SDL_USE_LIBUDEV */
  311. {
  312. #if defined(HAVE_INOTIFY)
  313. inotify_fd = SDL_inotify_init1();
  314. if (inotify_fd < 0) {
  315. SDL_LogWarn(SDL_LOG_CATEGORY_INPUT,
  316. "Unable to initialize inotify, falling back to polling: %s",
  317. strerror(errno));
  318. return;
  319. }
  320. /* We need to watch for attribute changes in addition to
  321. * creation, because when a device is first created, it has
  322. * permissions that we can't read. When udev chmods it to
  323. * something that we maybe *can* read, we'll get an
  324. * IN_ATTRIB event to tell us. */
  325. if (inotify_add_watch(inotify_fd, "/dev",
  326. IN_CREATE | IN_DELETE | IN_MOVE | IN_ATTRIB) < 0) {
  327. close(inotify_fd);
  328. inotify_fd = -1;
  329. SDL_LogWarn(SDL_LOG_CATEGORY_INPUT,
  330. "Unable to add inotify watch, falling back to polling: %s",
  331. strerror (errno));
  332. return;
  333. }
  334. SDL_HIDAPI_discovery.m_bCanGetNotifications = SDL_TRUE;
  335. #endif /* HAVE_INOTIFY */
  336. }
  337. }
  338. static void
  339. HIDAPI_UpdateDiscovery()
  340. {
  341. if (!SDL_HIDAPI_discovery.m_bCanGetNotifications) {
  342. const Uint32 SDL_HIDAPI_DETECT_INTERVAL_MS = 3000; /* Update every 3 seconds */
  343. Uint32 now = SDL_GetTicks();
  344. if (!SDL_HIDAPI_discovery.m_unLastDetect || SDL_TICKS_PASSED(now, SDL_HIDAPI_discovery.m_unLastDetect + SDL_HIDAPI_DETECT_INTERVAL_MS)) {
  345. SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
  346. SDL_HIDAPI_discovery.m_unLastDetect = now;
  347. }
  348. return;
  349. }
  350. #if defined(__WIN32__)
  351. #if 0 /* just let the usual SDL_PumpEvents loop dispatch these, fixing bug 4286. --ryan. */
  352. /* We'll only get messages on the same thread that created the window */
  353. if (SDL_ThreadID() == SDL_HIDAPI_discovery.m_nThreadID) {
  354. MSG msg;
  355. while (PeekMessage(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0, PM_NOREMOVE)) {
  356. if (GetMessageA(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0) != 0) {
  357. TranslateMessage(&msg);
  358. DispatchMessage(&msg);
  359. }
  360. }
  361. }
  362. #endif
  363. #endif /* __WIN32__ */
  364. #if defined(__MACOSX__)
  365. if (SDL_HIDAPI_discovery.m_notificationPort) {
  366. struct { mach_msg_header_t hdr; char payload[ 4096 ]; } msg;
  367. while (mach_msg(&msg.hdr, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(msg), SDL_HIDAPI_discovery.m_notificationMach, 0, MACH_PORT_NULL) == KERN_SUCCESS) {
  368. IODispatchCalloutFromMessage(NULL, &msg.hdr, SDL_HIDAPI_discovery.m_notificationPort);
  369. }
  370. }
  371. #endif
  372. #if defined(SDL_USE_LIBUDEV)
  373. if (linux_enumeration_method == ENUMERATION_LIBUDEV) {
  374. if (SDL_HIDAPI_discovery.m_nUdevFd >= 0) {
  375. /* Drain all notification events.
  376. * We don't expect a lot of device notifications so just
  377. * do a new discovery on any kind or number of notifications.
  378. * This could be made more restrictive if necessary.
  379. */
  380. for (;;) {
  381. struct pollfd PollUdev;
  382. struct udev_device *pUdevDevice;
  383. PollUdev.fd = SDL_HIDAPI_discovery.m_nUdevFd;
  384. PollUdev.events = POLLIN;
  385. if (poll(&PollUdev, 1, 0) != 1) {
  386. break;
  387. }
  388. pUdevDevice = usyms->udev_monitor_receive_device(SDL_HIDAPI_discovery.m_pUdevMonitor);
  389. if (pUdevDevice) {
  390. const char *action = NULL;
  391. action = usyms->udev_device_get_action(pUdevDevice);
  392. if (!action || SDL_strcmp(action, "add") == 0 || SDL_strcmp(action, "remove") == 0) {
  393. SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
  394. }
  395. usyms->udev_device_unref(pUdevDevice);
  396. }
  397. }
  398. }
  399. }
  400. else
  401. #endif /* SDL_USE_LIBUDEV */
  402. {
  403. #if defined(HAVE_INOTIFY)
  404. if (inotify_fd >= 0) {
  405. union
  406. {
  407. struct inotify_event event;
  408. char storage[4096];
  409. char enough_for_inotify[sizeof (struct inotify_event) + NAME_MAX + 1];
  410. } buf;
  411. ssize_t bytes;
  412. size_t remain = 0;
  413. size_t len;
  414. bytes = read(inotify_fd, &buf, sizeof (buf));
  415. if (bytes > 0) {
  416. remain = (size_t) bytes;
  417. }
  418. while (remain > 0) {
  419. if (buf.event.len > 0 &&
  420. !SDL_HIDAPI_discovery.m_bHaveDevicesChanged) {
  421. if (StrHasPrefix(buf.event.name, "hidraw") &&
  422. StrIsInteger(buf.event.name + strlen ("hidraw"))) {
  423. SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
  424. /* We found an hidraw change. We still continue to
  425. * drain the inotify fd to avoid leaving old
  426. * notifications in the queue. */
  427. }
  428. }
  429. len = sizeof (struct inotify_event) + buf.event.len;
  430. remain -= len;
  431. if (remain != 0) {
  432. memmove(&buf.storage[0], &buf.storage[len], remain);
  433. }
  434. }
  435. }
  436. #endif /* HAVE_INOTIFY */
  437. }
  438. }
  439. static void
  440. HIDAPI_ShutdownDiscovery()
  441. {
  442. #if defined(__WIN32__)
  443. if (SDL_HIDAPI_discovery.m_hNotify)
  444. UnregisterDeviceNotification(SDL_HIDAPI_discovery.m_hNotify);
  445. if (SDL_HIDAPI_discovery.m_hwndMsg) {
  446. DestroyWindow(SDL_HIDAPI_discovery.m_hwndMsg);
  447. }
  448. UnregisterClassA(SDL_HIDAPI_discovery.m_wndClass.lpszClassName, SDL_HIDAPI_discovery.m_wndClass.hInstance);
  449. #endif
  450. #if defined(__MACOSX__)
  451. if (SDL_HIDAPI_discovery.m_notificationPort) {
  452. IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort);
  453. }
  454. #endif
  455. #if defined(SDL_USE_LIBUDEV)
  456. if (linux_enumeration_method == ENUMERATION_LIBUDEV &&
  457. usyms) {
  458. if (SDL_HIDAPI_discovery.m_pUdevMonitor) {
  459. usyms->udev_monitor_unref(SDL_HIDAPI_discovery.m_pUdevMonitor);
  460. }
  461. if (SDL_HIDAPI_discovery.m_pUdev) {
  462. usyms->udev_unref(SDL_HIDAPI_discovery.m_pUdev);
  463. }
  464. SDL_UDEV_ReleaseUdevSyms();
  465. usyms = NULL;
  466. }
  467. #endif
  468. }
  469. void
  470. HIDAPI_DumpPacket(const char *prefix, Uint8 *data, int size)
  471. {
  472. int i;
  473. char *buffer;
  474. size_t length = SDL_strlen(prefix) + 11*(USB_PACKET_LENGTH/8) + (5*USB_PACKET_LENGTH*2) + 1 + 1;
  475. int start = 0, amount = size;
  476. buffer = (char *)SDL_malloc(length);
  477. SDL_snprintf(buffer, length, prefix, size);
  478. for (i = start; i < start+amount; ++i) {
  479. if ((i % 8) == 0) {
  480. SDL_snprintf(&buffer[SDL_strlen(buffer)], length - SDL_strlen(buffer), "\n%.2d: ", i);
  481. }
  482. SDL_snprintf(&buffer[SDL_strlen(buffer)], length - SDL_strlen(buffer), " 0x%.2x", data[i]);
  483. }
  484. SDL_strlcat(buffer, "\n", length);
  485. SDL_Log("%s", buffer);
  486. SDL_free(buffer);
  487. }
  488. float
  489. HIDAPI_RemapVal(float val, float val_min, float val_max, float output_min, float output_max)
  490. {
  491. return output_min + (output_max - output_min) * (val - val_min) / (val_max - val_min);
  492. }
  493. static void HIDAPI_JoystickDetect(void);
  494. static void HIDAPI_JoystickClose(SDL_Joystick * joystick);
  495. static SDL_bool
  496. HIDAPI_IsDeviceSupported(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name)
  497. {
  498. int i;
  499. SDL_GameControllerType type = SDL_GetJoystickGameControllerType(name, vendor_id, product_id, -1, 0, 0, 0);
  500. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  501. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  502. if (driver->enabled && driver->IsSupportedDevice(name, type, vendor_id, product_id, version, -1, 0, 0, 0)) {
  503. return SDL_TRUE;
  504. }
  505. }
  506. return SDL_FALSE;
  507. }
  508. static SDL_HIDAPI_DeviceDriver *
  509. HIDAPI_GetDeviceDriver(SDL_HIDAPI_Device *device)
  510. {
  511. const Uint16 USAGE_PAGE_GENERIC_DESKTOP = 0x0001;
  512. const Uint16 USAGE_JOYSTICK = 0x0004;
  513. const Uint16 USAGE_GAMEPAD = 0x0005;
  514. const Uint16 USAGE_MULTIAXISCONTROLLER = 0x0008;
  515. int i;
  516. SDL_GameControllerType type;
  517. SDL_JoystickGUID check_guid;
  518. /* Make sure we have a generic GUID here, otherwise if we pass a HIDAPI
  519. guid, this call will create a game controller mapping for the device.
  520. */
  521. check_guid = device->guid;
  522. check_guid.data[14] = 0;
  523. if (SDL_ShouldIgnoreJoystick(device->name, check_guid)) {
  524. return NULL;
  525. }
  526. if (device->vendor_id != USB_VENDOR_VALVE) {
  527. if (device->usage_page && device->usage_page != USAGE_PAGE_GENERIC_DESKTOP) {
  528. return NULL;
  529. }
  530. if (device->usage && device->usage != USAGE_JOYSTICK && device->usage != USAGE_GAMEPAD && device->usage != USAGE_MULTIAXISCONTROLLER) {
  531. return NULL;
  532. }
  533. }
  534. type = SDL_GetJoystickGameControllerType(device->name, device->vendor_id, device->product_id, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol);
  535. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  536. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  537. if (driver->enabled && driver->IsSupportedDevice(device->name, type, device->vendor_id, device->product_id, device->version, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol)) {
  538. return driver;
  539. }
  540. }
  541. return NULL;
  542. }
  543. static SDL_HIDAPI_Device *
  544. HIDAPI_GetDeviceByIndex(int device_index, SDL_JoystickID *pJoystickID)
  545. {
  546. SDL_HIDAPI_Device *device = SDL_HIDAPI_devices;
  547. while (device) {
  548. if (device->driver) {
  549. if (device_index < device->num_joysticks) {
  550. if (pJoystickID) {
  551. *pJoystickID = device->joysticks[device_index];
  552. }
  553. return device;
  554. }
  555. device_index -= device->num_joysticks;
  556. }
  557. device = device->next;
  558. }
  559. return NULL;
  560. }
  561. static SDL_HIDAPI_Device *
  562. HIDAPI_GetJoystickByInfo(const char *path, Uint16 vendor_id, Uint16 product_id)
  563. {
  564. SDL_HIDAPI_Device *device = SDL_HIDAPI_devices;
  565. while (device) {
  566. if (device->vendor_id == vendor_id && device->product_id == product_id &&
  567. SDL_strcmp(device->path, path) == 0) {
  568. break;
  569. }
  570. device = device->next;
  571. }
  572. return device;
  573. }
  574. static void
  575. HIDAPI_SetupDeviceDriver(SDL_HIDAPI_Device *device)
  576. {
  577. if (device->driver) {
  578. /* Already setup */
  579. return;
  580. }
  581. device->driver = HIDAPI_GetDeviceDriver(device);
  582. if (device->driver) {
  583. const char *name = device->driver->GetDeviceName(device->vendor_id, device->product_id);
  584. if (name) {
  585. SDL_free(device->name);
  586. device->name = SDL_strdup(name);
  587. }
  588. }
  589. /* Initialize the device, which may cause a connected event */
  590. if (device->driver && !device->driver->InitDevice(device)) {
  591. device->driver = NULL;
  592. }
  593. }
  594. static void
  595. HIDAPI_CleanupDeviceDriver(SDL_HIDAPI_Device *device)
  596. {
  597. if (!device->driver) {
  598. /* Already cleaned up */
  599. return;
  600. }
  601. /* Disconnect any joysticks */
  602. while (device->num_joysticks) {
  603. HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
  604. }
  605. device->driver->FreeDevice(device);
  606. device->driver = NULL;
  607. }
  608. static void SDLCALL
  609. SDL_HIDAPIDriverHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  610. {
  611. int i;
  612. SDL_HIDAPI_Device *device;
  613. SDL_bool enabled = SDL_GetStringBoolean(hint, SDL_TRUE);
  614. if (SDL_strcmp(name, SDL_HINT_JOYSTICK_HIDAPI) == 0) {
  615. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  616. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  617. driver->enabled = SDL_GetHintBoolean(driver->hint, enabled);
  618. }
  619. } else {
  620. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  621. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  622. if (SDL_strcmp(name, driver->hint) == 0) {
  623. driver->enabled = enabled;
  624. }
  625. }
  626. }
  627. SDL_HIDAPI_numdrivers = 0;
  628. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  629. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  630. if (driver->enabled) {
  631. ++SDL_HIDAPI_numdrivers;
  632. }
  633. }
  634. /* Update device list if driver availability changes */
  635. SDL_LockJoysticks();
  636. for (device = SDL_HIDAPI_devices; device; device = device->next) {
  637. if (device->driver && !device->driver->enabled) {
  638. HIDAPI_CleanupDeviceDriver(device);
  639. }
  640. HIDAPI_SetupDeviceDriver(device);
  641. }
  642. SDL_UnlockJoysticks();
  643. }
  644. static int
  645. HIDAPI_JoystickInit(void)
  646. {
  647. int i;
  648. if (initialized) {
  649. return 0;
  650. }
  651. #if defined(SDL_USE_LIBUDEV)
  652. if (linux_enumeration_method == ENUMERATION_UNSET) {
  653. if (SDL_getenv("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV") != NULL) {
  654. SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
  655. "udev disabled by SDL_HIDAPI_JOYSTICK_DISABLE_UDEV");
  656. linux_enumeration_method = ENUMERATION_FALLBACK;
  657. } else if (access("/.flatpak-info", F_OK) == 0
  658. || access("/run/host/container-manager", F_OK) == 0) {
  659. /* Explicitly check `/.flatpak-info` because, for old versions of
  660. * Flatpak, this was the only available way to tell if we were in
  661. * a Flatpak container. */
  662. SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
  663. "Container detected, disabling HIDAPI udev integration");
  664. linux_enumeration_method = ENUMERATION_FALLBACK;
  665. } else {
  666. SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
  667. "Using udev for HIDAPI joystick device discovery");
  668. linux_enumeration_method = ENUMERATION_LIBUDEV;
  669. }
  670. }
  671. #endif
  672. #if defined(__MACOSX__) || defined(__IPHONEOS__) || defined(__TVOS__)
  673. /* The hidapi framwork is weak-linked on Apple platforms */
  674. int HID_API_EXPORT HID_API_CALL hid_init(void) __attribute__((weak_import));
  675. if (hid_init == NULL) {
  676. SDL_SetError("Couldn't initialize hidapi, framework not available");
  677. return -1;
  678. }
  679. #endif /* __MACOSX__ || __IPHONEOS__ || __TVOS__ */
  680. if (hid_init() < 0) {
  681. SDL_SetError("Couldn't initialize hidapi");
  682. return -1;
  683. }
  684. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  685. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  686. SDL_AddHintCallback(driver->hint, SDL_HIDAPIDriverHintChanged, NULL);
  687. }
  688. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI,
  689. SDL_HIDAPIDriverHintChanged, NULL);
  690. HIDAPI_InitializeDiscovery();
  691. HIDAPI_JoystickDetect();
  692. HIDAPI_UpdateDevices();
  693. initialized = SDL_TRUE;
  694. return 0;
  695. }
  696. SDL_bool
  697. HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID)
  698. {
  699. SDL_JoystickID joystickID;
  700. SDL_JoystickID *joysticks = (SDL_JoystickID *)SDL_realloc(device->joysticks, (device->num_joysticks + 1)*sizeof(*device->joysticks));
  701. if (!joysticks) {
  702. return SDL_FALSE;
  703. }
  704. joystickID = SDL_GetNextJoystickInstanceID();
  705. device->joysticks = joysticks;
  706. device->joysticks[device->num_joysticks++] = joystickID;
  707. ++SDL_HIDAPI_numjoysticks;
  708. SDL_PrivateJoystickAdded(joystickID);
  709. if (pJoystickID) {
  710. *pJoystickID = joystickID;
  711. }
  712. return SDL_TRUE;
  713. }
  714. void
  715. HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID)
  716. {
  717. int i, size;
  718. for (i = 0; i < device->num_joysticks; ++i) {
  719. if (device->joysticks[i] == joystickID) {
  720. SDL_Joystick *joystick = SDL_JoystickFromInstanceID(joystickID);
  721. if (joystick) {
  722. HIDAPI_JoystickClose(joystick);
  723. }
  724. size = (device->num_joysticks - i - 1) * sizeof(SDL_JoystickID);
  725. SDL_memmove(&device->joysticks[i], &device->joysticks[i+1], size);
  726. --device->num_joysticks;
  727. --SDL_HIDAPI_numjoysticks;
  728. if (device->num_joysticks == 0) {
  729. SDL_free(device->joysticks);
  730. device->joysticks = NULL;
  731. }
  732. if (!shutting_down) {
  733. SDL_PrivateJoystickRemoved(joystickID);
  734. }
  735. return;
  736. }
  737. }
  738. }
  739. static int
  740. HIDAPI_JoystickGetCount(void)
  741. {
  742. return SDL_HIDAPI_numjoysticks;
  743. }
  744. static char *
  745. HIDAPI_ConvertString(const wchar_t *wide_string)
  746. {
  747. char *string = NULL;
  748. if (wide_string) {
  749. string = SDL_iconv_string("UTF-8", "WCHAR_T", (char*)wide_string, (SDL_wcslen(wide_string)+1)*sizeof(wchar_t));
  750. if (!string) {
  751. if (sizeof(wchar_t) == sizeof(Uint16)) {
  752. string = SDL_iconv_string("UTF-8", "UCS-2-INTERNAL", (char*)wide_string, (SDL_wcslen(wide_string)+1)*sizeof(wchar_t));
  753. } else if (sizeof(wchar_t) == sizeof(Uint32)) {
  754. string = SDL_iconv_string("UTF-8", "UCS-4-INTERNAL", (char*)wide_string, (SDL_wcslen(wide_string)+1)*sizeof(wchar_t));
  755. }
  756. }
  757. }
  758. return string;
  759. }
  760. static void
  761. HIDAPI_AddDevice(struct hid_device_info *info)
  762. {
  763. SDL_HIDAPI_Device *device;
  764. SDL_HIDAPI_Device *curr, *last = NULL;
  765. for (curr = SDL_HIDAPI_devices, last = NULL; curr; last = curr, curr = curr->next) {
  766. continue;
  767. }
  768. device = (SDL_HIDAPI_Device *)SDL_calloc(1, sizeof(*device));
  769. if (!device) {
  770. return;
  771. }
  772. device->path = SDL_strdup(info->path);
  773. if (!device->path) {
  774. SDL_free(device);
  775. return;
  776. }
  777. device->seen = SDL_TRUE;
  778. device->vendor_id = info->vendor_id;
  779. device->product_id = info->product_id;
  780. device->version = info->release_number;
  781. device->interface_number = info->interface_number;
  782. device->interface_class = info->interface_class;
  783. device->interface_subclass = info->interface_subclass;
  784. device->interface_protocol = info->interface_protocol;
  785. device->usage_page = info->usage_page;
  786. device->usage = info->usage;
  787. {
  788. /* FIXME: Is there any way to tell whether this is a Bluetooth device? */
  789. const Uint16 vendor = device->vendor_id;
  790. const Uint16 product = device->product_id;
  791. const Uint16 version = device->version;
  792. Uint16 *guid16 = (Uint16 *)device->guid.data;
  793. *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_USB);
  794. *guid16++ = 0;
  795. *guid16++ = SDL_SwapLE16(vendor);
  796. *guid16++ = 0;
  797. *guid16++ = SDL_SwapLE16(product);
  798. *guid16++ = 0;
  799. *guid16++ = SDL_SwapLE16(version);
  800. *guid16++ = 0;
  801. /* Note that this is a HIDAPI device for special handling elsewhere */
  802. device->guid.data[14] = 'h';
  803. device->guid.data[15] = 0;
  804. }
  805. device->dev_lock = SDL_CreateMutex();
  806. /* Need the device name before getting the driver to know whether to ignore this device */
  807. {
  808. char *manufacturer_string = HIDAPI_ConvertString(info->manufacturer_string);
  809. char *product_string = HIDAPI_ConvertString(info->product_string);
  810. char *serial_number = HIDAPI_ConvertString(info->serial_number);
  811. device->name = SDL_CreateJoystickName(device->vendor_id, device->product_id, manufacturer_string, product_string);
  812. if (SDL_strncmp(device->name, "0x", 2) == 0) {
  813. /* Couldn't find a controller name, try to give it one based on device type */
  814. const char *name = NULL;
  815. switch (SDL_GetJoystickGameControllerType(NULL, device->vendor_id, device->product_id, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol)) {
  816. case SDL_CONTROLLER_TYPE_XBOX360:
  817. name = "Xbox 360 Controller";
  818. break;
  819. case SDL_CONTROLLER_TYPE_XBOXONE:
  820. name = "Xbox One Controller";
  821. break;
  822. case SDL_CONTROLLER_TYPE_PS3:
  823. name = "PS3 Controller";
  824. break;
  825. case SDL_CONTROLLER_TYPE_PS4:
  826. name = "PS4 Controller";
  827. break;
  828. case SDL_CONTROLLER_TYPE_PS5:
  829. name = "PS5 Controller";
  830. break;
  831. case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO:
  832. name = "Nintendo Switch Pro Controller";
  833. break;
  834. default:
  835. break;
  836. }
  837. if (name) {
  838. SDL_free(device->name);
  839. device->name = SDL_strdup(name);
  840. }
  841. }
  842. if (manufacturer_string) {
  843. SDL_free(manufacturer_string);
  844. }
  845. if (product_string) {
  846. SDL_free(product_string);
  847. }
  848. if (serial_number && *serial_number) {
  849. device->serial = serial_number;
  850. } else {
  851. SDL_free(serial_number);
  852. }
  853. if (!device->name) {
  854. SDL_free(device->serial);
  855. SDL_free(device->path);
  856. SDL_free(device);
  857. return;
  858. }
  859. }
  860. /* Add it to the list */
  861. if (last) {
  862. last->next = device;
  863. } else {
  864. SDL_HIDAPI_devices = device;
  865. }
  866. HIDAPI_SetupDeviceDriver(device);
  867. #ifdef DEBUG_HIDAPI
  868. SDL_Log("Added HIDAPI device '%s' VID 0x%.4x, PID 0x%.4x, version %d, serial %s, interface %d, interface_class %d, interface_subclass %d, interface_protocol %d, usage page 0x%.4x, usage 0x%.4x, path = %s, driver = %s (%s)\n", device->name, device->vendor_id, device->product_id, device->version, device->serial ? device->serial : "NONE", device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol, device->usage_page, device->usage, device->path, device->driver ? device->driver->hint : "NONE", device->driver && device->driver->enabled ? "ENABLED" : "DISABLED");
  869. #endif
  870. }
  871. static void
  872. HIDAPI_DelDevice(SDL_HIDAPI_Device *device)
  873. {
  874. SDL_HIDAPI_Device *curr, *last;
  875. #ifdef DEBUG_HIDAPI
  876. SDL_Log("Removing HIDAPI device '%s' VID 0x%.4x, PID 0x%.4x, version %d, serial %s, interface %d, interface_class %d, interface_subclass %d, interface_protocol %d, usage page 0x%.4x, usage 0x%.4x, path = %s, driver = %s (%s)\n", device->name, device->vendor_id, device->product_id, device->version, device->serial ? device->serial : "NONE", device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol, device->usage_page, device->usage, device->path, device->driver ? device->driver->hint : "NONE", device->driver && device->driver->enabled ? "ENABLED" : "DISABLED");
  877. #endif
  878. for (curr = SDL_HIDAPI_devices, last = NULL; curr; last = curr, curr = curr->next) {
  879. if (curr == device) {
  880. if (last) {
  881. last->next = curr->next;
  882. } else {
  883. SDL_HIDAPI_devices = curr->next;
  884. }
  885. HIDAPI_CleanupDeviceDriver(device);
  886. /* Make sure the rumble thread is done with this device */
  887. while (SDL_AtomicGet(&device->rumble_pending) > 0) {
  888. SDL_Delay(10);
  889. }
  890. SDL_DestroyMutex(device->dev_lock);
  891. SDL_free(device->serial);
  892. SDL_free(device->name);
  893. SDL_free(device->path);
  894. SDL_free(device);
  895. return;
  896. }
  897. }
  898. }
  899. static void
  900. HIDAPI_UpdateDeviceList(void)
  901. {
  902. SDL_HIDAPI_Device *device;
  903. struct hid_device_info *devs, *info;
  904. SDL_LockJoysticks();
  905. /* Prepare the existing device list */
  906. device = SDL_HIDAPI_devices;
  907. while (device) {
  908. device->seen = SDL_FALSE;
  909. device = device->next;
  910. }
  911. /* Enumerate the devices */
  912. if (SDL_HIDAPI_numdrivers > 0) {
  913. devs = hid_enumerate(0, 0);
  914. if (devs) {
  915. for (info = devs; info; info = info->next) {
  916. device = HIDAPI_GetJoystickByInfo(info->path, info->vendor_id, info->product_id);
  917. if (device) {
  918. device->seen = SDL_TRUE;
  919. } else {
  920. HIDAPI_AddDevice(info);
  921. }
  922. }
  923. hid_free_enumeration(devs);
  924. }
  925. }
  926. /* Remove any devices that weren't seen or have been disconnected due to read errors */
  927. device = SDL_HIDAPI_devices;
  928. while (device) {
  929. SDL_HIDAPI_Device *next = device->next;
  930. if (!device->seen ||
  931. (device->driver && device->num_joysticks == 0 && !device->dev)) {
  932. HIDAPI_DelDevice(device);
  933. }
  934. device = next;
  935. }
  936. SDL_UnlockJoysticks();
  937. }
  938. static SDL_bool
  939. HIDAPI_IsEquivalentToDevice(Uint16 vendor_id, Uint16 product_id, SDL_HIDAPI_Device *device)
  940. {
  941. if (vendor_id == device->vendor_id && product_id == device->product_id) {
  942. return SDL_TRUE;
  943. }
  944. if (vendor_id == USB_VENDOR_MICROSOFT) {
  945. /* If we're looking for the wireless XBox 360 controller, also look for the dongle */
  946. if (product_id == 0x02a1 && device->product_id == 0x0719) {
  947. return SDL_TRUE;
  948. }
  949. /* If we're looking for the raw input Xbox One controller, match it against any other Xbox One controller */
  950. if (product_id == USB_PRODUCT_XBOX_ONE_RAW_INPUT_CONTROLLER &&
  951. SDL_GetJoystickGameControllerType(device->name, device->vendor_id, device->product_id, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol) == SDL_CONTROLLER_TYPE_XBOXONE) {
  952. return SDL_TRUE;
  953. }
  954. /* If we're looking for an XInput controller, match it against any other Xbox controller */
  955. if (product_id == USB_PRODUCT_XBOX_ONE_XINPUT_CONTROLLER) {
  956. SDL_GameControllerType type = SDL_GetJoystickGameControllerType(device->name, device->vendor_id, device->product_id, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol);
  957. if (type == SDL_CONTROLLER_TYPE_XBOX360 || type == SDL_CONTROLLER_TYPE_XBOXONE) {
  958. return SDL_TRUE;
  959. }
  960. }
  961. }
  962. return SDL_FALSE;
  963. }
  964. SDL_bool
  965. HIDAPI_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name)
  966. {
  967. SDL_HIDAPI_Device *device;
  968. SDL_bool supported = SDL_FALSE;
  969. SDL_bool result = SDL_FALSE;
  970. /* Make sure we're initialized, as this could be called from other drivers during startup */
  971. if (HIDAPI_JoystickInit() < 0) {
  972. return SDL_FALSE;
  973. }
  974. /* Only update the device list for devices we know might be supported.
  975. If we did this for every device, it would hit the USB driver too hard and potentially
  976. lock up the system. This won't catch devices that we support but can only detect using
  977. USB interface details, like Xbox controllers, but hopefully the device list update is
  978. responsive enough to catch those.
  979. */
  980. supported = HIDAPI_IsDeviceSupported(vendor_id, product_id, version, name);
  981. #if defined(SDL_JOYSTICK_HIDAPI_XBOX360) || defined(SDL_JOYSTICK_HIDAPI_XBOXONE)
  982. if (!supported &&
  983. (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box") || SDL_strstr(name, "XBOX"))) {
  984. supported = SDL_TRUE;
  985. }
  986. #endif /* SDL_JOYSTICK_HIDAPI_XBOX360 || SDL_JOYSTICK_HIDAPI_XBOXONE */
  987. if (supported) {
  988. if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) {
  989. HIDAPI_UpdateDeviceList();
  990. SDL_AtomicUnlock(&SDL_HIDAPI_spinlock);
  991. }
  992. }
  993. /* Note that this isn't a perfect check - there may be multiple devices with 0 VID/PID,
  994. or a different name than we have it listed here, etc, but if we support the device
  995. and we have something similar in our device list, mark it as present.
  996. */
  997. SDL_LockJoysticks();
  998. device = SDL_HIDAPI_devices;
  999. while (device) {
  1000. if (device->driver &&
  1001. HIDAPI_IsEquivalentToDevice(vendor_id, product_id, device)) {
  1002. result = SDL_TRUE;
  1003. }
  1004. device = device->next;
  1005. }
  1006. SDL_UnlockJoysticks();
  1007. #ifdef DEBUG_HIDAPI
  1008. SDL_Log("HIDAPI_IsDevicePresent() returning %s for 0x%.4x / 0x%.4x\n", result ? "true" : "false", vendor_id, product_id);
  1009. #endif
  1010. return result;
  1011. }
  1012. static void
  1013. HIDAPI_JoystickDetect(void)
  1014. {
  1015. if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) {
  1016. HIDAPI_UpdateDiscovery();
  1017. if (SDL_HIDAPI_discovery.m_bHaveDevicesChanged) {
  1018. /* FIXME: We probably need to schedule an update in a few seconds as well */
  1019. HIDAPI_UpdateDeviceList();
  1020. SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_FALSE;
  1021. }
  1022. SDL_AtomicUnlock(&SDL_HIDAPI_spinlock);
  1023. }
  1024. }
  1025. void
  1026. HIDAPI_UpdateDevices(void)
  1027. {
  1028. SDL_HIDAPI_Device *device;
  1029. /* Update the devices, which may change connected joysticks and send events */
  1030. /* Prepare the existing device list */
  1031. if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) {
  1032. device = SDL_HIDAPI_devices;
  1033. while (device) {
  1034. if (device->driver) {
  1035. if (SDL_TryLockMutex(device->dev_lock) == 0) {
  1036. device->updating = SDL_TRUE;
  1037. device->driver->UpdateDevice(device);
  1038. device->updating = SDL_FALSE;
  1039. SDL_UnlockMutex(device->dev_lock);
  1040. }
  1041. }
  1042. device = device->next;
  1043. }
  1044. SDL_AtomicUnlock(&SDL_HIDAPI_spinlock);
  1045. }
  1046. }
  1047. static const char *
  1048. HIDAPI_JoystickGetDeviceName(int device_index)
  1049. {
  1050. SDL_HIDAPI_Device *device;
  1051. const char *name = NULL;
  1052. device = HIDAPI_GetDeviceByIndex(device_index, NULL);
  1053. if (device) {
  1054. /* FIXME: The device could be freed after this name is returned... */
  1055. name = device->name;
  1056. }
  1057. return name;
  1058. }
  1059. static int
  1060. HIDAPI_JoystickGetDevicePlayerIndex(int device_index)
  1061. {
  1062. SDL_HIDAPI_Device *device;
  1063. SDL_JoystickID instance_id;
  1064. int player_index = -1;
  1065. device = HIDAPI_GetDeviceByIndex(device_index, &instance_id);
  1066. if (device) {
  1067. player_index = device->driver->GetDevicePlayerIndex(device, instance_id);
  1068. }
  1069. return player_index;
  1070. }
  1071. static void
  1072. HIDAPI_JoystickSetDevicePlayerIndex(int device_index, int player_index)
  1073. {
  1074. SDL_HIDAPI_Device *device;
  1075. SDL_JoystickID instance_id;
  1076. device = HIDAPI_GetDeviceByIndex(device_index, &instance_id);
  1077. if (device) {
  1078. device->driver->SetDevicePlayerIndex(device, instance_id, player_index);
  1079. }
  1080. }
  1081. static SDL_JoystickGUID
  1082. HIDAPI_JoystickGetDeviceGUID(int device_index)
  1083. {
  1084. SDL_HIDAPI_Device *device;
  1085. SDL_JoystickGUID guid;
  1086. device = HIDAPI_GetDeviceByIndex(device_index, NULL);
  1087. if (device) {
  1088. SDL_memcpy(&guid, &device->guid, sizeof(guid));
  1089. } else {
  1090. SDL_zero(guid);
  1091. }
  1092. return guid;
  1093. }
  1094. static SDL_JoystickID
  1095. HIDAPI_JoystickGetDeviceInstanceID(int device_index)
  1096. {
  1097. SDL_JoystickID joystickID = -1;
  1098. HIDAPI_GetDeviceByIndex(device_index, &joystickID);
  1099. return joystickID;
  1100. }
  1101. static int
  1102. HIDAPI_JoystickOpen(SDL_Joystick * joystick, int device_index)
  1103. {
  1104. SDL_JoystickID joystickID;
  1105. SDL_HIDAPI_Device *device = HIDAPI_GetDeviceByIndex(device_index, &joystickID);
  1106. struct joystick_hwdata *hwdata;
  1107. hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(*hwdata));
  1108. if (!hwdata) {
  1109. return SDL_OutOfMemory();
  1110. }
  1111. hwdata->device = device;
  1112. if (!device->driver->OpenJoystick(device, joystick)) {
  1113. SDL_free(hwdata);
  1114. return -1;
  1115. }
  1116. if (!joystick->serial && device->serial) {
  1117. joystick->serial = SDL_strdup(device->serial);
  1118. }
  1119. joystick->hwdata = hwdata;
  1120. return 0;
  1121. }
  1122. static int
  1123. HIDAPI_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  1124. {
  1125. int result;
  1126. if (joystick->hwdata) {
  1127. SDL_HIDAPI_Device *device = joystick->hwdata->device;
  1128. result = device->driver->RumbleJoystick(device, joystick, low_frequency_rumble, high_frequency_rumble);
  1129. } else {
  1130. SDL_SetError("Rumble failed, device disconnected");
  1131. result = -1;
  1132. }
  1133. return result;
  1134. }
  1135. static int
  1136. HIDAPI_JoystickRumbleTriggers(SDL_Joystick * joystick, Uint16 left_rumble, Uint16 right_rumble)
  1137. {
  1138. int result;
  1139. if (joystick->hwdata) {
  1140. SDL_HIDAPI_Device *device = joystick->hwdata->device;
  1141. result = device->driver->RumbleJoystickTriggers(device, joystick, left_rumble, right_rumble);
  1142. } else {
  1143. SDL_SetError("Rumble failed, device disconnected");
  1144. result = -1;
  1145. }
  1146. return result;
  1147. }
  1148. static SDL_bool
  1149. HIDAPI_JoystickHasLED(SDL_Joystick * joystick)
  1150. {
  1151. SDL_bool result = SDL_FALSE;
  1152. if (joystick->hwdata) {
  1153. SDL_HIDAPI_Device *device = joystick->hwdata->device;
  1154. result = device->driver->HasJoystickLED(device, joystick);
  1155. }
  1156. return result;
  1157. }
  1158. static int
  1159. HIDAPI_JoystickSetLED(SDL_Joystick * joystick, Uint8 red, Uint8 green, Uint8 blue)
  1160. {
  1161. int result;
  1162. if (joystick->hwdata) {
  1163. SDL_HIDAPI_Device *device = joystick->hwdata->device;
  1164. result = device->driver->SetJoystickLED(device, joystick, red, green, blue);
  1165. } else {
  1166. SDL_SetError("SetLED failed, device disconnected");
  1167. result = -1;
  1168. }
  1169. return result;
  1170. }
  1171. static int
  1172. HIDAPI_JoystickSetSensorsEnabled(SDL_Joystick * joystick, SDL_bool enabled)
  1173. {
  1174. int result;
  1175. if (joystick->hwdata) {
  1176. SDL_HIDAPI_Device *device = joystick->hwdata->device;
  1177. result = device->driver->SetJoystickSensorsEnabled(device, joystick, enabled);
  1178. } else {
  1179. SDL_SetError("SetSensorsEnabled failed, device disconnected");
  1180. result = -1;
  1181. }
  1182. return result;
  1183. }
  1184. static void
  1185. HIDAPI_JoystickUpdate(SDL_Joystick * joystick)
  1186. {
  1187. /* This is handled in SDL_HIDAPI_UpdateDevices() */
  1188. }
  1189. static void
  1190. HIDAPI_JoystickClose(SDL_Joystick * joystick)
  1191. {
  1192. if (joystick->hwdata) {
  1193. SDL_HIDAPI_Device *device = joystick->hwdata->device;
  1194. int i;
  1195. /* Wait up to 30 ms for pending rumble to complete */
  1196. if (device->updating) {
  1197. /* Unlock the device so rumble can complete */
  1198. SDL_UnlockMutex(device->dev_lock);
  1199. }
  1200. for (i = 0; i < 3; ++i) {
  1201. if (SDL_AtomicGet(&device->rumble_pending) > 0) {
  1202. SDL_Delay(10);
  1203. }
  1204. }
  1205. if (device->updating) {
  1206. /* Relock the device */
  1207. SDL_LockMutex(device->dev_lock);
  1208. }
  1209. device->driver->CloseJoystick(device, joystick);
  1210. SDL_free(joystick->hwdata);
  1211. joystick->hwdata = NULL;
  1212. }
  1213. }
  1214. static void
  1215. HIDAPI_JoystickQuit(void)
  1216. {
  1217. int i;
  1218. shutting_down = SDL_TRUE;
  1219. HIDAPI_ShutdownDiscovery();
  1220. SDL_HIDAPI_QuitRumble();
  1221. #if defined(HAVE_INOTIFY)
  1222. if (inotify_fd >= 0) {
  1223. close(inotify_fd);
  1224. inotify_fd = -1;
  1225. }
  1226. #endif
  1227. while (SDL_HIDAPI_devices) {
  1228. HIDAPI_DelDevice(SDL_HIDAPI_devices);
  1229. }
  1230. /* Make sure the drivers cleaned up properly */
  1231. SDL_assert(SDL_HIDAPI_numjoysticks == 0);
  1232. for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) {
  1233. SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i];
  1234. SDL_DelHintCallback(driver->hint, SDL_HIDAPIDriverHintChanged, NULL);
  1235. }
  1236. SDL_DelHintCallback(SDL_HINT_JOYSTICK_HIDAPI,
  1237. SDL_HIDAPIDriverHintChanged, NULL);
  1238. hid_exit();
  1239. shutting_down = SDL_FALSE;
  1240. initialized = SDL_FALSE;
  1241. }
  1242. static SDL_bool
  1243. HIDAPI_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out)
  1244. {
  1245. return SDL_FALSE;
  1246. }
  1247. SDL_JoystickDriver SDL_HIDAPI_JoystickDriver =
  1248. {
  1249. HIDAPI_JoystickInit,
  1250. HIDAPI_JoystickGetCount,
  1251. HIDAPI_JoystickDetect,
  1252. HIDAPI_JoystickGetDeviceName,
  1253. HIDAPI_JoystickGetDevicePlayerIndex,
  1254. HIDAPI_JoystickSetDevicePlayerIndex,
  1255. HIDAPI_JoystickGetDeviceGUID,
  1256. HIDAPI_JoystickGetDeviceInstanceID,
  1257. HIDAPI_JoystickOpen,
  1258. HIDAPI_JoystickRumble,
  1259. HIDAPI_JoystickRumbleTriggers,
  1260. HIDAPI_JoystickHasLED,
  1261. HIDAPI_JoystickSetLED,
  1262. HIDAPI_JoystickSetSensorsEnabled,
  1263. HIDAPI_JoystickUpdate,
  1264. HIDAPI_JoystickClose,
  1265. HIDAPI_JoystickQuit,
  1266. HIDAPI_JoystickGetGamepadMapping
  1267. };
  1268. #endif /* SDL_JOYSTICK_HIDAPI */
  1269. /* vi: set ts=4 sw=4 expandtab: */