Debian Codegraph @

src/macosx/hidjoy.m

raw
1 /* ______ ___ ___
2 * /\ _ \ /\_ \ /\_ \
3 * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
4 * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
5 * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
6 * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
7 * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
8 * /\____/
9 * \_/__/
10 *
11 * HID Joystick driver routines for MacOS X.
12 *
13 * By Angelo Mottola.
14 * New API (Leopard) support and hotplugging by Trent Gamblin.
15 *
16 * See readme.txt for copyright information.
17 */
18
19 #include "allegro5/allegro.h"
20 #include "allegro5/platform/aintosx.h"
21
22 #import <CoreFoundation/CoreFoundation.h>
23 #import <IOKit/hid/IOHIDKeys.h>
24
25 #ifndef ALLEGRO_MACOSX
26 #error something is wrong with the makefile
27 #endif
28
29 #import <IOKit/hid/IOHIDBase.h>
30
31 /* State transitions:
32 * unused -> born
33 * born -> alive
34 * born -> dying
35 * active -> dying
36 * dying -> unused
37 */
38 typedef enum {
39 JOY_STATE_UNUSED,
40 JOY_STATE_BORN,
41 JOY_STATE_ALIVE,
42 JOY_STATE_DYING
43 } CONFIG_STATE;
44
45 // These values can be found in the USB HID Usage Tables:
46 // http://www.usb.org/developers/hidpage
47 #define GENERIC_DESKTOP_USAGE_PAGE 0x01
48 #define JOYSTICK_USAGE_NUMBER 0x04
49 #define GAMEPAD_USAGE_NUMBER 0x05
50
51 typedef struct {
52 IOHIDElementRef elem;
53 _AL_JOYSTICK_OUTPUT output;
54 } BUTTON_MAPPING;
55
56 typedef struct {
57 IOHIDElementRef elem;
58 long min;
59 long max;
60 _AL_JOYSTICK_OUTPUT x_output;
61 _AL_JOYSTICK_OUTPUT y_output;
62 } HAT_MAPPING;
63
64 typedef struct {
65 IOHIDElementRef elem;
66 long min;
67 long max;
68 _AL_JOYSTICK_OUTPUT output;
69 } AXIS_MAPPING;
70
71 typedef struct {
72 ALLEGRO_JOYSTICK parent;
73 BUTTON_MAPPING buttons[_AL_MAX_JOYSTICK_BUTTONS];
74 AXIS_MAPPING axes[_AL_MAX_JOYSTICK_STICKS * _AL_MAX_JOYSTICK_AXES];
75 HAT_MAPPING hats[_AL_MAX_JOYSTICK_STICKS];
76 int hat_state[_AL_MAX_JOYSTICK_AXES];
77 CONFIG_STATE cfg_state;
78 ALLEGRO_JOYSTICK_STATE state;
79 IOHIDDeviceRef ident;
80 char *name;
81 } ALLEGRO_JOYSTICK_OSX;
82
83 static IOHIDManagerRef hidManagerRef;
84 static _AL_VECTOR joysticks;
85 static CONFIG_STATE new_joystick_state = JOY_STATE_ALIVE;
86 static bool initialized = false;
87 static ALLEGRO_MUTEX *add_mutex;
88
89 ALLEGRO_DEBUG_CHANNEL("MacOSX")
90
91 // function to create matching dictionary (for devices)
92 static CFMutableDictionaryRef CreateDeviceMatchingDictionary(
93 UInt32 inUsagePage,
94 UInt32 inUsage
95 ) {
96 // create a dictionary to add usage page/usages to
97 CFMutableDictionaryRef result = CFDictionaryCreateMutable(
98 kCFAllocatorDefault,
99 0,
100 &kCFTypeDictionaryKeyCallBacks,
101 &kCFTypeDictionaryValueCallBacks
102 );
103
104 if (result) {
105 // Add key for device type to refine the matching dictionary.
106 CFNumberRef pageCFNumberRef = CFNumberCreate(
107 kCFAllocatorDefault,
108 kCFNumberIntType,
109 &inUsagePage
110 );
111
112 if (pageCFNumberRef) {
113 CFStringRef usage_page = CFSTR(kIOHIDDeviceUsagePageKey);
114
115 CFDictionarySetValue(
116 result,
117 usage_page,
118 pageCFNumberRef
119 );
120
121 CFRelease(pageCFNumberRef);
122
123 // note: the usage is only valid if the usage page is also defined
124
125 CFNumberRef usageCFNumberRef = CFNumberCreate(
126 kCFAllocatorDefault,
127 kCFNumberIntType,
128 &inUsage
129 );
130
131 if (usageCFNumberRef) {
132 CFStringRef usage_key = CFSTR(kIOHIDDeviceUsageKey);
133
134 CFDictionarySetValue(
135 result,
136 usage_key,
137 usageCFNumberRef
138 );
139
140 CFRelease(usageCFNumberRef);
141 }
142 }
143 }
144
145 return result;
146 }
147
148 static ALLEGRO_JOYSTICK_OSX *find_joystick(IOHIDDeviceRef ident)
149 {
150 int i;
151 for (i = 0; i < (int)_al_vector_size(&joysticks); i++) {
152 ALLEGRO_JOYSTICK_OSX *joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
153 if (ident == joy->ident) {
154 return joy;
155 }
156 }
157
158 return NULL;
159 }
160
161 static ALLEGRO_JOYSTICK_OSX *find_or_insert_joystick(IOHIDDeviceRef ident)
162 {
163 ALLEGRO_JOYSTICK_OSX *joy = find_joystick(ident);
164 if (joy)
165 return joy;
166 for (int i = 0; i < (int)_al_vector_size(&joysticks); i++) {
167 joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
168 if (joy->cfg_state == JOY_STATE_UNUSED) {
169 joy->ident = ident;
170 return joy;
171 }
172 }
173
174 joy = al_calloc(1, sizeof(ALLEGRO_JOYSTICK_OSX));
175 joy->ident = ident;
176 ALLEGRO_JOYSTICK_OSX **back = _al_vector_alloc_back(&joysticks);
177 *back = joy;
178 return joy;
179 }
180
181 static const char *get_element_name(IOHIDElementRef elem, const char *default_name)
182 {
183 CFStringRef name = IOHIDElementGetName(elem);
184 if (name) {
185 return CFStringGetCStringPtr(name, kCFStringEncodingUTF8);
186 }
187 else
188 return default_name;
189 }
190
191 static bool compat_5_2_9(void) {
192 // Broken usages.
193 return _al_get_joystick_compat_version() < AL_ID(5, 2, 10, 0);
194 }
195
196 static bool compat_5_2_10(void) {
197 // Different axis normalization, hat events + mappings.
198 return _al_get_joystick_compat_version() < AL_ID(5, 2, 11, 0);
199 }
200
201 static void add_elements(CFArrayRef elements, ALLEGRO_JOYSTICK_OSX *joy)
202 {
203 int i;
204 char default_name[100];
205 int stick_class = -1;
206 int axis = 0;
207 int num_sticks = -1;
208 int num_buttons = 0;
209 int num_hats = 0;
210 int num_axes = 0;
211 bool old_style = compat_5_2_9();
212
213 for (i = 0; i < CFArrayGetCount(elements); i++) {
214 IOHIDElementRef elem = (IOHIDElementRef)CFArrayGetValueAtIndex(
215 elements,
216 i
217 );
218
219 int usage = IOHIDElementGetUsage(elem);
220 int usage_page = IOHIDElementGetUsagePage(elem);
221 if (IOHIDElementGetType(elem) == kIOHIDElementTypeInput_Button) {
222 int idx;
223 if (old_style)
224 idx = usage - 1;
225 else {
226 idx = num_buttons;
227 // 0x09 is the Button Page.
228 if (usage_page != 0x09)
229 continue;
230 }
231 if (idx >= 0 && idx < _AL_MAX_JOYSTICK_BUTTONS && !joy->buttons[idx].elem) {
232 joy->buttons[idx].elem = elem;
233 joy->buttons[idx].output = _al_new_joystick_button_output(idx);
234 sprintf(default_name, "Button %d", idx);
235 joy->parent.info.button[idx].name = _al_strdup(get_element_name(elem, default_name));
236 num_buttons++;
237 }
238 }
239 else if (IOHIDElementGetType(elem) == kIOHIDElementTypeInput_Misc) {
240 long min = IOHIDElementGetLogicalMin(elem);
241 long max = IOHIDElementGetLogicalMax(elem);
242 int new_stick_class = -1;
243
244 switch (usage) {
245 case kHIDUsage_GD_X:
246 case kHIDUsage_GD_Y:
247 case kHIDUsage_GD_Z:
248 new_stick_class = 1;
249 break;
250
251 case kHIDUsage_GD_Rx:
252 case kHIDUsage_GD_Ry:
253 case kHIDUsage_GD_Rz:
254 new_stick_class = 2;
255 break;
256
257 case kHIDUsage_GD_Hatswitch:
258 new_stick_class = 3;
259 break;
260 }
261
262 if (new_stick_class < 0)
263 continue;
264
265 if (stick_class != new_stick_class) {
266 if (num_sticks >= _AL_MAX_JOYSTICK_STICKS - 1)
267 break;
268
269 num_sticks++;
270
271 stick_class = new_stick_class;
272 axis = 0;
273
274 char *buf = al_malloc(20);
275 sprintf(buf, "Stick %d", num_sticks);
276 joy->parent.info.stick[num_sticks].name = buf;
277 }
278 else
279 axis++;
280
281 if (stick_class == 3) {
282 if (num_hats >= _AL_MAX_JOYSTICK_AXES)
283 continue;
284
285 HAT_MAPPING *map = &joy->hats[num_hats];
286 map->min = min;
287 map->max = max;
288 map->elem = elem;
289 map->x_output = _al_new_joystick_stick_output(num_sticks, 0);
290 map->y_output = _al_new_joystick_stick_output(num_sticks, 1);
291
292 for (axis = 0; axis < 2; axis++) {
293 sprintf(default_name, "Axis %i", axis);
294 joy->parent.info.stick[num_sticks].axis[axis].name = _al_strdup(get_element_name(elem, default_name));
295 }
296 joy->parent.info.stick[num_sticks].num_axes = 2;
297
298 num_hats++;
299 }
300 else {
301 if (num_axes >= _AL_MAX_JOYSTICK_STICKS * _AL_MAX_JOYSTICK_AXES)
302 continue;
303
304 AXIS_MAPPING *map = &joy->axes[num_axes];
305 map->min = min;
306 map->max = max;
307 map->elem = elem;
308 map->output = _al_new_joystick_stick_output(num_sticks, axis);
309
310 sprintf(default_name, "Axis %i", axis);
311 joy->parent.info.stick[num_sticks].axis[axis].name = _al_strdup(get_element_name(elem, default_name));
312 joy->parent.info.stick[num_sticks].num_axes++;
313
314 num_axes++;
315 }
316 }
317 }
318 joy->parent.info.num_sticks = num_sticks + 1;
319 joy->parent.info.num_buttons = num_buttons;
320 }
321
322 static NSInteger element_compare_func(id val1, id val2)
323 {
324 IOHIDElementRef elem1 = [(NSValue *)val1 pointerValue];
325 IOHIDElementRef elem2 = [(NSValue *)val2 pointerValue];
326
327 int usage1 = IOHIDElementGetUsage(elem1);
328 int usage2 = IOHIDElementGetUsage(elem2);
329 if (usage1 < usage2)
330 return kCFCompareLessThan;
331 if (usage1 > usage2)
332 return kCFCompareGreaterThan;
333 return kCFCompareEqualTo;
334 }
335
336 static bool add_elements_with_mapping(CFArrayRef elements, ALLEGRO_JOYSTICK_OSX *joy, const _AL_JOYSTICK_MAPPING *mapping)
337 {
338 int num_buttons = 0;
339 int num_hats = 0;
340 int num_axes = 0;
341 int num_buttons_mapped = 0;
342 int num_hats_mapped = 0;
343 int num_axes_mapped = 0;
344 _AL_JOYSTICK_OUTPUT *output;
345
346 NSMutableArray* buttons_elems = [[[NSMutableArray alloc] init] autorelease];
347 NSMutableArray* axes_elems = [[[NSMutableArray alloc] init] autorelease];
348 NSMutableArray* hats_elems = [[[NSMutableArray alloc] init] autorelease];
349
350 for (int i = 0; i < CFArrayGetCount(elements); i++) {
351 IOHIDElementRef elem = (IOHIDElementRef)CFArrayGetValueAtIndex(
352 elements,
353 i
354 );
355
356 int usage = IOHIDElementGetUsage(elem);
357 int usage_page = IOHIDElementGetUsagePage(elem);
358 if (IOHIDElementGetType(elem) == kIOHIDElementTypeInput_Button) {
359 // 0x09 is the Button Page.
360 if (usage_page != 0x09)
361 continue;
362 [buttons_elems addObject: [NSValue valueWithPointer:elem]];
363 }
364 else if (IOHIDElementGetType(elem) == kIOHIDElementTypeInput_Misc) {
365 switch (usage) {
366 case kHIDUsage_GD_X:
367 case kHIDUsage_GD_Y:
368 case kHIDUsage_GD_Z:
369 case kHIDUsage_GD_Rx:
370 case kHIDUsage_GD_Ry:
371 case kHIDUsage_GD_Rz:
372 case kHIDUsage_GD_Slider:
373 case kHIDUsage_GD_Dial:
374 case kHIDUsage_GD_Wheel:
375 case kHIDUsage_Sim_Accelerator:
376 case kHIDUsage_Sim_Brake: {
377 [axes_elems addObject: [NSValue valueWithPointer:elem]];
378 break;
379 }
380 case kHIDUsage_GD_Hatswitch: {
381 [hats_elems addObject: [NSValue valueWithPointer:elem]];
382 break;
383 }
384 default:
385 continue;
386 }
387 }
388 }
389
390 // This sorting is inspired by what GLFW does.
391 [buttons_elems sortWithOptions:NSSortStable
392 usingComparator:^NSComparisonResult(id val1, id val2) {
393 return element_compare_func(val1, val2);
394 }];
395 [axes_elems sortWithOptions:NSSortStable
396 usingComparator:^NSComparisonResult(id val1, id val2) {
397 return element_compare_func(val1, val2);
398 }];
399 [hats_elems sortWithOptions:NSSortStable
400 usingComparator:^NSComparisonResult(id val1, id val2) {
401 return element_compare_func(val1, val2);
402 }];
403
404 for (int i = 0; i < (int)[buttons_elems count]; i++) {
405 IOHIDElementRef elem = [(NSValue *)buttons_elems[i] pointerValue];
406 int idx = num_buttons;
407 if (idx >= 0 && idx < _AL_MAX_JOYSTICK_BUTTONS && !joy->buttons[idx].elem) {
408 joy->buttons[idx].elem = elem;
409 output = _al_get_joystick_output(&mapping->button_map, idx);
410 if (output) {
411 joy->buttons[idx].output = *output;
412 num_buttons_mapped++;
413 }
414 num_buttons++;
415 }
416 }
417
418 for (int i = 0; i < (int)[axes_elems count]; i++) {
419 IOHIDElementRef elem = [(NSValue *)axes_elems[i] pointerValue];
420 int usage = IOHIDElementGetUsage(elem);
421 long min = IOHIDElementGetLogicalMin(elem);
422 long max = IOHIDElementGetLogicalMax(elem);
423 if (num_axes >= _AL_MAX_JOYSTICK_STICKS * _AL_MAX_JOYSTICK_AXES)
424 continue;
425
426 AXIS_MAPPING *map = &joy->axes[num_axes];
427 map->min = min;
428 map->max = max;
429 map->elem = elem;
430 output = _al_get_joystick_output(&mapping->axis_map, num_axes);
431 if (output) {
432 map->output = *output;
433 num_axes_mapped++;
434 }
435 num_axes++;
436 }
437
438 for (int i = 0; i < (int)[hats_elems count]; i++) {
439 IOHIDElementRef elem = [(NSValue *)hats_elems[i] pointerValue];
440 long min = IOHIDElementGetLogicalMin(elem);
441 long max = IOHIDElementGetLogicalMax(elem);
442 if (num_hats >= _AL_MAX_JOYSTICK_AXES)
443 continue;
444
445 HAT_MAPPING *map = &joy->hats[num_hats];
446 map->min = min;
447 map->max = max;
448 map->elem = elem;
449 output = _al_get_joystick_output(&mapping->hat_map, 2 * num_hats);
450 if (output) {
451 map->x_output = *output;
452 num_hats_mapped++;
453 }
454 output = _al_get_joystick_output(&mapping->hat_map, 2 * num_hats + 1);
455 if (output) {
456 map->y_output = *output;
457 num_hats_mapped++;
458 }
459 num_hats++;
460 }
461
462 if (num_axes_mapped != (int)_al_vector_size(&mapping->axis_map)) {
463 ALLEGRO_ERROR("Could not use mapping, some axes are not mapped.\n");
464 return false;
465 }
466 if (num_hats_mapped != (int)_al_vector_size(&mapping->hat_map)) {
467 ALLEGRO_ERROR("Could not use mapping, some hats are not mapped.\n");
468 return false;
469 }
470 if (num_buttons_mapped != (int)_al_vector_size(&mapping->button_map)) {
471 ALLEGRO_ERROR("Could not use mapping, some buttons are not mapped.\n");
472 return false;
473 }
474 return true;
475 }
476
477 static void set_joystick_name(ALLEGRO_JOYSTICK_OSX *joy)
478 {
479 CFStringRef str;
480
481 str = IOHIDDeviceGetProperty(joy->ident, CFSTR(kIOHIDProductKey));
482 if (str) {
483 CFIndex length = CFStringGetLength(str);
484 CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
485 if (joy->name) {
486 al_free(joy->name);
487 }
488 joy->name = (char *)al_malloc(maxSize);
489 if (joy->name) {
490 if (CFStringGetCString(str, joy->name, maxSize, kCFStringEncodingUTF8)) {
491 return;
492 }
493 }
494 }
495 joy->name = _al_strdup("Joystick");
496 }
497
498 static void osx_joy_generate_configure_event(void)
499 {
500 if (!initialized) return;
501
502 ALLEGRO_EVENT event;
503 event.joystick.type = ALLEGRO_EVENT_JOYSTICK_CONFIGURATION;
504 event.joystick.timestamp = al_current_time();
505
506 _al_generate_joystick_event(&event);
507 }
508
509 static void add_joystick_device(IOHIDDeviceRef ref, bool emit_reconfigure_event)
510 {
511 al_lock_mutex(add_mutex);
512
513 ALLEGRO_JOYSTICK_OSX *joy = find_or_insert_joystick(ref);
514
515 if (joy && (joy->cfg_state == JOY_STATE_BORN || joy->cfg_state == JOY_STATE_ALIVE)) {
516 al_unlock_mutex(add_mutex);
517 return;
518 }
519
520 joy->cfg_state = new_joystick_state;
521
522 CFArrayRef elements = IOHIDDeviceCopyMatchingElements(
523 ref,
524 NULL,
525 kIOHIDOptionsTypeNone
526 );
527
528 CFTypeRef type;
529
530 type = IOHIDDeviceGetProperty(joy->ident, CFSTR(kIOHIDVendorIDKey));
531 int32_t vendor = 0;
532 if (type)
533 CFNumberGetValue(type, kCFNumberSInt32Type, &vendor);
534
535 type = IOHIDDeviceGetProperty(joy->ident, CFSTR(kIOHIDProductIDKey));
536 int32_t product = 0;
537 if (type)
538 CFNumberGetValue(type, kCFNumberSInt32Type, &product);
539
540 type = IOHIDDeviceGetProperty(joy->ident, CFSTR(kIOHIDVersionNumberKey));
541 int32_t version = 0;
542 if (type)
543 CFNumberGetValue(type, kCFNumberSInt32Type, &version);
544
545 CFStringRef str;
546
547 str = IOHIDDeviceGetProperty(joy->ident, CFSTR(kIOHIDManufacturerKey));
548 char manufacturer_str[256];
549 if (!str || !CFStringGetCString(str, manufacturer_str, sizeof(manufacturer_str), kCFStringEncodingUTF8))
550 manufacturer_str[0] = '\0';
551
552 str = IOHIDDeviceGetProperty(joy->ident, CFSTR(kIOHIDProductKey));
553 char product_str[256];
554 if (!str || !CFStringGetCString(str, product_str, sizeof(product_str), kCFStringEncodingUTF8))
555 product_str[0] = '\0';
556
557 ALLEGRO_JOYSTICK_GUID guid = _al_new_joystick_guid(0x03, (uint16_t)vendor, (uint16_t)product, (uint16_t)version, manufacturer_str, product_str, 0, 0);
558
559 const _AL_JOYSTICK_MAPPING *mapping = _al_get_gamepad_mapping("Mac OS X", guid);
560
561 joy->parent.info.guid = guid;
562 if (mapping && add_elements_with_mapping(elements, joy, mapping)) {
563 _al_fill_gamepad_info(&joy->parent.info);
564 joy->name = _al_strdup(mapping->name);
565 }
566 else {
567 set_joystick_name(joy);
568 add_elements(elements, joy);
569 }
570
571 CFRelease(elements);
572
573 al_unlock_mutex(add_mutex);
574
575 if (emit_reconfigure_event) osx_joy_generate_configure_event();
576
577 ALLEGRO_INFO("Found joystick (%d buttons, %d sticks)\n",
578 joy->parent.info.num_buttons, joy->parent.info.num_sticks);
579 }
580
581 static int enumerate_and_create_initial_joystick_devices(IOHIDManagerRef manager)
582 {
583 int i;
584 int num_joysticks_enumerated = 0;
585
586 CFSetRef devices = IOHIDManagerCopyDevices(manager);
587 if (devices == NULL)
588 {
589 // There are no devices to enumerate
590 }
591 else
592 {
593 CFIndex num_devices = CFSetGetCount(devices);
594 IOHIDDeviceRef *device_arr = al_calloc(num_devices, sizeof(IOHIDDeviceRef));
595 CFSetGetValues(devices, (const void **) device_arr);
596
597 for (i = 0; i < num_devices; i++) {
598 IOHIDDeviceRef dev = device_arr[i];
599 add_joystick_device(dev, false);
600 num_joysticks_enumerated++;
601 }
602 al_free(device_arr);
603 CFRelease(devices);
604 }
605
606 return num_joysticks_enumerated;
607 }
608
609 static void device_add_callback(
610 void *context,
611 IOReturn result,
612 void *sender,
613 IOHIDDeviceRef ref
614 ) {
615 (void)context;
616 (void)result;
617 (void)sender;
618
619 add_joystick_device(ref, true);
620 }
621
622 static void device_remove_callback(
623 void *context,
624 IOReturn result,
625 void *sender,
626 IOHIDDeviceRef ref
627 ) {
628 (void)context;
629 (void)result;
630 (void)sender;
631
632 int i;
633 for (i = 0; i < (int)_al_vector_size(&joysticks); i++) {
634 ALLEGRO_JOYSTICK_OSX *joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
635 if (joy->ident == ref) {
636 joy->cfg_state = JOY_STATE_DYING;
637 osx_joy_generate_configure_event();
638 return;
639 }
640 }
641 }
642
643 #define MAX_HAT_DIRECTIONS 8
644 struct HAT_MAPPING {
645 int axisV;
646 int axisH;
647 } hat_mapping[MAX_HAT_DIRECTIONS + 1] = {
648 { -1, 0 }, // 0
649 { -1, 1 }, // 1
650 { 0, 1 }, // 2
651 { 1, 1 }, // 3
652 { 1, 0 }, // 4
653 { 1, -1 }, // 5
654 { 0, -1 }, // 6
655 { -1, -1 }, // 7
656 { 0, 0 }, // 8
657 };
658
659 static void value_callback(
660 void *context,
661 IOReturn result,
662 void *sender,
663 IOHIDValueRef value
664 ) {
665 if (!initialized) return;
666
667 (void)context;
668 (void)result;
669 (void)sender;
670
671 IOHIDElementRef elem = IOHIDValueGetElement(value);
672 int int_value = (int)IOHIDValueGetIntegerValue(value);
673 IOHIDDeviceRef ref = IOHIDElementGetDevice(elem);
674 ALLEGRO_JOYSTICK_OSX *joy = find_joystick(ref);
675
676 if (!joy) return;
677
678 ALLEGRO_EVENT_SOURCE *es = al_get_joystick_event_source();
679 _al_event_source_lock(es);
680
681 for (int i = 0; i < _AL_MAX_JOYSTICK_BUTTONS; i++) {
682 BUTTON_MAPPING *map = &joy->buttons[i];
683 if (!map->elem)
684 break;
685 if (map->elem != elem)
686 continue;
687 _al_joystick_generate_button_event(&joy->parent, &joy->state, map->output, int_value);
688 }
689
690 for (int i = 0; i < _AL_MAX_JOYSTICK_STICKS * _AL_MAX_JOYSTICK_AXES; i++) {
691 AXIS_MAPPING *map = &joy->axes[i];
692 if (!map->elem)
693 break;
694 if (map->elem != elem)
695 continue;
696
697 float pos;
698 long min = map->min;
699 long max = map->max;
700 if (compat_5_2_10()) {
701 if (min < 0) {
702 if (int_value < 0)
703 pos = -(float)int_value / min;
704 else
705 pos = (float)int_value / max;
706 }
707 else {
708 pos = ((float)int_value / max * 2) - 1;
709 }
710 }
711 else {
712 long range = max - min;
713 if (range > 0)
714 pos = 2. * ((float)int_value - min) / range - 1.;
715 else
716 /* TODO: Add auto-calibration? */
717 pos = (float)int_value;
718 }
719 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->output, pos);
720 }
721
722 for (int i = 0; i < _AL_MAX_JOYSTICK_AXES; i++) {
723 HAT_MAPPING *map = &joy->hats[i];
724 if (!map->elem)
725 break;
726 if (map->elem != elem)
727 continue;
728
729 long min = map->min;
730 long max = map->max;
731 if (compat_5_2_10()) {
732 if (int_value >= min && int_value <= max) {
733 long index = int_value - min;
734 if (index < MAX_HAT_DIRECTIONS) {
735 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->x_output, (float)hat_mapping[index].axisH);
736 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->y_output, (float)hat_mapping[index].axisV);
737 }
738 } else {
739 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->x_output, 0);
740 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->y_output, 0);
741 }
742 }
743 else {
744 long state = (int)(int_value - min);
745 if (state < 0 || state >= MAX_HAT_DIRECTIONS)
746 state = MAX_HAT_DIRECTIONS;
747 float old_dx = (float)hat_mapping[joy->hat_state[i]].axisH;
748 float old_dy = (float)hat_mapping[joy->hat_state[i]].axisV;
749 float dx = (float)hat_mapping[state].axisH;
750 float dy = (float)hat_mapping[state].axisV;
751 joy->hat_state[i] = (int)state;
752
753 if (old_dx != dx)
754 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->x_output, dx);
755 if (old_dy != dy)
756 _al_joystick_generate_axis_event(&joy->parent, &joy->state, map->y_output, dy);
757 }
758 }
759
760 _al_event_source_unlock(es);
761 }
762
763 static void destroy_joystick(ALLEGRO_JOYSTICK_OSX *joy) {
764 _al_destroy_joystick_info(&joy->parent.info);
765 al_free(joy->name);
766 memset(joy, 0, sizeof(ALLEGRO_JOYSTICK_OSX));
767 }
768
769 /* init_joystick:
770 * Initializes the HID joystick driver.
771 */
772 static bool init_joystick(void)
773 {
774 add_mutex = al_create_mutex();
775
776 hidManagerRef = IOHIDManagerCreate(
777 kCFAllocatorDefault,
778 kIOHIDOptionsTypeNone
779 );
780
781 if (CFGetTypeID(hidManagerRef) != IOHIDManagerGetTypeID()) {
782 ALLEGRO_ERROR("Unable to create HID Manager\n");
783 return false;
784 }
785
786 // Set which devices we want to match
787 CFMutableDictionaryRef criteria0 = CreateDeviceMatchingDictionary(
788 GENERIC_DESKTOP_USAGE_PAGE,
789 JOYSTICK_USAGE_NUMBER
790 );
791 CFMutableDictionaryRef criteria1 = CreateDeviceMatchingDictionary(
792 GENERIC_DESKTOP_USAGE_PAGE,
793 GAMEPAD_USAGE_NUMBER
794 );
795 CFMutableDictionaryRef criteria_list[] = {
796 criteria0,
797 criteria1
798 };
799 CFArrayRef criteria = CFArrayCreate(
800 kCFAllocatorDefault,
801 (const void **)criteria_list,
802 2, NULL
803 );
804
805 IOHIDManagerSetDeviceMatchingMultiple(
806 hidManagerRef,
807 criteria
808 );
809
810 CFRelease(criteria0);
811 CFRelease(criteria1);
812 CFRelease(criteria);
813
814 /* Register for plug/unplug notifications */
815 IOHIDManagerRegisterDeviceMatchingCallback(
816 hidManagerRef,
817 device_add_callback,
818 NULL
819 );
820 IOHIDManagerRegisterDeviceRemovalCallback(
821 hidManagerRef,
822 device_remove_callback,
823 NULL
824 );
825
826 // Register for value changes
827 IOHIDManagerRegisterInputValueCallback(
828 hidManagerRef,
829 value_callback,
830 NULL
831 );
832
833 IOHIDManagerScheduleWithRunLoop(
834 hidManagerRef,
835 CFRunLoopGetMain(),
836 kCFRunLoopDefaultMode
837 );
838
839 _al_vector_init(&joysticks, sizeof(ALLEGRO_JOYSTICK_OSX *));
840
841 al_lock_mutex(add_mutex);
842
843 IOReturn ret = IOHIDManagerOpen(
844 hidManagerRef,
845 kIOHIDOptionsTypeSeizeDevice
846 );
847
848 al_unlock_mutex(add_mutex);
849
850 if (ret != kIOReturnSuccess) {
851 return false;
852 }
853
854 int num_joysticks_created = enumerate_and_create_initial_joystick_devices(hidManagerRef);
855 if (num_joysticks_created > 0) osx_joy_generate_configure_event();
856
857 new_joystick_state = JOY_STATE_BORN;
858
859 initialized = true;
860
861 return true;
862 }
863
864 /* exit_joystick:
865 * Shuts down the HID joystick driver.
866 */
867 static void exit_joystick(void)
868 {
869 al_destroy_mutex(add_mutex);
870
871 IOHIDManagerUnscheduleFromRunLoop(
872 hidManagerRef,
873 CFRunLoopGetCurrent(),
874 kCFRunLoopDefaultMode
875 );
876 // Unregister from value changes
877 IOHIDManagerRegisterInputValueCallback(
878 hidManagerRef,
879 NULL,
880 NULL
881 );
882 IOHIDManagerClose(
883 hidManagerRef,
884 kIOHIDOptionsTypeNone
885 );
886 CFRelease(hidManagerRef);
887
888 for (int i = 0; i < (int)_al_vector_size(&joysticks); i++) {
889 ALLEGRO_JOYSTICK_OSX *joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
890 destroy_joystick(joy);
891 }
892 _al_vector_free(&joysticks);
893
894 initialized = false;
895 }
896
897 /* num_joysticks:
898 * Return number of active joysticks
899 */
900 static int num_joysticks(void)
901 {
902 int i;
903 int count = 0;
904 for (i = 0; i < (int)_al_vector_size(&joysticks); i++) {
905 ALLEGRO_JOYSTICK_OSX *joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
906 if (joy->cfg_state == JOY_STATE_ALIVE) {
907 count++;
908 }
909 }
910
911 return count;
912 }
913
914 /* get_joystick:
915 * Get a pointer to a joystick structure
916 */
917 static ALLEGRO_JOYSTICK* get_joystick(int index)
918 {
919 ASSERT(index >= 0 && index < (int)_al_vector_size(&joysticks));
920
921 int i;
922 int count = 0;
923 for (i = 0; i < (int)_al_vector_size(&joysticks); i++) {
924 ALLEGRO_JOYSTICK_OSX *joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
925 if (joy->cfg_state == JOY_STATE_ALIVE ||
926 joy->cfg_state == JOY_STATE_DYING) {
927 if (count == index) {
928 return (ALLEGRO_JOYSTICK *)joy;
929 }
930 count++;
931 }
932 }
933
934 return NULL;
935 }
936
937 /* release_joystick:
938 * Release a pointer that has been obtained
939 */
940 static void release_joystick(ALLEGRO_JOYSTICK* joy __attribute__((unused)) )
941 {
942 // No-op
943 }
944
945 /* get_joystick_state:
946 * Get the current status of a joystick
947 */
948 static void get_joystick_state(ALLEGRO_JOYSTICK *joy_, ALLEGRO_JOYSTICK_STATE *ret_state)
949 {
950 ALLEGRO_JOYSTICK_OSX *joy = (ALLEGRO_JOYSTICK_OSX *) joy_;
951 ALLEGRO_EVENT_SOURCE *es = al_get_joystick_event_source();
952
953 _al_event_source_lock(es);
954 {
955 *ret_state = joy->state;
956 }
957 _al_event_source_unlock(es);
958 }
959
960 static bool reconfigure_joysticks(void)
961 {
962 int i;
963 bool ret = false;
964 for (i = 0; i < (int)_al_vector_size(&joysticks); i++) {
965 ALLEGRO_JOYSTICK_OSX *joy = *(ALLEGRO_JOYSTICK_OSX **)_al_vector_ref(&joysticks, i);
966 if (joy->cfg_state == JOY_STATE_DYING) {
967 destroy_joystick(joy);
968 joy->cfg_state = JOY_STATE_UNUSED;
969 }
970 else if (joy->cfg_state == JOY_STATE_BORN)
971 joy->cfg_state = JOY_STATE_ALIVE;
972 else
973 continue;
974 ret = true;
975 }
976
977 return ret;
978 }
979
980 static const char *get_joystick_name(ALLEGRO_JOYSTICK *joy_)
981 {
982 ALLEGRO_JOYSTICK_OSX *joy = (ALLEGRO_JOYSTICK_OSX *)joy_;
983 return joy->name;
984 }
985
986 static bool get_joystick_active(ALLEGRO_JOYSTICK *joy_)
987 {
988 ALLEGRO_JOYSTICK_OSX *joy = (ALLEGRO_JOYSTICK_OSX *)joy_;
989 return joy->cfg_state == JOY_STATE_ALIVE || joy->cfg_state == JOY_STATE_DYING;
990 }
991
992 ALLEGRO_JOYSTICK_DRIVER* _al_osx_get_joystick_driver(void)
993 {
994 static ALLEGRO_JOYSTICK_DRIVER* vt = NULL;
995 if (vt == NULL) {
996 vt = al_malloc(sizeof(*vt));
997 memset(vt, 0, sizeof(*vt));
998 vt->joydrv_ascii_name = "OSX HID Driver";
999 vt->init_joystick = init_joystick;
1000 vt->exit_joystick = exit_joystick;
1001 vt->reconfigure_joysticks = reconfigure_joysticks;
1002 vt->num_joysticks = num_joysticks;
1003 vt->get_joystick = get_joystick;
1004 vt->release_joystick = release_joystick;
1005 vt->get_joystick_state = get_joystick_state;
1006 vt->get_name = get_joystick_name;
1007 vt->get_active = get_joystick_active;
1008 }
1009 return vt;
1010 }
1011
1012 /* Local variables: */
1013 /* c-basic-offset: 3 */
1014 /* indent-tabs-mode: nil */
1015 /* End: */