joypad_macos.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /**************************************************************************/
  2. /* joypad_macos.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "joypad_macos.h"
  31. #include <machine/endian.h>
  32. #define GODOT_JOY_LOOP_RUN_MODE CFSTR("GodotJoypad")
  33. static JoypadMacOS *self = nullptr;
  34. joypad::joypad() {
  35. ff_constant_force.lMagnitude = 10000;
  36. ff_effect.dwDuration = 0;
  37. ff_effect.dwSamplePeriod = 0;
  38. ff_effect.dwGain = 10000;
  39. ff_effect.dwFlags = FFEFF_OBJECTOFFSETS;
  40. ff_effect.dwTriggerButton = FFEB_NOTRIGGER;
  41. ff_effect.dwStartDelay = 0;
  42. ff_effect.dwTriggerRepeatInterval = 0;
  43. ff_effect.lpEnvelope = nullptr;
  44. ff_effect.cbTypeSpecificParams = sizeof(FFCONSTANTFORCE);
  45. ff_effect.lpvTypeSpecificParams = &ff_constant_force;
  46. ff_effect.dwSize = sizeof(ff_effect);
  47. }
  48. void joypad::free() {
  49. if (device_ref) {
  50. IOHIDDeviceUnscheduleFromRunLoop(device_ref, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
  51. }
  52. if (ff_device) {
  53. FFDeviceReleaseEffect(ff_device, ff_object);
  54. FFReleaseDevice(ff_device);
  55. ff_device = nullptr;
  56. memfree(ff_axes);
  57. memfree(ff_directions);
  58. }
  59. }
  60. bool joypad::has_element(IOHIDElementCookie p_cookie, Vector<rec_element> *p_list) const {
  61. for (int i = 0; i < p_list->size(); i++) {
  62. if (p_cookie == p_list->get(i).cookie) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. int joypad::get_hid_element_state(rec_element *p_element) const {
  69. int value = 0;
  70. if (p_element && p_element->ref) {
  71. IOHIDValueRef valueRef;
  72. if (IOHIDDeviceGetValue(device_ref, p_element->ref, &valueRef) == kIOReturnSuccess) {
  73. value = (SInt32)IOHIDValueGetIntegerValue(valueRef);
  74. // Record min and max for auto calibration.
  75. if (value < p_element->min) {
  76. p_element->min = value;
  77. }
  78. if (value > p_element->max) {
  79. p_element->max = value;
  80. }
  81. }
  82. }
  83. return value;
  84. }
  85. void joypad::add_hid_element(IOHIDElementRef p_element) {
  86. const CFTypeID elementTypeID = p_element ? CFGetTypeID(p_element) : 0;
  87. if (p_element && (elementTypeID == IOHIDElementGetTypeID())) {
  88. const IOHIDElementCookie cookie = IOHIDElementGetCookie(p_element);
  89. const uint32_t usagePage = IOHIDElementGetUsagePage(p_element);
  90. const uint32_t usage = IOHIDElementGetUsage(p_element);
  91. Vector<rec_element> *list = nullptr;
  92. switch (IOHIDElementGetType(p_element)) {
  93. case kIOHIDElementTypeInput_Misc:
  94. case kIOHIDElementTypeInput_Button:
  95. case kIOHIDElementTypeInput_Axis: {
  96. switch (usagePage) {
  97. case kHIDPage_GenericDesktop:
  98. switch (usage) {
  99. case kHIDUsage_GD_X:
  100. case kHIDUsage_GD_Y:
  101. case kHIDUsage_GD_Z:
  102. case kHIDUsage_GD_Rx:
  103. case kHIDUsage_GD_Ry:
  104. case kHIDUsage_GD_Rz:
  105. case kHIDUsage_GD_Slider:
  106. case kHIDUsage_GD_Dial:
  107. case kHIDUsage_GD_Wheel:
  108. if (!has_element(cookie, &axis_elements)) {
  109. list = &axis_elements;
  110. }
  111. break;
  112. case kHIDUsage_GD_Hatswitch:
  113. if (!has_element(cookie, &hat_elements)) {
  114. list = &hat_elements;
  115. }
  116. break;
  117. case kHIDUsage_GD_DPadUp:
  118. case kHIDUsage_GD_DPadDown:
  119. case kHIDUsage_GD_DPadRight:
  120. case kHIDUsage_GD_DPadLeft:
  121. case kHIDUsage_GD_Start:
  122. case kHIDUsage_GD_Select:
  123. if (!has_element(cookie, &button_elements)) {
  124. list = &button_elements;
  125. }
  126. break;
  127. }
  128. break;
  129. case kHIDPage_Simulation:
  130. switch (usage) {
  131. case kHIDUsage_Sim_Rudder:
  132. case kHIDUsage_Sim_Throttle:
  133. case kHIDUsage_Sim_Accelerator:
  134. case kHIDUsage_Sim_Brake:
  135. if (!has_element(cookie, &axis_elements)) {
  136. list = &axis_elements;
  137. }
  138. break;
  139. default:
  140. break;
  141. }
  142. break;
  143. case kHIDPage_Button:
  144. case kHIDPage_Consumer:
  145. if (!has_element(cookie, &button_elements)) {
  146. list = &button_elements;
  147. }
  148. break;
  149. default:
  150. break;
  151. }
  152. } break;
  153. case kIOHIDElementTypeCollection: {
  154. CFArrayRef array = IOHIDElementGetChildren(p_element);
  155. if (array) {
  156. add_hid_elements(array);
  157. }
  158. } break;
  159. default:
  160. break;
  161. }
  162. if (list) { // Add to list.
  163. rec_element element;
  164. element.ref = p_element;
  165. element.usage = usage;
  166. element.min = (SInt32)IOHIDElementGetLogicalMin(p_element);
  167. element.max = (SInt32)IOHIDElementGetLogicalMax(p_element);
  168. element.cookie = IOHIDElementGetCookie(p_element);
  169. list->push_back(element);
  170. list->sort_custom<rec_element::Comparator>();
  171. }
  172. }
  173. }
  174. static void hid_element_added(const void *p_value, void *p_parameter) {
  175. joypad *joy = static_cast<joypad *>(p_parameter);
  176. joy->add_hid_element((IOHIDElementRef)p_value);
  177. }
  178. void joypad::add_hid_elements(CFArrayRef p_array) {
  179. CFRange range = { 0, CFArrayGetCount(p_array) };
  180. CFArrayApplyFunction(p_array, range, hid_element_added, this);
  181. }
  182. static void joypad_removed_callback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) {
  183. self->_device_removed(res, ioHIDDeviceObject);
  184. }
  185. static void joypad_added_callback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) {
  186. self->_device_added(res, ioHIDDeviceObject);
  187. }
  188. static bool is_joypad(IOHIDDeviceRef p_device_ref) {
  189. int usage_page = 0;
  190. int usage = 0;
  191. CFTypeRef refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDPrimaryUsagePageKey));
  192. if (refCF) {
  193. CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &usage_page);
  194. }
  195. if (usage_page != kHIDPage_GenericDesktop) {
  196. return false;
  197. }
  198. refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDPrimaryUsageKey));
  199. if (refCF) {
  200. CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &usage);
  201. }
  202. if ((usage != kHIDUsage_GD_Joystick &&
  203. usage != kHIDUsage_GD_GamePad &&
  204. usage != kHIDUsage_GD_MultiAxisController)) {
  205. return false;
  206. }
  207. return true;
  208. }
  209. void JoypadMacOS::_device_added(IOReturn p_res, IOHIDDeviceRef p_device) {
  210. if (p_res != kIOReturnSuccess || have_device(p_device)) {
  211. return;
  212. }
  213. joypad new_joypad;
  214. if (is_joypad(p_device)) {
  215. configure_joypad(p_device, &new_joypad);
  216. #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
  217. if (IOHIDDeviceGetService) {
  218. #endif
  219. const io_service_t ioservice = IOHIDDeviceGetService(p_device);
  220. if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK) && new_joypad.config_force_feedback(ioservice)) {
  221. new_joypad.ffservice = ioservice;
  222. }
  223. #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
  224. }
  225. #endif
  226. device_list.push_back(new_joypad);
  227. }
  228. IOHIDDeviceScheduleWithRunLoop(p_device, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
  229. }
  230. void JoypadMacOS::_device_removed(IOReturn p_res, IOHIDDeviceRef p_device) {
  231. int device = get_joy_ref(p_device);
  232. ERR_FAIL_COND(device == -1);
  233. input->joy_connection_changed(device_list[device].id, false, "");
  234. device_list.write[device].free();
  235. device_list.remove_at(device);
  236. }
  237. static String _hex_str(uint8_t p_byte) {
  238. static const char *dict = "0123456789abcdef";
  239. char ret[3];
  240. ret[2] = 0;
  241. ret[0] = dict[p_byte >> 4];
  242. ret[1] = dict[p_byte & 0xF];
  243. return ret;
  244. }
  245. bool JoypadMacOS::configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy) {
  246. p_joy->device_ref = p_device_ref;
  247. // Get device name.
  248. String name;
  249. char c_name[256];
  250. CFTypeRef refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDProductKey));
  251. if (!refCF) {
  252. refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDManufacturerKey));
  253. }
  254. if ((!refCF) || (!CFStringGetCString((CFStringRef)refCF, c_name, sizeof(c_name), kCFStringEncodingUTF8))) {
  255. name = "Unidentified Joypad";
  256. } else {
  257. name = c_name;
  258. }
  259. int id = input->get_unused_joy_id();
  260. ERR_FAIL_COND_V(id == -1, false);
  261. p_joy->id = id;
  262. int vendor = 0;
  263. refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDVendorIDKey));
  264. if (refCF) {
  265. CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &vendor);
  266. }
  267. int product_id = 0;
  268. refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDProductIDKey));
  269. if (refCF) {
  270. CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &product_id);
  271. }
  272. int version = 0;
  273. refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDVersionNumberKey));
  274. if (refCF) {
  275. CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &version);
  276. }
  277. if (vendor && product_id) {
  278. char uid[128];
  279. snprintf(uid, 128, "%08x%08x%08x%08x", OSSwapHostToBigInt32(3), OSSwapHostToBigInt32(vendor), OSSwapHostToBigInt32(product_id), OSSwapHostToBigInt32(version));
  280. input->joy_connection_changed(id, true, name, uid);
  281. } else {
  282. // Bluetooth device.
  283. String guid = "05000000";
  284. for (int i = 0; i < 12; i++) {
  285. if (i < name.size()) {
  286. guid += _hex_str(name[i]);
  287. } else {
  288. guid += "00";
  289. }
  290. }
  291. input->joy_connection_changed(id, true, name, guid);
  292. }
  293. CFArrayRef array = IOHIDDeviceCopyMatchingElements(p_device_ref, nullptr, kIOHIDOptionsTypeNone);
  294. if (array) {
  295. p_joy->add_hid_elements(array);
  296. CFRelease(array);
  297. }
  298. // Xbox controller hat values start at 1 rather than 0.
  299. p_joy->offset_hat = vendor == 0x45e &&
  300. (product_id == 0x0b05 ||
  301. product_id == 0x02e0 ||
  302. product_id == 0x02fd ||
  303. product_id == 0x0b13);
  304. return true;
  305. }
  306. #define FF_ERR() \
  307. { \
  308. if (ret != FF_OK) { \
  309. FFReleaseDevice(ff_device); \
  310. ff_device = nullptr; \
  311. return false; \
  312. } \
  313. }
  314. bool joypad::config_force_feedback(io_service_t p_service) {
  315. HRESULT ret = FFCreateDevice(p_service, &ff_device);
  316. ERR_FAIL_COND_V(ret != FF_OK, false);
  317. ret = FFDeviceSendForceFeedbackCommand(ff_device, FFSFFC_RESET);
  318. FF_ERR();
  319. ret = FFDeviceSendForceFeedbackCommand(ff_device, FFSFFC_SETACTUATORSON);
  320. FF_ERR();
  321. if (check_ff_features()) {
  322. ret = FFDeviceCreateEffect(ff_device, kFFEffectType_ConstantForce_ID, &ff_effect, &ff_object);
  323. FF_ERR();
  324. return true;
  325. }
  326. FFReleaseDevice(ff_device);
  327. ff_device = nullptr;
  328. return false;
  329. }
  330. #undef FF_ERR
  331. #define TEST_FF(ff) (features.supportedEffects & (ff))
  332. bool joypad::check_ff_features() {
  333. FFCAPABILITIES features;
  334. HRESULT ret = FFDeviceGetForceFeedbackCapabilities(ff_device, &features);
  335. if (ret == FF_OK && (features.supportedEffects & FFCAP_ET_CONSTANTFORCE)) {
  336. uint32_t val;
  337. ret = FFDeviceGetForceFeedbackProperty(ff_device, FFPROP_FFGAIN, &val, sizeof(val));
  338. if (ret != FF_OK) {
  339. return false;
  340. }
  341. int num_axes = features.numFfAxes;
  342. ff_axes = (DWORD *)memalloc(sizeof(DWORD) * num_axes);
  343. ff_directions = (LONG *)memalloc(sizeof(LONG) * num_axes);
  344. for (int i = 0; i < num_axes; i++) {
  345. ff_axes[i] = features.ffAxes[i];
  346. ff_directions[i] = 0;
  347. }
  348. ff_effect.cAxes = num_axes;
  349. ff_effect.rgdwAxes = ff_axes;
  350. ff_effect.rglDirection = ff_directions;
  351. return true;
  352. }
  353. return false;
  354. }
  355. static BitField<HatMask> process_hat_value(int p_min, int p_max, int p_value, bool p_offset_hat) {
  356. int range = (p_max - p_min + 1);
  357. int value = p_value - p_min;
  358. BitField<HatMask> hat_value;
  359. if (range == 4) {
  360. value *= 2;
  361. }
  362. if (p_offset_hat) {
  363. value -= 1;
  364. }
  365. switch (value) {
  366. case 0:
  367. hat_value.set_flag(HatMask::UP);
  368. break;
  369. case 1:
  370. hat_value.set_flag(HatMask::UP);
  371. hat_value.set_flag(HatMask::RIGHT);
  372. break;
  373. case 2:
  374. hat_value.set_flag(HatMask::RIGHT);
  375. break;
  376. case 3:
  377. hat_value.set_flag(HatMask::DOWN);
  378. hat_value.set_flag(HatMask::RIGHT);
  379. break;
  380. case 4:
  381. hat_value.set_flag(HatMask::DOWN);
  382. break;
  383. case 5:
  384. hat_value.set_flag(HatMask::DOWN);
  385. hat_value.set_flag(HatMask::LEFT);
  386. break;
  387. case 6:
  388. hat_value.set_flag(HatMask::LEFT);
  389. break;
  390. case 7:
  391. hat_value.set_flag(HatMask::UP);
  392. hat_value.set_flag(HatMask::LEFT);
  393. break;
  394. default:
  395. break;
  396. }
  397. return hat_value;
  398. }
  399. void JoypadMacOS::poll_joypads() const {
  400. while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
  401. // No-op. Pending callbacks will fire.
  402. }
  403. }
  404. static float axis_correct(int p_value, int p_min, int p_max) {
  405. // Convert to a value between -1.0f and 1.0f.
  406. return 2.0f * (p_value - p_min) / (p_max - p_min) - 1.0f;
  407. }
  408. void JoypadMacOS::process_joypads() {
  409. poll_joypads();
  410. for (int i = 0; i < device_list.size(); i++) {
  411. joypad &joy = device_list.write[i];
  412. for (int j = 0; j < joy.axis_elements.size(); j++) {
  413. rec_element &elem = joy.axis_elements.write[j];
  414. int value = joy.get_hid_element_state(&elem);
  415. input->joy_axis(joy.id, (JoyAxis)j, axis_correct(value, elem.min, elem.max));
  416. }
  417. for (int j = 0; j < joy.button_elements.size(); j++) {
  418. int value = joy.get_hid_element_state(&joy.button_elements.write[j]);
  419. input->joy_button(joy.id, (JoyButton)j, (value >= 1));
  420. }
  421. for (int j = 0; j < joy.hat_elements.size(); j++) {
  422. rec_element &elem = joy.hat_elements.write[j];
  423. int value = joy.get_hid_element_state(&elem);
  424. BitField<HatMask> hat_value = process_hat_value(elem.min, elem.max, value, joy.offset_hat);
  425. input->joy_hat(joy.id, hat_value);
  426. }
  427. if (joy.ffservice) {
  428. uint64_t timestamp = input->get_joy_vibration_timestamp(joy.id);
  429. if (timestamp > joy.ff_timestamp) {
  430. Vector2 strength = input->get_joy_vibration_strength(joy.id);
  431. float duration = input->get_joy_vibration_duration(joy.id);
  432. if (strength.x == 0 && strength.y == 0) {
  433. joypad_vibration_stop(joy.id, timestamp);
  434. } else {
  435. float gain = MAX(strength.x, strength.y);
  436. joypad_vibration_start(joy.id, gain, duration, timestamp);
  437. }
  438. }
  439. }
  440. }
  441. }
  442. void JoypadMacOS::joypad_vibration_start(int p_id, float p_magnitude, float p_duration, uint64_t p_timestamp) {
  443. joypad *joy = &device_list.write[get_joy_index(p_id)];
  444. joy->ff_timestamp = p_timestamp;
  445. joy->ff_effect.dwDuration = p_duration * FF_SECONDS;
  446. joy->ff_effect.dwGain = p_magnitude * FF_FFNOMINALMAX;
  447. FFEffectSetParameters(joy->ff_object, &joy->ff_effect, FFEP_DURATION | FFEP_GAIN);
  448. FFEffectStart(joy->ff_object, 1, 0);
  449. }
  450. void JoypadMacOS::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
  451. joypad *joy = &device_list.write[get_joy_index(p_id)];
  452. joy->ff_timestamp = p_timestamp;
  453. FFEffectStop(joy->ff_object);
  454. }
  455. int JoypadMacOS::get_joy_index(int p_id) const {
  456. for (int i = 0; i < device_list.size(); i++) {
  457. if (device_list[i].id == p_id) {
  458. return i;
  459. }
  460. }
  461. return -1;
  462. }
  463. int JoypadMacOS::get_joy_ref(IOHIDDeviceRef p_device) const {
  464. for (int i = 0; i < device_list.size(); i++) {
  465. if (device_list[i].device_ref == p_device) {
  466. return i;
  467. }
  468. }
  469. return -1;
  470. }
  471. bool JoypadMacOS::have_device(IOHIDDeviceRef p_device) const {
  472. for (int i = 0; i < device_list.size(); i++) {
  473. if (device_list[i].device_ref == p_device) {
  474. return true;
  475. }
  476. }
  477. return false;
  478. }
  479. static CFDictionaryRef create_match_dictionary(const UInt32 page, const UInt32 usage, int *okay) {
  480. CFDictionaryRef retval = nullptr;
  481. CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
  482. CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
  483. if (pageNumRef && usageNumRef) {
  484. const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) };
  485. const void *vals[2] = { (void *)pageNumRef, (void *)usageNumRef };
  486. retval = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  487. }
  488. if (pageNumRef) {
  489. CFRelease(pageNumRef);
  490. }
  491. if (usageNumRef) {
  492. CFRelease(usageNumRef);
  493. }
  494. if (!retval) {
  495. *okay = 0;
  496. }
  497. return retval;
  498. }
  499. void JoypadMacOS::config_hid_manager(CFArrayRef p_matching_array) const {
  500. CFRunLoopRef runloop = CFRunLoopGetCurrent();
  501. IOReturn ret = IOHIDManagerOpen(hid_manager, kIOHIDOptionsTypeNone);
  502. ERR_FAIL_COND(ret != kIOReturnSuccess);
  503. IOHIDManagerSetDeviceMatchingMultiple(hid_manager, p_matching_array);
  504. IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, joypad_added_callback, nullptr);
  505. IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, joypad_removed_callback, nullptr);
  506. IOHIDManagerScheduleWithRunLoop(hid_manager, runloop, GODOT_JOY_LOOP_RUN_MODE);
  507. while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
  508. // No-op. Callback fires once per existing device.
  509. }
  510. }
  511. JoypadMacOS::JoypadMacOS(Input *in) {
  512. self = this;
  513. input = in;
  514. int okay = 1;
  515. const void *vals[] = {
  516. (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick, &okay),
  517. (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad, &okay),
  518. (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay),
  519. };
  520. const size_t n_elements = sizeof(vals) / sizeof(vals[0]);
  521. CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, n_elements, &kCFTypeArrayCallBacks) : nullptr;
  522. for (size_t i = 0; i < n_elements; i++) {
  523. if (vals[i]) {
  524. CFRelease((CFTypeRef)vals[i]);
  525. }
  526. }
  527. if (array) {
  528. hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
  529. if (hid_manager) {
  530. config_hid_manager(array);
  531. }
  532. CFRelease(array);
  533. }
  534. }
  535. JoypadMacOS::~JoypadMacOS() {
  536. for (int i = 0; i < device_list.size(); i++) {
  537. device_list.write[i].free();
  538. }
  539. IOHIDManagerUnscheduleFromRunLoop(hid_manager, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
  540. IOHIDManagerClose(hid_manager, kIOHIDOptionsTypeNone);
  541. CFRelease(hid_manager);
  542. hid_manager = nullptr;
  543. }