src/hidapi/libusb/hid.c
changeset 12999 a7ca9815bc79
parent 12958 b810b78d32cc
child 13003 200f23b4f8d2
equal deleted inserted replaced
12998:b87ba0fad17e 12999:a7ca9815bc79
    20  files located at the root of the source distribution.
    20  files located at the root of the source distribution.
    21  These files may also be found in the public source
    21  These files may also be found in the public source
    22  code repository located at:
    22  code repository located at:
    23         https://github.com/libusb/hidapi .
    23         https://github.com/libusb/hidapi .
    24 ********************************************************/
    24 ********************************************************/
       
    25 
       
    26 /* This file is heavily modified from the original libusb.c, for portability.
       
    27  * Last upstream update was from July 25, 2019, Git commit 93dca807.
       
    28  */
       
    29 
    25 #include "../../SDL_internal.h"
    30 #include "../../SDL_internal.h"
       
    31 #include "SDL_thread.h"
       
    32 #include "SDL_mutex.h"
    26 
    33 
    27 #ifdef SDL_JOYSTICK_HIDAPI
    34 #ifdef SDL_JOYSTICK_HIDAPI
    28 
    35 
    29 #ifndef _GNU_SOURCE
       
    30 #define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
       
    31 #endif
       
    32 
       
    33 /* C */
       
    34 #include <stdio.h>
       
    35 #include <string.h>
       
    36 #include <stdlib.h>
       
    37 #include <ctype.h>
       
    38 #include <locale.h>
       
    39 #include <errno.h>
       
    40 
       
    41 /* Unix */
       
    42 #include <unistd.h>
       
    43 #include <sys/types.h>
       
    44 #include <sys/stat.h>
       
    45 #include <sys/ioctl.h>
       
    46 #include <sys/utsname.h>
       
    47 #include <fcntl.h>
       
    48 #include <pthread.h>
       
    49 #include <wchar.h>
       
    50 
       
    51 /* GNU / LibUSB */
       
    52 #include <libusb.h>
    36 #include <libusb.h>
    53 #ifndef __ANDROID__
       
    54 #include <iconv.h>
       
    55 #endif
       
    56 
    37 
    57 #include "hidapi.h"
    38 #include "hidapi.h"
    58 
    39 
    59 #ifdef NAMESPACE
    40 #ifdef NAMESPACE
    60 namespace NAMESPACE
    41 namespace NAMESPACE
    61 {
    42 {
    62 #endif
    43 #endif
    63 
       
    64 #ifdef __ANDROID__
       
    65 
    44 
    66 /* Barrier implementation because Android/Bionic don't have pthread_barrier.
    45 /* Barrier implementation because Android/Bionic don't have pthread_barrier.
    67    This implementation came from Brent Priddy and was posted on
    46    This implementation came from Brent Priddy and was posted on
    68    StackOverflow. It is used with his permission. */
    47    StackOverflow. It is used with his permission. */
    69 typedef int pthread_barrierattr_t;
    48 
    70 typedef struct pthread_barrier {
    49 typedef struct _SDL_ThreadBarrier
    71     pthread_mutex_t mutex;
    50 {
    72     pthread_cond_t cond;
    51 	SDL_mutex *mutex;
    73     int count;
    52 	SDL_cond *cond;
    74     int trip_count;
    53 	Uint32 count;
    75 } pthread_barrier_t;
    54 	Uint32 trip_count;
    76 
    55 } SDL_ThreadBarrier;
    77 static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
    56 
    78 {
    57 static int SDL_CreateThreadBarrier(SDL_ThreadBarrier *barrier, Uint32 count)
    79 	if(count == 0) {
    58 {
    80 		errno = EINVAL;
    59 	if (barrier == NULL) {
    81 		return -1;
    60 		return SDL_SetError("barrier must be non-NULL");
    82 	}
    61 	}
    83 
    62 	if (count == 0) {
    84 	if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
    63 		return SDL_SetError("count must be > 0");
    85 		return -1;
    64 	}
    86 	}
    65 
    87 	if(pthread_cond_init(&barrier->cond, 0) < 0) {
    66 	barrier->mutex = SDL_CreateMutex();
    88 		pthread_mutex_destroy(&barrier->mutex);
    67 	if (barrier->mutex == NULL) {
    89 		return -1;
    68 		return -1; /* Error set by CreateMutex */
    90 	}
    69 	}
       
    70 	barrier->cond = SDL_CreateCond();
       
    71 	if (barrier->cond == NULL) {
       
    72 		return -1; /* Error set by CreateCond */
       
    73 	}
       
    74 
    91 	barrier->trip_count = count;
    75 	barrier->trip_count = count;
    92 	barrier->count = 0;
    76 	barrier->count = 0;
    93 
    77 
    94 	return 0;
    78 	return 0;
    95 }
    79 }
    96 
    80 
    97 static int pthread_barrier_destroy(pthread_barrier_t *barrier)
    81 static void SDL_DestroyThreadBarrier(SDL_ThreadBarrier *barrier)
    98 {
    82 {
    99 	pthread_cond_destroy(&barrier->cond);
    83 	SDL_DestroyCond(barrier->cond);
   100 	pthread_mutex_destroy(&barrier->mutex);
    84 	SDL_DestroyMutex(barrier->mutex);
       
    85 }
       
    86 
       
    87 static int SDL_WaitThreadBarrier(SDL_ThreadBarrier *barrier)
       
    88 {
       
    89 	SDL_LockMutex(barrier->mutex);
       
    90 	barrier->count += 1;
       
    91 	if (barrier->count >= barrier->trip_count) {
       
    92 		barrier->count = 0;
       
    93 		SDL_CondBroadcast(barrier->cond);
       
    94 		SDL_UnlockMutex(barrier->mutex);
       
    95 		return 1;
       
    96 	}
       
    97 	SDL_CondWait(barrier->cond, barrier->mutex);
       
    98 	SDL_UnlockMutex(barrier->mutex);
   101 	return 0;
    99 	return 0;
   102 }
   100 }
   103 
       
   104 static int pthread_barrier_wait(pthread_barrier_t *barrier)
       
   105 {
       
   106 	pthread_mutex_lock(&barrier->mutex);
       
   107 	++(barrier->count);
       
   108 	if(barrier->count >= barrier->trip_count)
       
   109 	{
       
   110 		barrier->count = 0;
       
   111 		pthread_cond_broadcast(&barrier->cond);
       
   112 		pthread_mutex_unlock(&barrier->mutex);
       
   113 		return 1;
       
   114 	}
       
   115 	else
       
   116 	{
       
   117 		pthread_cond_wait(&barrier->cond, &(barrier->mutex));
       
   118 		pthread_mutex_unlock(&barrier->mutex);
       
   119 		return 0;
       
   120 	}
       
   121 }
       
   122 
       
   123 #endif
       
   124 
   101 
   125 #if defined(__cplusplus) && !defined(NAMESPACE)
   102 #if defined(__cplusplus) && !defined(NAMESPACE)
   126 extern "C" {
   103 extern "C" {
   127 #endif
   104 #endif
   128 
   105 
   171 
   148 
   172 	/* Whether blocking reads are used */
   149 	/* Whether blocking reads are used */
   173 	int blocking; /* boolean */
   150 	int blocking; /* boolean */
   174 
   151 
   175 	/* Read thread objects */
   152 	/* Read thread objects */
   176 	pthread_t thread;
   153 	SDL_Thread *thread;
   177 	pthread_mutex_t mutex; /* Protects input_reports */
   154 	SDL_mutex *mutex; /* Protects input_reports */
   178 	pthread_cond_t condition;
   155 	SDL_cond *condition;
   179 	pthread_barrier_t barrier; /* Ensures correct startup sequence */
   156 	SDL_ThreadBarrier barrier; /* Ensures correct startup sequence */
   180 	int shutdown_thread;
   157 	int shutdown_thread;
   181 	int cancelled;
   158 	int cancelled;
   182 	struct libusb_transfer *transfer;
   159 	struct libusb_transfer *transfer;
   183 
   160 
   184 	/* List of received input reports. */
   161 	/* List of received input reports. */
   190 uint16_t get_usb_code_for_current_locale(void);
   167 uint16_t get_usb_code_for_current_locale(void);
   191 static int return_data(hid_device *dev, unsigned char *data, size_t length);
   168 static int return_data(hid_device *dev, unsigned char *data, size_t length);
   192 
   169 
   193 static hid_device *new_hid_device(void)
   170 static hid_device *new_hid_device(void)
   194 {
   171 {
   195 	hid_device *dev = (hid_device *)calloc(1, sizeof(hid_device));
   172 	hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
   196 	dev->blocking = 1;
   173 	dev->blocking = 1;
   197 
   174 
   198 	pthread_mutex_init(&dev->mutex, NULL);
   175 	dev->mutex = SDL_CreateMutex();
   199 	pthread_cond_init(&dev->condition, NULL);
   176 	dev->condition = SDL_CreateCond();
   200 	pthread_barrier_init(&dev->barrier, NULL, 2);
   177 	SDL_CreateThreadBarrier(&dev->barrier, 2);
   201 
   178 
   202 	return dev;
   179 	return dev;
   203 }
   180 }
   204 
   181 
   205 static void free_hid_device(hid_device *dev)
   182 static void free_hid_device(hid_device *dev)
   206 {
   183 {
   207 	/* Clean up the thread objects */
   184 	/* Clean up the thread objects */
   208 	pthread_barrier_destroy(&dev->barrier);
   185 	SDL_DestroyThreadBarrier(&dev->barrier);
   209 	pthread_cond_destroy(&dev->condition);
   186 	SDL_DestroyCond(dev->condition);
   210 	pthread_mutex_destroy(&dev->mutex);
   187 	SDL_DestroyMutex(dev->mutex);
   211 
   188 
   212 	/* Free the device itself */
   189 	/* Free the device itself */
   213 	free(dev);
   190 	free(dev);
   214 }
   191 }
   215 
   192 
   216 #if 0
   193 #if 0
   217 /*TODO: Implement this funciton on hidapi/libusb.. */
   194 /*TODO: Implement this function on hidapi/libusb.. */
   218 static void register_error(hid_device *device, const char *op)
   195 static void register_error(hid_device *dev, const char *op)
   219 {
   196 {
   220 
   197 
   221 }
   198 }
   222 #endif
   199 #endif
   223 
   200 
   398 {
   375 {
   399 	char buf[512];
   376 	char buf[512];
   400 	int len;
   377 	int len;
   401 	wchar_t *str = NULL;
   378 	wchar_t *str = NULL;
   402 
   379 
   403 #ifndef __ANDROID__ /* we don't use iconv on Android */
       
   404 	wchar_t wbuf[256];
   380 	wchar_t wbuf[256];
   405 	/* iconv variables */
   381 	SDL_iconv_t ic;
   406 	iconv_t ic;
       
   407 	size_t inbytes;
   382 	size_t inbytes;
   408 	size_t outbytes;
   383 	size_t outbytes;
   409 	size_t res;
   384 	size_t res;
   410 #ifdef __FreeBSD__
       
   411 	const char *inptr;
   385 	const char *inptr;
   412 #else
       
   413 	char *inptr;
       
   414 #endif
       
   415 	char *outptr;
   386 	char *outptr;
   416 #endif
       
   417 
   387 
   418 	/* Determine which language to use. */
   388 	/* Determine which language to use. */
   419 	uint16_t lang;
   389 	uint16_t lang;
   420 	lang = get_usb_code_for_current_locale();
   390 	lang = get_usb_code_for_current_locale();
   421 	if (!is_language_supported(dev, lang))
   391 	if (!is_language_supported(dev, lang))
   428 			(unsigned char*)buf,
   398 			(unsigned char*)buf,
   429 			sizeof(buf));
   399 			sizeof(buf));
   430 	if (len < 0)
   400 	if (len < 0)
   431 		return NULL;
   401 		return NULL;
   432 
   402 
   433 #ifdef __ANDROID__
       
   434 
       
   435 	/* Bionic does not have iconv support nor wcsdup() function, so it
       
   436 	   has to be done manually.  The following code will only work for
       
   437 	   code points that can be represented as a single UTF-16 character,
       
   438 	   and will incorrectly convert any code points which require more
       
   439 	   than one UTF-16 character.
       
   440 
       
   441 	   Skip over the first character (2-bytes).  */
       
   442 	len -= 2;
       
   443 	str = malloc((len / 2 + 1) * sizeof(wchar_t));
       
   444 	int i;
       
   445 	for (i = 0; i < len / 2; i++) {
       
   446 		str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8);
       
   447 	}
       
   448 	str[len / 2] = 0x00000000;
       
   449 
       
   450 #else
       
   451 
       
   452 	/* buf does not need to be explicitly NULL-terminated because
   403 	/* buf does not need to be explicitly NULL-terminated because
   453 	   it is only passed into iconv() which does not need it. */
   404 	   it is only passed into iconv() which does not need it. */
   454 
   405 
   455 	/* Initialize iconv. */
   406 	/* Initialize iconv. */
   456 	ic = iconv_open("WCHAR_T", "UTF-16LE");
   407 	ic = SDL_iconv_open("WCHAR_T", "UTF-16LE");
   457 	if (ic == (iconv_t)-1) {
   408 	if (ic == (SDL_iconv_t)-1) {
   458 		LOG("iconv_open() failed\n");
   409 		LOG("SDL_iconv_open() failed\n");
   459 		return NULL;
   410 		return NULL;
   460 	}
   411 	}
   461 
   412 
   462 	/* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
   413 	/* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
   463 	   Skip the first character (2-bytes). */
   414 	   Skip the first character (2-bytes). */
   464 	inptr = buf+2;
   415 	inptr = buf+2;
   465 	inbytes = len-2;
   416 	inbytes = len-2;
   466 	outptr = (char*) wbuf;
   417 	outptr = (char*) wbuf;
   467 	outbytes = sizeof(wbuf);
   418 	outbytes = sizeof(wbuf);
   468 	res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
   419 	res = SDL_iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
   469 	if (res == (size_t)-1) {
   420 	if (res == (size_t)-1) {
   470 		LOG("iconv() failed\n");
   421 		LOG("SDL_iconv() failed\n");
   471 		goto err;
   422 		goto err;
   472 	}
   423 	}
   473 
   424 
   474 	/* Write the terminating NULL. */
   425 	/* Write the terminating NULL. */
   475 	wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
   426 	wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
   478 
   429 
   479 	/* Allocate and copy the string. */
   430 	/* Allocate and copy the string. */
   480 	str = wcsdup(wbuf);
   431 	str = wcsdup(wbuf);
   481 
   432 
   482 err:
   433 err:
   483 	iconv_close(ic);
   434 	SDL_iconv_close(ic);
   484 
       
   485 #endif
       
   486 
   435 
   487 	return str;
   436 	return str;
   488 }
   437 }
   489 
   438 
   490 static char *make_path(libusb_device *dev, int interface_number)
   439 static char *make_path(libusb_device *dev, int interface_number)
   501 
   450 
   502 
   451 
   503 int HID_API_EXPORT hid_init(void)
   452 int HID_API_EXPORT hid_init(void)
   504 {
   453 {
   505 	if (!usb_context) {
   454 	if (!usb_context) {
       
   455 #ifndef _WIN32 /* TODO: Win32 setlocale */
   506 		const char *locale;
   456 		const char *locale;
       
   457 #endif /* _WIN32 */
   507 
   458 
   508 		/* Init Libusb */
   459 		/* Init Libusb */
   509 		if (libusb_init(&usb_context))
   460 		if (libusb_init(&usb_context))
   510 			return -1;
   461 			return -1;
   511 
   462 
       
   463 #ifndef _WIN32 /* TODO: Win32 setlocale */
   512 		/* Set the locale if it's not set. */
   464 		/* Set the locale if it's not set. */
   513 		locale = setlocale(LC_CTYPE, NULL);
   465 		locale = setlocale(LC_CTYPE, NULL);
   514 		if (!locale)
   466 		if (!locale)
   515 			setlocale(LC_CTYPE, "");
   467 			setlocale(LC_CTYPE, "");
       
   468 #endif /* _WIN32 */
   516 	}
   469 	}
   517 
   470 
   518 	return 0;
   471 	return 0;
   519 }
   472 }
   520 
   473 
   661 						if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
   614 						if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
   662 						    (product_id == 0x0 || product_id == dev_pid)) {
   615 						    (product_id == 0x0 || product_id == dev_pid)) {
   663 							struct hid_device_info *tmp;
   616 							struct hid_device_info *tmp;
   664 
   617 
   665 							/* VID/PID match. Create the record. */
   618 							/* VID/PID match. Create the record. */
   666 							tmp = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info));
   619 							tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
   667 							if (cur_dev) {
   620 							if (cur_dev) {
   668 								cur_dev->next = tmp;
   621 								cur_dev->next = tmp;
   669 							}
   622 							}
   670 							else {
   623 							else {
   671 								root = tmp;
   624 								root = tmp;
   834 	hid_device *dev = (hid_device *)transfer->user_data;
   787 	hid_device *dev = (hid_device *)transfer->user_data;
   835 	int res;
   788 	int res;
   836 
   789 
   837 	if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
   790 	if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
   838 
   791 
   839 		struct input_report *rpt = (struct input_report *)malloc(sizeof(*rpt));
   792 		struct input_report *rpt = (struct input_report*) malloc(sizeof(*rpt));
   840 		rpt->data = (uint8_t *)malloc(transfer->actual_length);
   793 		rpt->data = (uint8_t*) malloc(transfer->actual_length);
   841 		memcpy(rpt->data, transfer->buffer, transfer->actual_length);
   794 		memcpy(rpt->data, transfer->buffer, transfer->actual_length);
   842 		rpt->len = transfer->actual_length;
   795 		rpt->len = transfer->actual_length;
   843 		rpt->next = NULL;
   796 		rpt->next = NULL;
   844 
   797 
   845 		pthread_mutex_lock(&dev->mutex);
   798 		SDL_LockMutex(dev->mutex);
   846 
   799 
   847 		/* Attach the new report object to the end of the list. */
   800 		/* Attach the new report object to the end of the list. */
   848 		if (dev->input_reports == NULL) {
   801 		if (dev->input_reports == NULL) {
   849 			/* The list is empty. Put it at the root. */
   802 			/* The list is empty. Put it at the root. */
   850 			dev->input_reports = rpt;
   803 			dev->input_reports = rpt;
   851 			pthread_cond_signal(&dev->condition);
   804 			SDL_CondSignal(dev->condition);
   852 		}
   805 		}
   853 		else {
   806 		else {
   854 			/* Find the end of the list and attach. */
   807 			/* Find the end of the list and attach. */
   855 			struct input_report *cur = dev->input_reports;
   808 			struct input_report *cur = dev->input_reports;
   856 			int num_queued = 0;
   809 			int num_queued = 0;
   865 			   anything from the device. */
   818 			   anything from the device. */
   866 			if (num_queued > 30) {
   819 			if (num_queued > 30) {
   867 				return_data(dev, NULL, 0);
   820 				return_data(dev, NULL, 0);
   868 			}
   821 			}
   869 		}
   822 		}
   870 		pthread_mutex_unlock(&dev->mutex);
   823 		SDL_UnlockMutex(dev->mutex);
   871 	}
   824 	}
   872 	else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
   825 	else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
   873 		dev->shutdown_thread = 1;
   826 		dev->shutdown_thread = 1;
   874 		dev->cancelled = 1;
   827 		dev->cancelled = 1;
   875 		return;
   828 		return;
   894 		dev->cancelled = 1;
   847 		dev->cancelled = 1;
   895 	}
   848 	}
   896 }
   849 }
   897 
   850 
   898 
   851 
   899 static void *read_thread(void *param)
   852 static int read_thread(void *param)
   900 {
   853 {
   901 	hid_device *dev = (hid_device *)param;
   854 	hid_device *dev = (hid_device *)param;
   902 	unsigned char *buf;
   855 	uint8_t *buf;
   903 	const size_t length = dev->input_ep_max_packet_size;
   856 	const size_t length = dev->input_ep_max_packet_size;
   904 
   857 
   905 	/* Set up the transfer object. */
   858 	/* Set up the transfer object. */
   906 	buf = (unsigned char *)malloc(length);
   859 	buf = (uint8_t*) malloc(length);
   907 	dev->transfer = libusb_alloc_transfer(0);
   860 	dev->transfer = libusb_alloc_transfer(0);
   908 	libusb_fill_interrupt_transfer(dev->transfer,
   861 	libusb_fill_interrupt_transfer(dev->transfer,
   909 		dev->device_handle,
   862 		dev->device_handle,
   910 		dev->input_endpoint,
   863 		dev->input_endpoint,
   911 		buf,
   864 		buf,
   917 	/* Make the first submission. Further submissions are made
   870 	/* Make the first submission. Further submissions are made
   918 	   from inside read_callback() */
   871 	   from inside read_callback() */
   919 	libusb_submit_transfer(dev->transfer);
   872 	libusb_submit_transfer(dev->transfer);
   920 
   873 
   921 	/* Notify the main thread that the read thread is up and running. */
   874 	/* Notify the main thread that the read thread is up and running. */
   922 	pthread_barrier_wait(&dev->barrier);
   875 	SDL_WaitThreadBarrier(&dev->barrier);
   923 
   876 
   924 	/* Handle all the events. */
   877 	/* Handle all the events. */
   925 	while (!dev->shutdown_thread) {
   878 	while (!dev->shutdown_thread) {
   926 		int res;
   879 		int res;
   927 		res = libusb_handle_events(usb_context);
   880 		res = libusb_handle_events(usb_context);
   949 	/* Now that the read thread is stopping, Wake any threads which are
   902 	/* Now that the read thread is stopping, Wake any threads which are
   950 	   waiting on data (in hid_read_timeout()). Do this under a mutex to
   903 	   waiting on data (in hid_read_timeout()). Do this under a mutex to
   951 	   make sure that a thread which is about to go to sleep waiting on
   904 	   make sure that a thread which is about to go to sleep waiting on
   952 	   the condition actually will go to sleep before the condition is
   905 	   the condition actually will go to sleep before the condition is
   953 	   signaled. */
   906 	   signaled. */
   954 	pthread_mutex_lock(&dev->mutex);
   907 	SDL_LockMutex(dev->mutex);
   955 	pthread_cond_broadcast(&dev->condition);
   908 	SDL_CondBroadcast(dev->condition);
   956 	pthread_mutex_unlock(&dev->mutex);
   909 	SDL_UnlockMutex(dev->mutex);
   957 
   910 
   958 	/* The dev->transfer->buffer and dev->transfer objects are cleaned up
   911 	/* The dev->transfer->buffer and dev->transfer objects are cleaned up
   959 	   in hid_close(). They are not cleaned up here because this thread
   912 	   in hid_close(). They are not cleaned up here because this thread
   960 	   could end either due to a disconnect or due to a user
   913 	   could end either due to a disconnect or due to a user
   961 	   call to hid_close(). In both cases the objects can be safely
   914 	   call to hid_close(). In both cases the objects can be safely
   962 	   cleaned up after the call to pthread_join() (in hid_close()), but
   915 	   cleaned up after the call to pthread_join() (in hid_close()), but
   963 	   since hid_close() calls libusb_cancel_transfer(), on these objects,
   916 	   since hid_close() calls libusb_cancel_transfer(), on these objects,
   964 	   they can not be cleaned up here. */
   917 	   they can not be cleaned up here. */
   965 
   918 
   966 	return NULL;
   919 	return 0;
   967 }
   920 }
   968 
   921 
   969 
   922 
   970 hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
   923 hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
   971 {
   924 {
  1070 								/* Use this endpoint for OUTPUT */
  1023 								/* Use this endpoint for OUTPUT */
  1071 								dev->output_endpoint = ep->bEndpointAddress;
  1024 								dev->output_endpoint = ep->bEndpointAddress;
  1072 							}
  1025 							}
  1073 						}
  1026 						}
  1074 
  1027 
  1075 						pthread_create(&dev->thread, NULL, read_thread, dev);
  1028 						dev->thread = SDL_CreateThread(read_thread, NULL, dev);
  1076 
  1029 
  1077 						/* Wait here for the read thread to be initialized. */
  1030 						/* Wait here for the read thread to be initialized. */
  1078 						pthread_barrier_wait(&dev->barrier);
  1031 						SDL_WaitThreadBarrier(&dev->barrier);
  1079 
  1032 
  1080 					}
  1033 					}
  1081 					free(dev_path);
  1034 					free(dev_path);
  1082 				}
  1035 				}
  1083 			}
  1036 			}
  1164 	free(rpt->data);
  1117 	free(rpt->data);
  1165 	free(rpt);
  1118 	free(rpt);
  1166 	return len;
  1119 	return len;
  1167 }
  1120 }
  1168 
  1121 
       
  1122 #if 0 /* TODO: pthread_cleanup SDL? */
  1169 static void cleanup_mutex(void *param)
  1123 static void cleanup_mutex(void *param)
  1170 {
  1124 {
  1171 	hid_device *dev = (hid_device *)param;
  1125 	hid_device *dev = (hid_device *)param;
  1172 	pthread_mutex_unlock(&dev->mutex);
  1126 	SDL_UnlockMutex(dev->mutex);
  1173 }
  1127 }
       
  1128 #endif
  1174 
  1129 
  1175 
  1130 
  1176 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
  1131 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
  1177 {
  1132 {
  1178 	int bytes_read = -1;
  1133 	int bytes_read = -1;
  1182 	int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
  1137 	int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
  1183 	LOG("transferred: %d\n", transferred);
  1138 	LOG("transferred: %d\n", transferred);
  1184 	return transferred;
  1139 	return transferred;
  1185 #endif
  1140 #endif
  1186 
  1141 
  1187 	pthread_mutex_lock(&dev->mutex);
  1142 	SDL_LockMutex(dev->mutex);
  1188 	pthread_cleanup_push(&cleanup_mutex, dev);
  1143 	/* TODO: pthread_cleanup SDL? */
  1189 
  1144 
  1190 	/* There's an input report queued up. Return it. */
  1145 	/* There's an input report queued up. Return it. */
  1191 	if (dev->input_reports) {
  1146 	if (dev->input_reports) {
  1192 		/* Return the first one */
  1147 		/* Return the first one */
  1193 		bytes_read = return_data(dev, data, length);
  1148 		bytes_read = return_data(dev, data, length);
  1202 	}
  1157 	}
  1203 
  1158 
  1204 	if (milliseconds == -1) {
  1159 	if (milliseconds == -1) {
  1205 		/* Blocking */
  1160 		/* Blocking */
  1206 		while (!dev->input_reports && !dev->shutdown_thread) {
  1161 		while (!dev->input_reports && !dev->shutdown_thread) {
  1207 			pthread_cond_wait(&dev->condition, &dev->mutex);
  1162 			SDL_CondWait(dev->condition, dev->mutex);
  1208 		}
  1163 		}
  1209 		if (dev->input_reports) {
  1164 		if (dev->input_reports) {
  1210 			bytes_read = return_data(dev, data, length);
  1165 			bytes_read = return_data(dev, data, length);
  1211 		}
  1166 		}
  1212 	}
  1167 	}
  1213 	else if (milliseconds > 0) {
  1168 	else if (milliseconds > 0) {
  1214 		/* Non-blocking, but called with timeout. */
  1169 		/* Non-blocking, but called with timeout. */
  1215 		int res;
  1170 		int res;
  1216 		struct timespec ts;
       
  1217 		clock_gettime(CLOCK_REALTIME, &ts);
       
  1218 		ts.tv_sec += milliseconds / 1000;
       
  1219 		ts.tv_nsec += (milliseconds % 1000) * 1000000;
       
  1220 		if (ts.tv_nsec >= 1000000000L) {
       
  1221 			ts.tv_sec++;
       
  1222 			ts.tv_nsec -= 1000000000L;
       
  1223 		}
       
  1224 
  1171 
  1225 		while (!dev->input_reports && !dev->shutdown_thread) {
  1172 		while (!dev->input_reports && !dev->shutdown_thread) {
  1226 			res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
  1173 			res = SDL_CondWaitTimeout(dev->condition, dev->mutex, milliseconds);
  1227 			if (res == 0) {
  1174 			if (res == 0) {
  1228 				if (dev->input_reports) {
  1175 				if (dev->input_reports) {
  1229 					bytes_read = return_data(dev, data, length);
  1176 					bytes_read = return_data(dev, data, length);
  1230 					break;
  1177 					break;
  1231 				}
  1178 				}
  1232 
  1179 
  1233 				/* If we're here, there was a spurious wake up
  1180 				/* If we're here, there was a spurious wake up
  1234 				   or the read thread was shutdown. Run the
  1181 				   or the read thread was shutdown. Run the
  1235 				   loop again (ie: don't break). */
  1182 				   loop again (ie: don't break). */
  1236 			}
  1183 			}
  1237 			else if (res == ETIMEDOUT) {
  1184 			else if (res == SDL_MUTEX_TIMEDOUT) {
  1238 				/* Timed out. */
  1185 				/* Timed out. */
  1239 				bytes_read = 0;
  1186 				bytes_read = 0;
  1240 				break;
  1187 				break;
  1241 			}
  1188 			}
  1242 			else {
  1189 			else {
  1250 		/* Purely non-blocking */
  1197 		/* Purely non-blocking */
  1251 		bytes_read = 0;
  1198 		bytes_read = 0;
  1252 	}
  1199 	}
  1253 
  1200 
  1254 ret:
  1201 ret:
  1255 	pthread_mutex_unlock(&dev->mutex);
  1202 	SDL_UnlockMutex(dev->mutex);
  1256 	pthread_cleanup_pop(0);
  1203 	/* TODO: pthread_cleanup SDL? */
  1257 
  1204 
  1258 	return bytes_read;
  1205 	return bytes_read;
  1259 }
  1206 }
  1260 
  1207 
  1261 int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
  1208 int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
  1332 }
  1279 }
  1333 
  1280 
  1334 
  1281 
  1335 void HID_API_EXPORT hid_close(hid_device *dev)
  1282 void HID_API_EXPORT hid_close(hid_device *dev)
  1336 {
  1283 {
       
  1284 	int status;
       
  1285 
  1337 	if (!dev)
  1286 	if (!dev)
  1338 		return;
  1287 		return;
  1339 
  1288 
  1340 	/* Cause read_thread() to stop. */
  1289 	/* Cause read_thread() to stop. */
  1341 	dev->shutdown_thread = 1;
  1290 	dev->shutdown_thread = 1;
  1342 	libusb_cancel_transfer(dev->transfer);
  1291 	libusb_cancel_transfer(dev->transfer);
  1343 
  1292 
  1344 	/* Wait for read_thread() to end. */
  1293 	/* Wait for read_thread() to end. */
  1345 	pthread_join(dev->thread, NULL);
  1294 	SDL_WaitThread(dev->thread, &status);
  1346 
  1295 
  1347 	/* Clean up the Transfer objects allocated in read_thread(). */
  1296 	/* Clean up the Transfer objects allocated in read_thread(). */
  1348 	free(dev->transfer->buffer);
  1297 	free(dev->transfer->buffer);
  1349 	libusb_free_transfer(dev->transfer);
  1298 	libusb_free_transfer(dev->transfer);
  1350 
  1299 
  1353 
  1302 
  1354 	/* Close the handle */
  1303 	/* Close the handle */
  1355 	libusb_close(dev->device_handle);
  1304 	libusb_close(dev->device_handle);
  1356 
  1305 
  1357 	/* Clear out the queue of received reports. */
  1306 	/* Clear out the queue of received reports. */
  1358 	pthread_mutex_lock(&dev->mutex);
  1307 	SDL_LockMutex(dev->mutex);
  1359 	while (dev->input_reports) {
  1308 	while (dev->input_reports) {
  1360 		return_data(dev, NULL, 0);
  1309 		return_data(dev, NULL, 0);
  1361 	}
  1310 	}
  1362 	pthread_mutex_unlock(&dev->mutex);
  1311 	SDL_UnlockMutex(dev->mutex);
  1363 
  1312 
  1364 	free_hid_device(dev);
  1313 	free_hid_device(dev);
  1365 }
  1314 }
  1366 
  1315 
  1367 
  1316 
  1406 	const char *name;
  1355 	const char *name;
  1407 	const char *string_code;
  1356 	const char *string_code;
  1408 	uint16_t usb_code;
  1357 	uint16_t usb_code;
  1409 };
  1358 };
  1410 
  1359 
       
  1360 #ifndef _WIN32 /* TODO: Win32 setlocale */
  1411 #define LANG(name,code,usb_code) { name, code, usb_code }
  1361 #define LANG(name,code,usb_code) { name, code, usb_code }
  1412 static struct lang_map_entry lang_map[] = {
  1362 static struct lang_map_entry lang_map[] = {
  1413 	LANG("Afrikaans", "af", 0x0436),
  1363 	LANG("Afrikaans", "af", 0x0436),
  1414 	LANG("Albanian", "sq", 0x041C),
  1364 	LANG("Albanian", "sq", 0x041C),
  1415 	LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
  1365 	LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
  1450 	LANG("English - Canada", "en_ca", 0x1009),
  1400 	LANG("English - Canada", "en_ca", 0x1009),
  1451 	LANG("English - Caribbean", "en_cb", 0x2409),
  1401 	LANG("English - Caribbean", "en_cb", 0x2409),
  1452 	LANG("English - Ireland", "en_ie", 0x1809),
  1402 	LANG("English - Ireland", "en_ie", 0x1809),
  1453 	LANG("English - Jamaica", "en_jm", 0x2009),
  1403 	LANG("English - Jamaica", "en_jm", 0x2009),
  1454 	LANG("English - New Zealand", "en_nz", 0x1409),
  1404 	LANG("English - New Zealand", "en_nz", 0x1409),
  1455 	LANG("English - Phillippines", "en_ph", 0x3409),
  1405 	LANG("English - Philippines", "en_ph", 0x3409),
  1456 	LANG("English - Southern Africa", "en_za", 0x1C09),
  1406 	LANG("English - Southern Africa", "en_za", 0x1C09),
  1457 	LANG("English - Trinidad", "en_tt", 0x2C09),
  1407 	LANG("English - Trinidad", "en_tt", 0x2C09),
  1458 	LANG("English - Great Britain", "en_gb", 0x0809),
  1408 	LANG("English - Great Britain", "en_gb", 0x0809),
  1459 	LANG("English - United States", "en_us", 0x0409),
  1409 	LANG("English - United States", "en_us", 0x0409),
  1460 	LANG("Estonian", "et", 0x0425),
  1410 	LANG("Estonian", "et", 0x0425),
  1543 	LANG("Xhosa", "xh", 0x0434),
  1493 	LANG("Xhosa", "xh", 0x0434),
  1544 	LANG("Yiddish", "yi", 0x043D),
  1494 	LANG("Yiddish", "yi", 0x043D),
  1545 	LANG("Zulu", "zu", 0x0435),
  1495 	LANG("Zulu", "zu", 0x0435),
  1546 	LANG(NULL, NULL, 0x0),
  1496 	LANG(NULL, NULL, 0x0),
  1547 };
  1497 };
       
  1498 #endif /* _WIN32 */
  1548 
  1499 
  1549 uint16_t get_usb_code_for_current_locale(void)
  1500 uint16_t get_usb_code_for_current_locale(void)
  1550 {
  1501 {
       
  1502 #ifndef _WIN32 /* TODO: Win32 setlocale? */
  1551 	char *locale;
  1503 	char *locale;
  1552 	char search_string[64];
  1504 	char search_string[64];
  1553 	char *ptr;
  1505 	char *ptr;
  1554 	struct lang_map_entry *lang;
  1506 	struct lang_map_entry *lang;
  1555 
  1507 
  1603 		}
  1555 		}
  1604 		lang++;
  1556 		lang++;
  1605 	}
  1557 	}
  1606 #endif
  1558 #endif
  1607 
  1559 
       
  1560 #endif /* _WIN32 */
  1608 	/* Found nothing. */
  1561 	/* Found nothing. */
  1609 	return 0x0;
  1562 	return 0x0;
  1610 }
  1563 }
  1611 
  1564 
  1612 #if defined(__cplusplus) && !defined(NAMESPACE)
  1565 #if defined(__cplusplus) && !defined(NAMESPACE)