SDL_mfijoystick.m 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. // This is the iOS implementation of the SDL joystick API
  20. #include "../SDL_sysjoystick.h"
  21. #include "../SDL_joystick_c.h"
  22. #include "../hidapi/SDL_hidapijoystick_c.h"
  23. #include "../usb_ids.h"
  24. #include "../../events/SDL_events_c.h"
  25. #ifdef SDL_VIDEO_DRIVER_UIKIT
  26. #include "../../video/uikit/SDL_uikitvideo.h"
  27. #endif
  28. #include "SDL_mfijoystick_c.h"
  29. #if defined(SDL_PLATFORM_IOS) && !defined(SDL_PLATFORM_TVOS)
  30. #import <CoreMotion/CoreMotion.h>
  31. #endif
  32. #ifdef SDL_PLATFORM_MACOS
  33. #include <IOKit/hid/IOHIDManager.h>
  34. #include <AppKit/NSApplication.h>
  35. #ifndef NSAppKitVersionNumber10_15
  36. #define NSAppKitVersionNumber10_15 1894
  37. #endif
  38. #endif // SDL_PLATFORM_MACOS
  39. #import <GameController/GameController.h>
  40. #ifdef SDL_JOYSTICK_MFI
  41. static id connectObserver = nil;
  42. static id disconnectObserver = nil;
  43. #include <objc/message.h>
  44. // Fix build errors when using an older SDK by defining these selectors
  45. @interface GCController (SDL)
  46. #if !((__IPHONE_OS_VERSION_MAX_ALLOWED >= 140500) || (__APPLETV_OS_VERSION_MAX_ALLOWED >= 140500) || (__MAC_OS_X_VERSION_MAX_ALLOWED >= 110300))
  47. @property(class, nonatomic, readwrite) BOOL shouldMonitorBackgroundEvents;
  48. #endif
  49. @end
  50. #import <CoreHaptics/CoreHaptics.h>
  51. #endif // SDL_JOYSTICK_MFI
  52. static SDL_JoystickDeviceItem *deviceList = NULL;
  53. static int numjoysticks = 0;
  54. int SDL_AppleTVRemoteOpenedAsJoystick = 0;
  55. static SDL_JoystickDeviceItem *GetDeviceForIndex(int device_index)
  56. {
  57. SDL_JoystickDeviceItem *device = deviceList;
  58. int i = 0;
  59. while (i < device_index) {
  60. if (device == NULL) {
  61. return NULL;
  62. }
  63. device = device->next;
  64. i++;
  65. }
  66. return device;
  67. }
  68. #ifdef SDL_JOYSTICK_MFI
  69. static bool IsControllerPS4(GCController *controller)
  70. {
  71. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  72. if ([controller.productCategory isEqualToString:@"DualShock 4"]) {
  73. return true;
  74. }
  75. } else {
  76. if ([controller.vendorName containsString:@"DUALSHOCK"]) {
  77. return true;
  78. }
  79. }
  80. return false;
  81. }
  82. static bool IsControllerPS5(GCController *controller)
  83. {
  84. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  85. if ([controller.productCategory isEqualToString:@"DualSense"]) {
  86. return true;
  87. }
  88. } else {
  89. if ([controller.vendorName containsString:@"DualSense"]) {
  90. return true;
  91. }
  92. }
  93. return false;
  94. }
  95. static bool IsControllerXbox(GCController *controller)
  96. {
  97. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  98. if ([controller.productCategory isEqualToString:@"Xbox One"]) {
  99. return true;
  100. }
  101. } else {
  102. if ([controller.vendorName containsString:@"Xbox"]) {
  103. return true;
  104. }
  105. }
  106. return false;
  107. }
  108. static bool IsControllerSwitchPro(GCController *controller)
  109. {
  110. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  111. if ([controller.productCategory isEqualToString:@"Switch Pro Controller"]) {
  112. return true;
  113. }
  114. }
  115. return false;
  116. }
  117. static bool IsControllerSwitchJoyConL(GCController *controller)
  118. {
  119. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  120. if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (L)"]) {
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. static bool IsControllerSwitchJoyConR(GCController *controller)
  127. {
  128. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  129. if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (R)"]) {
  130. return true;
  131. }
  132. }
  133. return false;
  134. }
  135. static bool IsControllerSwitchJoyConPair(GCController *controller)
  136. {
  137. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  138. if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (L/R)"]) {
  139. return true;
  140. }
  141. }
  142. return false;
  143. }
  144. static bool IsControllerStadia(GCController *controller)
  145. {
  146. if ([controller.vendorName hasPrefix:@"Stadia"]) {
  147. return true;
  148. }
  149. return false;
  150. }
  151. static bool IsControllerBackboneOne(GCController *controller)
  152. {
  153. if ([controller.vendorName hasPrefix:@"Backbone One"]) {
  154. return true;
  155. }
  156. return false;
  157. }
  158. static void CheckControllerSiriRemote(GCController *controller, int *is_siri_remote)
  159. {
  160. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  161. if ([controller.productCategory hasPrefix:@"Siri Remote"]) {
  162. *is_siri_remote = 1;
  163. SDL_sscanf(controller.productCategory.UTF8String, "Siri Remote (%i%*s Generation)", is_siri_remote);
  164. return;
  165. }
  166. }
  167. *is_siri_remote = 0;
  168. }
  169. static bool ElementAlreadyHandled(SDL_JoystickDeviceItem *device, NSString *element, NSDictionary<NSString *, GCControllerElement *> *elements)
  170. {
  171. if ([element isEqualToString:@"Left Thumbstick Left"] ||
  172. [element isEqualToString:@"Left Thumbstick Right"]) {
  173. if (elements[@"Left Thumbstick X Axis"]) {
  174. return true;
  175. }
  176. }
  177. if ([element isEqualToString:@"Left Thumbstick Up"] ||
  178. [element isEqualToString:@"Left Thumbstick Down"]) {
  179. if (elements[@"Left Thumbstick Y Axis"]) {
  180. return true;
  181. }
  182. }
  183. if ([element isEqualToString:@"Right Thumbstick Left"] ||
  184. [element isEqualToString:@"Right Thumbstick Right"]) {
  185. if (elements[@"Right Thumbstick X Axis"]) {
  186. return true;
  187. }
  188. }
  189. if ([element isEqualToString:@"Right Thumbstick Up"] ||
  190. [element isEqualToString:@"Right Thumbstick Down"]) {
  191. if (elements[@"Right Thumbstick Y Axis"]) {
  192. return true;
  193. }
  194. }
  195. if (device->is_siri_remote) {
  196. if ([element isEqualToString:@"Direction Pad Left"] ||
  197. [element isEqualToString:@"Direction Pad Right"]) {
  198. if (elements[@"Direction Pad X Axis"]) {
  199. return true;
  200. }
  201. }
  202. if ([element isEqualToString:@"Direction Pad Up"] ||
  203. [element isEqualToString:@"Direction Pad Down"]) {
  204. if (elements[@"Direction Pad Y Axis"]) {
  205. return true;
  206. }
  207. }
  208. } else {
  209. if ([element isEqualToString:@"Direction Pad X Axis"]) {
  210. if (elements[@"Direction Pad Left"] &&
  211. elements[@"Direction Pad Right"]) {
  212. return true;
  213. }
  214. }
  215. if ([element isEqualToString:@"Direction Pad Y Axis"]) {
  216. if (elements[@"Direction Pad Up"] &&
  217. elements[@"Direction Pad Down"]) {
  218. return true;
  219. }
  220. }
  221. }
  222. if ([element isEqualToString:@"Cardinal Direction Pad X Axis"]) {
  223. if (elements[@"Cardinal Direction Pad Left"] &&
  224. elements[@"Cardinal Direction Pad Right"]) {
  225. return true;
  226. }
  227. }
  228. if ([element isEqualToString:@"Cardinal Direction Pad Y Axis"]) {
  229. if (elements[@"Cardinal Direction Pad Up"] &&
  230. elements[@"Cardinal Direction Pad Down"]) {
  231. return true;
  232. }
  233. }
  234. if ([element isEqualToString:@"Touchpad 1 X Axis"] ||
  235. [element isEqualToString:@"Touchpad 1 Y Axis"] ||
  236. [element isEqualToString:@"Touchpad 1 Left"] ||
  237. [element isEqualToString:@"Touchpad 1 Right"] ||
  238. [element isEqualToString:@"Touchpad 1 Up"] ||
  239. [element isEqualToString:@"Touchpad 1 Down"] ||
  240. [element isEqualToString:@"Touchpad 2 X Axis"] ||
  241. [element isEqualToString:@"Touchpad 2 Y Axis"] ||
  242. [element isEqualToString:@"Touchpad 2 Left"] ||
  243. [element isEqualToString:@"Touchpad 2 Right"] ||
  244. [element isEqualToString:@"Touchpad 2 Up"] ||
  245. [element isEqualToString:@"Touchpad 2 Down"]) {
  246. // The touchpad is handled separately
  247. return true;
  248. }
  249. if ([element isEqualToString:@"Button Home"]) {
  250. if (device->is_switch_joycon_pair) {
  251. // The Nintendo Switch JoyCon home button doesn't ever show as being held down
  252. return true;
  253. }
  254. #ifdef SDL_PLATFORM_TVOS
  255. // The OS uses the home button, it's not available to apps
  256. return true;
  257. #endif
  258. }
  259. if ([element isEqualToString:@"Button Share"]) {
  260. if (device->is_backbone_one) {
  261. // The Backbone app uses share button
  262. return true;
  263. }
  264. }
  265. return false;
  266. }
  267. static bool IOS_AddMFIJoystickDevice(SDL_JoystickDeviceItem *device, GCController *controller)
  268. {
  269. Uint16 vendor = 0;
  270. Uint16 product = 0;
  271. Uint8 subtype = 0;
  272. const char *name = NULL;
  273. if (@available(macOS 11.3, iOS 14.5, tvOS 14.5, *)) {
  274. if (!GCController.shouldMonitorBackgroundEvents) {
  275. GCController.shouldMonitorBackgroundEvents = YES;
  276. }
  277. }
  278. /* Explicitly retain the controller because SDL_JoystickDeviceItem is a
  279. * struct, and ARC doesn't work with structs. */
  280. device->controller = (__bridge GCController *)CFBridgingRetain(controller);
  281. if (controller.vendorName) {
  282. name = controller.vendorName.UTF8String;
  283. }
  284. if (!name) {
  285. name = "MFi Gamepad";
  286. }
  287. device->name = SDL_CreateJoystickName(0, 0, NULL, name);
  288. #ifdef DEBUG_CONTROLLER_PROFILE
  289. NSLog(@"Product name: %@\n", controller.vendorName);
  290. NSLog(@"Product category: %@\n", controller.productCategory);
  291. NSLog(@"Elements available:\n");
  292. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  293. NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;
  294. for (id key in controller.physicalInputProfile.buttons) {
  295. NSLog(@"\tButton: %@ (%s)\n", key, elements[key].analog ? "analog" : "digital");
  296. }
  297. for (id key in controller.physicalInputProfile.axes) {
  298. NSLog(@"\tAxis: %@\n", key);
  299. }
  300. for (id key in controller.physicalInputProfile.dpads) {
  301. NSLog(@"\tHat: %@\n", key);
  302. }
  303. }
  304. #endif // DEBUG_CONTROLLER_PROFILE
  305. device->is_xbox = IsControllerXbox(controller);
  306. device->is_ps4 = IsControllerPS4(controller);
  307. device->is_ps5 = IsControllerPS5(controller);
  308. device->is_switch_pro = IsControllerSwitchPro(controller);
  309. device->is_switch_joycon_pair = IsControllerSwitchJoyConPair(controller);
  310. device->is_stadia = IsControllerStadia(controller);
  311. device->is_backbone_one = IsControllerBackboneOne(controller);
  312. device->is_switch_joyconL = IsControllerSwitchJoyConL(controller);
  313. device->is_switch_joyconR = IsControllerSwitchJoyConR(controller);
  314. #ifdef SDL_JOYSTICK_HIDAPI
  315. if ((device->is_xbox && (HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_XBOXONE) ||
  316. HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_XBOX360))) ||
  317. (device->is_ps4 && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_PS4)) ||
  318. (device->is_ps5 && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_PS5)) ||
  319. (device->is_switch_pro && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO)) ||
  320. (device->is_switch_joycon_pair && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR, 0, "")) ||
  321. (device->is_stadia && HIDAPI_IsDevicePresent(USB_VENDOR_GOOGLE, USB_PRODUCT_GOOGLE_STADIA_CONTROLLER, 0, "")) ||
  322. (device->is_switch_joyconL && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT, 0, "")) ||
  323. (device->is_switch_joyconR && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT, 0, "")) ||
  324. (SDL_strcmp(name, "8Bitdo SN30 Pro") == 0 && (HIDAPI_IsDevicePresent(USB_VENDOR_8BITDO, USB_PRODUCT_8BITDO_SN30_PRO, 0, "") || HIDAPI_IsDevicePresent(USB_VENDOR_8BITDO, USB_PRODUCT_8BITDO_SN30_PRO_BT, 0, ""))) ||
  325. (SDL_strcmp(name, "8BitDo Pro 2") == 0 && (HIDAPI_IsDevicePresent(USB_VENDOR_8BITDO, USB_PRODUCT_8BITDO_PRO_2, 0, "") || HIDAPI_IsDevicePresent(USB_VENDOR_8BITDO, USB_PRODUCT_8BITDO_PRO_2_BT, 0, "")))) {
  326. // The HIDAPI driver is taking care of this device
  327. return false;
  328. }
  329. #endif
  330. if (device->is_xbox && SDL_strncmp(name, "GamePad-", 8) == 0) {
  331. // This is a Steam Virtual Gamepad, which isn't supported by GCController
  332. return false;
  333. }
  334. CheckControllerSiriRemote(controller, &device->is_siri_remote);
  335. if (device->is_siri_remote && !SDL_GetHintBoolean(SDL_HINT_TV_REMOTE_AS_JOYSTICK, true)) {
  336. // Ignore remotes, they'll be handled as keyboard input
  337. return false;
  338. }
  339. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  340. if (controller.physicalInputProfile.buttons[GCInputDualShockTouchpadButton] != nil) {
  341. device->has_dualshock_touchpad = TRUE;
  342. }
  343. if (controller.physicalInputProfile.buttons[GCInputXboxPaddleOne] != nil) {
  344. device->has_xbox_paddles = TRUE;
  345. }
  346. if (controller.physicalInputProfile.buttons[@"Button Share"] != nil) {
  347. device->has_xbox_share_button = TRUE;
  348. }
  349. }
  350. if (device->is_backbone_one) {
  351. vendor = USB_VENDOR_BACKBONE;
  352. if (device->is_ps5) {
  353. product = USB_PRODUCT_BACKBONE_ONE_IOS_PS5;
  354. } else {
  355. product = USB_PRODUCT_BACKBONE_ONE_IOS;
  356. }
  357. } else if (device->is_xbox) {
  358. vendor = USB_VENDOR_MICROSOFT;
  359. if (device->has_xbox_paddles) {
  360. // Assume Xbox One Elite Series 2 Controller unless/until GCController flows VID/PID
  361. product = USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH;
  362. } else if (device->has_xbox_share_button) {
  363. // Assume Xbox Series X Controller unless/until GCController flows VID/PID
  364. product = USB_PRODUCT_XBOX_SERIES_X_BLE;
  365. } else {
  366. // Assume Xbox One S Bluetooth Controller unless/until GCController flows VID/PID
  367. product = USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH;
  368. }
  369. } else if (device->is_ps4) {
  370. // Assume DS4 Slim unless/until GCController flows VID/PID
  371. vendor = USB_VENDOR_SONY;
  372. product = USB_PRODUCT_SONY_DS4_SLIM;
  373. if (device->has_dualshock_touchpad) {
  374. subtype = 1;
  375. }
  376. } else if (device->is_ps5) {
  377. vendor = USB_VENDOR_SONY;
  378. product = USB_PRODUCT_SONY_DS5;
  379. } else if (device->is_switch_pro) {
  380. vendor = USB_VENDOR_NINTENDO;
  381. product = USB_PRODUCT_NINTENDO_SWITCH_PRO;
  382. device->has_nintendo_buttons = TRUE;
  383. } else if (device->is_switch_joycon_pair) {
  384. vendor = USB_VENDOR_NINTENDO;
  385. product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR;
  386. device->has_nintendo_buttons = TRUE;
  387. } else if (device->is_switch_joyconL) {
  388. vendor = USB_VENDOR_NINTENDO;
  389. product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT;
  390. } else if (device->is_switch_joyconR) {
  391. vendor = USB_VENDOR_NINTENDO;
  392. product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT;
  393. } else if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  394. vendor = USB_VENDOR_APPLE;
  395. product = 4;
  396. subtype = 4;
  397. } else if (controller.extendedGamepad) {
  398. vendor = USB_VENDOR_APPLE;
  399. product = 1;
  400. subtype = 1;
  401. #ifdef SDL_PLATFORM_TVOS
  402. } else if (controller.microGamepad) {
  403. vendor = USB_VENDOR_APPLE;
  404. product = 3;
  405. subtype = 3;
  406. #endif
  407. } else {
  408. // We don't know how to get input events from this device
  409. return false;
  410. }
  411. if (SDL_ShouldIgnoreJoystick(vendor, product, 0, name)) {
  412. return false;
  413. }
  414. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  415. NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;
  416. // Provide both axes and analog buttons as SDL axes
  417. NSArray *axes = [[[elements allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]
  418. filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
  419. if (ElementAlreadyHandled(device, (NSString *)object, elements)) {
  420. return false;
  421. }
  422. GCControllerElement *element = elements[object];
  423. if (element.analog) {
  424. if ([element isKindOfClass:[GCControllerAxisInput class]] ||
  425. [element isKindOfClass:[GCControllerButtonInput class]]) {
  426. return true;
  427. }
  428. }
  429. return false;
  430. }]];
  431. NSArray *buttons = [[[elements allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]
  432. filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
  433. if (ElementAlreadyHandled(device, (NSString *)object, elements)) {
  434. return false;
  435. }
  436. GCControllerElement *element = elements[object];
  437. if ([element isKindOfClass:[GCControllerButtonInput class]]) {
  438. return true;
  439. }
  440. return false;
  441. }]];
  442. /* Explicitly retain the arrays because SDL_JoystickDeviceItem is a
  443. * struct, and ARC doesn't work with structs. */
  444. device->naxes = (int)axes.count;
  445. device->axes = (__bridge NSArray *)CFBridgingRetain(axes);
  446. device->nbuttons = (int)buttons.count;
  447. device->buttons = (__bridge NSArray *)CFBridgingRetain(buttons);
  448. subtype = 4;
  449. #ifdef DEBUG_CONTROLLER_PROFILE
  450. NSLog(@"Elements used:\n", controller.vendorName);
  451. for (id key in device->buttons) {
  452. NSLog(@"\tButton: %@ (%s)\n", key, elements[key].analog ? "analog" : "digital");
  453. }
  454. for (id key in device->axes) {
  455. NSLog(@"\tAxis: %@\n", key);
  456. }
  457. #endif // DEBUG_CONTROLLER_PROFILE
  458. #ifdef SDL_PLATFORM_TVOS
  459. // tvOS turns the menu button into a system gesture, so we grab it here instead
  460. if (elements[GCInputButtonMenu] && !elements[@"Button Home"]) {
  461. device->pause_button_index = (int)[device->buttons indexOfObject:GCInputButtonMenu];
  462. }
  463. #endif
  464. } else if (controller.extendedGamepad) {
  465. GCExtendedGamepad *gamepad = controller.extendedGamepad;
  466. int nbuttons = 0;
  467. BOOL has_direct_menu = FALSE;
  468. // These buttons are part of the original MFi spec
  469. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_SOUTH);
  470. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_EAST);
  471. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_WEST);
  472. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_NORTH);
  473. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
  474. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
  475. nbuttons += 6;
  476. // These buttons are available on some newer controllers
  477. if (@available(macOS 10.14.1, iOS 12.1, tvOS 12.1, *)) {
  478. if (gamepad.leftThumbstickButton) {
  479. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK);
  480. ++nbuttons;
  481. }
  482. if (gamepad.rightThumbstickButton) {
  483. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK);
  484. ++nbuttons;
  485. }
  486. }
  487. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  488. if (gamepad.buttonOptions) {
  489. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_BACK);
  490. ++nbuttons;
  491. }
  492. }
  493. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_START);
  494. ++nbuttons;
  495. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  496. if (gamepad.buttonMenu) {
  497. has_direct_menu = TRUE;
  498. }
  499. }
  500. #ifdef SDL_PLATFORM_TVOS
  501. // The single menu button isn't very reliable, at least as of tvOS 16.1
  502. if ((device->button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) == 0) {
  503. has_direct_menu = FALSE;
  504. }
  505. #endif
  506. if (!has_direct_menu) {
  507. device->pause_button_index = (nbuttons - 1);
  508. }
  509. device->naxes = 6; // 2 thumbsticks and 2 triggers
  510. device->nhats = 1; // d-pad
  511. device->nbuttons = nbuttons;
  512. }
  513. #ifdef SDL_PLATFORM_TVOS
  514. else if (controller.microGamepad) {
  515. int nbuttons = 0;
  516. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_SOUTH);
  517. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_WEST); // Button X on microGamepad
  518. device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_EAST);
  519. nbuttons += 3;
  520. device->pause_button_index = (nbuttons - 1);
  521. device->naxes = 2; // treat the touch surface as two axes
  522. device->nhats = 0; // apparently the touch surface-as-dpad is buggy
  523. device->nbuttons = nbuttons;
  524. controller.microGamepad.allowsRotation = SDL_GetHintBoolean(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, false);
  525. }
  526. #endif
  527. else {
  528. // We don't know how to get input events from this device
  529. return false;
  530. }
  531. Uint16 signature;
  532. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  533. signature = 0;
  534. signature = SDL_crc16(signature, device->name, SDL_strlen(device->name));
  535. for (id key in device->axes) {
  536. const char *string = ((NSString *)key).UTF8String;
  537. signature = SDL_crc16(signature, string, SDL_strlen(string));
  538. }
  539. for (id key in device->buttons) {
  540. const char *string = ((NSString *)key).UTF8String;
  541. signature = SDL_crc16(signature, string, SDL_strlen(string));
  542. }
  543. } else {
  544. signature = device->button_mask;
  545. }
  546. device->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_BLUETOOTH, vendor, product, signature, NULL, name, 'm', subtype);
  547. /* This will be set when the first button press of the controller is
  548. * detected. */
  549. controller.playerIndex = -1;
  550. return true;
  551. }
  552. #endif // SDL_JOYSTICK_MFI
  553. #ifdef SDL_JOYSTICK_MFI
  554. static void IOS_AddJoystickDevice(GCController *controller)
  555. {
  556. SDL_JoystickDeviceItem *device = deviceList;
  557. while (device != NULL) {
  558. if (device->controller == controller) {
  559. return;
  560. }
  561. device = device->next;
  562. }
  563. device = (SDL_JoystickDeviceItem *)SDL_calloc(1, sizeof(SDL_JoystickDeviceItem));
  564. if (device == NULL) {
  565. return;
  566. }
  567. device->instance_id = SDL_GetNextObjectID();
  568. device->pause_button_index = -1;
  569. if (controller) {
  570. #ifdef SDL_JOYSTICK_MFI
  571. if (!IOS_AddMFIJoystickDevice(device, controller)) {
  572. SDL_free(device->name);
  573. SDL_free(device);
  574. return;
  575. }
  576. #else
  577. SDL_free(device);
  578. return;
  579. #endif // SDL_JOYSTICK_MFI
  580. }
  581. if (deviceList == NULL) {
  582. deviceList = device;
  583. } else {
  584. SDL_JoystickDeviceItem *lastdevice = deviceList;
  585. while (lastdevice->next != NULL) {
  586. lastdevice = lastdevice->next;
  587. }
  588. lastdevice->next = device;
  589. }
  590. ++numjoysticks;
  591. SDL_PrivateJoystickAdded(device->instance_id);
  592. }
  593. #endif // SDL_JOYSTICK_MFI
  594. static SDL_JoystickDeviceItem *IOS_RemoveJoystickDevice(SDL_JoystickDeviceItem *device)
  595. {
  596. SDL_JoystickDeviceItem *prev = NULL;
  597. SDL_JoystickDeviceItem *next = NULL;
  598. SDL_JoystickDeviceItem *item = deviceList;
  599. if (device == NULL) {
  600. return NULL;
  601. }
  602. next = device->next;
  603. while (item != NULL) {
  604. if (item == device) {
  605. break;
  606. }
  607. prev = item;
  608. item = item->next;
  609. }
  610. // Unlink the device item from the device list.
  611. if (prev) {
  612. prev->next = device->next;
  613. } else if (device == deviceList) {
  614. deviceList = device->next;
  615. }
  616. if (device->joystick) {
  617. device->joystick->hwdata = NULL;
  618. }
  619. #ifdef SDL_JOYSTICK_MFI
  620. @autoreleasepool {
  621. // These were explicitly retained in the struct, so they should be explicitly released before freeing the struct.
  622. if (device->controller) {
  623. GCController *controller = CFBridgingRelease((__bridge CFTypeRef)(device->controller));
  624. controller.controllerPausedHandler = nil;
  625. device->controller = nil;
  626. }
  627. if (device->axes) {
  628. CFRelease((__bridge CFTypeRef)device->axes);
  629. device->axes = nil;
  630. }
  631. if (device->buttons) {
  632. CFRelease((__bridge CFTypeRef)device->buttons);
  633. device->buttons = nil;
  634. }
  635. }
  636. #endif // SDL_JOYSTICK_MFI
  637. --numjoysticks;
  638. SDL_PrivateJoystickRemoved(device->instance_id);
  639. SDL_free(device->name);
  640. SDL_free(device);
  641. return next;
  642. }
  643. #ifdef SDL_PLATFORM_TVOS
  644. static void SDLCALL SDL_AppleTVRemoteRotationHintChanged(void *udata, const char *name, const char *oldValue, const char *newValue)
  645. {
  646. BOOL allowRotation = newValue != NULL && *newValue != '0';
  647. @autoreleasepool {
  648. for (GCController *controller in [GCController controllers]) {
  649. if (controller.microGamepad) {
  650. controller.microGamepad.allowsRotation = allowRotation;
  651. }
  652. }
  653. }
  654. }
  655. #endif // SDL_PLATFORM_TVOS
  656. static bool IOS_JoystickInit(void)
  657. {
  658. if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_MFI, true)) {
  659. return true;
  660. }
  661. #ifdef SDL_PLATFORM_MACOS
  662. if (@available(macOS 11.0, *)) {
  663. // Continue with initialization on macOS 11+
  664. } else {
  665. return true;
  666. }
  667. #endif
  668. @autoreleasepool {
  669. #ifdef SDL_JOYSTICK_MFI
  670. NSNotificationCenter *center;
  671. #endif
  672. #ifdef SDL_JOYSTICK_MFI
  673. // GameController.framework was added in iOS 7.
  674. if (![GCController class]) {
  675. return true;
  676. }
  677. /* For whatever reason, this always returns an empty array on
  678. macOS 11.0.1 */
  679. for (GCController *controller in [GCController controllers]) {
  680. IOS_AddJoystickDevice(controller);
  681. }
  682. #ifdef SDL_PLATFORM_TVOS
  683. SDL_AddHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION,
  684. SDL_AppleTVRemoteRotationHintChanged, NULL);
  685. #endif // SDL_PLATFORM_TVOS
  686. center = [NSNotificationCenter defaultCenter];
  687. connectObserver = [center addObserverForName:GCControllerDidConnectNotification
  688. object:nil
  689. queue:nil
  690. usingBlock:^(NSNotification *note) {
  691. GCController *controller = note.object;
  692. SDL_LockJoysticks();
  693. IOS_AddJoystickDevice(controller);
  694. SDL_UnlockJoysticks();
  695. }];
  696. disconnectObserver = [center addObserverForName:GCControllerDidDisconnectNotification
  697. object:nil
  698. queue:nil
  699. usingBlock:^(NSNotification *note) {
  700. GCController *controller = note.object;
  701. SDL_JoystickDeviceItem *device;
  702. SDL_LockJoysticks();
  703. for (device = deviceList; device != NULL; device = device->next) {
  704. if (device->controller == controller) {
  705. IOS_RemoveJoystickDevice(device);
  706. break;
  707. }
  708. }
  709. SDL_UnlockJoysticks();
  710. }];
  711. #endif // SDL_JOYSTICK_MFI
  712. #ifdef SDL_VIDEO_DRIVER_UIKIT
  713. UIKit_SetGameControllerInteraction(true);
  714. #endif
  715. }
  716. return true;
  717. }
  718. static int IOS_JoystickGetCount(void)
  719. {
  720. return numjoysticks;
  721. }
  722. static void IOS_JoystickDetect(void)
  723. {
  724. }
  725. static bool IOS_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name)
  726. {
  727. // We don't override any other drivers through this method
  728. return false;
  729. }
  730. static const char *IOS_JoystickGetDeviceName(int device_index)
  731. {
  732. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  733. return device ? device->name : "Unknown";
  734. }
  735. static const char *IOS_JoystickGetDevicePath(int device_index)
  736. {
  737. return NULL;
  738. }
  739. static int IOS_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index)
  740. {
  741. return -1;
  742. }
  743. static int IOS_JoystickGetDevicePlayerIndex(int device_index)
  744. {
  745. #ifdef SDL_JOYSTICK_MFI
  746. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  747. if (device && device->controller) {
  748. return (int)device->controller.playerIndex;
  749. }
  750. #endif
  751. return -1;
  752. }
  753. static void IOS_JoystickSetDevicePlayerIndex(int device_index, int player_index)
  754. {
  755. #ifdef SDL_JOYSTICK_MFI
  756. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  757. if (device && device->controller) {
  758. device->controller.playerIndex = player_index;
  759. }
  760. #endif
  761. }
  762. static SDL_GUID IOS_JoystickGetDeviceGUID(int device_index)
  763. {
  764. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  765. SDL_GUID guid;
  766. if (device) {
  767. guid = device->guid;
  768. } else {
  769. SDL_zero(guid);
  770. }
  771. return guid;
  772. }
  773. static SDL_JoystickID IOS_JoystickGetDeviceInstanceID(int device_index)
  774. {
  775. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  776. return device ? device->instance_id : 0;
  777. }
  778. static bool IOS_JoystickOpen(SDL_Joystick *joystick, int device_index)
  779. {
  780. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  781. if (device == NULL) {
  782. return SDL_SetError("Could not open Joystick: no hardware device for the specified index");
  783. }
  784. joystick->hwdata = device;
  785. joystick->naxes = device->naxes;
  786. joystick->nhats = device->nhats;
  787. joystick->nbuttons = device->nbuttons;
  788. if (device->has_dualshock_touchpad) {
  789. SDL_PrivateJoystickAddTouchpad(joystick, 2);
  790. }
  791. device->joystick = joystick;
  792. @autoreleasepool {
  793. #ifdef SDL_JOYSTICK_MFI
  794. if (device->pause_button_index >= 0) {
  795. GCController *controller = device->controller;
  796. controller.controllerPausedHandler = ^(GCController *c) {
  797. if (joystick->hwdata) {
  798. joystick->hwdata->pause_button_pressed = SDL_GetTicks();
  799. }
  800. };
  801. }
  802. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  803. GCController *controller = joystick->hwdata->controller;
  804. GCMotion *motion = controller.motion;
  805. if (motion && motion.hasRotationRate) {
  806. SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 0.0f);
  807. }
  808. if (motion && motion.hasGravityAndUserAcceleration) {
  809. SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 0.0f);
  810. }
  811. }
  812. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  813. GCController *controller = joystick->hwdata->controller;
  814. for (id key in controller.physicalInputProfile.buttons) {
  815. GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key];
  816. if ([button isBoundToSystemGesture]) {
  817. button.preferredSystemGestureState = GCSystemGestureStateDisabled;
  818. }
  819. }
  820. }
  821. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  822. GCController *controller = device->controller;
  823. if (controller.light) {
  824. SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN, true);
  825. }
  826. if (controller.haptics) {
  827. for (GCHapticsLocality locality in controller.haptics.supportedLocalities) {
  828. if ([locality isEqualToString:GCHapticsLocalityHandles]) {
  829. SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true);
  830. } else if ([locality isEqualToString:GCHapticsLocalityTriggers]) {
  831. SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true);
  832. }
  833. }
  834. }
  835. }
  836. #endif // SDL_JOYSTICK_MFI
  837. }
  838. if (device->is_siri_remote) {
  839. ++SDL_AppleTVRemoteOpenedAsJoystick;
  840. }
  841. return true;
  842. }
  843. #ifdef SDL_JOYSTICK_MFI
  844. static Uint8 IOS_MFIJoystickHatStateForDPad(GCControllerDirectionPad *dpad)
  845. {
  846. Uint8 hat = 0;
  847. if (dpad.up.isPressed) {
  848. hat |= SDL_HAT_UP;
  849. } else if (dpad.down.isPressed) {
  850. hat |= SDL_HAT_DOWN;
  851. }
  852. if (dpad.left.isPressed) {
  853. hat |= SDL_HAT_LEFT;
  854. } else if (dpad.right.isPressed) {
  855. hat |= SDL_HAT_RIGHT;
  856. }
  857. if (hat == 0) {
  858. return SDL_HAT_CENTERED;
  859. }
  860. return hat;
  861. }
  862. #endif
  863. static void IOS_MFIJoystickUpdate(SDL_Joystick *joystick)
  864. {
  865. #ifdef SDL_JOYSTICK_MFI
  866. @autoreleasepool {
  867. SDL_JoystickDeviceItem *device = joystick->hwdata;
  868. GCController *controller = device->controller;
  869. Uint8 hatstate = SDL_HAT_CENTERED;
  870. int i;
  871. Uint64 timestamp = SDL_GetTicksNS();
  872. #ifdef DEBUG_CONTROLLER_STATE
  873. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  874. if (controller.physicalInputProfile) {
  875. for (id key in controller.physicalInputProfile.buttons) {
  876. GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key];
  877. if (button.isPressed)
  878. NSLog(@"Button %@ = %s\n", key, button.isPressed ? "pressed" : "released");
  879. }
  880. for (id key in controller.physicalInputProfile.axes) {
  881. GCControllerAxisInput *axis = controller.physicalInputProfile.axes[key];
  882. if (axis.value != 0.0f)
  883. NSLog(@"Axis %@ = %g\n", key, axis.value);
  884. }
  885. for (id key in controller.physicalInputProfile.dpads) {
  886. GCControllerDirectionPad *dpad = controller.physicalInputProfile.dpads[key];
  887. if (dpad.up.isPressed || dpad.down.isPressed || dpad.left.isPressed || dpad.right.isPressed) {
  888. NSLog(@"Hat %@ =%s%s%s%s\n", key,
  889. dpad.up.isPressed ? " UP" : "",
  890. dpad.down.isPressed ? " DOWN" : "",
  891. dpad.left.isPressed ? " LEFT" : "",
  892. dpad.right.isPressed ? " RIGHT" : "");
  893. }
  894. }
  895. }
  896. }
  897. #endif // DEBUG_CONTROLLER_STATE
  898. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  899. NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;
  900. NSDictionary<NSString *, GCControllerButtonInput *> *buttons = controller.physicalInputProfile.buttons;
  901. int axis = 0;
  902. for (id key in device->axes) {
  903. Sint16 value;
  904. GCControllerElement *element = elements[key];
  905. if ([element isKindOfClass:[GCControllerAxisInput class]]) {
  906. value = (Sint16)([(GCControllerAxisInput *)element value] * 32767);
  907. } else {
  908. value = (Sint16)([(GCControllerButtonInput *)element value] * 32767);
  909. }
  910. SDL_SendJoystickAxis(timestamp, joystick, axis++, value);
  911. }
  912. int button = 0;
  913. for (id key in device->buttons) {
  914. bool down;
  915. if (button == device->pause_button_index) {
  916. down = (device->pause_button_pressed > 0);
  917. } else {
  918. down = buttons[key].isPressed;
  919. }
  920. SDL_SendJoystickButton(timestamp, joystick, button++, down);
  921. }
  922. } else if (controller.extendedGamepad) {
  923. bool isstack;
  924. GCExtendedGamepad *gamepad = controller.extendedGamepad;
  925. // Axis order matches the XInput Windows mappings.
  926. Sint16 axes[] = {
  927. (Sint16)(gamepad.leftThumbstick.xAxis.value * 32767),
  928. (Sint16)(gamepad.leftThumbstick.yAxis.value * -32767),
  929. (Sint16)((gamepad.leftTrigger.value * 65535) - 32768),
  930. (Sint16)(gamepad.rightThumbstick.xAxis.value * 32767),
  931. (Sint16)(gamepad.rightThumbstick.yAxis.value * -32767),
  932. (Sint16)((gamepad.rightTrigger.value * 65535) - 32768),
  933. };
  934. // Button order matches the XInput Windows mappings.
  935. bool *buttons = SDL_small_alloc(bool, joystick->nbuttons, &isstack);
  936. int button_count = 0;
  937. if (buttons == NULL) {
  938. return;
  939. }
  940. // These buttons are part of the original MFi spec
  941. buttons[button_count++] = gamepad.buttonA.isPressed;
  942. buttons[button_count++] = gamepad.buttonB.isPressed;
  943. buttons[button_count++] = gamepad.buttonX.isPressed;
  944. buttons[button_count++] = gamepad.buttonY.isPressed;
  945. buttons[button_count++] = gamepad.leftShoulder.isPressed;
  946. buttons[button_count++] = gamepad.rightShoulder.isPressed;
  947. // These buttons are available on some newer controllers
  948. if (@available(macOS 10.14.1, iOS 12.1, tvOS 12.1, *)) {
  949. if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK)) {
  950. buttons[button_count++] = gamepad.leftThumbstickButton.isPressed;
  951. }
  952. if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK)) {
  953. buttons[button_count++] = gamepad.rightThumbstickButton.isPressed;
  954. }
  955. }
  956. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  957. if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) {
  958. buttons[button_count++] = gamepad.buttonOptions.isPressed;
  959. }
  960. }
  961. if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_START)) {
  962. if (device->pause_button_index >= 0) {
  963. // Guaranteed if buttonMenu is not supported on this OS
  964. buttons[button_count++] = (device->pause_button_pressed > 0);
  965. } else {
  966. if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {
  967. buttons[button_count++] = gamepad.buttonMenu.isPressed;
  968. }
  969. }
  970. }
  971. hatstate = IOS_MFIJoystickHatStateForDPad(gamepad.dpad);
  972. for (i = 0; i < SDL_arraysize(axes); i++) {
  973. SDL_SendJoystickAxis(timestamp, joystick, i, axes[i]);
  974. }
  975. for (i = 0; i < button_count; i++) {
  976. SDL_SendJoystickButton(timestamp, joystick, i, buttons[i]);
  977. }
  978. SDL_small_free(buttons, isstack);
  979. }
  980. #ifdef SDL_PLATFORM_TVOS
  981. else if (controller.microGamepad) {
  982. GCMicroGamepad *gamepad = controller.microGamepad;
  983. Sint16 axes[] = {
  984. (Sint16)(gamepad.dpad.xAxis.value * 32767),
  985. (Sint16)(gamepad.dpad.yAxis.value * -32767),
  986. };
  987. for (i = 0; i < SDL_arraysize(axes); i++) {
  988. SDL_SendJoystickAxis(timestamp, joystick, i, axes[i]);
  989. }
  990. bool buttons[joystick->nbuttons];
  991. int button_count = 0;
  992. buttons[button_count++] = gamepad.buttonA.isPressed;
  993. buttons[button_count++] = gamepad.buttonX.isPressed;
  994. buttons[button_count++] = (device->pause_button_pressed > 0);
  995. for (i = 0; i < button_count; i++) {
  996. SDL_SendJoystickButton(timestamp, joystick, i, buttons[i]);
  997. }
  998. }
  999. #endif // SDL_PLATFORM_TVOS
  1000. if (joystick->nhats > 0) {
  1001. SDL_SendJoystickHat(timestamp, joystick, 0, hatstate);
  1002. }
  1003. if (device->pause_button_pressed) {
  1004. // The pause callback is instantaneous, so we extend the duration to allow "holding down" by pressing it repeatedly
  1005. const int PAUSE_BUTTON_PRESS_DURATION_MS = 250;
  1006. if (SDL_GetTicks() >= device->pause_button_pressed + PAUSE_BUTTON_PRESS_DURATION_MS) {
  1007. device->pause_button_pressed = 0;
  1008. }
  1009. }
  1010. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1011. if (device->has_dualshock_touchpad) {
  1012. GCControllerDirectionPad *dpad;
  1013. dpad = controller.physicalInputProfile.dpads[GCInputDualShockTouchpadOne];
  1014. if (dpad.xAxis.value != 0.f || dpad.yAxis.value != 0.f) {
  1015. SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, true, (1.0f + dpad.xAxis.value) * 0.5f, 1.0f - (1.0f + dpad.yAxis.value) * 0.5f, 1.0f);
  1016. } else {
  1017. SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, false, 0.0f, 0.0f, 1.0f);
  1018. }
  1019. dpad = controller.physicalInputProfile.dpads[GCInputDualShockTouchpadTwo];
  1020. if (dpad.xAxis.value != 0.f || dpad.yAxis.value != 0.f) {
  1021. SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, true, (1.0f + dpad.xAxis.value) * 0.5f, 1.0f - (1.0f + dpad.yAxis.value) * 0.5f, 1.0f);
  1022. } else {
  1023. SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, false, 0.0f, 0.0f, 1.0f);
  1024. }
  1025. }
  1026. }
  1027. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1028. GCMotion *motion = controller.motion;
  1029. if (motion && motion.sensorsActive) {
  1030. float data[3];
  1031. if (motion.hasRotationRate) {
  1032. GCRotationRate rate = motion.rotationRate;
  1033. data[0] = rate.x;
  1034. data[1] = rate.z;
  1035. data[2] = -rate.y;
  1036. SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, timestamp, data, 3);
  1037. }
  1038. if (motion.hasGravityAndUserAcceleration) {
  1039. GCAcceleration accel = motion.acceleration;
  1040. data[0] = -accel.x * SDL_STANDARD_GRAVITY;
  1041. data[1] = -accel.y * SDL_STANDARD_GRAVITY;
  1042. data[2] = -accel.z * SDL_STANDARD_GRAVITY;
  1043. SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, timestamp, data, 3);
  1044. }
  1045. }
  1046. }
  1047. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1048. GCDeviceBattery *battery = controller.battery;
  1049. if (battery) {
  1050. SDL_PowerState state = SDL_POWERSTATE_UNKNOWN;
  1051. int percent = (int)SDL_roundf(battery.batteryLevel * 100.0f);
  1052. switch (battery.batteryState) {
  1053. case GCDeviceBatteryStateDischarging:
  1054. state = SDL_POWERSTATE_ON_BATTERY;
  1055. break;
  1056. case GCDeviceBatteryStateCharging:
  1057. state = SDL_POWERSTATE_CHARGING;
  1058. break;
  1059. case GCDeviceBatteryStateFull:
  1060. state = SDL_POWERSTATE_CHARGED;
  1061. break;
  1062. default:
  1063. break;
  1064. }
  1065. SDL_SendJoystickPowerInfo(joystick, state, percent);
  1066. }
  1067. }
  1068. }
  1069. #endif // SDL_JOYSTICK_MFI
  1070. }
  1071. #ifdef SDL_JOYSTICK_MFI
  1072. @interface SDL3_RumbleMotor : NSObject
  1073. @property(nonatomic, strong) CHHapticEngine *engine API_AVAILABLE(macos(11.0), ios(13.0), tvos(14.0));
  1074. @property(nonatomic, strong) id<CHHapticPatternPlayer> player API_AVAILABLE(macos(11.0), ios(13.0), tvos(14.0));
  1075. @property bool active;
  1076. @end
  1077. @implementation SDL3_RumbleMotor
  1078. {
  1079. }
  1080. - (void)cleanup
  1081. {
  1082. @autoreleasepool {
  1083. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1084. if (self.player != nil) {
  1085. [self.player cancelAndReturnError:nil];
  1086. self.player = nil;
  1087. }
  1088. if (self.engine != nil) {
  1089. [self.engine stopWithCompletionHandler:nil];
  1090. self.engine = nil;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. - (bool)setIntensity:(float)intensity
  1096. {
  1097. @autoreleasepool {
  1098. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1099. NSError *error = nil;
  1100. CHHapticDynamicParameter *param;
  1101. if (self.engine == nil) {
  1102. return SDL_SetError("Haptics engine was stopped");
  1103. }
  1104. if (intensity == 0.0f) {
  1105. if (self.player && self.active) {
  1106. [self.player stopAtTime:0 error:&error];
  1107. }
  1108. self.active = false;
  1109. return true;
  1110. }
  1111. if (self.player == nil) {
  1112. CHHapticEventParameter *event_param = [[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticIntensity value:1.0f];
  1113. CHHapticEvent *event = [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticContinuous parameters:[NSArray arrayWithObjects:event_param, nil] relativeTime:0 duration:GCHapticDurationInfinite];
  1114. CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithEvents:[NSArray arrayWithObject:event] parameters:[[NSArray alloc] init] error:&error];
  1115. if (error != nil) {
  1116. return SDL_SetError("Couldn't create haptic pattern: %s", [error.localizedDescription UTF8String]);
  1117. }
  1118. self.player = [self.engine createPlayerWithPattern:pattern error:&error];
  1119. if (error != nil) {
  1120. return SDL_SetError("Couldn't create haptic player: %s", [error.localizedDescription UTF8String]);
  1121. }
  1122. self.active = false;
  1123. }
  1124. param = [[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl value:intensity relativeTime:0];
  1125. [self.player sendParameters:[NSArray arrayWithObject:param] atTime:0 error:&error];
  1126. if (error != nil) {
  1127. return SDL_SetError("Couldn't update haptic player: %s", [error.localizedDescription UTF8String]);
  1128. }
  1129. if (!self.active) {
  1130. [self.player startAtTime:0 error:&error];
  1131. self.active = true;
  1132. }
  1133. }
  1134. return true;
  1135. }
  1136. }
  1137. - (id)initWithController:(GCController *)controller locality:(GCHapticsLocality)locality API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
  1138. {
  1139. @autoreleasepool {
  1140. NSError *error;
  1141. __weak __typeof(self) weakSelf;
  1142. self = [super init];
  1143. weakSelf = self;
  1144. self.engine = [controller.haptics createEngineWithLocality:locality];
  1145. if (self.engine == nil) {
  1146. SDL_SetError("Couldn't create haptics engine");
  1147. return nil;
  1148. }
  1149. [self.engine startAndReturnError:&error];
  1150. if (error != nil) {
  1151. SDL_SetError("Couldn't start haptics engine");
  1152. return nil;
  1153. }
  1154. self.engine.stoppedHandler = ^(CHHapticEngineStoppedReason stoppedReason) {
  1155. SDL3_RumbleMotor *_this = weakSelf;
  1156. if (_this == nil) {
  1157. return;
  1158. }
  1159. _this.player = nil;
  1160. _this.engine = nil;
  1161. };
  1162. self.engine.resetHandler = ^{
  1163. SDL3_RumbleMotor *_this = weakSelf;
  1164. if (_this == nil) {
  1165. return;
  1166. }
  1167. _this.player = nil;
  1168. [_this.engine startAndReturnError:nil];
  1169. };
  1170. return self;
  1171. }
  1172. }
  1173. @end
  1174. @interface SDL3_RumbleContext : NSObject
  1175. @property(nonatomic, strong) SDL3_RumbleMotor *lowFrequencyMotor;
  1176. @property(nonatomic, strong) SDL3_RumbleMotor *highFrequencyMotor;
  1177. @property(nonatomic, strong) SDL3_RumbleMotor *leftTriggerMotor;
  1178. @property(nonatomic, strong) SDL3_RumbleMotor *rightTriggerMotor;
  1179. @end
  1180. @implementation SDL3_RumbleContext
  1181. {
  1182. }
  1183. - (id)initWithLowFrequencyMotor:(SDL3_RumbleMotor *)low_frequency_motor
  1184. HighFrequencyMotor:(SDL3_RumbleMotor *)high_frequency_motor
  1185. LeftTriggerMotor:(SDL3_RumbleMotor *)left_trigger_motor
  1186. RightTriggerMotor:(SDL3_RumbleMotor *)right_trigger_motor
  1187. {
  1188. self = [super init];
  1189. self.lowFrequencyMotor = low_frequency_motor;
  1190. self.highFrequencyMotor = high_frequency_motor;
  1191. self.leftTriggerMotor = left_trigger_motor;
  1192. self.rightTriggerMotor = right_trigger_motor;
  1193. return self;
  1194. }
  1195. - (bool)rumbleWithLowFrequency:(Uint16)low_frequency_rumble andHighFrequency:(Uint16)high_frequency_rumble
  1196. {
  1197. bool result = true;
  1198. result &= [self.lowFrequencyMotor setIntensity:((float)low_frequency_rumble / 65535.0f)];
  1199. result &= [self.highFrequencyMotor setIntensity:((float)high_frequency_rumble / 65535.0f)];
  1200. return result;
  1201. }
  1202. - (bool)rumbleLeftTrigger:(Uint16)left_rumble andRightTrigger:(Uint16)right_rumble
  1203. {
  1204. bool result = false;
  1205. if (self.leftTriggerMotor && self.rightTriggerMotor) {
  1206. result &= [self.leftTriggerMotor setIntensity:((float)left_rumble / 65535.0f)];
  1207. result &= [self.rightTriggerMotor setIntensity:((float)right_rumble / 65535.0f)];
  1208. } else {
  1209. result = SDL_Unsupported();
  1210. }
  1211. return result;
  1212. }
  1213. - (void)cleanup
  1214. {
  1215. [self.lowFrequencyMotor cleanup];
  1216. [self.highFrequencyMotor cleanup];
  1217. }
  1218. @end
  1219. static SDL3_RumbleContext *IOS_JoystickInitRumble(GCController *controller)
  1220. {
  1221. @autoreleasepool {
  1222. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1223. SDL3_RumbleMotor *low_frequency_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftHandle];
  1224. SDL3_RumbleMotor *high_frequency_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightHandle];
  1225. SDL3_RumbleMotor *left_trigger_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftTrigger];
  1226. SDL3_RumbleMotor *right_trigger_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightTrigger];
  1227. if (low_frequency_motor && high_frequency_motor) {
  1228. return [[SDL3_RumbleContext alloc] initWithLowFrequencyMotor:low_frequency_motor
  1229. HighFrequencyMotor:high_frequency_motor
  1230. LeftTriggerMotor:left_trigger_motor
  1231. RightTriggerMotor:right_trigger_motor];
  1232. }
  1233. }
  1234. }
  1235. return nil;
  1236. }
  1237. #endif // SDL_JOYSTICK_MFI
  1238. static bool IOS_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  1239. {
  1240. #ifdef SDL_JOYSTICK_MFI
  1241. SDL_JoystickDeviceItem *device = joystick->hwdata;
  1242. if (device == NULL) {
  1243. return SDL_SetError("Controller is no longer connected");
  1244. }
  1245. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1246. if (!device->rumble && device->controller && device->controller.haptics) {
  1247. SDL3_RumbleContext *rumble = IOS_JoystickInitRumble(device->controller);
  1248. if (rumble) {
  1249. device->rumble = (void *)CFBridgingRetain(rumble);
  1250. }
  1251. }
  1252. }
  1253. if (device->rumble) {
  1254. SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble;
  1255. return [rumble rumbleWithLowFrequency:low_frequency_rumble andHighFrequency:high_frequency_rumble];
  1256. }
  1257. #endif
  1258. return SDL_Unsupported();
  1259. }
  1260. static bool IOS_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  1261. {
  1262. #ifdef SDL_JOYSTICK_MFI
  1263. SDL_JoystickDeviceItem *device = joystick->hwdata;
  1264. if (device == NULL) {
  1265. return SDL_SetError("Controller is no longer connected");
  1266. }
  1267. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1268. if (!device->rumble && device->controller && device->controller.haptics) {
  1269. SDL3_RumbleContext *rumble = IOS_JoystickInitRumble(device->controller);
  1270. if (rumble) {
  1271. device->rumble = (void *)CFBridgingRetain(rumble);
  1272. }
  1273. }
  1274. }
  1275. if (device->rumble) {
  1276. SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble;
  1277. return [rumble rumbleLeftTrigger:left_rumble andRightTrigger:right_rumble];
  1278. }
  1279. #endif
  1280. return SDL_Unsupported();
  1281. }
  1282. static bool IOS_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  1283. {
  1284. @autoreleasepool {
  1285. SDL_JoystickDeviceItem *device = joystick->hwdata;
  1286. if (device == NULL) {
  1287. return SDL_SetError("Controller is no longer connected");
  1288. }
  1289. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1290. GCController *controller = device->controller;
  1291. GCDeviceLight *light = controller.light;
  1292. if (light) {
  1293. light.color = [[GCColor alloc] initWithRed:(float)red / 255.0f
  1294. green:(float)green / 255.0f
  1295. blue:(float)blue / 255.0f];
  1296. return true;
  1297. }
  1298. }
  1299. }
  1300. return SDL_Unsupported();
  1301. }
  1302. static bool IOS_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size)
  1303. {
  1304. return SDL_Unsupported();
  1305. }
  1306. static bool IOS_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled)
  1307. {
  1308. @autoreleasepool {
  1309. SDL_JoystickDeviceItem *device = joystick->hwdata;
  1310. if (device == NULL) {
  1311. return SDL_SetError("Controller is no longer connected");
  1312. }
  1313. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1314. GCController *controller = device->controller;
  1315. GCMotion *motion = controller.motion;
  1316. if (motion) {
  1317. motion.sensorsActive = enabled ? YES : NO;
  1318. return true;
  1319. }
  1320. }
  1321. }
  1322. return SDL_Unsupported();
  1323. }
  1324. static void IOS_JoystickUpdate(SDL_Joystick *joystick)
  1325. {
  1326. SDL_JoystickDeviceItem *device = joystick->hwdata;
  1327. if (device == NULL) {
  1328. return;
  1329. }
  1330. if (device->controller) {
  1331. IOS_MFIJoystickUpdate(joystick);
  1332. }
  1333. }
  1334. static void IOS_JoystickClose(SDL_Joystick *joystick)
  1335. {
  1336. SDL_JoystickDeviceItem *device = joystick->hwdata;
  1337. if (device == NULL) {
  1338. return;
  1339. }
  1340. device->joystick = NULL;
  1341. #ifdef SDL_JOYSTICK_MFI
  1342. @autoreleasepool {
  1343. if (device->rumble) {
  1344. SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble;
  1345. [rumble cleanup];
  1346. CFRelease(device->rumble);
  1347. device->rumble = NULL;
  1348. }
  1349. if (device->controller) {
  1350. GCController *controller = device->controller;
  1351. controller.controllerPausedHandler = nil;
  1352. controller.playerIndex = -1;
  1353. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1354. for (id key in controller.physicalInputProfile.buttons) {
  1355. GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key];
  1356. if ([button isBoundToSystemGesture]) {
  1357. button.preferredSystemGestureState = GCSystemGestureStateEnabled;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. }
  1363. #endif // SDL_JOYSTICK_MFI
  1364. if (device->is_siri_remote) {
  1365. --SDL_AppleTVRemoteOpenedAsJoystick;
  1366. }
  1367. }
  1368. static void IOS_JoystickQuit(void)
  1369. {
  1370. @autoreleasepool {
  1371. #ifdef SDL_JOYSTICK_MFI
  1372. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  1373. if (connectObserver) {
  1374. [center removeObserver:connectObserver name:GCControllerDidConnectNotification object:nil];
  1375. connectObserver = nil;
  1376. }
  1377. if (disconnectObserver) {
  1378. [center removeObserver:disconnectObserver name:GCControllerDidDisconnectNotification object:nil];
  1379. disconnectObserver = nil;
  1380. }
  1381. #ifdef SDL_PLATFORM_TVOS
  1382. SDL_RemoveHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION,
  1383. SDL_AppleTVRemoteRotationHintChanged, NULL);
  1384. #endif // SDL_PLATFORM_TVOS
  1385. #endif // SDL_JOYSTICK_MFI
  1386. while (deviceList != NULL) {
  1387. IOS_RemoveJoystickDevice(deviceList);
  1388. }
  1389. #ifdef SDL_VIDEO_DRIVER_UIKIT
  1390. UIKit_SetGameControllerInteraction(false);
  1391. #endif
  1392. }
  1393. numjoysticks = 0;
  1394. }
  1395. static bool IOS_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out)
  1396. {
  1397. SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);
  1398. if (device == NULL) {
  1399. return false;
  1400. }
  1401. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1402. int axis = 0;
  1403. for (id key in device->axes) {
  1404. if ([(NSString *)key isEqualToString:@"Left Thumbstick X Axis"] ||
  1405. [(NSString *)key isEqualToString:@"Direction Pad X Axis"]) {
  1406. out->leftx.kind = EMappingKind_Axis;
  1407. out->leftx.target = axis;
  1408. } else if ([(NSString *)key isEqualToString:@"Left Thumbstick Y Axis"] ||
  1409. [(NSString *)key isEqualToString:@"Direction Pad Y Axis"]) {
  1410. out->lefty.kind = EMappingKind_Axis;
  1411. out->lefty.target = axis;
  1412. out->lefty.axis_reversed = true;
  1413. } else if ([(NSString *)key isEqualToString:@"Right Thumbstick X Axis"]) {
  1414. out->rightx.kind = EMappingKind_Axis;
  1415. out->rightx.target = axis;
  1416. } else if ([(NSString *)key isEqualToString:@"Right Thumbstick Y Axis"]) {
  1417. out->righty.kind = EMappingKind_Axis;
  1418. out->righty.target = axis;
  1419. out->righty.axis_reversed = true;
  1420. } else if ([(NSString *)key isEqualToString:GCInputLeftTrigger]) {
  1421. out->lefttrigger.kind = EMappingKind_Axis;
  1422. out->lefttrigger.target = axis;
  1423. out->lefttrigger.half_axis_positive = true;
  1424. } else if ([(NSString *)key isEqualToString:GCInputRightTrigger]) {
  1425. out->righttrigger.kind = EMappingKind_Axis;
  1426. out->righttrigger.target = axis;
  1427. out->righttrigger.half_axis_positive = true;
  1428. }
  1429. ++axis;
  1430. }
  1431. int button = 0;
  1432. for (id key in device->buttons) {
  1433. SDL_InputMapping *mapping = NULL;
  1434. if ([(NSString *)key isEqualToString:GCInputButtonA]) {
  1435. if (device->is_siri_remote > 1) {
  1436. // GCInputButtonA is triggered for any D-Pad press, ignore it in favor of "Button Center"
  1437. } else if (device->has_nintendo_buttons) {
  1438. mapping = &out->b;
  1439. } else {
  1440. mapping = &out->a;
  1441. }
  1442. } else if ([(NSString *)key isEqualToString:GCInputButtonB]) {
  1443. if (device->has_nintendo_buttons) {
  1444. mapping = &out->a;
  1445. } else if (device->is_switch_joyconL || device->is_switch_joyconR) {
  1446. mapping = &out->x;
  1447. } else {
  1448. mapping = &out->b;
  1449. }
  1450. } else if ([(NSString *)key isEqualToString:GCInputButtonX]) {
  1451. if (device->has_nintendo_buttons) {
  1452. mapping = &out->y;
  1453. } else if (device->is_switch_joyconL || device->is_switch_joyconR) {
  1454. mapping = &out->b;
  1455. } else {
  1456. mapping = &out->x;
  1457. }
  1458. } else if ([(NSString *)key isEqualToString:GCInputButtonY]) {
  1459. if (device->has_nintendo_buttons) {
  1460. mapping = &out->x;
  1461. } else {
  1462. mapping = &out->y;
  1463. }
  1464. } else if ([(NSString *)key isEqualToString:@"Direction Pad Left"]) {
  1465. mapping = &out->dpleft;
  1466. } else if ([(NSString *)key isEqualToString:@"Direction Pad Right"]) {
  1467. mapping = &out->dpright;
  1468. } else if ([(NSString *)key isEqualToString:@"Direction Pad Up"]) {
  1469. mapping = &out->dpup;
  1470. } else if ([(NSString *)key isEqualToString:@"Direction Pad Down"]) {
  1471. mapping = &out->dpdown;
  1472. } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Left"]) {
  1473. mapping = &out->dpleft;
  1474. } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Right"]) {
  1475. mapping = &out->dpright;
  1476. } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Up"]) {
  1477. mapping = &out->dpup;
  1478. } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Down"]) {
  1479. mapping = &out->dpdown;
  1480. } else if ([(NSString *)key isEqualToString:GCInputLeftShoulder]) {
  1481. mapping = &out->leftshoulder;
  1482. } else if ([(NSString *)key isEqualToString:GCInputRightShoulder]) {
  1483. mapping = &out->rightshoulder;
  1484. } else if ([(NSString *)key isEqualToString:GCInputLeftThumbstickButton]) {
  1485. mapping = &out->leftstick;
  1486. } else if ([(NSString *)key isEqualToString:GCInputRightThumbstickButton]) {
  1487. mapping = &out->rightstick;
  1488. } else if ([(NSString *)key isEqualToString:@"Button Home"]) {
  1489. mapping = &out->guide;
  1490. } else if ([(NSString *)key isEqualToString:GCInputButtonMenu]) {
  1491. if (device->is_siri_remote) {
  1492. mapping = &out->b;
  1493. } else {
  1494. mapping = &out->start;
  1495. }
  1496. } else if ([(NSString *)key isEqualToString:GCInputButtonOptions]) {
  1497. mapping = &out->back;
  1498. } else if ([(NSString *)key isEqualToString:@"Button Share"]) {
  1499. mapping = &out->misc1;
  1500. } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleOne]) {
  1501. mapping = &out->right_paddle1;
  1502. } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleTwo]) {
  1503. mapping = &out->right_paddle2;
  1504. } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleThree]) {
  1505. mapping = &out->left_paddle1;
  1506. } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleFour]) {
  1507. mapping = &out->left_paddle2;
  1508. } else if ([(NSString *)key isEqualToString:GCInputLeftTrigger]) {
  1509. mapping = &out->lefttrigger;
  1510. } else if ([(NSString *)key isEqualToString:GCInputRightTrigger]) {
  1511. mapping = &out->righttrigger;
  1512. } else if ([(NSString *)key isEqualToString:GCInputDualShockTouchpadButton]) {
  1513. mapping = &out->touchpad;
  1514. } else if ([(NSString *)key isEqualToString:@"Button Center"]) {
  1515. mapping = &out->a;
  1516. }
  1517. if (mapping && mapping->kind == EMappingKind_None) {
  1518. mapping->kind = EMappingKind_Button;
  1519. mapping->target = button;
  1520. }
  1521. ++button;
  1522. }
  1523. return true;
  1524. }
  1525. return false;
  1526. }
  1527. #if defined(SDL_JOYSTICK_MFI) && defined(SDL_PLATFORM_MACOS)
  1528. bool IOS_SupportedHIDDevice(IOHIDDeviceRef device)
  1529. {
  1530. if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_MFI, true)) {
  1531. return false;
  1532. }
  1533. if (@available(macOS 11.0, *)) {
  1534. const int MAX_ATTEMPTS = 3;
  1535. for (int attempt = 0; attempt < MAX_ATTEMPTS; ++attempt) {
  1536. if ([GCController supportsHIDDevice:device]) {
  1537. return true;
  1538. }
  1539. // The framework may not have seen the device yet
  1540. SDL_Delay(10);
  1541. }
  1542. }
  1543. return false;
  1544. }
  1545. #endif
  1546. #ifdef SDL_JOYSTICK_MFI
  1547. /* NOLINTNEXTLINE(readability-non-const-parameter): getCString takes a non-const char* */
  1548. static void GetAppleSFSymbolsNameForElement(GCControllerElement *element, char *name)
  1549. {
  1550. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1551. if (element) {
  1552. [element.sfSymbolsName getCString:name maxLength:255 encoding:NSASCIIStringEncoding];
  1553. }
  1554. }
  1555. }
  1556. static GCControllerDirectionPad *GetDirectionalPadForController(GCController *controller)
  1557. {
  1558. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1559. return controller.physicalInputProfile.dpads[GCInputDirectionPad];
  1560. }
  1561. if (controller.extendedGamepad) {
  1562. return controller.extendedGamepad.dpad;
  1563. }
  1564. if (controller.microGamepad) {
  1565. return controller.microGamepad.dpad;
  1566. }
  1567. return nil;
  1568. }
  1569. #endif // SDL_JOYSTICK_MFI
  1570. const char *IOS_GetAppleSFSymbolsNameForButton(SDL_Gamepad *gamepad, SDL_GamepadButton button)
  1571. {
  1572. char elementName[256];
  1573. elementName[0] = '\0';
  1574. #ifdef SDL_JOYSTICK_MFI
  1575. if (gamepad && SDL_GetGamepadJoystick(gamepad)->driver == &SDL_IOS_JoystickDriver) {
  1576. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1577. GCController *controller = SDL_GetGamepadJoystick(gamepad)->hwdata->controller;
  1578. NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;
  1579. switch (button) {
  1580. case SDL_GAMEPAD_BUTTON_SOUTH:
  1581. GetAppleSFSymbolsNameForElement(elements[GCInputButtonA], elementName);
  1582. break;
  1583. case SDL_GAMEPAD_BUTTON_EAST:
  1584. GetAppleSFSymbolsNameForElement(elements[GCInputButtonB], elementName);
  1585. break;
  1586. case SDL_GAMEPAD_BUTTON_WEST:
  1587. GetAppleSFSymbolsNameForElement(elements[GCInputButtonX], elementName);
  1588. break;
  1589. case SDL_GAMEPAD_BUTTON_NORTH:
  1590. GetAppleSFSymbolsNameForElement(elements[GCInputButtonY], elementName);
  1591. break;
  1592. case SDL_GAMEPAD_BUTTON_BACK:
  1593. GetAppleSFSymbolsNameForElement(elements[GCInputButtonOptions], elementName);
  1594. break;
  1595. case SDL_GAMEPAD_BUTTON_GUIDE:
  1596. GetAppleSFSymbolsNameForElement(elements[@"Button Home"], elementName);
  1597. break;
  1598. case SDL_GAMEPAD_BUTTON_START:
  1599. GetAppleSFSymbolsNameForElement(elements[GCInputButtonMenu], elementName);
  1600. break;
  1601. case SDL_GAMEPAD_BUTTON_LEFT_STICK:
  1602. GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstickButton], elementName);
  1603. break;
  1604. case SDL_GAMEPAD_BUTTON_RIGHT_STICK:
  1605. GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstickButton], elementName);
  1606. break;
  1607. case SDL_GAMEPAD_BUTTON_LEFT_SHOULDER:
  1608. GetAppleSFSymbolsNameForElement(elements[GCInputLeftShoulder], elementName);
  1609. break;
  1610. case SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER:
  1611. GetAppleSFSymbolsNameForElement(elements[GCInputRightShoulder], elementName);
  1612. break;
  1613. case SDL_GAMEPAD_BUTTON_DPAD_UP:
  1614. {
  1615. GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);
  1616. if (dpad) {
  1617. GetAppleSFSymbolsNameForElement(dpad.up, elementName);
  1618. if (SDL_strlen(elementName) == 0) {
  1619. SDL_strlcpy(elementName, "dpad.up.fill", sizeof(elementName));
  1620. }
  1621. }
  1622. break;
  1623. }
  1624. case SDL_GAMEPAD_BUTTON_DPAD_DOWN:
  1625. {
  1626. GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);
  1627. if (dpad) {
  1628. GetAppleSFSymbolsNameForElement(dpad.down, elementName);
  1629. if (SDL_strlen(elementName) == 0) {
  1630. SDL_strlcpy(elementName, "dpad.down.fill", sizeof(elementName));
  1631. }
  1632. }
  1633. break;
  1634. }
  1635. case SDL_GAMEPAD_BUTTON_DPAD_LEFT:
  1636. {
  1637. GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);
  1638. if (dpad) {
  1639. GetAppleSFSymbolsNameForElement(dpad.left, elementName);
  1640. if (SDL_strlen(elementName) == 0) {
  1641. SDL_strlcpy(elementName, "dpad.left.fill", sizeof(elementName));
  1642. }
  1643. }
  1644. break;
  1645. }
  1646. case SDL_GAMEPAD_BUTTON_DPAD_RIGHT:
  1647. {
  1648. GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);
  1649. if (dpad) {
  1650. GetAppleSFSymbolsNameForElement(dpad.right, elementName);
  1651. if (SDL_strlen(elementName) == 0) {
  1652. SDL_strlcpy(elementName, "dpad.right.fill", sizeof(elementName));
  1653. }
  1654. }
  1655. break;
  1656. }
  1657. case SDL_GAMEPAD_BUTTON_MISC1:
  1658. GetAppleSFSymbolsNameForElement(elements[GCInputDualShockTouchpadButton], elementName);
  1659. break;
  1660. case SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1:
  1661. GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleOne], elementName);
  1662. break;
  1663. case SDL_GAMEPAD_BUTTON_LEFT_PADDLE1:
  1664. GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleThree], elementName);
  1665. break;
  1666. case SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2:
  1667. GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleTwo], elementName);
  1668. break;
  1669. case SDL_GAMEPAD_BUTTON_LEFT_PADDLE2:
  1670. GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleFour], elementName);
  1671. break;
  1672. case SDL_GAMEPAD_BUTTON_TOUCHPAD:
  1673. GetAppleSFSymbolsNameForElement(elements[GCInputDualShockTouchpadButton], elementName);
  1674. break;
  1675. default:
  1676. break;
  1677. }
  1678. }
  1679. }
  1680. #endif // SDL_JOYSTICK_MFI
  1681. return *elementName ? SDL_GetPersistentString(elementName) : NULL;
  1682. }
  1683. const char *IOS_GetAppleSFSymbolsNameForAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis)
  1684. {
  1685. char elementName[256];
  1686. elementName[0] = '\0';
  1687. #ifdef SDL_JOYSTICK_MFI
  1688. if (gamepad && SDL_GetGamepadJoystick(gamepad)->driver == &SDL_IOS_JoystickDriver) {
  1689. if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
  1690. GCController *controller = SDL_GetGamepadJoystick(gamepad)->hwdata->controller;
  1691. NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;
  1692. switch (axis) {
  1693. case SDL_GAMEPAD_AXIS_LEFTX:
  1694. GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstick], elementName);
  1695. break;
  1696. case SDL_GAMEPAD_AXIS_LEFTY:
  1697. GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstick], elementName);
  1698. break;
  1699. case SDL_GAMEPAD_AXIS_RIGHTX:
  1700. GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstick], elementName);
  1701. break;
  1702. case SDL_GAMEPAD_AXIS_RIGHTY:
  1703. GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstick], elementName);
  1704. break;
  1705. case SDL_GAMEPAD_AXIS_LEFT_TRIGGER:
  1706. GetAppleSFSymbolsNameForElement(elements[GCInputLeftTrigger], elementName);
  1707. break;
  1708. case SDL_GAMEPAD_AXIS_RIGHT_TRIGGER:
  1709. GetAppleSFSymbolsNameForElement(elements[GCInputRightTrigger], elementName);
  1710. break;
  1711. default:
  1712. break;
  1713. }
  1714. }
  1715. }
  1716. #endif // SDL_JOYSTICK_MFI
  1717. return *elementName ? SDL_GetPersistentString(elementName) : NULL;
  1718. }
  1719. SDL_JoystickDriver SDL_IOS_JoystickDriver = {
  1720. IOS_JoystickInit,
  1721. IOS_JoystickGetCount,
  1722. IOS_JoystickDetect,
  1723. IOS_JoystickIsDevicePresent,
  1724. IOS_JoystickGetDeviceName,
  1725. IOS_JoystickGetDevicePath,
  1726. IOS_JoystickGetDeviceSteamVirtualGamepadSlot,
  1727. IOS_JoystickGetDevicePlayerIndex,
  1728. IOS_JoystickSetDevicePlayerIndex,
  1729. IOS_JoystickGetDeviceGUID,
  1730. IOS_JoystickGetDeviceInstanceID,
  1731. IOS_JoystickOpen,
  1732. IOS_JoystickRumble,
  1733. IOS_JoystickRumbleTriggers,
  1734. IOS_JoystickSetLED,
  1735. IOS_JoystickSendEffect,
  1736. IOS_JoystickSetSensorsEnabled,
  1737. IOS_JoystickUpdate,
  1738. IOS_JoystickClose,
  1739. IOS_JoystickQuit,
  1740. IOS_JoystickGetGamepadMapping
  1741. };