hid.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. /*******************************************************
  2. HIDAPI - Multi-Platform library for
  3. communication with HID devices.
  4. Alan Ott
  5. Signal 11 Software
  6. 8/22/2009
  7. Linux Version - 6/2/2010
  8. Libusb Version - 8/13/2010
  9. FreeBSD Version - 11/1/2011
  10. Copyright 2009, All Rights Reserved.
  11. At the discretion of the user of this library,
  12. this software may be licensed under the terms of the
  13. GNU General Public License v3, a BSD-Style license, or the
  14. original HIDAPI license as outlined in the LICENSE.txt,
  15. LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
  16. files located at the root of the source distribution.
  17. These files may also be found in the public source
  18. code repository located at:
  19. https://github.com/libusb/hidapi .
  20. ********************************************************/
  21. /* This file is heavily modified from the original libusb.c, for portability.
  22. * Last upstream update was from July 25, 2019, Git commit 93dca807.
  23. */
  24. #include "../../SDL_internal.h"
  25. #include "../../thread/SDL_systhread.h"
  26. #include "SDL_hints.h"
  27. #include "SDL_mutex.h"
  28. #include "SDL_thread.h"
  29. #ifdef realloc
  30. #undef realloc
  31. #endif
  32. #define realloc SDL_realloc
  33. #ifdef snprintf
  34. #undef snprintf
  35. #endif
  36. #define snprintf SDL_snprintf
  37. #ifdef strdup
  38. #undef strdup
  39. #endif
  40. #define strdup SDL_strdup
  41. #ifdef strncpy
  42. #undef strncpy
  43. #endif
  44. #define strncpy SDL_strlcpy
  45. #ifdef tolower
  46. #undef tolower
  47. #endif
  48. #define tolower SDL_tolower
  49. #ifdef wcsncpy
  50. #undef wcsncpy
  51. #endif
  52. #define wcsncpy SDL_wcslcpy
  53. #ifndef HAVE_WCSDUP
  54. #ifdef HAVE__WCSDUP
  55. #define wcsdup _wcsdup
  56. #else
  57. #define wcsdup _dupwcs
  58. static wchar_t *_dupwcs(const wchar_t *src)
  59. {
  60. wchar_t *dst = NULL;
  61. if (src) {
  62. size_t len = SDL_wcslen(src) + 1;
  63. len *= sizeof(wchar_t);
  64. dst = (wchar_t *) malloc(len);
  65. if (dst) memcpy(dst, src, len);
  66. }
  67. return dst;
  68. }
  69. #endif
  70. #endif /* HAVE_WCSDUP */
  71. #include <libusb.h>
  72. #ifndef _WIN32
  73. #define HAVE_SETLOCALE
  74. #include <locale.h> /* setlocale */
  75. #endif
  76. #include "../hidapi/hidapi.h"
  77. #ifdef NAMESPACE
  78. namespace NAMESPACE
  79. {
  80. #endif
  81. /* Barrier implementation because Android/Bionic don't have pthread_barrier.
  82. This implementation came from Brent Priddy and was posted on
  83. StackOverflow. It is used with his permission. */
  84. typedef struct _SDL_ThreadBarrier
  85. {
  86. SDL_mutex *mutex;
  87. SDL_cond *cond;
  88. Uint32 count;
  89. Uint32 trip_count;
  90. } SDL_ThreadBarrier;
  91. static int SDL_CreateThreadBarrier(SDL_ThreadBarrier *barrier, Uint32 count)
  92. {
  93. SDL_assert(barrier != NULL);
  94. SDL_assert(count != 0);
  95. barrier->mutex = SDL_CreateMutex();
  96. if (barrier->mutex == NULL) {
  97. return -1; /* Error set by CreateMutex */
  98. }
  99. barrier->cond = SDL_CreateCond();
  100. if (barrier->cond == NULL) {
  101. return -1; /* Error set by CreateCond */
  102. }
  103. barrier->trip_count = count;
  104. barrier->count = 0;
  105. return 0;
  106. }
  107. static void SDL_DestroyThreadBarrier(SDL_ThreadBarrier *barrier)
  108. {
  109. SDL_DestroyCond(barrier->cond);
  110. SDL_DestroyMutex(barrier->mutex);
  111. }
  112. static int SDL_WaitThreadBarrier(SDL_ThreadBarrier *barrier)
  113. {
  114. SDL_LockMutex(barrier->mutex);
  115. barrier->count += 1;
  116. if (barrier->count >= barrier->trip_count) {
  117. barrier->count = 0;
  118. SDL_CondBroadcast(barrier->cond);
  119. SDL_UnlockMutex(barrier->mutex);
  120. return 1;
  121. }
  122. SDL_CondWait(barrier->cond, barrier->mutex);
  123. SDL_UnlockMutex(barrier->mutex);
  124. return 0;
  125. }
  126. #if defined(__cplusplus) && !defined(NAMESPACE)
  127. extern "C" {
  128. #endif
  129. #ifdef DEBUG_PRINTF
  130. #define LOG(...) fprintf(stderr, __VA_ARGS__)
  131. #else
  132. #define LOG(...) do {} while (0)
  133. #endif
  134. #ifndef __FreeBSD__
  135. #define DETACH_KERNEL_DRIVER
  136. #endif
  137. /* Uncomment to enable the retrieval of Usage and Usage Page in
  138. hid_enumerate(). Warning, on platforms different from FreeBSD
  139. this is very invasive as it requires the detach
  140. and re-attach of the kernel driver. See comments inside hid_enumerate().
  141. libusb HIDAPI programs are encouraged to use the interface number
  142. instead to differentiate between interfaces on a composite HID device. */
  143. /*#define INVASIVE_GET_USAGE*/
  144. /* Linked List of input reports received from the device. */
  145. struct input_report {
  146. uint8_t *data;
  147. size_t len;
  148. struct input_report *next;
  149. };
  150. struct hid_device_ {
  151. /* Handle to the actual device. */
  152. libusb_device_handle *device_handle;
  153. /* Endpoint information */
  154. int input_endpoint;
  155. int output_endpoint;
  156. int input_ep_max_packet_size;
  157. /* The interface number of the HID */
  158. int interface;
  159. int detached_driver;
  160. /* Indexes of Strings */
  161. int manufacturer_index;
  162. int product_index;
  163. int serial_index;
  164. /* Whether blocking reads are used */
  165. int blocking; /* boolean */
  166. /* Read thread objects */
  167. SDL_Thread *thread;
  168. SDL_mutex *mutex; /* Protects input_reports */
  169. SDL_cond *condition;
  170. SDL_ThreadBarrier barrier; /* Ensures correct startup sequence */
  171. int shutdown_thread;
  172. int transfer_loop_finished;
  173. struct libusb_transfer *transfer;
  174. /* Quirks */
  175. int skip_output_report_id;
  176. int no_output_reports_on_intr_ep;
  177. /* List of received input reports. */
  178. struct input_report *input_reports;
  179. };
  180. static libusb_context *usb_context = NULL;
  181. uint16_t get_usb_code_for_current_locale(void);
  182. static int return_data(hid_device *dev, unsigned char *data, size_t length);
  183. static hid_device *new_hid_device(void)
  184. {
  185. hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
  186. dev->blocking = 1;
  187. dev->mutex = SDL_CreateMutex();
  188. dev->condition = SDL_CreateCond();
  189. SDL_CreateThreadBarrier(&dev->barrier, 2);
  190. return dev;
  191. }
  192. static void free_hid_device(hid_device *dev)
  193. {
  194. /* Clean up the thread objects */
  195. SDL_DestroyThreadBarrier(&dev->barrier);
  196. SDL_DestroyCond(dev->condition);
  197. SDL_DestroyMutex(dev->mutex);
  198. /* Free the device itself */
  199. free(dev);
  200. }
  201. #if 0
  202. /*TODO: Implement this function on hidapi/libusb.. */
  203. static void register_error(hid_device *dev, const char *op)
  204. {
  205. }
  206. #endif
  207. #ifdef INVASIVE_GET_USAGE
  208. /* Get bytes from a HID Report Descriptor.
  209. Only call with a num_bytes of 0, 1, 2, or 4. */
  210. static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
  211. {
  212. /* Return if there aren't enough bytes. */
  213. if (cur + num_bytes >= len)
  214. return 0;
  215. if (num_bytes == 0)
  216. return 0;
  217. else if (num_bytes == 1) {
  218. return rpt[cur+1];
  219. }
  220. else if (num_bytes == 2) {
  221. return (rpt[cur+2] * 256 + rpt[cur+1]);
  222. }
  223. else if (num_bytes == 4) {
  224. return (rpt[cur+4] * 0x01000000 +
  225. rpt[cur+3] * 0x00010000 +
  226. rpt[cur+2] * 0x00000100 +
  227. rpt[cur+1] * 0x00000001);
  228. }
  229. else
  230. return 0;
  231. }
  232. /* Retrieves the device's Usage Page and Usage from the report
  233. descriptor. The algorithm is simple, as it just returns the first
  234. Usage and Usage Page that it finds in the descriptor.
  235. The return value is 0 on success and -1 on failure. */
  236. static int get_usage(uint8_t *report_descriptor, size_t size,
  237. unsigned short *usage_page, unsigned short *usage)
  238. {
  239. unsigned int i = 0;
  240. int size_code;
  241. int data_len, key_size;
  242. int usage_found = 0, usage_page_found = 0;
  243. while (i < size) {
  244. int key = report_descriptor[i];
  245. int key_cmd = key & 0xfc;
  246. //printf("key: %02hhx\n", key);
  247. if ((key & 0xf0) == 0xf0) {
  248. /* This is a Long Item. The next byte contains the
  249. length of the data section (value) for this key.
  250. See the HID specification, version 1.11, section
  251. 6.2.2.3, titled "Long Items." */
  252. if (i+1 < size)
  253. data_len = report_descriptor[i+1];
  254. else
  255. data_len = 0; /* malformed report */
  256. key_size = 3;
  257. }
  258. else {
  259. /* This is a Short Item. The bottom two bits of the
  260. key contain the size code for the data section
  261. (value) for this key. Refer to the HID
  262. specification, version 1.11, section 6.2.2.2,
  263. titled "Short Items." */
  264. size_code = key & 0x3;
  265. switch (size_code) {
  266. case 0:
  267. case 1:
  268. case 2:
  269. data_len = size_code;
  270. break;
  271. case 3:
  272. data_len = 4;
  273. break;
  274. default:
  275. /* Can't ever happen since size_code is & 0x3 */
  276. data_len = 0;
  277. break;
  278. }
  279. key_size = 1;
  280. }
  281. if (key_cmd == 0x4) {
  282. *usage_page = get_bytes(report_descriptor, size, data_len, i);
  283. usage_page_found = 1;
  284. //printf("Usage Page: %x\n", (uint32_t)*usage_page);
  285. }
  286. if (key_cmd == 0x8) {
  287. *usage = get_bytes(report_descriptor, size, data_len, i);
  288. usage_found = 1;
  289. //printf("Usage: %x\n", (uint32_t)*usage);
  290. }
  291. if (usage_page_found && usage_found)
  292. return 0; /* success */
  293. /* Skip over this key and it's associated data */
  294. i += data_len + key_size;
  295. }
  296. return -1; /* failure */
  297. }
  298. #endif /* INVASIVE_GET_USAGE */
  299. #if defined(__FreeBSD__) && __FreeBSD__ < 10
  300. /* The libusb version included in FreeBSD < 10 doesn't have this function. In
  301. mainline libusb, it's inlined in libusb.h. This function will bear a striking
  302. resemblance to that one, because there's about one way to code it.
  303. Note that the data parameter is Unicode in UTF-16LE encoding.
  304. Return value is the number of bytes in data, or LIBUSB_ERROR_*.
  305. */
  306. static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
  307. uint8_t descriptor_index, uint16_t lang_id,
  308. unsigned char *data, int length)
  309. {
  310. return libusb_control_transfer(dev,
  311. LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
  312. LIBUSB_REQUEST_GET_DESCRIPTOR,
  313. (LIBUSB_DT_STRING << 8) | descriptor_index,
  314. lang_id, data, (uint16_t) length, 1000);
  315. }
  316. #endif
  317. /* Get the first language the device says it reports. This comes from
  318. USB string #0. */
  319. static uint16_t get_first_language(libusb_device_handle *dev)
  320. {
  321. uint16_t buf[32];
  322. int len;
  323. /* Get the string from libusb. */
  324. len = libusb_get_string_descriptor(dev,
  325. 0x0, /* String ID */
  326. 0x0, /* Language */
  327. (unsigned char*)buf,
  328. sizeof(buf));
  329. if (len < 4)
  330. return 0x0;
  331. return buf[1]; /* First two bytes are len and descriptor type. */
  332. }
  333. static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
  334. {
  335. uint16_t buf[32];
  336. int len;
  337. int i;
  338. /* Get the string from libusb. */
  339. len = libusb_get_string_descriptor(dev,
  340. 0x0, /* String ID */
  341. 0x0, /* Language */
  342. (unsigned char*)buf,
  343. sizeof(buf));
  344. if (len < 4)
  345. return 0x0;
  346. len /= 2; /* language IDs are two-bytes each. */
  347. /* Start at index 1 because there are two bytes of protocol data. */
  348. for (i = 1; i < len; i++) {
  349. if (buf[i] == lang)
  350. return 1;
  351. }
  352. return 0;
  353. }
  354. /* This function returns a newly allocated wide string containing the USB
  355. device string numbered by the index. The returned string must be freed
  356. by using free(). */
  357. #if defined(__OS2__) /* don't use iconv on OS/2: no support for wchar_t. */
  358. #define NO_ICONV
  359. #endif
  360. static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
  361. {
  362. char buf[512];
  363. int len;
  364. wchar_t *str = NULL;
  365. #if !defined(NO_ICONV)
  366. wchar_t wbuf[256];
  367. SDL_iconv_t ic;
  368. size_t inbytes;
  369. size_t outbytes;
  370. size_t res;
  371. const char *inptr;
  372. char *outptr;
  373. #else
  374. int i;
  375. #endif
  376. /* Determine which language to use. */
  377. uint16_t lang;
  378. lang = get_usb_code_for_current_locale();
  379. if (!is_language_supported(dev, lang))
  380. lang = get_first_language(dev);
  381. /* Get the string from libusb. */
  382. len = libusb_get_string_descriptor(dev,
  383. idx,
  384. lang,
  385. (unsigned char*)buf,
  386. sizeof(buf));
  387. if (len < 0)
  388. return NULL;
  389. #if defined(NO_ICONV) /* original hidapi code for NO_ICONV : */
  390. /* Bionic does not have wchar_t iconv support, so it
  391. has to be done manually. The following code will only work for
  392. code points that can be represented as a single UTF-16 character,
  393. and will incorrectly convert any code points which require more
  394. than one UTF-16 character.
  395. Skip over the first character (2-bytes). */
  396. len -= 2;
  397. str = (wchar_t*) malloc((len / 2 + 1) * sizeof(wchar_t));
  398. for (i = 0; i < len / 2; i++) {
  399. str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8);
  400. }
  401. str[len / 2] = 0x00000000;
  402. #else
  403. /* buf does not need to be explicitly NULL-terminated because
  404. it is only passed into iconv() which does not need it. */
  405. /* Initialize iconv. */
  406. ic = SDL_iconv_open("WCHAR_T", "UTF-16LE");
  407. if (ic == (SDL_iconv_t)-1) {
  408. LOG("SDL_iconv_open() failed\n");
  409. return NULL;
  410. }
  411. /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
  412. Skip the first character (2-bytes). */
  413. inptr = buf+2;
  414. inbytes = len-2;
  415. outptr = (char*) wbuf;
  416. outbytes = sizeof(wbuf);
  417. res = SDL_iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
  418. if (res == (size_t)-1) {
  419. LOG("SDL_iconv() failed\n");
  420. goto err;
  421. }
  422. /* Write the terminating NULL. */
  423. wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
  424. if (outbytes >= sizeof(wbuf[0]))
  425. *((wchar_t*)outptr) = 0x00000000;
  426. /* Allocate and copy the string. */
  427. str = wcsdup(wbuf);
  428. err:
  429. SDL_iconv_close(ic);
  430. #endif
  431. return str;
  432. }
  433. struct usb_string_cache_entry {
  434. uint16_t vid;
  435. uint16_t pid;
  436. wchar_t *vendor;
  437. wchar_t *product;
  438. };
  439. static struct usb_string_cache_entry *usb_string_cache = NULL;
  440. static size_t usb_string_cache_size = 0;
  441. static size_t usb_string_cache_insert_pos = 0;
  442. static int usb_string_cache_grow()
  443. {
  444. struct usb_string_cache_entry *new_cache;
  445. size_t allocSize;
  446. size_t new_cache_size;
  447. new_cache_size = usb_string_cache_size + 8;
  448. allocSize = sizeof(struct usb_string_cache_entry) * new_cache_size;
  449. new_cache = (struct usb_string_cache_entry *)realloc(usb_string_cache, allocSize);
  450. if (!new_cache)
  451. return -1;
  452. usb_string_cache = new_cache;
  453. usb_string_cache_size = new_cache_size;
  454. return 0;
  455. }
  456. static void usb_string_cache_destroy()
  457. {
  458. size_t i;
  459. for (i = 0; i < usb_string_cache_insert_pos; i++) {
  460. free(usb_string_cache[i].vendor);
  461. free(usb_string_cache[i].product);
  462. }
  463. free(usb_string_cache);
  464. usb_string_cache = NULL;
  465. usb_string_cache_size = 0;
  466. usb_string_cache_insert_pos = 0;
  467. }
  468. static struct usb_string_cache_entry *usb_string_cache_insert()
  469. {
  470. struct usb_string_cache_entry *new_entry = NULL;
  471. if (usb_string_cache_insert_pos >= usb_string_cache_size) {
  472. if (usb_string_cache_grow() < 0)
  473. return NULL;
  474. }
  475. new_entry = &usb_string_cache[usb_string_cache_insert_pos];
  476. usb_string_cache_insert_pos++;
  477. return new_entry;
  478. }
  479. static int usb_string_can_cache(uint16_t vid, uint16_t pid)
  480. {
  481. if (!vid || !pid) {
  482. /* We can't cache these, they aren't unique */
  483. return 0;
  484. }
  485. if (vid == 0x0f0d && pid == 0x00dc) {
  486. /* HORI reuses this VID/PID for many different products */
  487. return 0;
  488. }
  489. /* We can cache these strings */
  490. return 1;
  491. }
  492. static const struct usb_string_cache_entry *usb_string_cache_find(struct libusb_device_descriptor *desc, struct libusb_device_handle *handle)
  493. {
  494. struct usb_string_cache_entry *entry = NULL;
  495. size_t i;
  496. /* Search for existing string cache entry */
  497. for (i = 0; i < usb_string_cache_insert_pos; i++) {
  498. entry = &usb_string_cache[i];
  499. if (entry->vid != desc->idVendor)
  500. continue;
  501. if (entry->pid != desc->idProduct)
  502. continue;
  503. return entry;
  504. }
  505. /* Not found, create one. */
  506. entry = usb_string_cache_insert();
  507. if (!entry)
  508. return NULL;
  509. entry->vid = desc->idVendor;
  510. entry->pid = desc->idProduct;
  511. if (desc->iManufacturer > 0)
  512. entry->vendor = get_usb_string(handle, desc->iManufacturer);
  513. else
  514. entry->vendor = NULL;
  515. if (desc->iProduct > 0)
  516. entry->product = get_usb_string(handle, desc->iProduct);
  517. else
  518. entry->product = NULL;
  519. return entry;
  520. }
  521. static char *make_path(libusb_device *dev, int interface_number)
  522. {
  523. char str[64];
  524. snprintf(str, sizeof(str), "%04x:%04x:%02x",
  525. libusb_get_bus_number(dev),
  526. libusb_get_device_address(dev),
  527. interface_number);
  528. str[sizeof(str)-1] = '\0';
  529. return strdup(str);
  530. }
  531. int HID_API_EXPORT hid_init(void)
  532. {
  533. if (!usb_context) {
  534. /* Init Libusb */
  535. if (libusb_init(&usb_context))
  536. return -1;
  537. #ifdef HAVE_SETLOCALE
  538. /* Set the locale if it's not set. */
  539. {
  540. const char *locale = setlocale(LC_CTYPE, NULL);
  541. if (!locale)
  542. setlocale(LC_CTYPE, "");
  543. }
  544. #endif
  545. }
  546. return 0;
  547. }
  548. int HID_API_EXPORT hid_exit(void)
  549. {
  550. usb_string_cache_destroy();
  551. if (usb_context) {
  552. libusb_exit(usb_context);
  553. usb_context = NULL;
  554. }
  555. return 0;
  556. }
  557. static int is_xbox360(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc)
  558. {
  559. static const int XB360_IFACE_SUBCLASS = 93;
  560. static const int XB360_IFACE_PROTOCOL = 1; /* Wired */
  561. static const int XB360W_IFACE_PROTOCOL = 129; /* Wireless */
  562. static const int SUPPORTED_VENDORS[] = {
  563. 0x0079, /* GPD Win 2 */
  564. 0x044f, /* Thrustmaster */
  565. 0x045e, /* Microsoft */
  566. 0x046d, /* Logitech */
  567. 0x056e, /* Elecom */
  568. 0x06a3, /* Saitek */
  569. 0x0738, /* Mad Catz */
  570. 0x07ff, /* Mad Catz */
  571. 0x0e6f, /* PDP */
  572. 0x0f0d, /* Hori */
  573. 0x1038, /* SteelSeries */
  574. 0x11c9, /* Nacon */
  575. 0x12ab, /* Unknown */
  576. 0x1430, /* RedOctane */
  577. 0x146b, /* BigBen */
  578. 0x1532, /* Razer Sabertooth */
  579. 0x15e4, /* Numark */
  580. 0x162e, /* Joytech */
  581. 0x1689, /* Razer Onza */
  582. 0x1949, /* Lab126, Inc. */
  583. 0x1bad, /* Harmonix */
  584. 0x20d6, /* PowerA */
  585. 0x24c6, /* PowerA */
  586. 0x2c22, /* Qanba */
  587. 0x2dc8, /* 8BitDo */
  588. 0x9886, /* ASTRO Gaming */
  589. };
  590. if (intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC &&
  591. intf_desc->bInterfaceSubClass == XB360_IFACE_SUBCLASS &&
  592. (intf_desc->bInterfaceProtocol == XB360_IFACE_PROTOCOL ||
  593. intf_desc->bInterfaceProtocol == XB360W_IFACE_PROTOCOL)) {
  594. int i;
  595. for (i = 0; i < sizeof(SUPPORTED_VENDORS)/sizeof(SUPPORTED_VENDORS[0]); ++i) {
  596. if (vendor_id == SUPPORTED_VENDORS[i]) {
  597. return 1;
  598. }
  599. }
  600. }
  601. return 0;
  602. }
  603. static int is_xboxone(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc)
  604. {
  605. static const int XB1_IFACE_SUBCLASS = 71;
  606. static const int XB1_IFACE_PROTOCOL = 208;
  607. static const int SUPPORTED_VENDORS[] = {
  608. 0x03f0, /* HP */
  609. 0x044f, /* Thrustmaster */
  610. 0x045e, /* Microsoft */
  611. 0x0738, /* Mad Catz */
  612. 0x0b05, /* ASUS */
  613. 0x0e6f, /* PDP */
  614. 0x0f0d, /* Hori */
  615. 0x10f5, /* Turtle Beach */
  616. 0x1532, /* Razer Wildcat */
  617. 0x20d6, /* PowerA */
  618. 0x24c6, /* PowerA */
  619. 0x2dc8, /* 8BitDo */
  620. 0x2e24, /* Hyperkin */
  621. 0x3537, /* GameSir */
  622. };
  623. if (intf_desc->bInterfaceNumber == 0 &&
  624. intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC &&
  625. intf_desc->bInterfaceSubClass == XB1_IFACE_SUBCLASS &&
  626. intf_desc->bInterfaceProtocol == XB1_IFACE_PROTOCOL) {
  627. int i;
  628. for (i = 0; i < sizeof(SUPPORTED_VENDORS)/sizeof(SUPPORTED_VENDORS[0]); ++i) {
  629. if (vendor_id == SUPPORTED_VENDORS[i]) {
  630. return 1;
  631. }
  632. }
  633. }
  634. return 0;
  635. }
  636. static int should_enumerate_interface(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc)
  637. {
  638. //printf("Checking interface 0x%x %d/%d/%d/%d\n", vendor_id, intf_desc->bInterfaceNumber, intf_desc->bInterfaceClass, intf_desc->bInterfaceSubClass, intf_desc->bInterfaceProtocol);
  639. if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID)
  640. return 1;
  641. /* Also enumerate Xbox 360 controllers */
  642. if (is_xbox360(vendor_id, intf_desc))
  643. return 1;
  644. /* Also enumerate Xbox One controllers */
  645. if (is_xboxone(vendor_id, intf_desc))
  646. return 1;
  647. return 0;
  648. }
  649. struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
  650. {
  651. libusb_device **devs;
  652. libusb_device *dev;
  653. libusb_device_handle *handle;
  654. ssize_t num_devs;
  655. int i = 0;
  656. struct hid_device_info *root = NULL; /* return object */
  657. struct hid_device_info *cur_dev = NULL;
  658. const char *hint = SDL_GetHint(SDL_HINT_HIDAPI_IGNORE_DEVICES);
  659. if(hid_init() < 0)
  660. return NULL;
  661. num_devs = libusb_get_device_list(usb_context, &devs);
  662. if (num_devs < 0)
  663. return NULL;
  664. while ((dev = devs[i++]) != NULL) {
  665. struct libusb_device_descriptor desc;
  666. struct libusb_config_descriptor *conf_desc = NULL;
  667. int j, k;
  668. int interface_num = 0;
  669. int res = libusb_get_device_descriptor(dev, &desc);
  670. unsigned short dev_vid = desc.idVendor;
  671. unsigned short dev_pid = desc.idProduct;
  672. /* See if there are any devices we should skip in enumeration */
  673. if (hint) {
  674. char vendor_match[16], product_match[16];
  675. SDL_snprintf(vendor_match, sizeof(vendor_match), "0x%.4x/0x0000", dev_vid);
  676. SDL_snprintf(product_match, sizeof(product_match), "0x%.4x/0x%.4x", dev_vid, dev_pid);
  677. if (SDL_strcasestr(hint, vendor_match) || SDL_strcasestr(hint, product_match)) {
  678. continue;
  679. }
  680. }
  681. res = libusb_get_active_config_descriptor(dev, &conf_desc);
  682. if (res < 0)
  683. libusb_get_config_descriptor(dev, 0, &conf_desc);
  684. if (conf_desc) {
  685. for (j = 0; j < conf_desc->bNumInterfaces; j++) {
  686. const struct libusb_interface *intf = &conf_desc->interface[j];
  687. for (k = 0; k < intf->num_altsetting; k++) {
  688. const struct libusb_interface_descriptor *intf_desc;
  689. intf_desc = &intf->altsetting[k];
  690. if (should_enumerate_interface(dev_vid, intf_desc)) {
  691. interface_num = intf_desc->bInterfaceNumber;
  692. /* Check the VID/PID against the arguments */
  693. if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
  694. (product_id == 0x0 || product_id == dev_pid)) {
  695. res = libusb_open(dev, &handle);
  696. if (res >= 0) {
  697. struct hid_device_info *tmp;
  698. const struct usb_string_cache_entry *string_cache;
  699. /* VID/PID match. Create the record. */
  700. tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
  701. if (cur_dev) {
  702. cur_dev->next = tmp;
  703. }
  704. else {
  705. root = tmp;
  706. }
  707. cur_dev = tmp;
  708. /* Fill out the record */
  709. cur_dev->next = NULL;
  710. cur_dev->path = make_path(dev, interface_num);
  711. /* Serial Number */
  712. if (desc.iSerialNumber > 0)
  713. cur_dev->serial_number =
  714. get_usb_string(handle, desc.iSerialNumber);
  715. /* Manufacturer and Product strings */
  716. if (usb_string_can_cache(dev_vid, dev_pid)) {
  717. string_cache = usb_string_cache_find(&desc, handle);
  718. if (string_cache) {
  719. if (string_cache->vendor) {
  720. cur_dev->manufacturer_string = wcsdup(string_cache->vendor);
  721. }
  722. if (string_cache->product) {
  723. cur_dev->product_string = wcsdup(string_cache->product);
  724. }
  725. }
  726. } else {
  727. if (desc.iManufacturer > 0)
  728. cur_dev->manufacturer_string =
  729. get_usb_string(handle, desc.iManufacturer);
  730. if (desc.iProduct > 0)
  731. cur_dev->product_string =
  732. get_usb_string(handle, desc.iProduct);
  733. }
  734. #ifdef INVASIVE_GET_USAGE
  735. {
  736. /*
  737. This section is removed because it is too
  738. invasive on the system. Getting a Usage Page
  739. and Usage requires parsing the HID Report
  740. descriptor. Getting a HID Report descriptor
  741. involves claiming the interface. Claiming the
  742. interface involves detaching the kernel driver.
  743. Detaching the kernel driver is hard on the system
  744. because it will unclaim interfaces (if another
  745. app has them claimed) and the re-attachment of
  746. the driver will sometimes change /dev entry names.
  747. It is for these reasons that this section is
  748. #if 0. For composite devices, use the interface
  749. field in the hid_device_info struct to distinguish
  750. between interfaces. */
  751. unsigned char data[256];
  752. #ifdef DETACH_KERNEL_DRIVER
  753. int detached = 0;
  754. /* Usage Page and Usage */
  755. res = libusb_kernel_driver_active(handle, interface_num);
  756. if (res == 1) {
  757. res = libusb_detach_kernel_driver(handle, interface_num);
  758. if (res < 0)
  759. LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
  760. else
  761. detached = 1;
  762. }
  763. #endif
  764. res = libusb_claim_interface(handle, interface_num);
  765. if (res >= 0) {
  766. /* Get the HID Report Descriptor. */
  767. res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
  768. if (res >= 0) {
  769. unsigned short page=0, usage=0;
  770. /* Parse the usage and usage page
  771. out of the report descriptor. */
  772. get_usage(data, res, &page, &usage);
  773. cur_dev->usage_page = page;
  774. cur_dev->usage = usage;
  775. }
  776. else
  777. LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
  778. /* Release the interface */
  779. res = libusb_release_interface(handle, interface_num);
  780. if (res < 0)
  781. LOG("Can't release the interface.\n");
  782. }
  783. else
  784. LOG("Can't claim interface %d\n", res);
  785. #ifdef DETACH_KERNEL_DRIVER
  786. /* Re-attach kernel driver if necessary. */
  787. if (detached) {
  788. res = libusb_attach_kernel_driver(handle, interface_num);
  789. if (res < 0)
  790. LOG("Couldn't re-attach kernel driver.\n");
  791. }
  792. #endif
  793. }
  794. #endif /* INVASIVE_GET_USAGE */
  795. libusb_close(handle);
  796. /* VID/PID */
  797. cur_dev->vendor_id = dev_vid;
  798. cur_dev->product_id = dev_pid;
  799. /* Release Number */
  800. cur_dev->release_number = desc.bcdDevice;
  801. /* Interface Number */
  802. cur_dev->interface_number = interface_num;
  803. cur_dev->interface_class = intf_desc->bInterfaceClass;
  804. cur_dev->interface_subclass = intf_desc->bInterfaceSubClass;
  805. cur_dev->interface_protocol = intf_desc->bInterfaceProtocol;
  806. } else
  807. LOG("Can't open device 0x%.4x/0x%.4x during enumeration: %d\n", dev_vid, dev_pid, res);
  808. }
  809. }
  810. } /* altsettings */
  811. } /* interfaces */
  812. libusb_free_config_descriptor(conf_desc);
  813. }
  814. }
  815. libusb_free_device_list(devs, 1);
  816. return root;
  817. }
  818. void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
  819. {
  820. struct hid_device_info *d = devs;
  821. while (d) {
  822. struct hid_device_info *next = d->next;
  823. free(d->path);
  824. free(d->serial_number);
  825. free(d->manufacturer_string);
  826. free(d->product_string);
  827. free(d);
  828. d = next;
  829. }
  830. }
  831. hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
  832. {
  833. struct hid_device_info *devs, *cur_dev;
  834. const char *path_to_open = NULL;
  835. hid_device *handle = NULL;
  836. devs = hid_enumerate(vendor_id, product_id);
  837. cur_dev = devs;
  838. while (cur_dev) {
  839. if (cur_dev->vendor_id == vendor_id &&
  840. cur_dev->product_id == product_id) {
  841. if (serial_number) {
  842. if (cur_dev->serial_number &&
  843. wcscmp(serial_number, cur_dev->serial_number) == 0) {
  844. path_to_open = cur_dev->path;
  845. break;
  846. }
  847. }
  848. else {
  849. path_to_open = cur_dev->path;
  850. break;
  851. }
  852. }
  853. cur_dev = cur_dev->next;
  854. }
  855. if (path_to_open) {
  856. /* Open the device */
  857. handle = hid_open_path(path_to_open, 0);
  858. }
  859. hid_free_enumeration(devs);
  860. return handle;
  861. }
  862. static void LIBUSB_CALL read_callback(struct libusb_transfer *transfer)
  863. {
  864. hid_device *dev = (hid_device *)transfer->user_data;
  865. int res;
  866. if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
  867. struct input_report *rpt = (struct input_report*) malloc(sizeof(*rpt));
  868. rpt->data = (uint8_t*) malloc(transfer->actual_length);
  869. memcpy(rpt->data, transfer->buffer, transfer->actual_length);
  870. rpt->len = transfer->actual_length;
  871. rpt->next = NULL;
  872. SDL_LockMutex(dev->mutex);
  873. /* Attach the new report object to the end of the list. */
  874. if (dev->input_reports == NULL) {
  875. /* The list is empty. Put it at the root. */
  876. dev->input_reports = rpt;
  877. SDL_CondSignal(dev->condition);
  878. }
  879. else {
  880. /* Find the end of the list and attach. */
  881. struct input_report *cur = dev->input_reports;
  882. int num_queued = 0;
  883. while (cur->next != NULL) {
  884. cur = cur->next;
  885. num_queued++;
  886. }
  887. cur->next = rpt;
  888. /* Pop one off if we've reached 30 in the queue. This
  889. way we don't grow forever if the user never reads
  890. anything from the device. */
  891. if (num_queued > 30) {
  892. return_data(dev, NULL, 0);
  893. }
  894. }
  895. SDL_UnlockMutex(dev->mutex);
  896. }
  897. else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
  898. dev->shutdown_thread = 1;
  899. }
  900. else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
  901. dev->shutdown_thread = 1;
  902. }
  903. else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
  904. //LOG("Timeout (normal)\n");
  905. }
  906. else {
  907. LOG("Unknown transfer code: %d\n", transfer->status);
  908. }
  909. if (dev->shutdown_thread) {
  910. dev->transfer_loop_finished = 1;
  911. return;
  912. }
  913. /* Re-submit the transfer object. */
  914. res = libusb_submit_transfer(transfer);
  915. if (res != 0) {
  916. LOG("Unable to submit URB. libusb error code: %d\n", res);
  917. dev->shutdown_thread = 1;
  918. dev->transfer_loop_finished = 1;
  919. }
  920. }
  921. static int SDLCALL read_thread(void *param)
  922. {
  923. int res;
  924. hid_device *dev = (hid_device *)param;
  925. uint8_t *buf;
  926. const size_t length = dev->input_ep_max_packet_size;
  927. /* Set up the transfer object. */
  928. buf = (uint8_t*) malloc(length);
  929. dev->transfer = libusb_alloc_transfer(0);
  930. libusb_fill_interrupt_transfer(dev->transfer,
  931. dev->device_handle,
  932. dev->input_endpoint,
  933. buf,
  934. length,
  935. read_callback,
  936. dev,
  937. 5000/*timeout*/);
  938. /* Make the first submission. Further submissions are made
  939. from inside read_callback() */
  940. res = libusb_submit_transfer(dev->transfer);
  941. if(res < 0) {
  942. LOG("libusb_submit_transfer failed: %d %s. Stopping read_thread from running\n", res, libusb_error_name(res));
  943. dev->shutdown_thread = 1;
  944. dev->transfer_loop_finished = 1;
  945. }
  946. /* Notify the main thread that the read thread is up and running. */
  947. SDL_WaitThreadBarrier(&dev->barrier);
  948. /* Handle all the events. */
  949. while (!dev->shutdown_thread) {
  950. res = libusb_handle_events(usb_context);
  951. if (res < 0) {
  952. /* There was an error. */
  953. LOG("read_thread(): libusb reports error # %d\n", res);
  954. /* Break out of this loop only on fatal error.*/
  955. if (res != LIBUSB_ERROR_BUSY &&
  956. res != LIBUSB_ERROR_TIMEOUT &&
  957. res != LIBUSB_ERROR_OVERFLOW &&
  958. res != LIBUSB_ERROR_INTERRUPTED) {
  959. dev->shutdown_thread = 1;
  960. break;
  961. }
  962. }
  963. }
  964. /* Cancel any transfer that may be pending. This call will fail
  965. if no transfers are pending, but that's OK. */
  966. libusb_cancel_transfer(dev->transfer);
  967. while (!dev->transfer_loop_finished)
  968. libusb_handle_events_completed(usb_context, &dev->transfer_loop_finished);
  969. /* Now that the read thread is stopping, Wake any threads which are
  970. waiting on data (in hid_read_timeout()). Do this under a mutex to
  971. make sure that a thread which is about to go to sleep waiting on
  972. the condition actually will go to sleep before the condition is
  973. signaled. */
  974. SDL_LockMutex(dev->mutex);
  975. SDL_CondBroadcast(dev->condition);
  976. SDL_UnlockMutex(dev->mutex);
  977. /* The dev->transfer->buffer and dev->transfer objects are cleaned up
  978. in hid_close(). They are not cleaned up here because this thread
  979. could end either due to a disconnect or due to a user
  980. call to hid_close(). In both cases the objects can be safely
  981. cleaned up after the call to pthread_join() (in hid_close()), but
  982. since hid_close() calls libusb_cancel_transfer(), on these objects,
  983. they can not be cleaned up here. */
  984. return 0;
  985. }
  986. static void init_xbox360(libusb_device_handle *device_handle, unsigned short idVendor, unsigned short idProduct, struct libusb_config_descriptor *conf_desc)
  987. {
  988. if ((idVendor == 0x05ac && idProduct == 0x055b) /* Gamesir-G3w */ ||
  989. idVendor == 0x0f0d /* Hori Xbox controllers */) {
  990. unsigned char data[20];
  991. /* The HORIPAD FPS for Nintendo Switch requires this to enable input reports.
  992. This VID/PID is also shared with other HORI controllers, but they all seem
  993. to be fine with this as well.
  994. */
  995. libusb_control_transfer(device_handle, 0xC1, 0x01, 0x100, 0x0, data, sizeof(data), 100);
  996. }
  997. }
  998. static void init_xboxone(libusb_device_handle *device_handle, unsigned short idVendor, unsigned short idProduct, struct libusb_config_descriptor *conf_desc)
  999. {
  1000. static const int VENDOR_MICROSOFT = 0x045e;
  1001. static const int XB1_IFACE_SUBCLASS = 71;
  1002. static const int XB1_IFACE_PROTOCOL = 208;
  1003. int j, k, res;
  1004. for (j = 0; j < conf_desc->bNumInterfaces; j++) {
  1005. const struct libusb_interface *intf = &conf_desc->interface[j];
  1006. for (k = 0; k < intf->num_altsetting; k++) {
  1007. const struct libusb_interface_descriptor *intf_desc = &intf->altsetting[k];
  1008. if (intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC &&
  1009. intf_desc->bInterfaceSubClass == XB1_IFACE_SUBCLASS &&
  1010. intf_desc->bInterfaceProtocol == XB1_IFACE_PROTOCOL) {
  1011. int bSetAlternateSetting = 0;
  1012. /* Newer Microsoft Xbox One controllers have a high speed alternate setting */
  1013. if (idVendor == VENDOR_MICROSOFT &&
  1014. intf_desc->bInterfaceNumber == 0 && intf_desc->bAlternateSetting == 1) {
  1015. bSetAlternateSetting = 1;
  1016. } else if (intf_desc->bInterfaceNumber != 0 && intf_desc->bAlternateSetting == 0) {
  1017. bSetAlternateSetting = 1;
  1018. }
  1019. if (bSetAlternateSetting) {
  1020. res = libusb_claim_interface(device_handle, intf_desc->bInterfaceNumber);
  1021. if (res < 0) {
  1022. LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
  1023. continue;
  1024. }
  1025. LOG("Setting alternate setting for VID/PID 0x%x/0x%x interface %d to %d\n", idVendor, idProduct, intf_desc->bInterfaceNumber, intf_desc->bAlternateSetting);
  1026. res = libusb_set_interface_alt_setting(device_handle, intf_desc->bInterfaceNumber, intf_desc->bAlternateSetting);
  1027. if (res < 0) {
  1028. LOG("xbox init: can't set alt setting %d: %d\n", intf_desc->bInterfaceNumber, res);
  1029. }
  1030. libusb_release_interface(device_handle, intf_desc->bInterfaceNumber);
  1031. }
  1032. }
  1033. }
  1034. }
  1035. }
  1036. static void calculate_device_quirks(hid_device *dev, unsigned short idVendor, unsigned short idProduct)
  1037. {
  1038. static const int VENDOR_SONY = 0x054c;
  1039. static const int PRODUCT_PS3_CONTROLLER = 0x0268;
  1040. static const int PRODUCT_NAVIGATION_CONTROLLER = 0x042f;
  1041. if (idVendor == VENDOR_SONY &&
  1042. (idProduct == PRODUCT_PS3_CONTROLLER || idProduct == PRODUCT_NAVIGATION_CONTROLLER)) {
  1043. dev->skip_output_report_id = 1;
  1044. dev->no_output_reports_on_intr_ep = 1;
  1045. }
  1046. }
  1047. hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
  1048. {
  1049. hid_device *dev = NULL;
  1050. libusb_device **devs;
  1051. libusb_device *usb_dev;
  1052. int res;
  1053. int d = 0;
  1054. int good_open = 0;
  1055. if(hid_init() < 0)
  1056. return NULL;
  1057. dev = new_hid_device();
  1058. libusb_get_device_list(usb_context, &devs);
  1059. while ((usb_dev = devs[d++]) != NULL) {
  1060. struct libusb_device_descriptor desc;
  1061. struct libusb_config_descriptor *conf_desc = NULL;
  1062. int i,j,k;
  1063. libusb_get_device_descriptor(usb_dev, &desc);
  1064. res = libusb_get_active_config_descriptor(usb_dev, &conf_desc);
  1065. if (res < 0)
  1066. libusb_get_config_descriptor(usb_dev, 0, &conf_desc);
  1067. if (!conf_desc)
  1068. continue;
  1069. for (j = 0; j < conf_desc->bNumInterfaces && !good_open; j++) {
  1070. const struct libusb_interface *intf = &conf_desc->interface[j];
  1071. for (k = 0; k < intf->num_altsetting && !good_open; k++) {
  1072. const struct libusb_interface_descriptor *intf_desc;
  1073. intf_desc = &intf->altsetting[k];
  1074. if (should_enumerate_interface(desc.idVendor, intf_desc)) {
  1075. char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
  1076. if (!strcmp(dev_path, path)) {
  1077. int detached_driver = 0;
  1078. /* Matched Paths. Open this device */
  1079. /* OPEN HERE */
  1080. res = libusb_open(usb_dev, &dev->device_handle);
  1081. if (res < 0) {
  1082. LOG("can't open device\n");
  1083. free(dev_path);
  1084. break;
  1085. }
  1086. good_open = 1;
  1087. #ifdef DETACH_KERNEL_DRIVER
  1088. /* Detach the kernel driver, but only if the
  1089. device is managed by the kernel */
  1090. if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
  1091. res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
  1092. if (res < 0) {
  1093. libusb_close(dev->device_handle);
  1094. LOG("Unable to detach Kernel Driver\n");
  1095. free(dev_path);
  1096. good_open = 0;
  1097. break;
  1098. }
  1099. detached_driver = 1;
  1100. }
  1101. #endif
  1102. res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
  1103. if (res < 0) {
  1104. LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
  1105. free(dev_path);
  1106. libusb_close(dev->device_handle);
  1107. good_open = 0;
  1108. break;
  1109. }
  1110. /* Initialize XBox 360 controllers */
  1111. if (is_xbox360(desc.idVendor, intf_desc)) {
  1112. init_xbox360(dev->device_handle, desc.idVendor, desc.idProduct, conf_desc);
  1113. }
  1114. /* Initialize XBox One controllers */
  1115. if (is_xboxone(desc.idVendor, intf_desc)) {
  1116. init_xboxone(dev->device_handle, desc.idVendor, desc.idProduct, conf_desc);
  1117. }
  1118. /* Store off the string descriptor indexes */
  1119. dev->manufacturer_index = desc.iManufacturer;
  1120. dev->product_index = desc.iProduct;
  1121. dev->serial_index = desc.iSerialNumber;
  1122. /* Store off the interface number */
  1123. dev->interface = intf_desc->bInterfaceNumber;
  1124. dev->detached_driver = detached_driver;
  1125. /* Find the INPUT and OUTPUT endpoints. An
  1126. OUTPUT endpoint is not required. */
  1127. for (i = 0; i < intf_desc->bNumEndpoints; i++) {
  1128. const struct libusb_endpoint_descriptor *ep
  1129. = &intf_desc->endpoint[i];
  1130. /* Determine the type and direction of this
  1131. endpoint. */
  1132. int is_interrupt =
  1133. (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
  1134. == LIBUSB_TRANSFER_TYPE_INTERRUPT;
  1135. int is_output =
  1136. (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
  1137. == LIBUSB_ENDPOINT_OUT;
  1138. int is_input =
  1139. (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
  1140. == LIBUSB_ENDPOINT_IN;
  1141. /* Decide whether to use it for input or output. */
  1142. if (dev->input_endpoint == 0 &&
  1143. is_interrupt && is_input) {
  1144. /* Use this endpoint for INPUT */
  1145. dev->input_endpoint = ep->bEndpointAddress;
  1146. dev->input_ep_max_packet_size = ep->wMaxPacketSize;
  1147. }
  1148. if (dev->output_endpoint == 0 &&
  1149. is_interrupt && is_output) {
  1150. /* Use this endpoint for OUTPUT */
  1151. dev->output_endpoint = ep->bEndpointAddress;
  1152. }
  1153. }
  1154. calculate_device_quirks(dev, desc.idVendor, desc.idProduct);
  1155. dev->thread = SDL_CreateThreadInternal(read_thread, "libusb", 0, dev);
  1156. /* Wait here for the read thread to be initialized. */
  1157. SDL_WaitThreadBarrier(&dev->barrier);
  1158. }
  1159. free(dev_path);
  1160. }
  1161. }
  1162. }
  1163. libusb_free_config_descriptor(conf_desc);
  1164. }
  1165. libusb_free_device_list(devs, 1);
  1166. /* If we have a good handle, return it. */
  1167. if (good_open) {
  1168. return dev;
  1169. }
  1170. else {
  1171. /* Unable to open any devices. */
  1172. free_hid_device(dev);
  1173. return NULL;
  1174. }
  1175. }
  1176. int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
  1177. {
  1178. int res;
  1179. if (dev->output_endpoint <= 0 || dev->no_output_reports_on_intr_ep) {
  1180. int report_number = data[0];
  1181. int skipped_report_id = 0;
  1182. if (report_number == 0x0 || dev->skip_output_report_id) {
  1183. data++;
  1184. length--;
  1185. skipped_report_id = 1;
  1186. }
  1187. /* No interrupt out endpoint. Use the Control Endpoint */
  1188. res = libusb_control_transfer(dev->device_handle,
  1189. LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
  1190. 0x09/*HID Set_Report*/,
  1191. (2/*HID output*/ << 8) | report_number,
  1192. dev->interface,
  1193. (unsigned char *)data, length,
  1194. 1000/*timeout millis*/);
  1195. if (res < 0)
  1196. return -1;
  1197. if (skipped_report_id)
  1198. length++;
  1199. return length;
  1200. }
  1201. else {
  1202. /* Use the interrupt out endpoint */
  1203. int actual_length;
  1204. res = libusb_interrupt_transfer(dev->device_handle,
  1205. dev->output_endpoint,
  1206. (unsigned char*)data,
  1207. length,
  1208. &actual_length, 1000);
  1209. if (res < 0)
  1210. return -1;
  1211. return actual_length;
  1212. }
  1213. }
  1214. /* Helper function, to simplify hid_read().
  1215. This should be called with dev->mutex locked. */
  1216. static int return_data(hid_device *dev, unsigned char *data, size_t length)
  1217. {
  1218. /* Copy the data out of the linked list item (rpt) into the
  1219. return buffer (data), and delete the liked list item. */
  1220. struct input_report *rpt = dev->input_reports;
  1221. size_t len = (length < rpt->len)? length: rpt->len;
  1222. if (data && len > 0)
  1223. memcpy(data, rpt->data, len);
  1224. dev->input_reports = rpt->next;
  1225. free(rpt->data);
  1226. free(rpt);
  1227. return len;
  1228. }
  1229. #if 0 /* TODO: pthread_cleanup SDL? */
  1230. static void cleanup_mutex(void *param)
  1231. {
  1232. hid_device *dev = (hid_device *)param;
  1233. SDL_UnlockMutex(dev->mutex);
  1234. }
  1235. #endif
  1236. int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
  1237. {
  1238. #if 0
  1239. int transferred;
  1240. int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
  1241. LOG("transferred: %d\n", transferred);
  1242. return transferred;
  1243. #endif
  1244. int bytes_read;
  1245. SDL_LockMutex(dev->mutex);
  1246. /* TODO: pthread_cleanup SDL? */
  1247. bytes_read = -1;
  1248. /* There's an input report queued up. Return it. */
  1249. if (dev->input_reports) {
  1250. /* Return the first one */
  1251. bytes_read = return_data(dev, data, length);
  1252. goto ret;
  1253. }
  1254. if (dev->shutdown_thread) {
  1255. /* This means the device has been disconnected.
  1256. An error code of -1 should be returned. */
  1257. bytes_read = -1;
  1258. goto ret;
  1259. }
  1260. if (milliseconds == -1) {
  1261. /* Blocking */
  1262. while (!dev->input_reports && !dev->shutdown_thread) {
  1263. SDL_CondWait(dev->condition, dev->mutex);
  1264. }
  1265. if (dev->input_reports) {
  1266. bytes_read = return_data(dev, data, length);
  1267. }
  1268. }
  1269. else if (milliseconds > 0) {
  1270. /* Non-blocking, but called with timeout. */
  1271. int res;
  1272. while (!dev->input_reports && !dev->shutdown_thread) {
  1273. res = SDL_CondWaitTimeout(dev->condition, dev->mutex, milliseconds);
  1274. if (res == 0) {
  1275. if (dev->input_reports) {
  1276. bytes_read = return_data(dev, data, length);
  1277. break;
  1278. }
  1279. /* If we're here, there was a spurious wake up
  1280. or the read thread was shutdown. Run the
  1281. loop again (ie: don't break). */
  1282. }
  1283. else if (res == SDL_MUTEX_TIMEDOUT) {
  1284. /* Timed out. */
  1285. bytes_read = 0;
  1286. break;
  1287. }
  1288. else {
  1289. /* Error. */
  1290. bytes_read = -1;
  1291. break;
  1292. }
  1293. }
  1294. }
  1295. else {
  1296. /* Purely non-blocking */
  1297. bytes_read = 0;
  1298. }
  1299. ret:
  1300. SDL_UnlockMutex(dev->mutex);
  1301. /* TODO: pthread_cleanup SDL? */
  1302. return bytes_read;
  1303. }
  1304. int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
  1305. {
  1306. return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
  1307. }
  1308. int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
  1309. {
  1310. dev->blocking = !nonblock;
  1311. return 0;
  1312. }
  1313. int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
  1314. {
  1315. int res = -1;
  1316. int skipped_report_id = 0;
  1317. int report_number = data[0];
  1318. if (report_number == 0x0) {
  1319. data++;
  1320. length--;
  1321. skipped_report_id = 1;
  1322. }
  1323. res = libusb_control_transfer(dev->device_handle,
  1324. LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
  1325. 0x09/*HID set_report*/,
  1326. (3/*HID feature*/ << 8) | report_number,
  1327. dev->interface,
  1328. (unsigned char *)data, length,
  1329. 1000/*timeout millis*/);
  1330. if (res < 0)
  1331. return -1;
  1332. /* Account for the report ID */
  1333. if (skipped_report_id)
  1334. length++;
  1335. return length;
  1336. }
  1337. int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
  1338. {
  1339. int res = -1;
  1340. int skipped_report_id = 0;
  1341. int report_number = data[0];
  1342. if (report_number == 0x0) {
  1343. /* Offset the return buffer by 1, so that the report ID
  1344. will remain in byte 0. */
  1345. data++;
  1346. length--;
  1347. skipped_report_id = 1;
  1348. }
  1349. res = libusb_control_transfer(dev->device_handle,
  1350. LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
  1351. 0x01/*HID get_report*/,
  1352. (3/*HID feature*/ << 8) | report_number,
  1353. dev->interface,
  1354. (unsigned char *)data, length,
  1355. 1000/*timeout millis*/);
  1356. if (res < 0)
  1357. return -1;
  1358. if (skipped_report_id)
  1359. res++;
  1360. return res;
  1361. }
  1362. void HID_API_EXPORT hid_close(hid_device *dev)
  1363. {
  1364. int status;
  1365. if (!dev)
  1366. return;
  1367. /* Cause read_thread() to stop. */
  1368. dev->shutdown_thread = 1;
  1369. libusb_cancel_transfer(dev->transfer);
  1370. /* Wait for read_thread() to end. */
  1371. SDL_WaitThread(dev->thread, &status);
  1372. /* Clean up the Transfer objects allocated in read_thread(). */
  1373. free(dev->transfer->buffer);
  1374. dev->transfer->buffer = NULL;
  1375. libusb_free_transfer(dev->transfer);
  1376. /* release the interface */
  1377. libusb_release_interface(dev->device_handle, dev->interface);
  1378. #ifdef DETACH_KERNEL_DRIVER
  1379. /* Re-attach kernel driver if necessary. */
  1380. if (dev->detached_driver) {
  1381. int res = libusb_attach_kernel_driver(dev->device_handle, dev->interface);
  1382. if (res < 0)
  1383. LOG("Couldn't re-attach kernel driver.\n");
  1384. }
  1385. #endif
  1386. /* Close the handle */
  1387. libusb_close(dev->device_handle);
  1388. /* Clear out the queue of received reports. */
  1389. SDL_LockMutex(dev->mutex);
  1390. while (dev->input_reports) {
  1391. return_data(dev, NULL, 0);
  1392. }
  1393. SDL_UnlockMutex(dev->mutex);
  1394. free_hid_device(dev);
  1395. }
  1396. int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
  1397. {
  1398. return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
  1399. }
  1400. int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
  1401. {
  1402. return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
  1403. }
  1404. int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
  1405. {
  1406. return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
  1407. }
  1408. int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
  1409. {
  1410. wchar_t *str;
  1411. str = get_usb_string(dev->device_handle, string_index);
  1412. if (str) {
  1413. wcsncpy(string, str, maxlen);
  1414. string[maxlen-1] = L'\0';
  1415. free(str);
  1416. return 0;
  1417. }
  1418. else
  1419. return -1;
  1420. }
  1421. HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
  1422. {
  1423. return NULL;
  1424. }
  1425. struct lang_map_entry {
  1426. const char *name;
  1427. const char *string_code;
  1428. uint16_t usb_code;
  1429. };
  1430. #define LANG(name,code,usb_code) { name, code, usb_code }
  1431. static struct lang_map_entry lang_map[] = {
  1432. LANG("Afrikaans", "af", 0x0436),
  1433. LANG("Albanian", "sq", 0x041C),
  1434. LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
  1435. LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
  1436. LANG("Arabic - Algeria", "ar_dz", 0x1401),
  1437. LANG("Arabic - Egypt", "ar_eg", 0x0C01),
  1438. LANG("Arabic - Iraq", "ar_iq", 0x0801),
  1439. LANG("Arabic - Jordan", "ar_jo", 0x2C01),
  1440. LANG("Arabic - Kuwait", "ar_kw", 0x3401),
  1441. LANG("Arabic - Lebanon", "ar_lb", 0x3001),
  1442. LANG("Arabic - Libya", "ar_ly", 0x1001),
  1443. LANG("Arabic - Morocco", "ar_ma", 0x1801),
  1444. LANG("Arabic - Oman", "ar_om", 0x2001),
  1445. LANG("Arabic - Qatar", "ar_qa", 0x4001),
  1446. LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
  1447. LANG("Arabic - Syria", "ar_sy", 0x2801),
  1448. LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
  1449. LANG("Arabic - Yemen", "ar_ye", 0x2401),
  1450. LANG("Armenian", "hy", 0x042B),
  1451. LANG("Azeri - Latin", "az_az", 0x042C),
  1452. LANG("Azeri - Cyrillic", "az_az", 0x082C),
  1453. LANG("Basque", "eu", 0x042D),
  1454. LANG("Belarusian", "be", 0x0423),
  1455. LANG("Bulgarian", "bg", 0x0402),
  1456. LANG("Catalan", "ca", 0x0403),
  1457. LANG("Chinese - China", "zh_cn", 0x0804),
  1458. LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
  1459. LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
  1460. LANG("Chinese - Singapore", "zh_sg", 0x1004),
  1461. LANG("Chinese - Taiwan", "zh_tw", 0x0404),
  1462. LANG("Croatian", "hr", 0x041A),
  1463. LANG("Czech", "cs", 0x0405),
  1464. LANG("Danish", "da", 0x0406),
  1465. LANG("Dutch - Netherlands", "nl_nl", 0x0413),
  1466. LANG("Dutch - Belgium", "nl_be", 0x0813),
  1467. LANG("English - Australia", "en_au", 0x0C09),
  1468. LANG("English - Belize", "en_bz", 0x2809),
  1469. LANG("English - Canada", "en_ca", 0x1009),
  1470. LANG("English - Caribbean", "en_cb", 0x2409),
  1471. LANG("English - Ireland", "en_ie", 0x1809),
  1472. LANG("English - Jamaica", "en_jm", 0x2009),
  1473. LANG("English - New Zealand", "en_nz", 0x1409),
  1474. LANG("English - Philippines", "en_ph", 0x3409),
  1475. LANG("English - Southern Africa", "en_za", 0x1C09),
  1476. LANG("English - Trinidad", "en_tt", 0x2C09),
  1477. LANG("English - Great Britain", "en_gb", 0x0809),
  1478. LANG("English - United States", "en_us", 0x0409),
  1479. LANG("Estonian", "et", 0x0425),
  1480. LANG("Farsi", "fa", 0x0429),
  1481. LANG("Finnish", "fi", 0x040B),
  1482. LANG("Faroese", "fo", 0x0438),
  1483. LANG("French - France", "fr_fr", 0x040C),
  1484. LANG("French - Belgium", "fr_be", 0x080C),
  1485. LANG("French - Canada", "fr_ca", 0x0C0C),
  1486. LANG("French - Luxembourg", "fr_lu", 0x140C),
  1487. LANG("French - Switzerland", "fr_ch", 0x100C),
  1488. LANG("Gaelic - Ireland", "gd_ie", 0x083C),
  1489. LANG("Gaelic - Scotland", "gd", 0x043C),
  1490. LANG("German - Germany", "de_de", 0x0407),
  1491. LANG("German - Austria", "de_at", 0x0C07),
  1492. LANG("German - Liechtenstein", "de_li", 0x1407),
  1493. LANG("German - Luxembourg", "de_lu", 0x1007),
  1494. LANG("German - Switzerland", "de_ch", 0x0807),
  1495. LANG("Greek", "el", 0x0408),
  1496. LANG("Hebrew", "he", 0x040D),
  1497. LANG("Hindi", "hi", 0x0439),
  1498. LANG("Hungarian", "hu", 0x040E),
  1499. LANG("Icelandic", "is", 0x040F),
  1500. LANG("Indonesian", "id", 0x0421),
  1501. LANG("Italian - Italy", "it_it", 0x0410),
  1502. LANG("Italian - Switzerland", "it_ch", 0x0810),
  1503. LANG("Japanese", "ja", 0x0411),
  1504. LANG("Korean", "ko", 0x0412),
  1505. LANG("Latvian", "lv", 0x0426),
  1506. LANG("Lithuanian", "lt", 0x0427),
  1507. LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
  1508. LANG("Malay - Malaysia", "ms_my", 0x043E),
  1509. LANG("Malay ??? Brunei", "ms_bn", 0x083E),
  1510. LANG("Maltese", "mt", 0x043A),
  1511. LANG("Marathi", "mr", 0x044E),
  1512. LANG("Norwegian - Bokml", "no_no", 0x0414),
  1513. LANG("Norwegian - Nynorsk", "no_no", 0x0814),
  1514. LANG("Polish", "pl", 0x0415),
  1515. LANG("Portuguese - Portugal", "pt_pt", 0x0816),
  1516. LANG("Portuguese - Brazil", "pt_br", 0x0416),
  1517. LANG("Raeto-Romance", "rm", 0x0417),
  1518. LANG("Romanian - Romania", "ro", 0x0418),
  1519. LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
  1520. LANG("Russian", "ru", 0x0419),
  1521. LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
  1522. LANG("Sanskrit", "sa", 0x044F),
  1523. LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
  1524. LANG("Serbian - Latin", "sr_sp", 0x081A),
  1525. LANG("Setsuana", "tn", 0x0432),
  1526. LANG("Slovenian", "sl", 0x0424),
  1527. LANG("Slovak", "sk", 0x041B),
  1528. LANG("Sorbian", "sb", 0x042E),
  1529. LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
  1530. LANG("Spanish - Argentina", "es_ar", 0x2C0A),
  1531. LANG("Spanish - Bolivia", "es_bo", 0x400A),
  1532. LANG("Spanish - Chile", "es_cl", 0x340A),
  1533. LANG("Spanish - Colombia", "es_co", 0x240A),
  1534. LANG("Spanish - Costa Rica", "es_cr", 0x140A),
  1535. LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
  1536. LANG("Spanish - Ecuador", "es_ec", 0x300A),
  1537. LANG("Spanish - Guatemala", "es_gt", 0x100A),
  1538. LANG("Spanish - Honduras", "es_hn", 0x480A),
  1539. LANG("Spanish - Mexico", "es_mx", 0x080A),
  1540. LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
  1541. LANG("Spanish - Panama", "es_pa", 0x180A),
  1542. LANG("Spanish - Peru", "es_pe", 0x280A),
  1543. LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
  1544. LANG("Spanish - Paraguay", "es_py", 0x3C0A),
  1545. LANG("Spanish - El Salvador", "es_sv", 0x440A),
  1546. LANG("Spanish - Uruguay", "es_uy", 0x380A),
  1547. LANG("Spanish - Venezuela", "es_ve", 0x200A),
  1548. LANG("Southern Sotho", "st", 0x0430),
  1549. LANG("Swahili", "sw", 0x0441),
  1550. LANG("Swedish - Sweden", "sv_se", 0x041D),
  1551. LANG("Swedish - Finland", "sv_fi", 0x081D),
  1552. LANG("Tamil", "ta", 0x0449),
  1553. LANG("Tatar", "tt", 0X0444),
  1554. LANG("Thai", "th", 0x041E),
  1555. LANG("Turkish", "tr", 0x041F),
  1556. LANG("Tsonga", "ts", 0x0431),
  1557. LANG("Ukrainian", "uk", 0x0422),
  1558. LANG("Urdu", "ur", 0x0420),
  1559. LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
  1560. LANG("Uzbek ??? Latin", "uz_uz", 0x0443),
  1561. LANG("Vietnamese", "vi", 0x042A),
  1562. LANG("Xhosa", "xh", 0x0434),
  1563. LANG("Yiddish", "yi", 0x043D),
  1564. LANG("Zulu", "zu", 0x0435),
  1565. LANG(NULL, NULL, 0x0),
  1566. };
  1567. uint16_t get_usb_code_for_current_locale(void)
  1568. {
  1569. char *locale = NULL;
  1570. char search_string[64];
  1571. char *ptr;
  1572. struct lang_map_entry *lang;
  1573. /* Get the current locale. */
  1574. #ifdef HAVE_SETLOCALE
  1575. locale = setlocale(0, NULL);
  1576. #endif
  1577. if (!locale)
  1578. return 0x0;
  1579. /* Make a copy of the current locale string. */
  1580. strncpy(search_string, locale, sizeof(search_string));
  1581. search_string[sizeof(search_string)-1] = '\0';
  1582. /* Chop off the encoding part, and make it lower case. */
  1583. ptr = search_string;
  1584. while (*ptr) {
  1585. *ptr = tolower(*ptr);
  1586. if (*ptr == '.') {
  1587. *ptr = '\0';
  1588. break;
  1589. }
  1590. ptr++;
  1591. }
  1592. /* Find the entry which matches the string code of our locale. */
  1593. lang = lang_map;
  1594. while (lang->string_code) {
  1595. if (!strcmp(lang->string_code, search_string)) {
  1596. return lang->usb_code;
  1597. }
  1598. lang++;
  1599. }
  1600. /* There was no match. Find with just the language only. */
  1601. /* Chop off the variant. Chop it off at the '_'. */
  1602. ptr = search_string;
  1603. while (*ptr) {
  1604. *ptr = tolower(*ptr);
  1605. if (*ptr == '_') {
  1606. *ptr = '\0';
  1607. break;
  1608. }
  1609. ptr++;
  1610. }
  1611. #if 0 /* TODO: Do we need this? */
  1612. /* Find the entry which matches the string code of our language. */
  1613. lang = lang_map;
  1614. while (lang->string_code) {
  1615. if (!strcmp(lang->string_code, search_string)) {
  1616. return lang->usb_code;
  1617. }
  1618. lang++;
  1619. }
  1620. #endif
  1621. /* Found nothing. */
  1622. return 0x0;
  1623. }
  1624. #if defined(__cplusplus) && !defined(NAMESPACE)
  1625. }
  1626. #endif
  1627. #ifdef NAMESPACE
  1628. }
  1629. #endif