cocoa_joystick.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //========================================================================
  2. // GLFW 3.4 Cocoa - www.glfw.org
  3. //------------------------------------------------------------------------
  4. // Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org>
  5. // Copyright (c) 2012 Torsten Walluhn <tw@mad-cad.net>
  6. //
  7. // This software is provided 'as-is', without any express or implied
  8. // warranty. In no event will the authors be held liable for any damages
  9. // arising from the use of this software.
  10. //
  11. // Permission is granted to anyone to use this software for any purpose,
  12. // including commercial applications, and to alter it and redistribute it
  13. // freely, subject to the following restrictions:
  14. //
  15. // 1. The origin of this software must not be misrepresented; you must not
  16. // claim that you wrote the original software. If you use this software
  17. // in a product, an acknowledgment in the product documentation would
  18. // be appreciated but is not required.
  19. //
  20. // 2. Altered source versions must be plainly marked as such, and must not
  21. // be misrepresented as being the original software.
  22. //
  23. // 3. This notice may not be removed or altered from any source
  24. // distribution.
  25. //
  26. //========================================================================
  27. // It is fine to use C99 in this file because it will not be built with VS
  28. //========================================================================
  29. #include "internal.h"
  30. #include <unistd.h>
  31. #include <ctype.h>
  32. #include <string.h>
  33. #include <mach/mach.h>
  34. #include <mach/mach_error.h>
  35. #include <CoreFoundation/CoreFoundation.h>
  36. #include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
  37. // Joystick element information
  38. //
  39. typedef struct _GLFWjoyelementNS
  40. {
  41. IOHIDElementRef native;
  42. uint32_t usage;
  43. int index;
  44. long minimum;
  45. long maximum;
  46. } _GLFWjoyelementNS;
  47. // Returns the value of the specified element of the specified joystick
  48. //
  49. static long getElementValue(_GLFWjoystick* js, _GLFWjoyelementNS* element)
  50. {
  51. IOHIDValueRef valueRef;
  52. long value = 0;
  53. if (js->ns.device)
  54. {
  55. if (IOHIDDeviceGetValue(js->ns.device,
  56. element->native,
  57. &valueRef) == kIOReturnSuccess)
  58. {
  59. value = IOHIDValueGetIntegerValue(valueRef);
  60. }
  61. }
  62. return value;
  63. }
  64. // Comparison function for matching the SDL element order
  65. //
  66. static CFComparisonResult compareElements(const void* fp,
  67. const void* sp,
  68. void* user UNUSED)
  69. {
  70. const _GLFWjoyelementNS* fe = fp;
  71. const _GLFWjoyelementNS* se = sp;
  72. if (fe->usage < se->usage)
  73. return kCFCompareLessThan;
  74. if (fe->usage > se->usage)
  75. return kCFCompareGreaterThan;
  76. if (fe->index < se->index)
  77. return kCFCompareLessThan;
  78. if (fe->index > se->index)
  79. return kCFCompareGreaterThan;
  80. return kCFCompareEqualTo;
  81. }
  82. // Removes the specified joystick
  83. //
  84. static void closeJoystick(_GLFWjoystick* js)
  85. {
  86. int i;
  87. if (!js->present)
  88. return;
  89. for (i = 0; i < CFArrayGetCount(js->ns.axes); i++)
  90. free((void*) CFArrayGetValueAtIndex(js->ns.axes, i));
  91. CFRelease(js->ns.axes);
  92. for (i = 0; i < CFArrayGetCount(js->ns.buttons); i++)
  93. free((void*) CFArrayGetValueAtIndex(js->ns.buttons, i));
  94. CFRelease(js->ns.buttons);
  95. for (i = 0; i < CFArrayGetCount(js->ns.hats); i++)
  96. free((void*) CFArrayGetValueAtIndex(js->ns.hats, i));
  97. CFRelease(js->ns.hats);
  98. _glfwFreeJoystick(js);
  99. _glfwInputJoystick(js, GLFW_DISCONNECTED);
  100. }
  101. // Callback for user-initiated joystick addition
  102. //
  103. static void matchCallback(void* context UNUSED,
  104. IOReturn result UNUSED,
  105. void* sender UNUSED,
  106. IOHIDDeviceRef device)
  107. {
  108. int jid;
  109. char name[256];
  110. char guid[33];
  111. CFIndex i;
  112. CFTypeRef property;
  113. uint32_t vendor = 0, product = 0, version = 0;
  114. _GLFWjoystick* js;
  115. CFMutableArrayRef axes, buttons, hats;
  116. for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++)
  117. {
  118. if (_glfw.joysticks[jid].ns.device == device)
  119. return;
  120. }
  121. axes = CFArrayCreateMutable(NULL, 0, NULL);
  122. buttons = CFArrayCreateMutable(NULL, 0, NULL);
  123. hats = CFArrayCreateMutable(NULL, 0, NULL);
  124. property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey));
  125. if (property)
  126. {
  127. CFStringGetCString(property,
  128. name,
  129. sizeof(name),
  130. kCFStringEncodingUTF8);
  131. }
  132. else
  133. strncpy(name, "Unknown", sizeof(name));
  134. property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVendorIDKey));
  135. if (property)
  136. CFNumberGetValue(property, kCFNumberSInt32Type, &vendor);
  137. property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductIDKey));
  138. if (property)
  139. CFNumberGetValue(property, kCFNumberSInt32Type, &product);
  140. property = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVersionNumberKey));
  141. if (property)
  142. CFNumberGetValue(property, kCFNumberSInt32Type, &version);
  143. // Generate a joystick GUID that matches the SDL 2.0.5+ one
  144. if (vendor && product)
  145. {
  146. snprintf(guid, sizeof(guid), "03000000%02x%02x0000%02x%02x0000%02x%02x0000",
  147. (uint8_t) vendor, (uint8_t) (vendor >> 8),
  148. (uint8_t) product, (uint8_t) (product >> 8),
  149. (uint8_t) version, (uint8_t) (version >> 8));
  150. }
  151. else
  152. {
  153. snprintf(guid, sizeof(guid), "05000000%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x00",
  154. name[0], name[1], name[2], name[3],
  155. name[4], name[5], name[6], name[7],
  156. name[8], name[9], name[10]);
  157. }
  158. CFArrayRef elements =
  159. IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone);
  160. for (i = 0; i < CFArrayGetCount(elements); i++)
  161. {
  162. IOHIDElementRef native = (IOHIDElementRef)
  163. CFArrayGetValueAtIndex(elements, i);
  164. if (CFGetTypeID(native) != IOHIDElementGetTypeID())
  165. continue;
  166. const IOHIDElementType type = IOHIDElementGetType(native);
  167. if ((type != kIOHIDElementTypeInput_Axis) &&
  168. (type != kIOHIDElementTypeInput_Button) &&
  169. (type != kIOHIDElementTypeInput_Misc))
  170. {
  171. continue;
  172. }
  173. CFMutableArrayRef target = NULL;
  174. const uint32_t usage = IOHIDElementGetUsage(native);
  175. const uint32_t page = IOHIDElementGetUsagePage(native);
  176. if (page == kHIDPage_GenericDesktop)
  177. {
  178. switch (usage)
  179. {
  180. case kHIDUsage_GD_X:
  181. case kHIDUsage_GD_Y:
  182. case kHIDUsage_GD_Z:
  183. case kHIDUsage_GD_Rx:
  184. case kHIDUsage_GD_Ry:
  185. case kHIDUsage_GD_Rz:
  186. case kHIDUsage_GD_Slider:
  187. case kHIDUsage_GD_Dial:
  188. case kHIDUsage_GD_Wheel:
  189. target = axes;
  190. break;
  191. case kHIDUsage_GD_Hatswitch:
  192. target = hats;
  193. break;
  194. case kHIDUsage_GD_DPadUp:
  195. case kHIDUsage_GD_DPadRight:
  196. case kHIDUsage_GD_DPadDown:
  197. case kHIDUsage_GD_DPadLeft:
  198. case kHIDUsage_GD_SystemMainMenu:
  199. case kHIDUsage_GD_Select:
  200. case kHIDUsage_GD_Start:
  201. target = buttons;
  202. break;
  203. }
  204. }
  205. else if (page == kHIDPage_Simulation)
  206. {
  207. switch (usage)
  208. {
  209. case kHIDUsage_Sim_Accelerator:
  210. case kHIDUsage_Sim_Brake:
  211. case kHIDUsage_Sim_Throttle:
  212. case kHIDUsage_Sim_Rudder:
  213. case kHIDUsage_Sim_Steering:
  214. target = axes;
  215. break;
  216. }
  217. }
  218. else if (page == kHIDPage_Button || page == kHIDPage_Consumer)
  219. target = buttons;
  220. if (target)
  221. {
  222. _GLFWjoyelementNS* element = calloc(1, sizeof(_GLFWjoyelementNS));
  223. element->native = native;
  224. element->usage = usage;
  225. element->index = (int) CFArrayGetCount(target);
  226. element->minimum = IOHIDElementGetLogicalMin(native);
  227. element->maximum = IOHIDElementGetLogicalMax(native);
  228. CFArrayAppendValue(target, element);
  229. }
  230. }
  231. CFRelease(elements);
  232. CFArraySortValues(axes, CFRangeMake(0, CFArrayGetCount(axes)),
  233. compareElements, NULL);
  234. CFArraySortValues(buttons, CFRangeMake(0, CFArrayGetCount(buttons)),
  235. compareElements, NULL);
  236. CFArraySortValues(hats, CFRangeMake(0, CFArrayGetCount(hats)),
  237. compareElements, NULL);
  238. js = _glfwAllocJoystick(name, guid,
  239. (int) CFArrayGetCount(axes),
  240. (int) CFArrayGetCount(buttons),
  241. (int) CFArrayGetCount(hats));
  242. js->ns.device = device;
  243. js->ns.axes = axes;
  244. js->ns.buttons = buttons;
  245. js->ns.hats = hats;
  246. _glfwInputJoystick(js, GLFW_CONNECTED);
  247. }
  248. // Callback for user-initiated joystick removal
  249. //
  250. static void removeCallback(void* context UNUSED,
  251. IOReturn result UNUSED,
  252. void* sender UNUSED,
  253. IOHIDDeviceRef device)
  254. {
  255. int jid;
  256. for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++)
  257. {
  258. if (_glfw.joysticks[jid].ns.device == device)
  259. {
  260. closeJoystick(_glfw.joysticks + jid);
  261. break;
  262. }
  263. }
  264. }
  265. //////////////////////////////////////////////////////////////////////////
  266. ////// GLFW platform API //////
  267. //////////////////////////////////////////////////////////////////////////
  268. bool _glfwPlatformInitJoysticks(void)
  269. {
  270. CFMutableArrayRef matching;
  271. const long usages[] =
  272. {
  273. kHIDUsage_GD_Joystick,
  274. kHIDUsage_GD_GamePad,
  275. kHIDUsage_GD_MultiAxisController
  276. };
  277. _glfw.ns.hidManager = IOHIDManagerCreate(kCFAllocatorDefault,
  278. kIOHIDOptionsTypeNone);
  279. matching = CFArrayCreateMutable(kCFAllocatorDefault,
  280. 0,
  281. &kCFTypeArrayCallBacks);
  282. if (!matching)
  283. {
  284. _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to create array");
  285. return false;
  286. }
  287. for (size_t i = 0; i < sizeof(usages) / sizeof(long); i++)
  288. {
  289. const long page = kHIDPage_GenericDesktop;
  290. CFMutableDictionaryRef dict =
  291. CFDictionaryCreateMutable(kCFAllocatorDefault,
  292. 0,
  293. &kCFTypeDictionaryKeyCallBacks,
  294. &kCFTypeDictionaryValueCallBacks);
  295. if (!dict)
  296. continue;
  297. CFNumberRef pageRef = CFNumberCreate(kCFAllocatorDefault,
  298. kCFNumberLongType,
  299. &page);
  300. CFNumberRef usageRef = CFNumberCreate(kCFAllocatorDefault,
  301. kCFNumberLongType,
  302. &usages[i]);
  303. if (pageRef && usageRef)
  304. {
  305. CFDictionarySetValue(dict,
  306. CFSTR(kIOHIDDeviceUsagePageKey),
  307. pageRef);
  308. CFDictionarySetValue(dict,
  309. CFSTR(kIOHIDDeviceUsageKey),
  310. usageRef);
  311. CFArrayAppendValue(matching, dict);
  312. }
  313. if (pageRef)
  314. CFRelease(pageRef);
  315. if (usageRef)
  316. CFRelease(usageRef);
  317. CFRelease(dict);
  318. }
  319. IOHIDManagerSetDeviceMatchingMultiple(_glfw.ns.hidManager, matching);
  320. CFRelease(matching);
  321. IOHIDManagerRegisterDeviceMatchingCallback(_glfw.ns.hidManager,
  322. &matchCallback, NULL);
  323. IOHIDManagerRegisterDeviceRemovalCallback(_glfw.ns.hidManager,
  324. &removeCallback, NULL);
  325. IOHIDManagerScheduleWithRunLoop(_glfw.ns.hidManager,
  326. CFRunLoopGetMain(),
  327. kCFRunLoopDefaultMode);
  328. IOHIDManagerOpen(_glfw.ns.hidManager, kIOHIDOptionsTypeNone);
  329. // Execute the run loop once in order to register any initially-attached
  330. // joysticks
  331. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, false);
  332. return true;
  333. }
  334. void _glfwPlatformTerminateJoysticks(void)
  335. {
  336. int jid;
  337. for (jid = 0; jid <= GLFW_JOYSTICK_LAST; jid++)
  338. closeJoystick(_glfw.joysticks + jid);
  339. if (_glfw.ns.hidManager)
  340. {
  341. CFRelease(_glfw.ns.hidManager);
  342. _glfw.ns.hidManager = NULL;
  343. }
  344. }
  345. int _glfwPlatformPollJoystick(_GLFWjoystick* js, int mode)
  346. {
  347. if (mode & _GLFW_POLL_AXES)
  348. {
  349. CFIndex i;
  350. for (i = 0; i < CFArrayGetCount(js->ns.axes); i++)
  351. {
  352. _GLFWjoyelementNS* axis = (_GLFWjoyelementNS*)
  353. CFArrayGetValueAtIndex(js->ns.axes, i);
  354. const long raw = getElementValue(js, axis);
  355. // Perform auto calibration
  356. if (raw < axis->minimum)
  357. axis->minimum = raw;
  358. if (raw > axis->maximum)
  359. axis->maximum = raw;
  360. const long size = axis->maximum - axis->minimum;
  361. if (size == 0)
  362. _glfwInputJoystickAxis(js, (int) i, 0.f);
  363. else
  364. {
  365. const float value = (2.f * (raw - axis->minimum) / size) - 1.f;
  366. _glfwInputJoystickAxis(js, (int) i, value);
  367. }
  368. }
  369. }
  370. if (mode & _GLFW_POLL_BUTTONS)
  371. {
  372. CFIndex i;
  373. for (i = 0; i < CFArrayGetCount(js->ns.buttons); i++)
  374. {
  375. _GLFWjoyelementNS* button = (_GLFWjoyelementNS*)
  376. CFArrayGetValueAtIndex(js->ns.buttons, i);
  377. const char value = getElementValue(js, button) - button->minimum;
  378. const int state = (value > 0) ? GLFW_PRESS : GLFW_RELEASE;
  379. _glfwInputJoystickButton(js, (int) i, state);
  380. }
  381. for (i = 0; i < CFArrayGetCount(js->ns.hats); i++)
  382. {
  383. const int states[9] =
  384. {
  385. GLFW_HAT_UP,
  386. GLFW_HAT_RIGHT_UP,
  387. GLFW_HAT_RIGHT,
  388. GLFW_HAT_RIGHT_DOWN,
  389. GLFW_HAT_DOWN,
  390. GLFW_HAT_LEFT_DOWN,
  391. GLFW_HAT_LEFT,
  392. GLFW_HAT_LEFT_UP,
  393. GLFW_HAT_CENTERED
  394. };
  395. _GLFWjoyelementNS* hat = (_GLFWjoyelementNS*)
  396. CFArrayGetValueAtIndex(js->ns.hats, i);
  397. long state = getElementValue(js, hat) - hat->minimum;
  398. if (state < 0 || state > 8)
  399. state = 8;
  400. _glfwInputJoystickHat(js, (int) i, states[state]);
  401. }
  402. }
  403. return js->present;
  404. }
  405. void _glfwPlatformUpdateGamepadGUID(char* guid)
  406. {
  407. if ((strncmp(guid + 4, "000000000000", 12) == 0) &&
  408. (strncmp(guid + 20, "000000000000", 12) == 0))
  409. {
  410. char original[33];
  411. strncpy(original, guid, sizeof(original) - 1);
  412. snprintf(guid, 33, "03000000%.4s0000%.4s000000000000",
  413. original, original + 16);
  414. }
  415. }