SDL_hidapijoystick.c 48 KB

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