Path: blob/main/cad/PrusaSlicer/files/patch-src_hidapi_libusb_hid.c
16151 views
--- src/hidapi/libusb/hid.c.orig 2020-03-31 19:30:48 UTC1+++ src/hidapi/libusb/hid.c2@@ -0,0 +1,1514 @@3+/*******************************************************4+ HIDAPI - Multi-Platform library for5+ communication with HID devices.6+7+ Alan Ott8+ Signal 11 Software9+10+ 8/22/200911+ Linux Version - 6/2/201012+ Libusb Version - 8/13/201013+ FreeBSD Version - 11/1/201114+15+ Copyright 2009, All Rights Reserved.16+17+ At the discretion of the user of this library,18+ this software may be licensed under the terms of the19+ GNU General Public License v3, a BSD-Style license, or the20+ original HIDAPI license as outlined in the LICENSE.txt,21+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt22+ files located at the root of the source distribution.23+ These files may also be found in the public source24+ code repository located at:25+ http://github.com/signal11/hidapi .26+********************************************************/27+28+#define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */29+30+/* C */31+#include <stdio.h>32+#include <string.h>33+#include <stdlib.h>34+#include <ctype.h>35+#include <locale.h>36+#include <errno.h>37+38+/* Unix */39+#include <unistd.h>40+#include <sys/types.h>41+#include <sys/stat.h>42+#include <sys/ioctl.h>43+#include <sys/utsname.h>44+#include <fcntl.h>45+#include <pthread.h>46+#include <wchar.h>47+48+/* GNU / LibUSB */49+#include <libusb.h>50+#ifndef __ANDROID__51+#include <iconv.h>52+#endif53+54+#include "hidapi.h"55+56+#ifdef __ANDROID__57+58+/* Barrier implementation because Android/Bionic don't have pthread_barrier.59+ This implementation came from Brent Priddy and was posted on60+ StackOverflow. It is used with his permission. */61+typedef int pthread_barrierattr_t;62+typedef struct pthread_barrier {63+ pthread_mutex_t mutex;64+ pthread_cond_t cond;65+ int count;66+ int trip_count;67+} pthread_barrier_t;68+69+static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)70+{71+ if(count == 0) {72+ errno = EINVAL;73+ return -1;74+ }75+76+ if(pthread_mutex_init(&barrier->mutex, 0) < 0) {77+ return -1;78+ }79+ if(pthread_cond_init(&barrier->cond, 0) < 0) {80+ pthread_mutex_destroy(&barrier->mutex);81+ return -1;82+ }83+ barrier->trip_count = count;84+ barrier->count = 0;85+86+ return 0;87+}88+89+static int pthread_barrier_destroy(pthread_barrier_t *barrier)90+{91+ pthread_cond_destroy(&barrier->cond);92+ pthread_mutex_destroy(&barrier->mutex);93+ return 0;94+}95+96+static int pthread_barrier_wait(pthread_barrier_t *barrier)97+{98+ pthread_mutex_lock(&barrier->mutex);99+ ++(barrier->count);100+ if(barrier->count >= barrier->trip_count)101+ {102+ barrier->count = 0;103+ pthread_cond_broadcast(&barrier->cond);104+ pthread_mutex_unlock(&barrier->mutex);105+ return 1;106+ }107+ else108+ {109+ pthread_cond_wait(&barrier->cond, &(barrier->mutex));110+ pthread_mutex_unlock(&barrier->mutex);111+ return 0;112+ }113+}114+115+#endif116+117+#ifdef __cplusplus118+extern "C" {119+#endif120+121+#ifdef DEBUG_PRINTF122+#define LOG(...) fprintf(stderr, __VA_ARGS__)123+#else124+#define LOG(...) do {} while (0)125+#endif126+127+#ifndef __FreeBSD__128+#define DETACH_KERNEL_DRIVER129+#endif130+131+/* Uncomment to enable the retrieval of Usage and Usage Page in132+hid_enumerate(). Warning, on platforms different from FreeBSD133+this is very invasive as it requires the detach134+and re-attach of the kernel driver. See comments inside hid_enumerate().135+libusb HIDAPI programs are encouraged to use the interface number136+instead to differentiate between interfaces on a composite HID device. */137+/*#define INVASIVE_GET_USAGE*/138+139+/* Linked List of input reports received from the device. */140+struct input_report {141+ uint8_t *data;142+ size_t len;143+ struct input_report *next;144+};145+146+147+struct hid_device_ {148+ /* Handle to the actual device. */149+ libusb_device_handle *device_handle;150+151+ /* Endpoint information */152+ int input_endpoint;153+ int output_endpoint;154+ int input_ep_max_packet_size;155+156+ /* The interface number of the HID */157+ int interface;158+159+ /* Indexes of Strings */160+ int manufacturer_index;161+ int product_index;162+ int serial_index;163+164+ /* Whether blocking reads are used */165+ int blocking; /* boolean */166+167+ /* Read thread objects */168+ pthread_t thread;169+ pthread_mutex_t mutex; /* Protects input_reports */170+ pthread_cond_t condition;171+ pthread_barrier_t barrier; /* Ensures correct startup sequence */172+ int shutdown_thread;173+ int cancelled;174+ struct libusb_transfer *transfer;175+176+ /* List of received input reports. */177+ struct input_report *input_reports;178+};179+180+static libusb_context *usb_context = NULL;181+182+uint16_t get_usb_code_for_current_locale(void);183+static int return_data(hid_device *dev, unsigned char *data, size_t length);184+185+static hid_device *new_hid_device(void)186+{187+ hid_device *dev = calloc(1, sizeof(hid_device));188+ dev->blocking = 1;189+190+ pthread_mutex_init(&dev->mutex, NULL);191+ pthread_cond_init(&dev->condition, NULL);192+ pthread_barrier_init(&dev->barrier, NULL, 2);193+194+ return dev;195+}196+197+static void free_hid_device(hid_device *dev)198+{199+ /* Clean up the thread objects */200+ pthread_barrier_destroy(&dev->barrier);201+ pthread_cond_destroy(&dev->condition);202+ pthread_mutex_destroy(&dev->mutex);203+204+ /* Free the device itself */205+ free(dev);206+}207+208+#if 0209+/*TODO: Implement this funciton on hidapi/libusb.. */210+static void register_error(hid_device *dev, const char *op)211+{212+213+}214+#endif215+216+#ifdef INVASIVE_GET_USAGE217+/* Get bytes from a HID Report Descriptor.218+ Only call with a num_bytes of 0, 1, 2, or 4. */219+static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)220+{221+ /* Return if there aren't enough bytes. */222+ if (cur + num_bytes >= len)223+ return 0;224+225+ if (num_bytes == 0)226+ return 0;227+ else if (num_bytes == 1) {228+ return rpt[cur+1];229+ }230+ else if (num_bytes == 2) {231+ return (rpt[cur+2] * 256 + rpt[cur+1]);232+ }233+ else if (num_bytes == 4) {234+ return (rpt[cur+4] * 0x01000000 +235+ rpt[cur+3] * 0x00010000 +236+ rpt[cur+2] * 0x00000100 +237+ rpt[cur+1] * 0x00000001);238+ }239+ else240+ return 0;241+}242+243+/* Retrieves the device's Usage Page and Usage from the report244+ descriptor. The algorithm is simple, as it just returns the first245+ Usage and Usage Page that it finds in the descriptor.246+ The return value is 0 on success and -1 on failure. */247+static int get_usage(uint8_t *report_descriptor, size_t size,248+ unsigned short *usage_page, unsigned short *usage)249+{250+ unsigned int i = 0;251+ int size_code;252+ int data_len, key_size;253+ int usage_found = 0, usage_page_found = 0;254+255+ while (i < size) {256+ int key = report_descriptor[i];257+ int key_cmd = key & 0xfc;258+259+ //printf("key: %02hhx\n", key);260+261+ if ((key & 0xf0) == 0xf0) {262+ /* This is a Long Item. The next byte contains the263+ length of the data section (value) for this key.264+ See the HID specification, version 1.11, section265+ 6.2.2.3, titled "Long Items." */266+ if (i+1 < size)267+ data_len = report_descriptor[i+1];268+ else269+ data_len = 0; /* malformed report */270+ key_size = 3;271+ }272+ else {273+ /* This is a Short Item. The bottom two bits of the274+ key contain the size code for the data section275+ (value) for this key. Refer to the HID276+ specification, version 1.11, section 6.2.2.2,277+ titled "Short Items." */278+ size_code = key & 0x3;279+ switch (size_code) {280+ case 0:281+ case 1:282+ case 2:283+ data_len = size_code;284+ break;285+ case 3:286+ data_len = 4;287+ break;288+ default:289+ /* Can't ever happen since size_code is & 0x3 */290+ data_len = 0;291+ break;292+ };293+ key_size = 1;294+ }295+296+ if (key_cmd == 0x4) {297+ *usage_page = get_bytes(report_descriptor, size, data_len, i);298+ usage_page_found = 1;299+ //printf("Usage Page: %x\n", (uint32_t)*usage_page);300+ }301+ if (key_cmd == 0x8) {302+ *usage = get_bytes(report_descriptor, size, data_len, i);303+ usage_found = 1;304+ //printf("Usage: %x\n", (uint32_t)*usage);305+ }306+307+ if (usage_page_found && usage_found)308+ return 0; /* success */309+310+ /* Skip over this key and it's associated data */311+ i += data_len + key_size;312+ }313+314+ return -1; /* failure */315+}316+#endif /* INVASIVE_GET_USAGE */317+318+#if defined(__FreeBSD__) && __FreeBSD__ < 10319+/* The libusb version included in FreeBSD < 10 doesn't have this function. In320+ mainline libusb, it's inlined in libusb.h. This function will bear a striking321+ resemblance to that one, because there's about one way to code it.322+323+ Note that the data parameter is Unicode in UTF-16LE encoding.324+ Return value is the number of bytes in data, or LIBUSB_ERROR_*.325+ */326+static inline int libusb_get_string_descriptor(libusb_device_handle *dev,327+ uint8_t descriptor_index, uint16_t lang_id,328+ unsigned char *data, int length)329+{330+ return libusb_control_transfer(dev,331+ LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */332+ LIBUSB_REQUEST_GET_DESCRIPTOR,333+ (LIBUSB_DT_STRING << 8) | descriptor_index,334+ lang_id, data, (uint16_t) length, 1000);335+}336+337+#endif338+339+340+/* Get the first language the device says it reports. This comes from341+ USB string #0. */342+static uint16_t get_first_language(libusb_device_handle *dev)343+{344+ uint16_t buf[32];345+ int len;346+347+ /* Get the string from libusb. */348+ len = libusb_get_string_descriptor(dev,349+ 0x0, /* String ID */350+ 0x0, /* Language */351+ (unsigned char*)buf,352+ sizeof(buf));353+ if (len < 4)354+ return 0x0;355+356+ return buf[1]; /* First two bytes are len and descriptor type. */357+}358+359+static int is_language_supported(libusb_device_handle *dev, uint16_t lang)360+{361+ uint16_t buf[32];362+ int len;363+ int i;364+365+ /* Get the string from libusb. */366+ len = libusb_get_string_descriptor(dev,367+ 0x0, /* String ID */368+ 0x0, /* Language */369+ (unsigned char*)buf,370+ sizeof(buf));371+ if (len < 4)372+ return 0x0;373+374+375+ len /= 2; /* language IDs are two-bytes each. */376+ /* Start at index 1 because there are two bytes of protocol data. */377+ for (i = 1; i < len; i++) {378+ if (buf[i] == lang)379+ return 1;380+ }381+382+ return 0;383+}384+385+386+/* This function returns a newly allocated wide string containing the USB387+ device string numbered by the index. The returned string must be freed388+ by using free(). */389+static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)390+{391+ char buf[512];392+ int len;393+ wchar_t *str = NULL;394+395+#ifndef __ANDROID__ /* we don't use iconv on Android */396+ wchar_t wbuf[256];397+ /* iconv variables */398+ iconv_t ic;399+ size_t inbytes;400+ size_t outbytes;401+ size_t res;402+#ifdef __FreeBSD__403+ const char *inptr;404+#else405+ char *inptr;406+#endif407+ char *outptr;408+#endif409+410+ /* Determine which language to use. */411+ uint16_t lang;412+ lang = get_usb_code_for_current_locale();413+ if (!is_language_supported(dev, lang))414+ lang = get_first_language(dev);415+416+ /* Get the string from libusb. */417+ len = libusb_get_string_descriptor(dev,418+ idx,419+ lang,420+ (unsigned char*)buf,421+ sizeof(buf));422+ if (len < 0)423+ return NULL;424+425+#ifdef __ANDROID__426+427+ /* Bionic does not have iconv support nor wcsdup() function, so it428+ has to be done manually. The following code will only work for429+ code points that can be represented as a single UTF-16 character,430+ and will incorrectly convert any code points which require more431+ than one UTF-16 character.432+433+ Skip over the first character (2-bytes). */434+ len -= 2;435+ str = malloc((len / 2 + 1) * sizeof(wchar_t));436+ int i;437+ for (i = 0; i < len / 2; i++) {438+ str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8);439+ }440+ str[len / 2] = 0x00000000;441+442+#else443+444+ /* buf does not need to be explicitly NULL-terminated because445+ it is only passed into iconv() which does not need it. */446+447+ /* Initialize iconv. */448+ ic = iconv_open("WCHAR_T", "UTF-16LE");449+ if (ic == (iconv_t)-1) {450+ LOG("iconv_open() failed\n");451+ return NULL;452+ }453+454+ /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).455+ Skip the first character (2-bytes). */456+ inptr = buf+2;457+ inbytes = len-2;458+ outptr = (char*) wbuf;459+ outbytes = sizeof(wbuf);460+ res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);461+ if (res == (size_t)-1) {462+ LOG("iconv() failed\n");463+ goto err;464+ }465+466+ /* Write the terminating NULL. */467+ wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;468+ if (outbytes >= sizeof(wbuf[0]))469+ *((wchar_t*)outptr) = 0x00000000;470+471+ /* Allocate and copy the string. */472+ str = wcsdup(wbuf);473+474+err:475+ iconv_close(ic);476+477+#endif478+479+ return str;480+}481+482+static char *make_path(libusb_device *dev, int interface_number)483+{484+ char str[64];485+ snprintf(str, sizeof(str), "%04x:%04x:%02x",486+ libusb_get_bus_number(dev),487+ libusb_get_device_address(dev),488+ interface_number);489+ str[sizeof(str)-1] = '\0';490+491+ return strdup(str);492+}493+494+495+int HID_API_EXPORT hid_init(void)496+{497+ if (!usb_context) {498+ const char *locale;499+500+ /* Init Libusb */501+ if (libusb_init(&usb_context))502+ return -1;503+504+ /* Set the locale if it's not set. */505+ locale = setlocale(LC_CTYPE, NULL);506+ if (!locale)507+ setlocale(LC_CTYPE, "");508+ }509+510+ return 0;511+}512+513+int HID_API_EXPORT hid_exit(void)514+{515+ if (usb_context) {516+ libusb_exit(usb_context);517+ usb_context = NULL;518+ }519+520+ return 0;521+}522+523+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)524+{525+ libusb_device **devs;526+ libusb_device *dev;527+ libusb_device_handle *handle;528+ ssize_t num_devs;529+ int i = 0;530+531+ struct hid_device_info *root = NULL; /* return object */532+ struct hid_device_info *cur_dev = NULL;533+534+ if(hid_init() < 0)535+ return NULL;536+537+ num_devs = libusb_get_device_list(usb_context, &devs);538+ if (num_devs < 0)539+ return NULL;540+ while ((dev = devs[i++]) != NULL) {541+ struct libusb_device_descriptor desc;542+ struct libusb_config_descriptor *conf_desc = NULL;543+ int j, k;544+ int interface_num = 0;545+546+ int res = libusb_get_device_descriptor(dev, &desc);547+ unsigned short dev_vid = desc.idVendor;548+ unsigned short dev_pid = desc.idProduct;549+550+ res = libusb_get_active_config_descriptor(dev, &conf_desc);551+ if (res < 0)552+ libusb_get_config_descriptor(dev, 0, &conf_desc);553+ if (conf_desc) {554+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {555+ const struct libusb_interface *intf = &conf_desc->interface[j];556+ for (k = 0; k < intf->num_altsetting; k++) {557+ const struct libusb_interface_descriptor *intf_desc;558+ intf_desc = &intf->altsetting[k];559+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {560+ interface_num = intf_desc->bInterfaceNumber;561+562+ /* Check the VID/PID against the arguments */563+ if ((vendor_id == 0x0 || vendor_id == dev_vid) &&564+ (product_id == 0x0 || product_id == dev_pid)) {565+ struct hid_device_info *tmp;566+567+ /* VID/PID match. Create the record. */568+ tmp = calloc(1, sizeof(struct hid_device_info));569+ if (cur_dev) {570+ cur_dev->next = tmp;571+ }572+ else {573+ root = tmp;574+ }575+ cur_dev = tmp;576+577+ /* Fill out the record */578+ cur_dev->next = NULL;579+ cur_dev->path = make_path(dev, interface_num);580+581+ res = libusb_open(dev, &handle);582+583+ if (res >= 0) {584+ /* Serial Number */585+ if (desc.iSerialNumber > 0)586+ cur_dev->serial_number =587+ get_usb_string(handle, desc.iSerialNumber);588+589+ /* Manufacturer and Product strings */590+ if (desc.iManufacturer > 0)591+ cur_dev->manufacturer_string =592+ get_usb_string(handle, desc.iManufacturer);593+ if (desc.iProduct > 0)594+ cur_dev->product_string =595+ get_usb_string(handle, desc.iProduct);596+597+#ifdef INVASIVE_GET_USAGE598+{599+ /*600+ This section is removed because it is too601+ invasive on the system. Getting a Usage Page602+ and Usage requires parsing the HID Report603+ descriptor. Getting a HID Report descriptor604+ involves claiming the interface. Claiming the605+ interface involves detaching the kernel driver.606+ Detaching the kernel driver is hard on the system607+ because it will unclaim interfaces (if another608+ app has them claimed) and the re-attachment of609+ the driver will sometimes change /dev entry names.610+ It is for these reasons that this section is611+ #if 0. For composite devices, use the interface612+ field in the hid_device_info struct to distinguish613+ between interfaces. */614+ unsigned char data[256];615+#ifdef DETACH_KERNEL_DRIVER616+ int detached = 0;617+ /* Usage Page and Usage */618+ res = libusb_kernel_driver_active(handle, interface_num);619+ if (res == 1) {620+ res = libusb_detach_kernel_driver(handle, interface_num);621+ if (res < 0)622+ LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");623+ else624+ detached = 1;625+ }626+#endif627+ res = libusb_claim_interface(handle, interface_num);628+ if (res >= 0) {629+ /* Get the HID Report Descriptor. */630+ 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);631+ if (res >= 0) {632+ unsigned short page=0, usage=0;633+ /* Parse the usage and usage page634+ out of the report descriptor. */635+ get_usage(data, res, &page, &usage);636+ cur_dev->usage_page = page;637+ cur_dev->usage = usage;638+ }639+ else640+ LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);641+642+ /* Release the interface */643+ res = libusb_release_interface(handle, interface_num);644+ if (res < 0)645+ LOG("Can't release the interface.\n");646+ }647+ else648+ LOG("Can't claim interface %d\n", res);649+#ifdef DETACH_KERNEL_DRIVER650+ /* Re-attach kernel driver if necessary. */651+ if (detached) {652+ res = libusb_attach_kernel_driver(handle, interface_num);653+ if (res < 0)654+ LOG("Couldn't re-attach kernel driver.\n");655+ }656+#endif657+}658+#endif /* INVASIVE_GET_USAGE */659+660+ libusb_close(handle);661+ }662+ /* VID/PID */663+ cur_dev->vendor_id = dev_vid;664+ cur_dev->product_id = dev_pid;665+666+ /* Release Number */667+ cur_dev->release_number = desc.bcdDevice;668+669+ /* Interface Number */670+ cur_dev->interface_number = interface_num;671+ }672+ }673+ } /* altsettings */674+ } /* interfaces */675+ libusb_free_config_descriptor(conf_desc);676+ }677+ }678+679+ libusb_free_device_list(devs, 1);680+681+ return root;682+}683+684+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)685+{686+ struct hid_device_info *d = devs;687+ while (d) {688+ struct hid_device_info *next = d->next;689+ free(d->path);690+ free(d->serial_number);691+ free(d->manufacturer_string);692+ free(d->product_string);693+ free(d);694+ d = next;695+ }696+}697+698+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)699+{700+ struct hid_device_info *devs, *cur_dev;701+ const char *path_to_open = NULL;702+ hid_device *handle = NULL;703+704+ devs = hid_enumerate(vendor_id, product_id);705+ cur_dev = devs;706+ while (cur_dev) {707+ if (cur_dev->vendor_id == vendor_id &&708+ cur_dev->product_id == product_id) {709+ if (serial_number) {710+ if (cur_dev->serial_number &&711+ wcscmp(serial_number, cur_dev->serial_number) == 0) {712+ path_to_open = cur_dev->path;713+ break;714+ }715+ }716+ else {717+ path_to_open = cur_dev->path;718+ break;719+ }720+ }721+ cur_dev = cur_dev->next;722+ }723+724+ if (path_to_open) {725+ /* Open the device */726+ handle = hid_open_path(path_to_open);727+ }728+729+ hid_free_enumeration(devs);730+731+ return handle;732+}733+734+static void read_callback(struct libusb_transfer *transfer)735+{736+ hid_device *dev = transfer->user_data;737+ int res;738+739+ if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {740+741+ struct input_report *rpt = malloc(sizeof(*rpt));742+ rpt->data = malloc(transfer->actual_length);743+ memcpy(rpt->data, transfer->buffer, transfer->actual_length);744+ rpt->len = transfer->actual_length;745+ rpt->next = NULL;746+747+ pthread_mutex_lock(&dev->mutex);748+749+ /* Attach the new report object to the end of the list. */750+ if (dev->input_reports == NULL) {751+ /* The list is empty. Put it at the root. */752+ dev->input_reports = rpt;753+ pthread_cond_signal(&dev->condition);754+ }755+ else {756+ /* Find the end of the list and attach. */757+ struct input_report *cur = dev->input_reports;758+ int num_queued = 0;759+ while (cur->next != NULL) {760+ cur = cur->next;761+ num_queued++;762+ }763+ cur->next = rpt;764+765+ /* Pop one off if we've reached 30 in the queue. This766+ way we don't grow forever if the user never reads767+ anything from the device. */768+ if (num_queued > 30) {769+ return_data(dev, NULL, 0);770+ }771+ }772+ pthread_mutex_unlock(&dev->mutex);773+ }774+ else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {775+ dev->shutdown_thread = 1;776+ dev->cancelled = 1;777+ return;778+ }779+ else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {780+ dev->shutdown_thread = 1;781+ dev->cancelled = 1;782+ return;783+ }784+ else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {785+ //LOG("Timeout (normal)\n");786+ }787+ else {788+ LOG("Unknown transfer code: %d\n", transfer->status);789+ }790+791+ /* Re-submit the transfer object. */792+ res = libusb_submit_transfer(transfer);793+ if (res != 0) {794+ LOG("Unable to submit URB. libusb error code: %d\n", res);795+ dev->shutdown_thread = 1;796+ dev->cancelled = 1;797+ }798+}799+800+801+static void *read_thread(void *param)802+{803+ hid_device *dev = param;804+ unsigned char *buf;805+ const size_t length = dev->input_ep_max_packet_size;806+807+ /* Set up the transfer object. */808+ buf = malloc(length);809+ dev->transfer = libusb_alloc_transfer(0);810+ libusb_fill_interrupt_transfer(dev->transfer,811+ dev->device_handle,812+ dev->input_endpoint,813+ buf,814+ length,815+ read_callback,816+ dev,817+ 5000/*timeout*/);818+819+ /* Make the first submission. Further submissions are made820+ from inside read_callback() */821+ libusb_submit_transfer(dev->transfer);822+823+ /* Notify the main thread that the read thread is up and running. */824+ pthread_barrier_wait(&dev->barrier);825+826+ /* Handle all the events. */827+ while (!dev->shutdown_thread) {828+ int res;829+ res = libusb_handle_events(usb_context);830+ if (res < 0) {831+ /* There was an error. */832+ LOG("read_thread(): libusb reports error # %d\n", res);833+834+ /* Break out of this loop only on fatal error.*/835+ if (res != LIBUSB_ERROR_BUSY &&836+ res != LIBUSB_ERROR_TIMEOUT &&837+ res != LIBUSB_ERROR_OVERFLOW &&838+ res != LIBUSB_ERROR_INTERRUPTED) {839+ break;840+ }841+ }842+ }843+844+ /* Cancel any transfer that may be pending. This call will fail845+ if no transfers are pending, but that's OK. */846+ libusb_cancel_transfer(dev->transfer);847+848+ while (!dev->cancelled)849+ libusb_handle_events_completed(usb_context, &dev->cancelled);850+851+ /* Now that the read thread is stopping, Wake any threads which are852+ waiting on data (in hid_read_timeout()). Do this under a mutex to853+ make sure that a thread which is about to go to sleep waiting on854+ the condition actually will go to sleep before the condition is855+ signaled. */856+ pthread_mutex_lock(&dev->mutex);857+ pthread_cond_broadcast(&dev->condition);858+ pthread_mutex_unlock(&dev->mutex);859+860+ /* The dev->transfer->buffer and dev->transfer objects are cleaned up861+ in hid_close(). They are not cleaned up here because this thread862+ could end either due to a disconnect or due to a user863+ call to hid_close(). In both cases the objects can be safely864+ cleaned up after the call to pthread_join() (in hid_close()), but865+ since hid_close() calls libusb_cancel_transfer(), on these objects,866+ they can not be cleaned up here. */867+868+ return NULL;869+}870+871+872+hid_device * HID_API_EXPORT hid_open_path(const char *path)873+{874+ hid_device *dev = NULL;875+876+ libusb_device **devs;877+ libusb_device *usb_dev;878+ int res;879+ int d = 0;880+ int good_open = 0;881+882+ if(hid_init() < 0)883+ return NULL;884+885+ dev = new_hid_device();886+887+ libusb_get_device_list(usb_context, &devs);888+ while ((usb_dev = devs[d++]) != NULL) {889+ struct libusb_device_descriptor desc;890+ struct libusb_config_descriptor *conf_desc = NULL;891+ int i,j,k;892+ libusb_get_device_descriptor(usb_dev, &desc);893+894+ if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)895+ continue;896+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {897+ const struct libusb_interface *intf = &conf_desc->interface[j];898+ for (k = 0; k < intf->num_altsetting; k++) {899+ const struct libusb_interface_descriptor *intf_desc;900+ intf_desc = &intf->altsetting[k];901+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {902+ char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);903+ if (!strcmp(dev_path, path)) {904+ /* Matched Paths. Open this device */905+906+ /* OPEN HERE */907+ res = libusb_open(usb_dev, &dev->device_handle);908+ if (res < 0) {909+ LOG("can't open device\n");910+ free(dev_path);911+ break;912+ }913+ good_open = 1;914+#ifdef DETACH_KERNEL_DRIVER915+ /* Detach the kernel driver, but only if the916+ device is managed by the kernel */917+ if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {918+ res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);919+ if (res < 0) {920+ libusb_close(dev->device_handle);921+ LOG("Unable to detach Kernel Driver\n");922+ free(dev_path);923+ good_open = 0;924+ break;925+ }926+ }927+#endif928+ res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);929+ if (res < 0) {930+ LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);931+ free(dev_path);932+ libusb_close(dev->device_handle);933+ good_open = 0;934+ break;935+ }936+937+ /* Store off the string descriptor indexes */938+ dev->manufacturer_index = desc.iManufacturer;939+ dev->product_index = desc.iProduct;940+ dev->serial_index = desc.iSerialNumber;941+942+ /* Store off the interface number */943+ dev->interface = intf_desc->bInterfaceNumber;944+945+ /* Find the INPUT and OUTPUT endpoints. An946+ OUTPUT endpoint is not required. */947+ for (i = 0; i < intf_desc->bNumEndpoints; i++) {948+ const struct libusb_endpoint_descriptor *ep949+ = &intf_desc->endpoint[i];950+951+ /* Determine the type and direction of this952+ endpoint. */953+ int is_interrupt =954+ (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)955+ == LIBUSB_TRANSFER_TYPE_INTERRUPT;956+ int is_output =957+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)958+ == LIBUSB_ENDPOINT_OUT;959+ int is_input =960+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)961+ == LIBUSB_ENDPOINT_IN;962+963+ /* Decide whether to use it for input or output. */964+ if (dev->input_endpoint == 0 &&965+ is_interrupt && is_input) {966+ /* Use this endpoint for INPUT */967+ dev->input_endpoint = ep->bEndpointAddress;968+ dev->input_ep_max_packet_size = ep->wMaxPacketSize;969+ }970+ if (dev->output_endpoint == 0 &&971+ is_interrupt && is_output) {972+ /* Use this endpoint for OUTPUT */973+ dev->output_endpoint = ep->bEndpointAddress;974+ }975+ }976+977+ pthread_create(&dev->thread, NULL, read_thread, dev);978+979+ /* Wait here for the read thread to be initialized. */980+ pthread_barrier_wait(&dev->barrier);981+982+ }983+ free(dev_path);984+ }985+ }986+ }987+ libusb_free_config_descriptor(conf_desc);988+989+ }990+991+ libusb_free_device_list(devs, 1);992+993+ /* If we have a good handle, return it. */994+ if (good_open) {995+ return dev;996+ }997+ else {998+ /* Unable to open any devices. */999+ free_hid_device(dev);1000+ return NULL;1001+ }1002+}1003+1004+1005+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)1006+{1007+ int res;1008+ int report_number = data[0];1009+ int skipped_report_id = 0;1010+1011+ if (report_number == 0x0) {1012+ data++;1013+ length--;1014+ skipped_report_id = 1;1015+ }1016+1017+1018+ if (dev->output_endpoint <= 0) {1019+ /* No interrupt out endpoint. Use the Control Endpoint */1020+ res = libusb_control_transfer(dev->device_handle,1021+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,1022+ 0x09/*HID Set_Report*/,1023+ (2/*HID output*/ << 8) | report_number,1024+ dev->interface,1025+ (unsigned char *)data, length,1026+ 1000/*timeout millis*/);1027+1028+ if (res < 0)1029+ return -1;1030+1031+ if (skipped_report_id)1032+ length++;1033+1034+ return length;1035+ }1036+ else {1037+ /* Use the interrupt out endpoint */1038+ int actual_length;1039+ res = libusb_interrupt_transfer(dev->device_handle,1040+ dev->output_endpoint,1041+ (unsigned char*)data,1042+ length,1043+ &actual_length, 1000);1044+1045+ if (res < 0)1046+ return -1;1047+1048+ if (skipped_report_id)1049+ actual_length++;1050+1051+ return actual_length;1052+ }1053+}1054+1055+/* Helper function, to simplify hid_read().1056+ This should be called with dev->mutex locked. */1057+static int return_data(hid_device *dev, unsigned char *data, size_t length)1058+{1059+ /* Copy the data out of the linked list item (rpt) into the1060+ return buffer (data), and delete the liked list item. */1061+ struct input_report *rpt = dev->input_reports;1062+ size_t len = (length < rpt->len)? length: rpt->len;1063+ if (len > 0)1064+ memcpy(data, rpt->data, len);1065+ dev->input_reports = rpt->next;1066+ free(rpt->data);1067+ free(rpt);1068+ return len;1069+}1070+1071+static void cleanup_mutex(void *param)1072+{1073+ hid_device *dev = param;1074+ pthread_mutex_unlock(&dev->mutex);1075+}1076+1077+1078+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)1079+{1080+ int bytes_read = -1;1081+1082+#if 01083+ int transferred;1084+ int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);1085+ LOG("transferred: %d\n", transferred);1086+ return transferred;1087+#endif1088+1089+ pthread_mutex_lock(&dev->mutex);1090+ pthread_cleanup_push(&cleanup_mutex, dev);1091+1092+ /* There's an input report queued up. Return it. */1093+ if (dev->input_reports) {1094+ /* Return the first one */1095+ bytes_read = return_data(dev, data, length);1096+ goto ret;1097+ }1098+1099+ if (dev->shutdown_thread) {1100+ /* This means the device has been disconnected.1101+ An error code of -1 should be returned. */1102+ bytes_read = -1;1103+ goto ret;1104+ }1105+1106+ if (milliseconds == -1) {1107+ /* Blocking */1108+ while (!dev->input_reports && !dev->shutdown_thread) {1109+ pthread_cond_wait(&dev->condition, &dev->mutex);1110+ }1111+ if (dev->input_reports) {1112+ bytes_read = return_data(dev, data, length);1113+ }1114+ }1115+ else if (milliseconds > 0) {1116+ /* Non-blocking, but called with timeout. */1117+ int res;1118+ struct timespec ts;1119+ clock_gettime(CLOCK_REALTIME, &ts);1120+ ts.tv_sec += milliseconds / 1000;1121+ ts.tv_nsec += (milliseconds % 1000) * 1000000;1122+ if (ts.tv_nsec >= 1000000000L) {1123+ ts.tv_sec++;1124+ ts.tv_nsec -= 1000000000L;1125+ }1126+1127+ while (!dev->input_reports && !dev->shutdown_thread) {1128+ res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);1129+ if (res == 0) {1130+ if (dev->input_reports) {1131+ bytes_read = return_data(dev, data, length);1132+ break;1133+ }1134+1135+ /* If we're here, there was a spurious wake up1136+ or the read thread was shutdown. Run the1137+ loop again (ie: don't break). */1138+ }1139+ else if (res == ETIMEDOUT) {1140+ /* Timed out. */1141+ bytes_read = 0;1142+ break;1143+ }1144+ else {1145+ /* Error. */1146+ bytes_read = -1;1147+ break;1148+ }1149+ }1150+ }1151+ else {1152+ /* Purely non-blocking */1153+ bytes_read = 0;1154+ }1155+1156+ret:1157+ pthread_mutex_unlock(&dev->mutex);1158+ pthread_cleanup_pop(0);1159+1160+ return bytes_read;1161+}1162+1163+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)1164+{1165+ return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);1166+}1167+1168+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)1169+{1170+ dev->blocking = !nonblock;1171+1172+ return 0;1173+}1174+1175+1176+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)1177+{1178+ int res = -1;1179+ int skipped_report_id = 0;1180+ int report_number = data[0];1181+1182+ if (report_number == 0x0) {1183+ data++;1184+ length--;1185+ skipped_report_id = 1;1186+ }1187+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+ (3/*HID feature*/ << 8) | report_number,1192+ dev->interface,1193+ (unsigned char *)data, length,1194+ 1000/*timeout millis*/);1195+1196+ if (res < 0)1197+ return -1;1198+1199+ /* Account for the report ID */1200+ if (skipped_report_id)1201+ length++;1202+1203+ return length;1204+}1205+1206+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)1207+{1208+ int res = -1;1209+ int skipped_report_id = 0;1210+ int report_number = data[0];1211+1212+ if (report_number == 0x0) {1213+ /* Offset the return buffer by 1, so that the report ID1214+ will remain in byte 0. */1215+ data++;1216+ length--;1217+ skipped_report_id = 1;1218+ }1219+ res = libusb_control_transfer(dev->device_handle,1220+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,1221+ 0x01/*HID get_report*/,1222+ (3/*HID feature*/ << 8) | report_number,1223+ dev->interface,1224+ (unsigned char *)data, length,1225+ 1000/*timeout millis*/);1226+1227+ if (res < 0)1228+ return -1;1229+1230+ if (skipped_report_id)1231+ res++;1232+1233+ return res;1234+}1235+1236+1237+void HID_API_EXPORT hid_close(hid_device *dev)1238+{1239+ if (!dev)1240+ return;1241+1242+ /* Cause read_thread() to stop. */1243+ dev->shutdown_thread = 1;1244+ libusb_cancel_transfer(dev->transfer);1245+1246+ /* Wait for read_thread() to end. */1247+ pthread_join(dev->thread, NULL);1248+1249+ /* Clean up the Transfer objects allocated in read_thread(). */1250+ free(dev->transfer->buffer);1251+ libusb_free_transfer(dev->transfer);1252+1253+ /* release the interface */1254+ libusb_release_interface(dev->device_handle, dev->interface);1255+1256+ /* Close the handle */1257+ libusb_close(dev->device_handle);1258+1259+ /* Clear out the queue of received reports. */1260+ pthread_mutex_lock(&dev->mutex);1261+ while (dev->input_reports) {1262+ return_data(dev, NULL, 0);1263+ }1264+ pthread_mutex_unlock(&dev->mutex);1265+1266+ free_hid_device(dev);1267+}1268+1269+1270+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)1271+{1272+ return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);1273+}1274+1275+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)1276+{1277+ return hid_get_indexed_string(dev, dev->product_index, string, maxlen);1278+}1279+1280+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)1281+{1282+ return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);1283+}1284+1285+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)1286+{1287+ wchar_t *str;1288+1289+ str = get_usb_string(dev->device_handle, string_index);1290+ if (str) {1291+ wcsncpy(string, str, maxlen);1292+ string[maxlen-1] = L'\0';1293+ free(str);1294+ return 0;1295+ }1296+ else1297+ return -1;1298+}1299+1300+1301+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)1302+{1303+ return NULL;1304+}1305+1306+1307+struct lang_map_entry {1308+ const char *name;1309+ const char *string_code;1310+ uint16_t usb_code;1311+};1312+1313+#define LANG(name,code,usb_code) { name, code, usb_code }1314+static struct lang_map_entry lang_map[] = {1315+ LANG("Afrikaans", "af", 0x0436),1316+ LANG("Albanian", "sq", 0x041C),1317+ LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),1318+ LANG("Arabic - Bahrain", "ar_bh", 0x3C01),1319+ LANG("Arabic - Algeria", "ar_dz", 0x1401),1320+ LANG("Arabic - Egypt", "ar_eg", 0x0C01),1321+ LANG("Arabic - Iraq", "ar_iq", 0x0801),1322+ LANG("Arabic - Jordan", "ar_jo", 0x2C01),1323+ LANG("Arabic - Kuwait", "ar_kw", 0x3401),1324+ LANG("Arabic - Lebanon", "ar_lb", 0x3001),1325+ LANG("Arabic - Libya", "ar_ly", 0x1001),1326+ LANG("Arabic - Morocco", "ar_ma", 0x1801),1327+ LANG("Arabic - Oman", "ar_om", 0x2001),1328+ LANG("Arabic - Qatar", "ar_qa", 0x4001),1329+ LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),1330+ LANG("Arabic - Syria", "ar_sy", 0x2801),1331+ LANG("Arabic - Tunisia", "ar_tn", 0x1C01),1332+ LANG("Arabic - Yemen", "ar_ye", 0x2401),1333+ LANG("Armenian", "hy", 0x042B),1334+ LANG("Azeri - Latin", "az_az", 0x042C),1335+ LANG("Azeri - Cyrillic", "az_az", 0x082C),1336+ LANG("Basque", "eu", 0x042D),1337+ LANG("Belarusian", "be", 0x0423),1338+ LANG("Bulgarian", "bg", 0x0402),1339+ LANG("Catalan", "ca", 0x0403),1340+ LANG("Chinese - China", "zh_cn", 0x0804),1341+ LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),1342+ LANG("Chinese - Macau SAR", "zh_mo", 0x1404),1343+ LANG("Chinese - Singapore", "zh_sg", 0x1004),1344+ LANG("Chinese - Taiwan", "zh_tw", 0x0404),1345+ LANG("Croatian", "hr", 0x041A),1346+ LANG("Czech", "cs", 0x0405),1347+ LANG("Danish", "da", 0x0406),1348+ LANG("Dutch - Netherlands", "nl_nl", 0x0413),1349+ LANG("Dutch - Belgium", "nl_be", 0x0813),1350+ LANG("English - Australia", "en_au", 0x0C09),1351+ LANG("English - Belize", "en_bz", 0x2809),1352+ LANG("English - Canada", "en_ca", 0x1009),1353+ LANG("English - Caribbean", "en_cb", 0x2409),1354+ LANG("English - Ireland", "en_ie", 0x1809),1355+ LANG("English - Jamaica", "en_jm", 0x2009),1356+ LANG("English - New Zealand", "en_nz", 0x1409),1357+ LANG("English - Phillippines", "en_ph", 0x3409),1358+ LANG("English - Southern Africa", "en_za", 0x1C09),1359+ LANG("English - Trinidad", "en_tt", 0x2C09),1360+ LANG("English - Great Britain", "en_gb", 0x0809),1361+ LANG("English - United States", "en_us", 0x0409),1362+ LANG("Estonian", "et", 0x0425),1363+ LANG("Farsi", "fa", 0x0429),1364+ LANG("Finnish", "fi", 0x040B),1365+ LANG("Faroese", "fo", 0x0438),1366+ LANG("French - France", "fr_fr", 0x040C),1367+ LANG("French - Belgium", "fr_be", 0x080C),1368+ LANG("French - Canada", "fr_ca", 0x0C0C),1369+ LANG("French - Luxembourg", "fr_lu", 0x140C),1370+ LANG("French - Switzerland", "fr_ch", 0x100C),1371+ LANG("Gaelic - Ireland", "gd_ie", 0x083C),1372+ LANG("Gaelic - Scotland", "gd", 0x043C),1373+ LANG("German - Germany", "de_de", 0x0407),1374+ LANG("German - Austria", "de_at", 0x0C07),1375+ LANG("German - Liechtenstein", "de_li", 0x1407),1376+ LANG("German - Luxembourg", "de_lu", 0x1007),1377+ LANG("German - Switzerland", "de_ch", 0x0807),1378+ LANG("Greek", "el", 0x0408),1379+ LANG("Hebrew", "he", 0x040D),1380+ LANG("Hindi", "hi", 0x0439),1381+ LANG("Hungarian", "hu", 0x040E),1382+ LANG("Icelandic", "is", 0x040F),1383+ LANG("Indonesian", "id", 0x0421),1384+ LANG("Italian - Italy", "it_it", 0x0410),1385+ LANG("Italian - Switzerland", "it_ch", 0x0810),1386+ LANG("Japanese", "ja", 0x0411),1387+ LANG("Korean", "ko", 0x0412),1388+ LANG("Latvian", "lv", 0x0426),1389+ LANG("Lithuanian", "lt", 0x0427),1390+ LANG("F.Y.R.O. Macedonia", "mk", 0x042F),1391+ LANG("Malay - Malaysia", "ms_my", 0x043E),1392+ LANG("Malay – Brunei", "ms_bn", 0x083E),1393+ LANG("Maltese", "mt", 0x043A),1394+ LANG("Marathi", "mr", 0x044E),1395+ LANG("Norwegian - Bokml", "no_no", 0x0414),1396+ LANG("Norwegian - Nynorsk", "no_no", 0x0814),1397+ LANG("Polish", "pl", 0x0415),1398+ LANG("Portuguese - Portugal", "pt_pt", 0x0816),1399+ LANG("Portuguese - Brazil", "pt_br", 0x0416),1400+ LANG("Raeto-Romance", "rm", 0x0417),1401+ LANG("Romanian - Romania", "ro", 0x0418),1402+ LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),1403+ LANG("Russian", "ru", 0x0419),1404+ LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),1405+ LANG("Sanskrit", "sa", 0x044F),1406+ LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),1407+ LANG("Serbian - Latin", "sr_sp", 0x081A),1408+ LANG("Setsuana", "tn", 0x0432),1409+ LANG("Slovenian", "sl", 0x0424),1410+ LANG("Slovak", "sk", 0x041B),1411+ LANG("Sorbian", "sb", 0x042E),1412+ LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),1413+ LANG("Spanish - Argentina", "es_ar", 0x2C0A),1414+ LANG("Spanish - Bolivia", "es_bo", 0x400A),1415+ LANG("Spanish - Chile", "es_cl", 0x340A),1416+ LANG("Spanish - Colombia", "es_co", 0x240A),1417+ LANG("Spanish - Costa Rica", "es_cr", 0x140A),1418+ LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),1419+ LANG("Spanish - Ecuador", "es_ec", 0x300A),1420+ LANG("Spanish - Guatemala", "es_gt", 0x100A),1421+ LANG("Spanish - Honduras", "es_hn", 0x480A),1422+ LANG("Spanish - Mexico", "es_mx", 0x080A),1423+ LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),1424+ LANG("Spanish - Panama", "es_pa", 0x180A),1425+ LANG("Spanish - Peru", "es_pe", 0x280A),1426+ LANG("Spanish - Puerto Rico", "es_pr", 0x500A),1427+ LANG("Spanish - Paraguay", "es_py", 0x3C0A),1428+ LANG("Spanish - El Salvador", "es_sv", 0x440A),1429+ LANG("Spanish - Uruguay", "es_uy", 0x380A),1430+ LANG("Spanish - Venezuela", "es_ve", 0x200A),1431+ LANG("Southern Sotho", "st", 0x0430),1432+ LANG("Swahili", "sw", 0x0441),1433+ LANG("Swedish - Sweden", "sv_se", 0x041D),1434+ LANG("Swedish - Finland", "sv_fi", 0x081D),1435+ LANG("Tamil", "ta", 0x0449),1436+ LANG("Tatar", "tt", 0X0444),1437+ LANG("Thai", "th", 0x041E),1438+ LANG("Turkish", "tr", 0x041F),1439+ LANG("Tsonga", "ts", 0x0431),1440+ LANG("Ukrainian", "uk", 0x0422),1441+ LANG("Urdu", "ur", 0x0420),1442+ LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),1443+ LANG("Uzbek – Latin", "uz_uz", 0x0443),1444+ LANG("Vietnamese", "vi", 0x042A),1445+ LANG("Xhosa", "xh", 0x0434),1446+ LANG("Yiddish", "yi", 0x043D),1447+ LANG("Zulu", "zu", 0x0435),1448+ LANG(NULL, NULL, 0x0),1449+};1450+1451+uint16_t get_usb_code_for_current_locale(void)1452+{1453+ char *locale;1454+ char search_string[64];1455+ char *ptr;1456+ struct lang_map_entry *lang;1457+1458+ /* Get the current locale. */1459+ locale = setlocale(0, NULL);1460+ if (!locale)1461+ return 0x0;1462+1463+ /* Make a copy of the current locale string. */1464+ strncpy(search_string, locale, sizeof(search_string));1465+ search_string[sizeof(search_string)-1] = '\0';1466+1467+ /* Chop off the encoding part, and make it lower case. */1468+ ptr = search_string;1469+ while (*ptr) {1470+ *ptr = tolower(*ptr);1471+ if (*ptr == '.') {1472+ *ptr = '\0';1473+ break;1474+ }1475+ ptr++;1476+ }1477+1478+ /* Find the entry which matches the string code of our locale. */1479+ lang = lang_map;1480+ while (lang->string_code) {1481+ if (!strcmp(lang->string_code, search_string)) {1482+ return lang->usb_code;1483+ }1484+ lang++;1485+ }1486+1487+ /* There was no match. Find with just the language only. */1488+ /* Chop off the variant. Chop it off at the '_'. */1489+ ptr = search_string;1490+ while (*ptr) {1491+ *ptr = tolower(*ptr);1492+ if (*ptr == '_') {1493+ *ptr = '\0';1494+ break;1495+ }1496+ ptr++;1497+ }1498+1499+#if 0 /* TODO: Do we need this? */1500+ /* Find the entry which matches the string code of our language. */1501+ lang = lang_map;1502+ while (lang->string_code) {1503+ if (!strcmp(lang->string_code, search_string)) {1504+ return lang->usb_code;1505+ }1506+ lang++;1507+ }1508+#endif1509+1510+ /* Found nothing. */1511+ return 0x0;1512+}1513+1514+#ifdef __cplusplus1515+}1516+#endif151715181519