Skip to content

Commit c9c9455

Browse files
MarkOatesSiegeLord
authored andcommitted
Enumerate joysticks on initialization; Prevent duplicate joysticks
1 parent a864082 commit c9c9455

File tree

1 file changed

+38
-15
lines changed

1 file changed

+38
-15
lines changed

src/macosx/hidjoy.m

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -303,12 +303,20 @@ static void add_joystick_device(IOHIDDeviceRef ref, bool emit_reconfigure_event)
303303
al_lock_mutex(add_mutex);
304304

305305
ALLEGRO_JOYSTICK_OSX *joy = find_joystick(ref);
306+
307+
if (joy && (joy->cfg_state == JOY_STATE_BORN || joy->cfg_state == JOY_STATE_ALIVE))
308+
{
309+
al_unlock_mutex(add_mutex);
310+
return;
311+
}
312+
306313
if (joy == NULL) {
307314
joy = al_calloc(1, sizeof(ALLEGRO_JOYSTICK_OSX));
308315
joy->ident = ref;
309316
ALLEGRO_JOYSTICK_OSX **back = _al_vector_alloc_back(&joysticks);
310317
*back = joy;
311318
}
319+
312320
joy->cfg_state = new_joystick_state;
313321

314322
CFArrayRef elements = IOHIDDeviceCopyMatchingElements(
@@ -329,6 +337,34 @@ static void add_joystick_device(IOHIDDeviceRef ref, bool emit_reconfigure_event)
329337
joy->parent.info.num_buttons, joy->parent.info.num_sticks);
330338
}
331339

340+
static int enumerate_and_create_initial_joystick_devices(IOHIDManagerRef manager)
341+
{
342+
int i;
343+
int num_joysticks_enumerated = 0;
344+
345+
CFSetRef devices = IOHIDManagerCopyDevices(manager);
346+
if (devices == NULL)
347+
{
348+
// There are no devices to enumerate
349+
}
350+
else
351+
{
352+
CFIndex num_devices = CFSetGetCount(devices);
353+
IOHIDDeviceRef *device_arr = calloc(num_devices, sizeof(IOHIDDeviceRef));
354+
CFSetGetValues(devices, (const void **) device_arr);
355+
356+
for (i = 0; i < num_devices; i++) {
357+
IOHIDDeviceRef dev = device_arr[i];
358+
add_joystick_device(dev, false);
359+
num_joysticks_enumerated++;
360+
}
361+
}
362+
363+
CFRelease(devices);
364+
365+
return num_joysticks_enumerated;
366+
}
367+
332368
static void device_add_callback(
333369
void *context,
334370
IOReturn result,
@@ -586,21 +622,8 @@ static bool init_joystick(void)
586622
return false;
587623
}
588624

589-
// Wait for the devices to be enumerated
590-
int count;
591-
int size;
592-
do {
593-
al_rest(0.001);
594-
CFSetRef devices = IOHIDManagerCopyDevices(hidManagerRef);
595-
if (devices == nil) {
596-
break;
597-
}
598-
count = CFSetGetCount(devices);
599-
CFRelease(devices);
600-
al_lock_mutex(add_mutex);
601-
size = _al_vector_size(&joysticks);
602-
al_unlock_mutex(add_mutex);
603-
} while (size < count);
625+
int num_joysticks_created = enumerate_and_create_initial_joystick_devices(hidManagerRef);
626+
if (num_joysticks_created > 0) osx_joy_generate_configure_event();
604627

605628
new_joystick_state = JOY_STATE_BORN;
606629

0 commit comments

Comments
 (0)