Path: blob/master/thirdparty/sdl/joystick/apple/SDL_mfijoystick.m
9906 views
/*1Simple DirectMedia Layer2Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>34This software is provided 'as-is', without any express or implied5warranty. In no event will the authors be held liable for any damages6arising from the use of this software.78Permission is granted to anyone to use this software for any purpose,9including commercial applications, and to alter it and redistribute it10freely, subject to the following restrictions:11121. The origin of this software must not be misrepresented; you must not13claim that you wrote the original software. If you use this software14in a product, an acknowledgment in the product documentation would be15appreciated but is not required.162. Altered source versions must be plainly marked as such, and must not be17misrepresented as being the original software.183. This notice may not be removed or altered from any source distribution.19*/20#include "SDL_internal.h"2122// This is the iOS implementation of the SDL joystick API23#include "../SDL_sysjoystick.h"24#include "../SDL_joystick_c.h"25#include "../hidapi/SDL_hidapijoystick_c.h"26#include "../usb_ids.h"27#include "../../events/SDL_events_c.h"2829#include "SDL_mfijoystick_c.h"303132#if defined(SDL_PLATFORM_IOS) && !defined(SDL_PLATFORM_TVOS)33#import <CoreMotion/CoreMotion.h>34#endif3536#ifdef SDL_PLATFORM_MACOS37#include <IOKit/hid/IOHIDManager.h>38#include <AppKit/NSApplication.h>39#ifndef NSAppKitVersionNumber10_1540#define NSAppKitVersionNumber10_15 189441#endif42#endif // SDL_PLATFORM_MACOS4344#import <GameController/GameController.h>4546#ifdef SDL_JOYSTICK_MFI47static id connectObserver = nil;48static id disconnectObserver = nil;4950#include <objc/message.h>5152// Fix build errors when using an older SDK by defining these selectors53@interface GCController (SDL)54#if !((__IPHONE_OS_VERSION_MAX_ALLOWED >= 140500) || (__APPLETV_OS_VERSION_MAX_ALLOWED >= 140500) || (__MAC_OS_X_VERSION_MAX_ALLOWED >= 110300))55@property(class, nonatomic, readwrite) BOOL shouldMonitorBackgroundEvents;56#endif57@end5859#import <CoreHaptics/CoreHaptics.h>6061#endif // SDL_JOYSTICK_MFI6263static SDL_JoystickDeviceItem *deviceList = NULL;6465static int numjoysticks = 0;66int SDL_AppleTVRemoteOpenedAsJoystick = 0;6768static SDL_JoystickDeviceItem *GetDeviceForIndex(int device_index)69{70SDL_JoystickDeviceItem *device = deviceList;71int i = 0;7273while (i < device_index) {74if (device == NULL) {75return NULL;76}77device = device->next;78i++;79}8081return device;82}8384#ifdef SDL_JOYSTICK_MFI85static bool IsControllerPS4(GCController *controller)86{87if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {88if ([controller.productCategory isEqualToString:@"DualShock 4"]) {89return true;90}91} else {92if ([controller.vendorName containsString:@"DUALSHOCK"]) {93return true;94}95}96return false;97}98static bool IsControllerPS5(GCController *controller)99{100if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {101if ([controller.productCategory isEqualToString:@"DualSense"]) {102return true;103}104} else {105if ([controller.vendorName containsString:@"DualSense"]) {106return true;107}108}109return false;110}111static bool IsControllerXbox(GCController *controller)112{113if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {114if ([controller.productCategory isEqualToString:@"Xbox One"]) {115return true;116}117} else {118if ([controller.vendorName containsString:@"Xbox"]) {119return true;120}121}122return false;123}124static bool IsControllerSwitchPro(GCController *controller)125{126if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {127if ([controller.productCategory isEqualToString:@"Switch Pro Controller"]) {128return true;129}130}131return false;132}133static bool IsControllerSwitchJoyConL(GCController *controller)134{135if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {136if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (L)"]) {137return true;138}139}140return false;141}142static bool IsControllerSwitchJoyConR(GCController *controller)143{144if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {145if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (R)"]) {146return true;147}148}149return false;150}151static bool IsControllerSwitchJoyConPair(GCController *controller)152{153if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {154if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (L/R)"]) {155return true;156}157}158return false;159}160static bool IsControllerStadia(GCController *controller)161{162if ([controller.vendorName hasPrefix:@"Stadia"]) {163return true;164}165return false;166}167static bool IsControllerBackboneOne(GCController *controller)168{169if ([controller.vendorName hasPrefix:@"Backbone One"]) {170return true;171}172return false;173}174static void CheckControllerSiriRemote(GCController *controller, int *is_siri_remote)175{176if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {177if ([controller.productCategory hasPrefix:@"Siri Remote"]) {178*is_siri_remote = 1;179SDL_sscanf(controller.productCategory.UTF8String, "Siri Remote (%i%*s Generation)", is_siri_remote);180return;181}182}183*is_siri_remote = 0;184}185186static bool ElementAlreadyHandled(SDL_JoystickDeviceItem *device, NSString *element, NSDictionary<NSString *, GCControllerElement *> *elements)187{188if ([element isEqualToString:@"Left Thumbstick Left"] ||189[element isEqualToString:@"Left Thumbstick Right"]) {190if (elements[@"Left Thumbstick X Axis"]) {191return true;192}193}194if ([element isEqualToString:@"Left Thumbstick Up"] ||195[element isEqualToString:@"Left Thumbstick Down"]) {196if (elements[@"Left Thumbstick Y Axis"]) {197return true;198}199}200if ([element isEqualToString:@"Right Thumbstick Left"] ||201[element isEqualToString:@"Right Thumbstick Right"]) {202if (elements[@"Right Thumbstick X Axis"]) {203return true;204}205}206if ([element isEqualToString:@"Right Thumbstick Up"] ||207[element isEqualToString:@"Right Thumbstick Down"]) {208if (elements[@"Right Thumbstick Y Axis"]) {209return true;210}211}212if (device->is_siri_remote) {213if ([element isEqualToString:@"Direction Pad Left"] ||214[element isEqualToString:@"Direction Pad Right"]) {215if (elements[@"Direction Pad X Axis"]) {216return true;217}218}219if ([element isEqualToString:@"Direction Pad Up"] ||220[element isEqualToString:@"Direction Pad Down"]) {221if (elements[@"Direction Pad Y Axis"]) {222return true;223}224}225} else {226if ([element isEqualToString:@"Direction Pad X Axis"]) {227if (elements[@"Direction Pad Left"] &&228elements[@"Direction Pad Right"]) {229return true;230}231}232if ([element isEqualToString:@"Direction Pad Y Axis"]) {233if (elements[@"Direction Pad Up"] &&234elements[@"Direction Pad Down"]) {235return true;236}237}238}239if ([element isEqualToString:@"Cardinal Direction Pad X Axis"]) {240if (elements[@"Cardinal Direction Pad Left"] &&241elements[@"Cardinal Direction Pad Right"]) {242return true;243}244}245if ([element isEqualToString:@"Cardinal Direction Pad Y Axis"]) {246if (elements[@"Cardinal Direction Pad Up"] &&247elements[@"Cardinal Direction Pad Down"]) {248return true;249}250}251if ([element isEqualToString:@"Touchpad 1 X Axis"] ||252[element isEqualToString:@"Touchpad 1 Y Axis"] ||253[element isEqualToString:@"Touchpad 1 Left"] ||254[element isEqualToString:@"Touchpad 1 Right"] ||255[element isEqualToString:@"Touchpad 1 Up"] ||256[element isEqualToString:@"Touchpad 1 Down"] ||257[element isEqualToString:@"Touchpad 2 X Axis"] ||258[element isEqualToString:@"Touchpad 2 Y Axis"] ||259[element isEqualToString:@"Touchpad 2 Left"] ||260[element isEqualToString:@"Touchpad 2 Right"] ||261[element isEqualToString:@"Touchpad 2 Up"] ||262[element isEqualToString:@"Touchpad 2 Down"]) {263// The touchpad is handled separately264return true;265}266if ([element isEqualToString:@"Button Home"]) {267if (device->is_switch_joycon_pair) {268// The Nintendo Switch JoyCon home button doesn't ever show as being held down269return true;270}271#ifdef SDL_PLATFORM_TVOS272// The OS uses the home button, it's not available to apps273return true;274#endif275}276if ([element isEqualToString:@"Button Share"]) {277if (device->is_backbone_one) {278// The Backbone app uses share button279return true;280}281}282return false;283}284285static bool IOS_AddMFIJoystickDevice(SDL_JoystickDeviceItem *device, GCController *controller)286{287Uint16 vendor = 0;288Uint16 product = 0;289Uint8 subtype = 0;290const char *name = NULL;291292if (@available(macOS 11.3, iOS 14.5, tvOS 14.5, *)) {293if (!GCController.shouldMonitorBackgroundEvents) {294GCController.shouldMonitorBackgroundEvents = YES;295}296}297298/* Explicitly retain the controller because SDL_JoystickDeviceItem is a299* struct, and ARC doesn't work with structs. */300device->controller = (__bridge GCController *)CFBridgingRetain(controller);301302if (controller.vendorName) {303name = controller.vendorName.UTF8String;304}305306if (!name) {307name = "MFi Gamepad";308}309310device->name = SDL_CreateJoystickName(0, 0, NULL, name);311312#ifdef DEBUG_CONTROLLER_PROFILE313NSLog(@"Product name: %@\n", controller.vendorName);314NSLog(@"Product category: %@\n", controller.productCategory);315NSLog(@"Elements available:\n");316if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {317NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;318for (id key in controller.physicalInputProfile.buttons) {319NSLog(@"\tButton: %@ (%s)\n", key, elements[key].analog ? "analog" : "digital");320}321for (id key in controller.physicalInputProfile.axes) {322NSLog(@"\tAxis: %@\n", key);323}324for (id key in controller.physicalInputProfile.dpads) {325NSLog(@"\tHat: %@\n", key);326}327}328#endif // DEBUG_CONTROLLER_PROFILE329330device->is_xbox = IsControllerXbox(controller);331device->is_ps4 = IsControllerPS4(controller);332device->is_ps5 = IsControllerPS5(controller);333device->is_switch_pro = IsControllerSwitchPro(controller);334device->is_switch_joycon_pair = IsControllerSwitchJoyConPair(controller);335device->is_stadia = IsControllerStadia(controller);336device->is_backbone_one = IsControllerBackboneOne(controller);337device->is_switch_joyconL = IsControllerSwitchJoyConL(controller);338device->is_switch_joyconR = IsControllerSwitchJoyConR(controller);339#ifdef SDL_JOYSTICK_HIDAPI340if ((device->is_xbox && (HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_XBOXONE) ||341HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_XBOX360))) ||342(device->is_ps4 && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_PS4)) ||343(device->is_ps5 && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_PS5)) ||344(device->is_switch_pro && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO)) ||345(device->is_switch_joycon_pair && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR, 0, "")) ||346(device->is_stadia && HIDAPI_IsDevicePresent(USB_VENDOR_GOOGLE, USB_PRODUCT_GOOGLE_STADIA_CONTROLLER, 0, "")) ||347(device->is_switch_joyconL && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT, 0, "")) ||348(device->is_switch_joyconR && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT, 0, ""))) {349// The HIDAPI driver is taking care of this device350return false;351}352#endif353if (device->is_xbox && SDL_strncmp(name, "GamePad-", 8) == 0) {354// This is a Steam Virtual Gamepad, which isn't supported by GCController355return false;356}357CheckControllerSiriRemote(controller, &device->is_siri_remote);358359if (device->is_siri_remote && !SDL_GetHintBoolean(SDL_HINT_TV_REMOTE_AS_JOYSTICK, true)) {360// Ignore remotes, they'll be handled as keyboard input361return false;362}363364if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {365if (controller.physicalInputProfile.buttons[GCInputDualShockTouchpadButton] != nil) {366device->has_dualshock_touchpad = TRUE;367}368if (controller.physicalInputProfile.buttons[GCInputXboxPaddleOne] != nil) {369device->has_xbox_paddles = TRUE;370}371if (controller.physicalInputProfile.buttons[@"Button Share"] != nil) {372device->has_xbox_share_button = TRUE;373}374}375376if (device->is_backbone_one) {377vendor = USB_VENDOR_BACKBONE;378if (device->is_ps5) {379product = USB_PRODUCT_BACKBONE_ONE_IOS_PS5;380} else {381product = USB_PRODUCT_BACKBONE_ONE_IOS;382}383} else if (device->is_xbox) {384vendor = USB_VENDOR_MICROSOFT;385if (device->has_xbox_paddles) {386// Assume Xbox One Elite Series 2 Controller unless/until GCController flows VID/PID387product = USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH;388} else if (device->has_xbox_share_button) {389// Assume Xbox Series X Controller unless/until GCController flows VID/PID390product = USB_PRODUCT_XBOX_SERIES_X_BLE;391} else {392// Assume Xbox One S Bluetooth Controller unless/until GCController flows VID/PID393product = USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH;394}395} else if (device->is_ps4) {396// Assume DS4 Slim unless/until GCController flows VID/PID397vendor = USB_VENDOR_SONY;398product = USB_PRODUCT_SONY_DS4_SLIM;399if (device->has_dualshock_touchpad) {400subtype = 1;401}402} else if (device->is_ps5) {403vendor = USB_VENDOR_SONY;404product = USB_PRODUCT_SONY_DS5;405} else if (device->is_switch_pro) {406vendor = USB_VENDOR_NINTENDO;407product = USB_PRODUCT_NINTENDO_SWITCH_PRO;408device->has_nintendo_buttons = TRUE;409} else if (device->is_switch_joycon_pair) {410vendor = USB_VENDOR_NINTENDO;411product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR;412device->has_nintendo_buttons = TRUE;413} else if (device->is_switch_joyconL) {414vendor = USB_VENDOR_NINTENDO;415product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT;416} else if (device->is_switch_joyconR) {417vendor = USB_VENDOR_NINTENDO;418product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT;419} else if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {420vendor = USB_VENDOR_APPLE;421product = 4;422subtype = 4;423} else if (controller.extendedGamepad) {424vendor = USB_VENDOR_APPLE;425product = 1;426subtype = 1;427#ifdef SDL_PLATFORM_TVOS428} else if (controller.microGamepad) {429vendor = USB_VENDOR_APPLE;430product = 3;431subtype = 3;432#endif433} else {434// We don't know how to get input events from this device435return false;436}437438if (SDL_ShouldIgnoreJoystick(vendor, product, 0, name)) {439return false;440}441442if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {443NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;444445// Provide both axes and analog buttons as SDL axes446NSArray *axes = [[[elements allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]447filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {448if (ElementAlreadyHandled(device, (NSString *)object, elements)) {449return false;450}451452GCControllerElement *element = elements[object];453if (element.analog) {454if ([element isKindOfClass:[GCControllerAxisInput class]] ||455[element isKindOfClass:[GCControllerButtonInput class]]) {456return true;457}458}459return false;460}]];461NSArray *buttons = [[[elements allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]462filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {463if (ElementAlreadyHandled(device, (NSString *)object, elements)) {464return false;465}466467GCControllerElement *element = elements[object];468if ([element isKindOfClass:[GCControllerButtonInput class]]) {469return true;470}471return false;472}]];473/* Explicitly retain the arrays because SDL_JoystickDeviceItem is a474* struct, and ARC doesn't work with structs. */475device->naxes = (int)axes.count;476device->axes = (__bridge NSArray *)CFBridgingRetain(axes);477device->nbuttons = (int)buttons.count;478device->buttons = (__bridge NSArray *)CFBridgingRetain(buttons);479subtype = 4;480481#ifdef DEBUG_CONTROLLER_PROFILE482NSLog(@"Elements used:\n", controller.vendorName);483for (id key in device->buttons) {484NSLog(@"\tButton: %@ (%s)\n", key, elements[key].analog ? "analog" : "digital");485}486for (id key in device->axes) {487NSLog(@"\tAxis: %@\n", key);488}489#endif // DEBUG_CONTROLLER_PROFILE490491#ifdef SDL_PLATFORM_TVOS492// tvOS turns the menu button into a system gesture, so we grab it here instead493if (elements[GCInputButtonMenu] && !elements[@"Button Home"]) {494device->pause_button_index = (int)[device->buttons indexOfObject:GCInputButtonMenu];495}496#endif497} else if (controller.extendedGamepad) {498GCExtendedGamepad *gamepad = controller.extendedGamepad;499int nbuttons = 0;500BOOL has_direct_menu = FALSE;501502// These buttons are part of the original MFi spec503device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_SOUTH);504device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_EAST);505device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_WEST);506device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_NORTH);507device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);508device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);509nbuttons += 6;510511// These buttons are available on some newer controllers512if (@available(macOS 10.14.1, iOS 12.1, tvOS 12.1, *)) {513if (gamepad.leftThumbstickButton) {514device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK);515++nbuttons;516}517if (gamepad.rightThumbstickButton) {518device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK);519++nbuttons;520}521}522if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {523if (gamepad.buttonOptions) {524device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_BACK);525++nbuttons;526}527}528device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_START);529++nbuttons;530531if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {532if (gamepad.buttonMenu) {533has_direct_menu = TRUE;534}535}536#ifdef SDL_PLATFORM_TVOS537// The single menu button isn't very reliable, at least as of tvOS 16.1538if ((device->button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) == 0) {539has_direct_menu = FALSE;540}541#endif542if (!has_direct_menu) {543device->pause_button_index = (nbuttons - 1);544}545546device->naxes = 6; // 2 thumbsticks and 2 triggers547device->nhats = 1; // d-pad548device->nbuttons = nbuttons;549}550#ifdef SDL_PLATFORM_TVOS551else if (controller.microGamepad) {552int nbuttons = 0;553554device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_SOUTH);555device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_WEST); // Button X on microGamepad556device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_EAST);557nbuttons += 3;558device->pause_button_index = (nbuttons - 1);559560device->naxes = 2; // treat the touch surface as two axes561device->nhats = 0; // apparently the touch surface-as-dpad is buggy562device->nbuttons = nbuttons;563564controller.microGamepad.allowsRotation = SDL_GetHintBoolean(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, false);565}566#endif567else {568// We don't know how to get input events from this device569return false;570}571572Uint16 signature;573if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {574signature = 0;575signature = SDL_crc16(signature, device->name, SDL_strlen(device->name));576for (id key in device->axes) {577const char *string = ((NSString *)key).UTF8String;578signature = SDL_crc16(signature, string, SDL_strlen(string));579}580for (id key in device->buttons) {581const char *string = ((NSString *)key).UTF8String;582signature = SDL_crc16(signature, string, SDL_strlen(string));583}584} else {585signature = device->button_mask;586}587device->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_BLUETOOTH, vendor, product, signature, NULL, name, 'm', subtype);588589/* This will be set when the first button press of the controller is590* detected. */591controller.playerIndex = -1;592return true;593}594#endif // SDL_JOYSTICK_MFI595596#ifdef SDL_JOYSTICK_MFI597static void IOS_AddJoystickDevice(GCController *controller)598{599SDL_JoystickDeviceItem *device = deviceList;600601while (device != NULL) {602if (device->controller == controller) {603return;604}605device = device->next;606}607608device = (SDL_JoystickDeviceItem *)SDL_calloc(1, sizeof(SDL_JoystickDeviceItem));609if (device == NULL) {610return;611}612613device->instance_id = SDL_GetNextObjectID();614device->pause_button_index = -1;615616if (controller) {617#ifdef SDL_JOYSTICK_MFI618if (!IOS_AddMFIJoystickDevice(device, controller)) {619SDL_free(device->name);620SDL_free(device);621return;622}623#else624SDL_free(device);625return;626#endif // SDL_JOYSTICK_MFI627}628629if (deviceList == NULL) {630deviceList = device;631} else {632SDL_JoystickDeviceItem *lastdevice = deviceList;633while (lastdevice->next != NULL) {634lastdevice = lastdevice->next;635}636lastdevice->next = device;637}638639++numjoysticks;640641SDL_PrivateJoystickAdded(device->instance_id);642}643#endif // SDL_JOYSTICK_MFI644645static SDL_JoystickDeviceItem *IOS_RemoveJoystickDevice(SDL_JoystickDeviceItem *device)646{647SDL_JoystickDeviceItem *prev = NULL;648SDL_JoystickDeviceItem *next = NULL;649SDL_JoystickDeviceItem *item = deviceList;650651if (device == NULL) {652return NULL;653}654655next = device->next;656657while (item != NULL) {658if (item == device) {659break;660}661prev = item;662item = item->next;663}664665// Unlink the device item from the device list.666if (prev) {667prev->next = device->next;668} else if (device == deviceList) {669deviceList = device->next;670}671672if (device->joystick) {673device->joystick->hwdata = NULL;674}675676#ifdef SDL_JOYSTICK_MFI677@autoreleasepool {678// These were explicitly retained in the struct, so they should be explicitly released before freeing the struct.679if (device->controller) {680GCController *controller = CFBridgingRelease((__bridge CFTypeRef)(device->controller));681controller.controllerPausedHandler = nil;682device->controller = nil;683}684if (device->axes) {685CFRelease((__bridge CFTypeRef)device->axes);686device->axes = nil;687}688if (device->buttons) {689CFRelease((__bridge CFTypeRef)device->buttons);690device->buttons = nil;691}692}693#endif // SDL_JOYSTICK_MFI694695--numjoysticks;696697SDL_PrivateJoystickRemoved(device->instance_id);698699SDL_free(device->name);700SDL_free(device);701702return next;703}704705#ifdef SDL_PLATFORM_TVOS706static void SDLCALL SDL_AppleTVRemoteRotationHintChanged(void *udata, const char *name, const char *oldValue, const char *newValue)707{708BOOL allowRotation = newValue != NULL && *newValue != '0';709710@autoreleasepool {711for (GCController *controller in [GCController controllers]) {712if (controller.microGamepad) {713controller.microGamepad.allowsRotation = allowRotation;714}715}716}717}718#endif // SDL_PLATFORM_TVOS719720static bool IOS_JoystickInit(void)721{722if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_MFI, true)) {723return true;724}725726#ifdef SDL_PLATFORM_MACOS727if (@available(macOS 10.16, *)) {728// Continue with initialization on macOS 11+729} else {730return true;731}732#endif733734@autoreleasepool {735#ifdef SDL_JOYSTICK_MFI736NSNotificationCenter *center;737#endif738739#ifdef SDL_JOYSTICK_MFI740// GameController.framework was added in iOS 7.741if (![GCController class]) {742return true;743}744745/* For whatever reason, this always returns an empty array on746macOS 11.0.1 */747for (GCController *controller in [GCController controllers]) {748IOS_AddJoystickDevice(controller);749}750751#ifdef SDL_PLATFORM_TVOS752SDL_AddHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION,753SDL_AppleTVRemoteRotationHintChanged, NULL);754#endif // SDL_PLATFORM_TVOS755756center = [NSNotificationCenter defaultCenter];757758connectObserver = [center addObserverForName:GCControllerDidConnectNotification759object:nil760queue:nil761usingBlock:^(NSNotification *note) {762GCController *controller = note.object;763SDL_LockJoysticks();764IOS_AddJoystickDevice(controller);765SDL_UnlockJoysticks();766}];767768disconnectObserver = [center addObserverForName:GCControllerDidDisconnectNotification769object:nil770queue:nil771usingBlock:^(NSNotification *note) {772GCController *controller = note.object;773SDL_JoystickDeviceItem *device;774SDL_LockJoysticks();775for (device = deviceList; device != NULL; device = device->next) {776if (device->controller == controller) {777IOS_RemoveJoystickDevice(device);778break;779}780}781SDL_UnlockJoysticks();782}];783#endif // SDL_JOYSTICK_MFI784}785786return true;787}788789static int IOS_JoystickGetCount(void)790{791return numjoysticks;792}793794static void IOS_JoystickDetect(void)795{796}797798static bool IOS_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name)799{800// We don't override any other drivers through this method801return false;802}803804static const char *IOS_JoystickGetDeviceName(int device_index)805{806SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);807return device ? device->name : "Unknown";808}809810static const char *IOS_JoystickGetDevicePath(int device_index)811{812return NULL;813}814815static int IOS_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index)816{817return -1;818}819820static int IOS_JoystickGetDevicePlayerIndex(int device_index)821{822#ifdef SDL_JOYSTICK_MFI823SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);824if (device && device->controller) {825return (int)device->controller.playerIndex;826}827#endif828return -1;829}830831static void IOS_JoystickSetDevicePlayerIndex(int device_index, int player_index)832{833#ifdef SDL_JOYSTICK_MFI834SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);835if (device && device->controller) {836device->controller.playerIndex = player_index;837}838#endif839}840841static SDL_GUID IOS_JoystickGetDeviceGUID(int device_index)842{843SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);844SDL_GUID guid;845if (device) {846guid = device->guid;847} else {848SDL_zero(guid);849}850return guid;851}852853static SDL_JoystickID IOS_JoystickGetDeviceInstanceID(int device_index)854{855SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);856return device ? device->instance_id : 0;857}858859static bool IOS_JoystickOpen(SDL_Joystick *joystick, int device_index)860{861SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);862if (device == NULL) {863return SDL_SetError("Could not open Joystick: no hardware device for the specified index");864}865866joystick->hwdata = device;867868joystick->naxes = device->naxes;869joystick->nhats = device->nhats;870joystick->nbuttons = device->nbuttons;871872if (device->has_dualshock_touchpad) {873SDL_PrivateJoystickAddTouchpad(joystick, 2);874}875876device->joystick = joystick;877878@autoreleasepool {879#ifdef SDL_JOYSTICK_MFI880if (device->pause_button_index >= 0) {881GCController *controller = device->controller;882controller.controllerPausedHandler = ^(GCController *c) {883if (joystick->hwdata) {884joystick->hwdata->pause_button_pressed = SDL_GetTicks();885}886};887}888889if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {890GCController *controller = joystick->hwdata->controller;891GCMotion *motion = controller.motion;892if (motion && motion.hasRotationRate) {893SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 0.0f);894}895if (motion && motion.hasGravityAndUserAcceleration) {896SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 0.0f);897}898}899900if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {901GCController *controller = joystick->hwdata->controller;902for (id key in controller.physicalInputProfile.buttons) {903GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key];904if ([button isBoundToSystemGesture]) {905button.preferredSystemGestureState = GCSystemGestureStateDisabled;906}907}908}909910if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {911GCController *controller = device->controller;912if (controller.light) {913SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN, true);914}915916if (controller.haptics) {917for (GCHapticsLocality locality in controller.haptics.supportedLocalities) {918if ([locality isEqualToString:GCHapticsLocalityHandles]) {919SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true);920} else if ([locality isEqualToString:GCHapticsLocalityTriggers]) {921SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true);922}923}924}925}926#endif // SDL_JOYSTICK_MFI927}928if (device->is_siri_remote) {929++SDL_AppleTVRemoteOpenedAsJoystick;930}931932return true;933}934935#ifdef SDL_JOYSTICK_MFI936static Uint8 IOS_MFIJoystickHatStateForDPad(GCControllerDirectionPad *dpad)937{938Uint8 hat = 0;939940if (dpad.up.isPressed) {941hat |= SDL_HAT_UP;942} else if (dpad.down.isPressed) {943hat |= SDL_HAT_DOWN;944}945946if (dpad.left.isPressed) {947hat |= SDL_HAT_LEFT;948} else if (dpad.right.isPressed) {949hat |= SDL_HAT_RIGHT;950}951952if (hat == 0) {953return SDL_HAT_CENTERED;954}955956return hat;957}958#endif959960static void IOS_MFIJoystickUpdate(SDL_Joystick *joystick)961{962#ifdef SDL_JOYSTICK_MFI963@autoreleasepool {964SDL_JoystickDeviceItem *device = joystick->hwdata;965GCController *controller = device->controller;966Uint8 hatstate = SDL_HAT_CENTERED;967int i;968Uint64 timestamp = SDL_GetTicksNS();969970#ifdef DEBUG_CONTROLLER_STATE971if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {972if (controller.physicalInputProfile) {973for (id key in controller.physicalInputProfile.buttons) {974GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key];975if (button.isPressed)976NSLog(@"Button %@ = %s\n", key, button.isPressed ? "pressed" : "released");977}978for (id key in controller.physicalInputProfile.axes) {979GCControllerAxisInput *axis = controller.physicalInputProfile.axes[key];980if (axis.value != 0.0f)981NSLog(@"Axis %@ = %g\n", key, axis.value);982}983for (id key in controller.physicalInputProfile.dpads) {984GCControllerDirectionPad *dpad = controller.physicalInputProfile.dpads[key];985if (dpad.up.isPressed || dpad.down.isPressed || dpad.left.isPressed || dpad.right.isPressed) {986NSLog(@"Hat %@ =%s%s%s%s\n", key,987dpad.up.isPressed ? " UP" : "",988dpad.down.isPressed ? " DOWN" : "",989dpad.left.isPressed ? " LEFT" : "",990dpad.right.isPressed ? " RIGHT" : "");991}992}993}994}995#endif // DEBUG_CONTROLLER_STATE996997if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {998NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;999NSDictionary<NSString *, GCControllerButtonInput *> *buttons = controller.physicalInputProfile.buttons;10001001int axis = 0;1002for (id key in device->axes) {1003Sint16 value;1004GCControllerElement *element = elements[key];1005if ([element isKindOfClass:[GCControllerAxisInput class]]) {1006value = (Sint16)([(GCControllerAxisInput *)element value] * 32767);1007} else {1008value = (Sint16)([(GCControllerButtonInput *)element value] * 32767);1009}1010SDL_SendJoystickAxis(timestamp, joystick, axis++, value);1011}10121013int button = 0;1014for (id key in device->buttons) {1015bool down;1016if (button == device->pause_button_index) {1017down = (device->pause_button_pressed > 0);1018} else {1019down = buttons[key].isPressed;1020}1021SDL_SendJoystickButton(timestamp, joystick, button++, down);1022}1023} else if (controller.extendedGamepad) {1024bool isstack;1025GCExtendedGamepad *gamepad = controller.extendedGamepad;10261027// Axis order matches the XInput Windows mappings.1028Sint16 axes[] = {1029(Sint16)(gamepad.leftThumbstick.xAxis.value * 32767),1030(Sint16)(gamepad.leftThumbstick.yAxis.value * -32767),1031(Sint16)((gamepad.leftTrigger.value * 65535) - 32768),1032(Sint16)(gamepad.rightThumbstick.xAxis.value * 32767),1033(Sint16)(gamepad.rightThumbstick.yAxis.value * -32767),1034(Sint16)((gamepad.rightTrigger.value * 65535) - 32768),1035};10361037// Button order matches the XInput Windows mappings.1038bool *buttons = SDL_small_alloc(bool, joystick->nbuttons, &isstack);1039int button_count = 0;10401041if (buttons == NULL) {1042return;1043}10441045// These buttons are part of the original MFi spec1046buttons[button_count++] = gamepad.buttonA.isPressed;1047buttons[button_count++] = gamepad.buttonB.isPressed;1048buttons[button_count++] = gamepad.buttonX.isPressed;1049buttons[button_count++] = gamepad.buttonY.isPressed;1050buttons[button_count++] = gamepad.leftShoulder.isPressed;1051buttons[button_count++] = gamepad.rightShoulder.isPressed;10521053// These buttons are available on some newer controllers1054if (@available(macOS 10.14.1, iOS 12.1, tvOS 12.1, *)) {1055if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK)) {1056buttons[button_count++] = gamepad.leftThumbstickButton.isPressed;1057}1058if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK)) {1059buttons[button_count++] = gamepad.rightThumbstickButton.isPressed;1060}1061}1062if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {1063if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) {1064buttons[button_count++] = gamepad.buttonOptions.isPressed;1065}1066}1067if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_START)) {1068if (device->pause_button_index >= 0) {1069// Guaranteed if buttonMenu is not supported on this OS1070buttons[button_count++] = (device->pause_button_pressed > 0);1071} else {1072if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) {1073buttons[button_count++] = gamepad.buttonMenu.isPressed;1074}1075}1076}10771078hatstate = IOS_MFIJoystickHatStateForDPad(gamepad.dpad);10791080for (i = 0; i < SDL_arraysize(axes); i++) {1081SDL_SendJoystickAxis(timestamp, joystick, i, axes[i]);1082}10831084for (i = 0; i < button_count; i++) {1085SDL_SendJoystickButton(timestamp, joystick, i, buttons[i]);1086}10871088SDL_small_free(buttons, isstack);1089}1090#ifdef SDL_PLATFORM_TVOS1091else if (controller.microGamepad) {1092GCMicroGamepad *gamepad = controller.microGamepad;10931094Sint16 axes[] = {1095(Sint16)(gamepad.dpad.xAxis.value * 32767),1096(Sint16)(gamepad.dpad.yAxis.value * -32767),1097};10981099for (i = 0; i < SDL_arraysize(axes); i++) {1100SDL_SendJoystickAxis(timestamp, joystick, i, axes[i]);1101}11021103bool buttons[joystick->nbuttons];1104int button_count = 0;1105buttons[button_count++] = gamepad.buttonA.isPressed;1106buttons[button_count++] = gamepad.buttonX.isPressed;1107buttons[button_count++] = (device->pause_button_pressed > 0);11081109for (i = 0; i < button_count; i++) {1110SDL_SendJoystickButton(timestamp, joystick, i, buttons[i]);1111}1112}1113#endif // SDL_PLATFORM_TVOS11141115if (joystick->nhats > 0) {1116SDL_SendJoystickHat(timestamp, joystick, 0, hatstate);1117}11181119if (device->pause_button_pressed) {1120// The pause callback is instantaneous, so we extend the duration to allow "holding down" by pressing it repeatedly1121const int PAUSE_BUTTON_PRESS_DURATION_MS = 250;1122if (SDL_GetTicks() >= device->pause_button_pressed + PAUSE_BUTTON_PRESS_DURATION_MS) {1123device->pause_button_pressed = 0;1124}1125}11261127if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1128if (device->has_dualshock_touchpad) {1129GCControllerDirectionPad *dpad;11301131dpad = controller.physicalInputProfile.dpads[GCInputDualShockTouchpadOne];1132if (dpad.xAxis.value != 0.f || dpad.yAxis.value != 0.f) {1133SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, true, (1.0f + dpad.xAxis.value) * 0.5f, 1.0f - (1.0f + dpad.yAxis.value) * 0.5f, 1.0f);1134} else {1135SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, false, 0.0f, 0.0f, 1.0f);1136}11371138dpad = controller.physicalInputProfile.dpads[GCInputDualShockTouchpadTwo];1139if (dpad.xAxis.value != 0.f || dpad.yAxis.value != 0.f) {1140SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, true, (1.0f + dpad.xAxis.value) * 0.5f, 1.0f - (1.0f + dpad.yAxis.value) * 0.5f, 1.0f);1141} else {1142SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, false, 0.0f, 0.0f, 1.0f);1143}1144}1145}11461147if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1148GCMotion *motion = controller.motion;1149if (motion && motion.sensorsActive) {1150float data[3];11511152if (motion.hasRotationRate) {1153GCRotationRate rate = motion.rotationRate;1154data[0] = rate.x;1155data[1] = rate.z;1156data[2] = -rate.y;1157SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, timestamp, data, 3);1158}1159if (motion.hasGravityAndUserAcceleration) {1160GCAcceleration accel = motion.acceleration;1161data[0] = -accel.x * SDL_STANDARD_GRAVITY;1162data[1] = -accel.y * SDL_STANDARD_GRAVITY;1163data[2] = -accel.z * SDL_STANDARD_GRAVITY;1164SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, timestamp, data, 3);1165}1166}1167}11681169if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1170GCDeviceBattery *battery = controller.battery;1171if (battery) {1172SDL_PowerState state = SDL_POWERSTATE_UNKNOWN;1173int percent = (int)SDL_roundf(battery.batteryLevel * 100.0f);11741175switch (battery.batteryState) {1176case GCDeviceBatteryStateDischarging:1177state = SDL_POWERSTATE_ON_BATTERY;1178break;1179case GCDeviceBatteryStateCharging:1180state = SDL_POWERSTATE_CHARGING;1181break;1182case GCDeviceBatteryStateFull:1183state = SDL_POWERSTATE_CHARGED;1184break;1185default:1186break;1187}11881189SDL_SendJoystickPowerInfo(joystick, state, percent);1190}1191}1192}1193#endif // SDL_JOYSTICK_MFI1194}11951196#ifdef SDL_JOYSTICK_MFI1197@interface SDL3_RumbleMotor : NSObject1198@property(nonatomic, strong) CHHapticEngine *engine API_AVAILABLE(macos(10.16), ios(13.0), tvos(14.0));1199@property(nonatomic, strong) id<CHHapticPatternPlayer> player API_AVAILABLE(macos(10.16), ios(13.0), tvos(14.0));1200@property bool active;1201@end12021203@implementation SDL3_RumbleMotor1204{1205}12061207- (void)cleanup1208{1209@autoreleasepool {1210if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1211if (self.player != nil) {1212[self.player cancelAndReturnError:nil];1213self.player = nil;1214}1215if (self.engine != nil) {1216[self.engine stopWithCompletionHandler:nil];1217self.engine = nil;1218}1219}1220}1221}12221223- (bool)setIntensity:(float)intensity1224{1225@autoreleasepool {1226if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1227NSError *error = nil;1228CHHapticDynamicParameter *param;12291230if (self.engine == nil) {1231return SDL_SetError("Haptics engine was stopped");1232}12331234if (intensity == 0.0f) {1235if (self.player && self.active) {1236[self.player stopAtTime:0 error:&error];1237}1238self.active = false;1239return true;1240}12411242if (self.player == nil) {1243CHHapticEventParameter *event_param = [[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticIntensity value:1.0f];1244CHHapticEvent *event = [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticContinuous parameters:[NSArray arrayWithObjects:event_param, nil] relativeTime:0 duration:GCHapticDurationInfinite];1245CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithEvents:[NSArray arrayWithObject:event] parameters:[[NSArray alloc] init] error:&error];1246if (error != nil) {1247return SDL_SetError("Couldn't create haptic pattern: %s", [error.localizedDescription UTF8String]);1248}12491250self.player = [self.engine createPlayerWithPattern:pattern error:&error];1251if (error != nil) {1252return SDL_SetError("Couldn't create haptic player: %s", [error.localizedDescription UTF8String]);1253}1254self.active = false;1255}12561257param = [[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl value:intensity relativeTime:0];1258[self.player sendParameters:[NSArray arrayWithObject:param] atTime:0 error:&error];1259if (error != nil) {1260return SDL_SetError("Couldn't update haptic player: %s", [error.localizedDescription UTF8String]);1261}12621263if (!self.active) {1264[self.player startAtTime:0 error:&error];1265self.active = true;1266}1267}12681269return true;1270}1271}12721273- (id)initWithController:(GCController *)controller locality:(GCHapticsLocality)locality API_AVAILABLE(macos(10.16), ios(14.0), tvos(14.0))1274{1275@autoreleasepool {1276NSError *error;1277__weak __typeof(self) weakSelf;1278self = [super init];1279weakSelf = self;12801281self.engine = [controller.haptics createEngineWithLocality:locality];1282if (self.engine == nil) {1283SDL_SetError("Couldn't create haptics engine");1284return nil;1285}12861287[self.engine startAndReturnError:&error];1288if (error != nil) {1289SDL_SetError("Couldn't start haptics engine");1290return nil;1291}12921293self.engine.stoppedHandler = ^(CHHapticEngineStoppedReason stoppedReason) {1294SDL3_RumbleMotor *_this = weakSelf;1295if (_this == nil) {1296return;1297}12981299_this.player = nil;1300_this.engine = nil;1301};1302self.engine.resetHandler = ^{1303SDL3_RumbleMotor *_this = weakSelf;1304if (_this == nil) {1305return;1306}13071308_this.player = nil;1309[_this.engine startAndReturnError:nil];1310};13111312return self;1313}1314}13151316@end13171318@interface SDL3_RumbleContext : NSObject1319@property(nonatomic, strong) SDL3_RumbleMotor *lowFrequencyMotor;1320@property(nonatomic, strong) SDL3_RumbleMotor *highFrequencyMotor;1321@property(nonatomic, strong) SDL3_RumbleMotor *leftTriggerMotor;1322@property(nonatomic, strong) SDL3_RumbleMotor *rightTriggerMotor;1323@end13241325@implementation SDL3_RumbleContext1326{1327}13281329- (id)initWithLowFrequencyMotor:(SDL3_RumbleMotor *)low_frequency_motor1330HighFrequencyMotor:(SDL3_RumbleMotor *)high_frequency_motor1331LeftTriggerMotor:(SDL3_RumbleMotor *)left_trigger_motor1332RightTriggerMotor:(SDL3_RumbleMotor *)right_trigger_motor1333{1334self = [super init];1335self.lowFrequencyMotor = low_frequency_motor;1336self.highFrequencyMotor = high_frequency_motor;1337self.leftTriggerMotor = left_trigger_motor;1338self.rightTriggerMotor = right_trigger_motor;1339return self;1340}13411342- (bool)rumbleWithLowFrequency:(Uint16)low_frequency_rumble andHighFrequency:(Uint16)high_frequency_rumble1343{1344bool result = true;13451346result &= [self.lowFrequencyMotor setIntensity:((float)low_frequency_rumble / 65535.0f)];1347result &= [self.highFrequencyMotor setIntensity:((float)high_frequency_rumble / 65535.0f)];1348return result;1349}13501351- (bool)rumbleLeftTrigger:(Uint16)left_rumble andRightTrigger:(Uint16)right_rumble1352{1353bool result = false;13541355if (self.leftTriggerMotor && self.rightTriggerMotor) {1356result &= [self.leftTriggerMotor setIntensity:((float)left_rumble / 65535.0f)];1357result &= [self.rightTriggerMotor setIntensity:((float)right_rumble / 65535.0f)];1358} else {1359result = SDL_Unsupported();1360}1361return result;1362}13631364- (void)cleanup1365{1366[self.lowFrequencyMotor cleanup];1367[self.highFrequencyMotor cleanup];1368}13691370@end13711372static SDL3_RumbleContext *IOS_JoystickInitRumble(GCController *controller)1373{1374@autoreleasepool {1375if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1376SDL3_RumbleMotor *low_frequency_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftHandle];1377SDL3_RumbleMotor *high_frequency_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightHandle];1378SDL3_RumbleMotor *left_trigger_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftTrigger];1379SDL3_RumbleMotor *right_trigger_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightTrigger];1380if (low_frequency_motor && high_frequency_motor) {1381return [[SDL3_RumbleContext alloc] initWithLowFrequencyMotor:low_frequency_motor1382HighFrequencyMotor:high_frequency_motor1383LeftTriggerMotor:left_trigger_motor1384RightTriggerMotor:right_trigger_motor];1385}1386}1387}1388return nil;1389}13901391#endif // SDL_JOYSTICK_MFI13921393static bool IOS_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)1394{1395#ifdef SDL_JOYSTICK_MFI1396SDL_JoystickDeviceItem *device = joystick->hwdata;13971398if (device == NULL) {1399return SDL_SetError("Controller is no longer connected");1400}14011402if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1403if (!device->rumble && device->controller && device->controller.haptics) {1404SDL3_RumbleContext *rumble = IOS_JoystickInitRumble(device->controller);1405if (rumble) {1406device->rumble = (void *)CFBridgingRetain(rumble);1407}1408}1409}14101411if (device->rumble) {1412SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble;1413return [rumble rumbleWithLowFrequency:low_frequency_rumble andHighFrequency:high_frequency_rumble];1414}1415#endif1416return SDL_Unsupported();1417}14181419static bool IOS_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)1420{1421#ifdef SDL_JOYSTICK_MFI1422SDL_JoystickDeviceItem *device = joystick->hwdata;14231424if (device == NULL) {1425return SDL_SetError("Controller is no longer connected");1426}14271428if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1429if (!device->rumble && device->controller && device->controller.haptics) {1430SDL3_RumbleContext *rumble = IOS_JoystickInitRumble(device->controller);1431if (rumble) {1432device->rumble = (void *)CFBridgingRetain(rumble);1433}1434}1435}14361437if (device->rumble) {1438SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble;1439return [rumble rumbleLeftTrigger:left_rumble andRightTrigger:right_rumble];1440}1441#endif1442return SDL_Unsupported();1443}14441445static bool IOS_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)1446{1447@autoreleasepool {1448SDL_JoystickDeviceItem *device = joystick->hwdata;14491450if (device == NULL) {1451return SDL_SetError("Controller is no longer connected");1452}14531454if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1455GCController *controller = device->controller;1456GCDeviceLight *light = controller.light;1457if (light) {1458light.color = [[GCColor alloc] initWithRed:(float)red / 255.0f1459green:(float)green / 255.0f1460blue:(float)blue / 255.0f];1461return true;1462}1463}1464}1465return SDL_Unsupported();1466}14671468static bool IOS_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size)1469{1470return SDL_Unsupported();1471}14721473static bool IOS_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled)1474{1475@autoreleasepool {1476SDL_JoystickDeviceItem *device = joystick->hwdata;14771478if (device == NULL) {1479return SDL_SetError("Controller is no longer connected");1480}14811482if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1483GCController *controller = device->controller;1484GCMotion *motion = controller.motion;1485if (motion) {1486motion.sensorsActive = enabled ? YES : NO;1487return true;1488}1489}1490}14911492return SDL_Unsupported();1493}14941495static void IOS_JoystickUpdate(SDL_Joystick *joystick)1496{1497SDL_JoystickDeviceItem *device = joystick->hwdata;14981499if (device == NULL) {1500return;1501}15021503if (device->controller) {1504IOS_MFIJoystickUpdate(joystick);1505}1506}15071508static void IOS_JoystickClose(SDL_Joystick *joystick)1509{1510SDL_JoystickDeviceItem *device = joystick->hwdata;15111512if (device == NULL) {1513return;1514}15151516device->joystick = NULL;15171518#ifdef SDL_JOYSTICK_MFI1519@autoreleasepool {1520if (device->rumble) {1521SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble;15221523[rumble cleanup];1524CFRelease(device->rumble);1525device->rumble = NULL;1526}15271528if (device->controller) {1529GCController *controller = device->controller;1530controller.controllerPausedHandler = nil;1531controller.playerIndex = -1;15321533if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1534for (id key in controller.physicalInputProfile.buttons) {1535GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key];1536if ([button isBoundToSystemGesture]) {1537button.preferredSystemGestureState = GCSystemGestureStateEnabled;1538}1539}1540}1541}1542}1543#endif // SDL_JOYSTICK_MFI15441545if (device->is_siri_remote) {1546--SDL_AppleTVRemoteOpenedAsJoystick;1547}1548}15491550static void IOS_JoystickQuit(void)1551{1552@autoreleasepool {1553#ifdef SDL_JOYSTICK_MFI1554NSNotificationCenter *center = [NSNotificationCenter defaultCenter];15551556if (connectObserver) {1557[center removeObserver:connectObserver name:GCControllerDidConnectNotification object:nil];1558connectObserver = nil;1559}15601561if (disconnectObserver) {1562[center removeObserver:disconnectObserver name:GCControllerDidDisconnectNotification object:nil];1563disconnectObserver = nil;1564}15651566#ifdef SDL_PLATFORM_TVOS1567SDL_RemoveHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION,1568SDL_AppleTVRemoteRotationHintChanged, NULL);1569#endif // SDL_PLATFORM_TVOS1570#endif // SDL_JOYSTICK_MFI15711572while (deviceList != NULL) {1573IOS_RemoveJoystickDevice(deviceList);1574}1575}15761577numjoysticks = 0;1578}15791580static bool IOS_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out)1581{1582SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index);1583if (device == NULL) {1584return false;1585}15861587if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1588int axis = 0;1589for (id key in device->axes) {1590if ([(NSString *)key isEqualToString:@"Left Thumbstick X Axis"] ||1591[(NSString *)key isEqualToString:@"Direction Pad X Axis"]) {1592out->leftx.kind = EMappingKind_Axis;1593out->leftx.target = axis;1594} else if ([(NSString *)key isEqualToString:@"Left Thumbstick Y Axis"] ||1595[(NSString *)key isEqualToString:@"Direction Pad Y Axis"]) {1596out->lefty.kind = EMappingKind_Axis;1597out->lefty.target = axis;1598out->lefty.axis_reversed = true;1599} else if ([(NSString *)key isEqualToString:@"Right Thumbstick X Axis"]) {1600out->rightx.kind = EMappingKind_Axis;1601out->rightx.target = axis;1602} else if ([(NSString *)key isEqualToString:@"Right Thumbstick Y Axis"]) {1603out->righty.kind = EMappingKind_Axis;1604out->righty.target = axis;1605out->righty.axis_reversed = true;1606} else if ([(NSString *)key isEqualToString:GCInputLeftTrigger]) {1607out->lefttrigger.kind = EMappingKind_Axis;1608out->lefttrigger.target = axis;1609out->lefttrigger.half_axis_positive = true;1610} else if ([(NSString *)key isEqualToString:GCInputRightTrigger]) {1611out->righttrigger.kind = EMappingKind_Axis;1612out->righttrigger.target = axis;1613out->righttrigger.half_axis_positive = true;1614}1615++axis;1616}16171618int button = 0;1619for (id key in device->buttons) {1620SDL_InputMapping *mapping = NULL;16211622if ([(NSString *)key isEqualToString:GCInputButtonA]) {1623if (device->is_siri_remote > 1) {1624// GCInputButtonA is triggered for any D-Pad press, ignore it in favor of "Button Center"1625} else if (device->has_nintendo_buttons) {1626mapping = &out->b;1627} else {1628mapping = &out->a;1629}1630} else if ([(NSString *)key isEqualToString:GCInputButtonB]) {1631if (device->has_nintendo_buttons) {1632mapping = &out->a;1633} else if (device->is_switch_joyconL || device->is_switch_joyconR) {1634mapping = &out->x;1635} else {1636mapping = &out->b;1637}1638} else if ([(NSString *)key isEqualToString:GCInputButtonX]) {1639if (device->has_nintendo_buttons) {1640mapping = &out->y;1641} else if (device->is_switch_joyconL || device->is_switch_joyconR) {1642mapping = &out->b;1643} else {1644mapping = &out->x;1645}1646} else if ([(NSString *)key isEqualToString:GCInputButtonY]) {1647if (device->has_nintendo_buttons) {1648mapping = &out->x;1649} else {1650mapping = &out->y;1651}1652} else if ([(NSString *)key isEqualToString:@"Direction Pad Left"]) {1653mapping = &out->dpleft;1654} else if ([(NSString *)key isEqualToString:@"Direction Pad Right"]) {1655mapping = &out->dpright;1656} else if ([(NSString *)key isEqualToString:@"Direction Pad Up"]) {1657mapping = &out->dpup;1658} else if ([(NSString *)key isEqualToString:@"Direction Pad Down"]) {1659mapping = &out->dpdown;1660} else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Left"]) {1661mapping = &out->dpleft;1662} else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Right"]) {1663mapping = &out->dpright;1664} else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Up"]) {1665mapping = &out->dpup;1666} else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Down"]) {1667mapping = &out->dpdown;1668} else if ([(NSString *)key isEqualToString:GCInputLeftShoulder]) {1669mapping = &out->leftshoulder;1670} else if ([(NSString *)key isEqualToString:GCInputRightShoulder]) {1671mapping = &out->rightshoulder;1672} else if ([(NSString *)key isEqualToString:GCInputLeftThumbstickButton]) {1673mapping = &out->leftstick;1674} else if ([(NSString *)key isEqualToString:GCInputRightThumbstickButton]) {1675mapping = &out->rightstick;1676} else if ([(NSString *)key isEqualToString:@"Button Home"]) {1677mapping = &out->guide;1678} else if ([(NSString *)key isEqualToString:GCInputButtonMenu]) {1679if (device->is_siri_remote) {1680mapping = &out->b;1681} else {1682mapping = &out->start;1683}1684} else if ([(NSString *)key isEqualToString:GCInputButtonOptions]) {1685mapping = &out->back;1686} else if ([(NSString *)key isEqualToString:@"Button Share"]) {1687mapping = &out->misc1;1688} else if ([(NSString *)key isEqualToString:GCInputXboxPaddleOne]) {1689mapping = &out->right_paddle1;1690} else if ([(NSString *)key isEqualToString:GCInputXboxPaddleTwo]) {1691mapping = &out->right_paddle2;1692} else if ([(NSString *)key isEqualToString:GCInputXboxPaddleThree]) {1693mapping = &out->left_paddle1;1694} else if ([(NSString *)key isEqualToString:GCInputXboxPaddleFour]) {1695mapping = &out->left_paddle2;1696} else if ([(NSString *)key isEqualToString:GCInputLeftTrigger]) {1697mapping = &out->lefttrigger;1698} else if ([(NSString *)key isEqualToString:GCInputRightTrigger]) {1699mapping = &out->righttrigger;1700} else if ([(NSString *)key isEqualToString:GCInputDualShockTouchpadButton]) {1701mapping = &out->touchpad;1702} else if ([(NSString *)key isEqualToString:@"Button Center"]) {1703mapping = &out->a;1704}1705if (mapping && mapping->kind == EMappingKind_None) {1706mapping->kind = EMappingKind_Button;1707mapping->target = button;1708}1709++button;1710}17111712return true;1713}1714return false;1715}17161717#if defined(SDL_JOYSTICK_MFI) && defined(SDL_PLATFORM_MACOS)1718bool IOS_SupportedHIDDevice(IOHIDDeviceRef device)1719{1720if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_MFI, true)) {1721return false;1722}17231724if (@available(macOS 10.16, *)) {1725const int MAX_ATTEMPTS = 3;1726for (int attempt = 0; attempt < MAX_ATTEMPTS; ++attempt) {1727if ([GCController supportsHIDDevice:device]) {1728return true;1729}17301731// The framework may not have seen the device yet1732SDL_Delay(10);1733}1734}1735return false;1736}1737#endif17381739#ifdef SDL_JOYSTICK_MFI1740/* NOLINTNEXTLINE(readability-non-const-parameter): getCString takes a non-const char* */1741static void GetAppleSFSymbolsNameForElement(GCControllerElement *element, char *name)1742{1743if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1744if (element) {1745[element.sfSymbolsName getCString:name maxLength:255 encoding:NSASCIIStringEncoding];1746}1747}1748}17491750static GCControllerDirectionPad *GetDirectionalPadForController(GCController *controller)1751{1752if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1753return controller.physicalInputProfile.dpads[GCInputDirectionPad];1754}17551756if (controller.extendedGamepad) {1757return controller.extendedGamepad.dpad;1758}17591760if (controller.microGamepad) {1761return controller.microGamepad.dpad;1762}17631764return nil;1765}1766#endif // SDL_JOYSTICK_MFI17671768const char *IOS_GetAppleSFSymbolsNameForButton(SDL_Gamepad *gamepad, SDL_GamepadButton button)1769{1770char elementName[256];1771elementName[0] = '\0';17721773#ifdef SDL_JOYSTICK_MFI1774if (gamepad && SDL_GetGamepadJoystick(gamepad)->driver == &SDL_IOS_JoystickDriver) {1775if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1776GCController *controller = SDL_GetGamepadJoystick(gamepad)->hwdata->controller;1777NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;1778switch (button) {1779case SDL_GAMEPAD_BUTTON_SOUTH:1780GetAppleSFSymbolsNameForElement(elements[GCInputButtonA], elementName);1781break;1782case SDL_GAMEPAD_BUTTON_EAST:1783GetAppleSFSymbolsNameForElement(elements[GCInputButtonB], elementName);1784break;1785case SDL_GAMEPAD_BUTTON_WEST:1786GetAppleSFSymbolsNameForElement(elements[GCInputButtonX], elementName);1787break;1788case SDL_GAMEPAD_BUTTON_NORTH:1789GetAppleSFSymbolsNameForElement(elements[GCInputButtonY], elementName);1790break;1791case SDL_GAMEPAD_BUTTON_BACK:1792GetAppleSFSymbolsNameForElement(elements[GCInputButtonOptions], elementName);1793break;1794case SDL_GAMEPAD_BUTTON_GUIDE:1795GetAppleSFSymbolsNameForElement(elements[@"Button Home"], elementName);1796break;1797case SDL_GAMEPAD_BUTTON_START:1798GetAppleSFSymbolsNameForElement(elements[GCInputButtonMenu], elementName);1799break;1800case SDL_GAMEPAD_BUTTON_LEFT_STICK:1801GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstickButton], elementName);1802break;1803case SDL_GAMEPAD_BUTTON_RIGHT_STICK:1804GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstickButton], elementName);1805break;1806case SDL_GAMEPAD_BUTTON_LEFT_SHOULDER:1807GetAppleSFSymbolsNameForElement(elements[GCInputLeftShoulder], elementName);1808break;1809case SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER:1810GetAppleSFSymbolsNameForElement(elements[GCInputRightShoulder], elementName);1811break;1812case SDL_GAMEPAD_BUTTON_DPAD_UP:1813{1814GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);1815if (dpad) {1816GetAppleSFSymbolsNameForElement(dpad.up, elementName);1817if (SDL_strlen(elementName) == 0) {1818SDL_strlcpy(elementName, "dpad.up.fill", sizeof(elementName));1819}1820}1821break;1822}1823case SDL_GAMEPAD_BUTTON_DPAD_DOWN:1824{1825GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);1826if (dpad) {1827GetAppleSFSymbolsNameForElement(dpad.down, elementName);1828if (SDL_strlen(elementName) == 0) {1829SDL_strlcpy(elementName, "dpad.down.fill", sizeof(elementName));1830}1831}1832break;1833}1834case SDL_GAMEPAD_BUTTON_DPAD_LEFT:1835{1836GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);1837if (dpad) {1838GetAppleSFSymbolsNameForElement(dpad.left, elementName);1839if (SDL_strlen(elementName) == 0) {1840SDL_strlcpy(elementName, "dpad.left.fill", sizeof(elementName));1841}1842}1843break;1844}1845case SDL_GAMEPAD_BUTTON_DPAD_RIGHT:1846{1847GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller);1848if (dpad) {1849GetAppleSFSymbolsNameForElement(dpad.right, elementName);1850if (SDL_strlen(elementName) == 0) {1851SDL_strlcpy(elementName, "dpad.right.fill", sizeof(elementName));1852}1853}1854break;1855}1856case SDL_GAMEPAD_BUTTON_MISC1:1857GetAppleSFSymbolsNameForElement(elements[GCInputDualShockTouchpadButton], elementName);1858break;1859case SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1:1860GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleOne], elementName);1861break;1862case SDL_GAMEPAD_BUTTON_LEFT_PADDLE1:1863GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleThree], elementName);1864break;1865case SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2:1866GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleTwo], elementName);1867break;1868case SDL_GAMEPAD_BUTTON_LEFT_PADDLE2:1869GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleFour], elementName);1870break;1871case SDL_GAMEPAD_BUTTON_TOUCHPAD:1872GetAppleSFSymbolsNameForElement(elements[GCInputDualShockTouchpadButton], elementName);1873break;1874default:1875break;1876}1877}1878}1879#endif // SDL_JOYSTICK_MFI18801881return *elementName ? SDL_GetPersistentString(elementName) : NULL;1882}18831884const char *IOS_GetAppleSFSymbolsNameForAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis)1885{1886char elementName[256];1887elementName[0] = '\0';18881889#ifdef SDL_JOYSTICK_MFI1890if (gamepad && SDL_GetGamepadJoystick(gamepad)->driver == &SDL_IOS_JoystickDriver) {1891if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) {1892GCController *controller = SDL_GetGamepadJoystick(gamepad)->hwdata->controller;1893NSDictionary<NSString *, GCControllerElement *> *elements = controller.physicalInputProfile.elements;1894switch (axis) {1895case SDL_GAMEPAD_AXIS_LEFTX:1896GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstick], elementName);1897break;1898case SDL_GAMEPAD_AXIS_LEFTY:1899GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstick], elementName);1900break;1901case SDL_GAMEPAD_AXIS_RIGHTX:1902GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstick], elementName);1903break;1904case SDL_GAMEPAD_AXIS_RIGHTY:1905GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstick], elementName);1906break;1907case SDL_GAMEPAD_AXIS_LEFT_TRIGGER:1908GetAppleSFSymbolsNameForElement(elements[GCInputLeftTrigger], elementName);1909break;1910case SDL_GAMEPAD_AXIS_RIGHT_TRIGGER:1911GetAppleSFSymbolsNameForElement(elements[GCInputRightTrigger], elementName);1912break;1913default:1914break;1915}1916}1917}1918#endif // SDL_JOYSTICK_MFI19191920return *elementName ? SDL_GetPersistentString(elementName) : NULL;1921}19221923SDL_JoystickDriver SDL_IOS_JoystickDriver = {1924IOS_JoystickInit,1925IOS_JoystickGetCount,1926IOS_JoystickDetect,1927IOS_JoystickIsDevicePresent,1928IOS_JoystickGetDeviceName,1929IOS_JoystickGetDevicePath,1930IOS_JoystickGetDeviceSteamVirtualGamepadSlot,1931IOS_JoystickGetDevicePlayerIndex,1932IOS_JoystickSetDevicePlayerIndex,1933IOS_JoystickGetDeviceGUID,1934IOS_JoystickGetDeviceInstanceID,1935IOS_JoystickOpen,1936IOS_JoystickRumble,1937IOS_JoystickRumbleTriggers,1938IOS_JoystickSetLED,1939IOS_JoystickSendEffect,1940IOS_JoystickSetSensorsEnabled,1941IOS_JoystickUpdate,1942IOS_JoystickClose,1943IOS_JoystickQuit,1944IOS_JoystickGetGamepadMapping1945};194619471948