Reverted code formatting for Apple platforms

We didn't get the merge right, and rather than tease out exactly what happened, I'm just reverting for now.
This commit is contained in:
Sam Lantinga 2022-11-30 15:51:17 -08:00
parent 9e997cc787
commit 7b1000013e
48 changed files with 3489 additions and 3442 deletions

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,7 @@
extern int Cocoa_SetClipboardText(_THIS, const char *text);
extern char *Cocoa_GetClipboardText(_THIS);
extern SDL_bool Cocoa_HasClipboardText(_THIS);
extern void Cocoa_CheckClipboardUpdate(SDL_VideoData *data);
extern void Cocoa_CheckClipboardUpdate(SDL_VideoData * data);
#endif /* SDL_cocoaclipboard_h_ */

View File

@ -25,54 +25,53 @@
#include "SDL_cocoavideo.h"
#include "../../events/SDL_clipboardevents_c.h"
int Cocoa_SetClipboardText(_THIS, const char *text)
int
Cocoa_SetClipboardText(_THIS, const char *text)
{ @autoreleasepool
{
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
NSPasteboard *pasteboard;
NSString *format = NSPasteboardTypeString;
NSString *nsstr = [NSString stringWithUTF8String:text];
if (nsstr == nil) {
return SDL_SetError("Couldn't create NSString; is your string data in UTF-8 format?");
}
pasteboard = [NSPasteboard generalPasteboard];
data.clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil];
[pasteboard setString:nsstr forType:format];
return 0;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
NSPasteboard *pasteboard;
NSString *format = NSPasteboardTypeString;
NSString *nsstr = [NSString stringWithUTF8String:text];
if (nsstr == nil) {
return SDL_SetError("Couldn't create NSString; is your string data in UTF-8 format?");
}
}
pasteboard = [NSPasteboard generalPasteboard];
data.clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil];
[pasteboard setString:nsstr forType:format];
return 0;
}}
char *
Cocoa_GetClipboardText(_THIS)
{ @autoreleasepool
{
@autoreleasepool {
NSPasteboard *pasteboard;
NSString *format = NSPasteboardTypeString;
NSString *available;
char *text;
NSPasteboard *pasteboard;
NSString *format = NSPasteboardTypeString;
NSString *available;
char *text;
pasteboard = [NSPasteboard generalPasteboard];
available = [pasteboard availableTypeFromArray:[NSArray arrayWithObject:format]];
if ([available isEqualToString:format]) {
NSString *string;
const char *utf8;
pasteboard = [NSPasteboard generalPasteboard];
available = [pasteboard availableTypeFromArray:[NSArray arrayWithObject:format]];
if ([available isEqualToString:format]) {
NSString* string;
const char *utf8;
string = [pasteboard stringForType:format];
if (string == nil) {
utf8 = "";
} else {
utf8 = [string UTF8String];
}
text = SDL_strdup(utf8 ? utf8 : "");
string = [pasteboard stringForType:format];
if (string == nil) {
utf8 = "";
} else {
text = SDL_strdup("");
utf8 = [string UTF8String];
}
return text;
text = SDL_strdup(utf8 ? utf8 : "");
} else {
text = SDL_strdup("");
}
}
return text;
}}
SDL_bool
Cocoa_HasClipboardText(_THIS)
@ -86,22 +85,22 @@ Cocoa_HasClipboardText(_THIS)
return result;
}
void Cocoa_CheckClipboardUpdate(SDL_VideoData *data)
void
Cocoa_CheckClipboardUpdate(SDL_VideoData * data)
{ @autoreleasepool
{
@autoreleasepool {
NSPasteboard *pasteboard;
NSInteger count;
NSPasteboard *pasteboard;
NSInteger count;
pasteboard = [NSPasteboard generalPasteboard];
count = [pasteboard changeCount];
if (count != data.clipboard_count) {
if (data.clipboard_count) {
SDL_SendClipboardUpdate();
}
data.clipboard_count = count;
pasteboard = [NSPasteboard generalPasteboard];
count = [pasteboard changeCount];
if (count != data.clipboard_count) {
if (data.clipboard_count) {
SDL_SendClipboardUpdate();
}
data.clipboard_count = count;
}
}
}}
#endif /* SDL_VIDEO_DRIVER_COCOA */

View File

@ -25,7 +25,7 @@
extern void Cocoa_RegisterApp(void);
extern void Cocoa_PumpEvents(_THIS);
extern int Cocoa_WaitEventTimeout(_THIS, int timeout);
extern int Cocoa_WaitEventTimeout(_THIS, int timeout);
extern void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window);
extern void Cocoa_SuspendScreenSaver(_THIS);

View File

@ -45,7 +45,7 @@ static SDL_Window *FindSDLWindowForNSWindow(NSWindow *win)
SDL_VideoDevice *device = SDL_GetVideoDevice();
if (device && device->windows) {
for (sdlwindow = device->windows; sdlwindow; sdlwindow = sdlwindow->next) {
NSWindow *nswindow = ((__bridge SDL_WindowData *)sdlwindow->driverdata).nswindow;
NSWindow *nswindow = ((__bridge SDL_WindowData *) sdlwindow->driverdata).nswindow;
if (win == nswindow)
return sdlwindow;
}
@ -78,26 +78,26 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
SDL_VideoDevice *_this = SDL_GetVideoDevice();
switch ([theEvent type]) {
case NSEventTypeLeftMouseDown:
case NSEventTypeOtherMouseDown:
case NSEventTypeRightMouseDown:
case NSEventTypeLeftMouseUp:
case NSEventTypeOtherMouseUp:
case NSEventTypeRightMouseUp:
case NSEventTypeLeftMouseDragged:
case NSEventTypeRightMouseDragged:
case NSEventTypeOtherMouseDragged: /* usually middle mouse dragged */
case NSEventTypeMouseMoved:
case NSEventTypeScrollWheel:
Cocoa_HandleMouseEvent(_this, theEvent);
break;
case NSEventTypeKeyDown:
case NSEventTypeKeyUp:
case NSEventTypeFlagsChanged:
Cocoa_HandleKeyEvent(_this, theEvent);
break;
default:
break;
case NSEventTypeLeftMouseDown:
case NSEventTypeOtherMouseDown:
case NSEventTypeRightMouseDown:
case NSEventTypeLeftMouseUp:
case NSEventTypeOtherMouseUp:
case NSEventTypeRightMouseUp:
case NSEventTypeLeftMouseDragged:
case NSEventTypeRightMouseDragged:
case NSEventTypeOtherMouseDragged: /* usually middle mouse dragged */
case NSEventTypeMouseMoved:
case NSEventTypeScrollWheel:
Cocoa_HandleMouseEvent(_this, theEvent);
break;
case NSEventTypeKeyDown:
case NSEventTypeKeyUp:
case NSEventTypeFlagsChanged:
Cocoa_HandleKeyEvent(_this, theEvent);
break;
default:
break;
}
}
@ -116,23 +116,22 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
+ (void)registerUserDefaults
{
NSDictionary *appDefaults = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithBool:NO], @"AppleMomentumScrollSupported",
[NSNumber numberWithBool:NO], @"ApplePressAndHoldEnabled",
[NSNumber numberWithBool:YES], @"ApplePersistenceIgnoreState",
nil];
[NSNumber numberWithBool:NO], @"AppleMomentumScrollSupported",
[NSNumber numberWithBool:NO], @"ApplePressAndHoldEnabled",
[NSNumber numberWithBool:YES], @"ApplePersistenceIgnoreState",
nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
}
@end // SDLApplication
/* setAppleMenu disappeared from the headers in 10.4 */
@interface NSApplication (NSAppleMenu)
@interface NSApplication(NSAppleMenu)
- (void)setAppleMenu:(NSMenu *)menu;
@end
@interface SDLAppDelegate : NSObject <NSApplicationDelegate>
{
@public
@interface SDLAppDelegate : NSObject <NSApplicationDelegate> {
@public
BOOL seenFirstActivate;
}
@ -186,7 +185,7 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
- (void)windowWillClose:(NSNotification *)notification;
{
NSWindow *win = (NSWindow *)[notification object];
NSWindow *win = (NSWindow*)[notification object];
if (![win isKeyWindow]) {
return;
@ -293,7 +292,7 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
[i activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
SDL_Delay(300); /* !!! FIXME: this isn't right. */
SDL_Delay(300); /* !!! FIXME: this isn't right. */
[NSApp activateIgnoringOtherApps:YES];
}
@ -304,7 +303,7 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
- (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSString *path = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSString* path = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
SDL_SendDropFile(NULL, [path UTF8String]);
SDL_SendDropComplete(NULL);
}
@ -313,7 +312,8 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
static SDLAppDelegate *appDelegate = nil;
static NSString *GetApplicationName(void)
static NSString *
GetApplicationName(void)
{
NSString *appName;
@ -330,7 +330,8 @@ static NSString *GetApplicationName(void)
return appName;
}
static bool LoadMainMenuNibIfAvailable(void)
static bool
LoadMainMenuNibIfAvailable(void)
{
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
NSDictionary *infoDict;
@ -343,19 +344,20 @@ static bool LoadMainMenuNibIfAvailable(void)
infoDict = [[NSBundle mainBundle] infoDictionary];
if (infoDict) {
mainNibFileName = [infoDict valueForKey:@"NSMainNibFile"];
if (mainNibFileName) {
success = [[NSBundle mainBundle] loadNibNamed:mainNibFileName owner:[NSApplication sharedApplication] topLevelObjects:nil];
}
}
return success;
#else
return false;
#endif
}
static void CreateApplicationMenus(void)
static void
CreateApplicationMenus(void)
{
NSString *appName;
NSString *title;
@ -368,7 +370,7 @@ static void CreateApplicationMenus(void)
if (NSApp == nil) {
return;
}
mainMenu = [[NSMenu alloc] init];
/* Create the main menu bar */
@ -400,7 +402,7 @@ static void CreateApplicationMenus(void)
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
[menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
@ -426,7 +428,7 @@ static void CreateApplicationMenus(void)
[windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""];
/* Add the fullscreen toggle menu option. */
/* Cocoa should update the title to Enter or Exit Full Screen automatically.
* But if not, then just fallback to Toggle Full Screen.
@ -444,70 +446,71 @@ static void CreateApplicationMenus(void)
[NSApp setWindowsMenu:windowMenu];
}
void Cocoa_RegisterApp(void)
void
Cocoa_RegisterApp(void)
{ @autoreleasepool
{
@autoreleasepool {
/* This can get called more than once! Be careful what you initialize! */
/* This can get called more than once! Be careful what you initialize! */
if (NSApp == nil) {
[SDLApplication sharedApplication];
SDL_assert(NSApp != nil);
if (NSApp == nil) {
[SDLApplication sharedApplication];
SDL_assert(NSApp != nil);
s_bShouldHandleEventsInSDLApplication = SDL_TRUE;
s_bShouldHandleEventsInSDLApplication = SDL_TRUE;
if (!SDL_GetHintBoolean(SDL_HINT_MAC_BACKGROUND_APP, SDL_FALSE)) {
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
}
if (!SDL_GetHintBoolean(SDL_HINT_MAC_BACKGROUND_APP, SDL_FALSE)) {
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
}
/* If there aren't already menus in place, look to see if there's
* a nib we should use. If not, then manually create the basic
* menus we meed.
*/
if ([NSApp mainMenu] == nil) {
bool nibLoaded;
nibLoaded = LoadMainMenuNibIfAvailable();
if (!nibLoaded) {
CreateApplicationMenus();
}
}
[NSApp finishLaunching];
if ([NSApp delegate]) {
/* The SDL app delegate calls this in didFinishLaunching if it's
* attached to the NSApp, otherwise we need to call it manually.
*/
[SDLApplication registerUserDefaults];
/* If there aren't already menus in place, look to see if there's
* a nib we should use. If not, then manually create the basic
* menus we meed.
*/
if ([NSApp mainMenu] == nil) {
bool nibLoaded;
nibLoaded = LoadMainMenuNibIfAvailable();
if (!nibLoaded) {
CreateApplicationMenus();
}
}
if (NSApp && !appDelegate) {
appDelegate = [[SDLAppDelegate alloc] init];
/* If someone else has an app delegate, it means we can't turn a
* termination into SDL_Quit, and we can't handle application:openFile:
[NSApp finishLaunching];
if ([NSApp delegate]) {
/* The SDL app delegate calls this in didFinishLaunching if it's
* attached to the NSApp, otherwise we need to call it manually.
*/
if (![NSApp delegate]) {
/* Only register the URL event handler if we are being set as the
* app delegate to avoid replacing any existing event handler.
*/
[[NSAppleEventManager sharedAppleEventManager]
setEventHandler:appDelegate
andSelector:@selector(handleURLEvent:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
[(NSApplication *)NSApp setDelegate:appDelegate];
} else {
appDelegate->seenFirstActivate = YES;
}
[SDLApplication registerUserDefaults];
}
}
}
if (NSApp && !appDelegate) {
appDelegate = [[SDLAppDelegate alloc] init];
int Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate)
/* If someone else has an app delegate, it means we can't turn a
* termination into SDL_Quit, and we can't handle application:openFile:
*/
if (![NSApp delegate]) {
/* Only register the URL event handler if we are being set as the
* app delegate to avoid replacing any existing event handler.
*/
[[NSAppleEventManager sharedAppleEventManager]
setEventHandler:appDelegate
andSelector:@selector(handleURLEvent:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
[(NSApplication *)NSApp setDelegate:appDelegate];
} else {
appDelegate->seenFirstActivate = YES;
}
}
}}
int
Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate)
{
for (;;) {
NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:expiration inMode:NSDefaultRunLoopMode dequeue:YES];
if (event == nil) {
for ( ; ; ) {
NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:expiration inMode:NSDefaultRunLoopMode dequeue:YES ];
if ( event == nil ) {
return 0;
}
@ -517,62 +520,62 @@ int Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate)
// Pass events down to SDLApplication to be handled in sendEvent:
[NSApp sendEvent:event];
if (!accumulate) {
if ( !accumulate) {
break;
}
}
return 1;
}
int Cocoa_WaitEventTimeout(_THIS, int timeout)
int
Cocoa_WaitEventTimeout(_THIS, int timeout)
{ @autoreleasepool
{
@autoreleasepool {
if (timeout > 0) {
NSDate *limitDate = [NSDate dateWithTimeIntervalSinceNow:(double)timeout / 1000.0];
return Cocoa_PumpEventsUntilDate(_this, limitDate, false);
} else if (timeout == 0) {
return Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], false);
} else {
while (Cocoa_PumpEventsUntilDate(_this, [NSDate distantFuture], false) == 0) {
}
if (timeout > 0) {
NSDate *limitDate = [NSDate dateWithTimeIntervalSinceNow: (double) timeout / 1000.0];
return Cocoa_PumpEventsUntilDate(_this, limitDate, false);
} else if (timeout == 0) {
return Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], false);
} else {
while (Cocoa_PumpEventsUntilDate(_this, [NSDate distantFuture], false) == 0) {
}
return 1;
}
}
return 1;
}}
void Cocoa_PumpEvents(_THIS)
void
Cocoa_PumpEvents(_THIS)
{ @autoreleasepool
{
@autoreleasepool {
Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], true);
}
}
Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], true);
}}
void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window)
{ @autoreleasepool
{
@autoreleasepool {
NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
location:NSMakePoint(0, 0)
modifierFlags:0
timestamp:0.0
windowNumber:((__bridge SDL_WindowData *)window->driverdata).window_number
context:nil
subtype:0
data1:0
data2:0];
NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
location: NSMakePoint(0,0)
modifierFlags: 0
timestamp: 0.0
windowNumber: ((__bridge SDL_WindowData *) window->driverdata).window_number
context: nil
subtype: 0
data1: 0
data2: 0];
[NSApp postEvent:event atStart:YES];
[NSApp postEvent: event atStart: YES];
}}
void
Cocoa_SuspendScreenSaver(_THIS)
{ @autoreleasepool
{
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
if (data.screensaver_assertion) {
IOPMAssertionRelease(data.screensaver_assertion);
data.screensaver_assertion = kIOPMNullAssertionID;
}
}
void Cocoa_SuspendScreenSaver(_THIS)
{
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
if (data.screensaver_assertion) {
IOPMAssertionRelease(data.screensaver_assertion);
data.screensaver_assertion = kIOPMNullAssertionID;
}
if (_this->suspend_screensaver) {
/* FIXME: this should ideally describe the real reason why the game
@ -588,7 +591,7 @@ void Cocoa_SuspendScreenSaver(_THIS)
&assertion);
data.screensaver_assertion = assertion;
}
}
}}
#endif /* SDL_VIDEO_DRIVER_COCOA */

View File

@ -24,14 +24,14 @@
#define SDL_cocoakeyboard_h_
extern void Cocoa_InitKeyboard(_THIS);
extern void Cocoa_HandleKeyEvent(_THIS, NSEvent *event);
extern void Cocoa_HandleKeyEvent(_THIS, NSEvent * event);
extern void Cocoa_QuitKeyboard(_THIS);
extern void Cocoa_StartTextInput(_THIS);
extern void Cocoa_StopTextInput(_THIS);
extern void Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect);
extern void Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window *window, SDL_bool grabbed);
extern void Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window * window, SDL_bool grabbed);
#endif /* SDL_cocoakeyboard_h_ */

View File

@ -33,12 +33,11 @@
/*#define DEBUG_IME NSLog */
#define DEBUG_IME(...)
@interface SDLTranslatorResponder : NSView <NSTextInputClient>
{
@interface SDLTranslatorResponder : NSView <NSTextInputClient> {
NSString *_markedText;
NSRange _markedRange;
NSRange _selectedRange;
SDL_Rect _inputRect;
NSRange _markedRange;
NSRange _selectedRange;
SDL_Rect _inputRect;
}
- (void)doCommandBySelector:(SEL)myselector;
- (void)setInputRect:(const SDL_Rect *)rect;
@ -61,7 +60,7 @@
/* Could be NSString or NSAttributedString, so we have
* to test and convert it before return as SDL event */
if ([aString isKindOfClass:[NSAttributedString class]]) {
if ([aString isKindOfClass: [NSAttributedString class]]) {
str = [[aString string] UTF8String];
} else {
str = [aString UTF8String];
@ -117,10 +116,10 @@
_markedRange = NSMakeRange(0, [aString length]);
SDL_SendEditingText([aString UTF8String],
(int)selectedRange.location, (int)selectedRange.length);
(int) selectedRange.location, (int) selectedRange.length);
DEBUG_IME(@"setMarkedText: %@, (%d, %d)", _markedText,
selectedRange.location, selectedRange.length);
selectedRange.location, selectedRange.length);
}
- (void)unmarkText
@ -143,8 +142,8 @@
}
DEBUG_IME(@"firstRectForCharacterRange: (%d, %d): windowHeight = %g, rect = %@",
aRange.location, aRange.length, windowHeight,
NSStringFromRect(rect));
aRange.location, aRange.length, windowHeight,
NSStringFromRect(rect));
rect = [window convertRectToScreen:rect];
@ -159,7 +158,7 @@
- (NSInteger)conversationIdentifier
{
return (NSInteger)self;
return (NSInteger) self;
}
/* This method returns the index for character that is
@ -183,42 +182,43 @@
@end
static void HandleModifiers(_THIS, unsigned short scancode, unsigned int modifierFlags)
static void
HandleModifiers(_THIS, unsigned short scancode, unsigned int modifierFlags)
{
SDL_Scancode code = darwin_scancode_table[scancode];
const SDL_Scancode codes[] = {
SDL_SCANCODE_LSHIFT,
SDL_SCANCODE_LCTRL,
SDL_SCANCODE_LALT,
SDL_SCANCODE_LGUI,
SDL_SCANCODE_RSHIFT,
SDL_SCANCODE_RCTRL,
SDL_SCANCODE_RALT,
SDL_SCANCODE_RGUI,
SDL_SCANCODE_LSHIFT,
SDL_SCANCODE_LCTRL,
SDL_SCANCODE_LALT,
SDL_SCANCODE_LGUI,
};
const SDL_Scancode codes[] = {
SDL_SCANCODE_LSHIFT,
SDL_SCANCODE_LCTRL,
SDL_SCANCODE_LALT,
SDL_SCANCODE_LGUI,
SDL_SCANCODE_RSHIFT,
SDL_SCANCODE_RCTRL,
SDL_SCANCODE_RALT,
SDL_SCANCODE_RGUI,
SDL_SCANCODE_LSHIFT,
SDL_SCANCODE_LCTRL,
SDL_SCANCODE_LALT,
SDL_SCANCODE_LGUI, };
const unsigned int modifiers[] = {
NX_DEVICELSHIFTKEYMASK,
NX_DEVICELCTLKEYMASK,
NX_DEVICELALTKEYMASK,
NX_DEVICELCMDKEYMASK,
NX_DEVICERSHIFTKEYMASK,
NX_DEVICERCTLKEYMASK,
NX_DEVICERALTKEYMASK,
const unsigned int modifiers[] = {
NX_DEVICELSHIFTKEYMASK,
NX_DEVICELCTLKEYMASK,
NX_DEVICELALTKEYMASK,
NX_DEVICELCMDKEYMASK,
NX_DEVICERSHIFTKEYMASK,
NX_DEVICERCTLKEYMASK,
NX_DEVICERALTKEYMASK,
NX_DEVICERCMDKEYMASK,
NX_SHIFTMASK,
NX_CONTROLMASK,
NX_CONTROLMASK,
NX_ALTERNATEMASK,
NX_COMMANDMASK
};
NX_COMMANDMASK };
for (int i = 0; i < 12; i++) {
if (code == codes[i]) {
for (int i = 0; i < 12; i++)
{
if (code == codes[i])
{
if (modifierFlags & modifiers[i])
SDL_SendKeyboardKey(SDL_PRESSED, code);
else
@ -227,7 +227,8 @@ static void HandleModifiers(_THIS, unsigned short scancode, unsigned int modifie
}
}
static void UpdateKeymap(SDL_VideoData *data, SDL_bool send_event)
static void
UpdateKeymap(SDL_VideoData *data, SDL_bool send_event)
{
TISInputSourceRef key_layout;
const void *chr_data;
@ -270,11 +271,11 @@ static void UpdateKeymap(SDL_VideoData *data, SDL_bool send_event)
}
dead_key_state = 0;
err = UCKeyTranslate((UCKeyboardLayout *)chr_data,
i, kUCKeyActionDown,
0, keyboard_type,
kUCKeyTranslateNoDeadKeysMask,
&dead_key_state, 8, &len, s);
err = UCKeyTranslate ((UCKeyboardLayout *) chr_data,
i, kUCKeyActionDown,
0, keyboard_type,
kUCKeyTranslateNoDeadKeysMask,
&dead_key_state, 8, &len, s);
if (err != noErr) {
continue;
}
@ -291,9 +292,10 @@ cleanup:
CFRelease(key_layout);
}
void Cocoa_InitKeyboard(_THIS)
void
Cocoa_InitKeyboard(_THIS)
{
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
UpdateKeymap(data, SDL_FALSE);
@ -309,53 +311,54 @@ void Cocoa_InitKeyboard(_THIS)
SDL_ToggleModState(KMOD_CAPS, (data.modifierFlags & NSEventModifierFlagCapsLock) != 0);
}
void Cocoa_StartTextInput(_THIS)
void
Cocoa_StartTextInput(_THIS)
{ @autoreleasepool
{
@autoreleasepool {
NSView *parentView;
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
SDL_Window *window = SDL_GetKeyboardFocus();
NSWindow *nswindow = nil;
if (window) {
nswindow = ((__bridge SDL_WindowData *)window->driverdata).nswindow;
}
parentView = [nswindow contentView];
/* We only keep one field editor per process, since only the front most
* window can receive text input events, so it make no sense to keep more
* than one copy. When we switched to another window and requesting for
* text input, simply remove the field editor from its superview then add
* it to the front most window's content view */
if (!data.fieldEdit) {
data.fieldEdit =
[[SDLTranslatorResponder alloc] initWithFrame:NSMakeRect(0.0, 0.0, 0.0, 0.0)];
}
if (![[data.fieldEdit superview] isEqual:parentView]) {
/* DEBUG_IME(@"add fieldEdit to window contentView"); */
[data.fieldEdit removeFromSuperview];
[parentView addSubview:data.fieldEdit];
[nswindow makeFirstResponder:data.fieldEdit];
}
NSView *parentView;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
SDL_Window *window = SDL_GetKeyboardFocus();
NSWindow *nswindow = nil;
if (window) {
nswindow = ((__bridge SDL_WindowData*)window->driverdata).nswindow;
}
}
void Cocoa_StopTextInput(_THIS)
{
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
parentView = [nswindow contentView];
if (data && data.fieldEdit) {
[data.fieldEdit removeFromSuperview];
data.fieldEdit = nil;
}
/* We only keep one field editor per process, since only the front most
* window can receive text input events, so it make no sense to keep more
* than one copy. When we switched to another window and requesting for
* text input, simply remove the field editor from its superview then add
* it to the front most window's content view */
if (!data.fieldEdit) {
data.fieldEdit =
[[SDLTranslatorResponder alloc] initWithFrame: NSMakeRect(0.0, 0.0, 0.0, 0.0)];
}
}
void Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect)
if (![[data.fieldEdit superview] isEqual:parentView]) {
/* DEBUG_IME(@"add fieldEdit to window contentView"); */
[data.fieldEdit removeFromSuperview];
[parentView addSubview: data.fieldEdit];
[nswindow makeFirstResponder: data.fieldEdit];
}
}}
void
Cocoa_StopTextInput(_THIS)
{ @autoreleasepool
{
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
if (data && data.fieldEdit) {
[data.fieldEdit removeFromSuperview];
data.fieldEdit = nil;
}
}}
void
Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect)
{
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
if (!rect) {
SDL_InvalidParamError("rect");
@ -365,13 +368,14 @@ void Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect)
[data.fieldEdit setInputRect:rect];
}
void Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
void
Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
{
unsigned short scancode;
SDL_Scancode code;
SDL_VideoData *data = _this ? ((__bridge SDL_VideoData *)_this->driverdata) : nil;
SDL_VideoData *data = _this ? ((__bridge SDL_VideoData *) _this->driverdata) : nil;
if (!data) {
return; /* can happen when returning from fullscreen Space on shutdown */
return; /* can happen when returning from fullscreen Space on shutdown */
}
scancode = [event keyCode];
@ -420,20 +424,20 @@ void Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
SDL_SendKeyboardKey(SDL_RELEASED, code);
break;
case NSEventTypeFlagsChanged:
HandleModifiers(_this, scancode, (unsigned int)[event modifierFlags]);
HandleModifiers(_this, scancode, (unsigned int)[event modifierFlags]);
break;
default: /* just to avoid compiler warnings */
break;
}
}
void Cocoa_QuitKeyboard(_THIS)
void
Cocoa_QuitKeyboard(_THIS)
{
}
typedef int CGSConnection;
typedef enum
{
typedef enum {
CGSGlobalHotKeyEnable = 0,
CGSGlobalHotKeyDisable = 1,
} CGSGlobalHotKeyOperatingMode;
@ -441,7 +445,8 @@ typedef enum
extern CGSConnection _CGSDefaultConnection(void);
extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection connection, CGSGlobalHotKeyOperatingMode mode);
void Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window *window, SDL_bool grabbed)
void
Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
{
#if SDL_MAC_NO_SANDBOX
CGSSetGlobalHotKeyOperatingMode(_CGSDefaultConnection(), grabbed ? CGSGlobalHotKeyDisable : CGSGlobalHotKeyEnable);

View File

@ -27,18 +27,17 @@
#include "SDL_messagebox.h"
#include "SDL_cocoavideo.h"
@interface SDLMessageBoxPresenter : NSObject
{
@public
@interface SDLMessageBoxPresenter : NSObject {
@public
NSInteger clicked;
NSWindow *nswindow;
}
- (id)initWithParentWindow:(SDL_Window *)window;
- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
- (id) initWithParentWindow:(SDL_Window *)window;
- (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
@end
@implementation SDLMessageBoxPresenter
- (id)initWithParentWindow:(SDL_Window *)window
- (id) initWithParentWindow:(SDL_Window *)window
{
self = [super init];
if (self) {
@ -46,7 +45,7 @@
/* Retain the NSWindow because we'll show the alert later on the main thread */
if (window) {
nswindow = ((__bridge SDL_WindowData *)window->driverdata).nswindow;
nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow;
} else {
nswindow = nil;
}
@ -55,23 +54,19 @@
return self;
}
- (void)showAlert:(NSAlert *)alert
- (void)showAlert:(NSAlert*)alert
{
if (nswindow) {
#ifdef MAC_OS_X_VERSION_10_9
if ([alert respondsToSelector:@selector(beginSheetModalForWindow:completionHandler:)]) {
[alert beginSheetModalForWindow:nswindow
completionHandler:^(NSModalResponse returnCode) {
self->clicked = returnCode;
}];
[alert beginSheetModalForWindow:nswindow completionHandler:^(NSModalResponse returnCode) {
self->clicked = returnCode;
}];
} else
#endif
{
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
[alert beginSheetModalForWindow:nswindow
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
[alert beginSheetModalForWindow:nswindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
#endif
}
@ -86,18 +81,20 @@
}
}
- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
- (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
clicked = returnCode;
}
@end
static void Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue)
static void
Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue)
{
NSAlert *alert;
NSAlert* alert;
const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons;
SDLMessageBoxPresenter *presenter;
SDLMessageBoxPresenter* presenter;
NSInteger clicked;
int i;
Cocoa_RegisterApp();
@ -153,21 +150,19 @@ static void Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, i
}
/* Display a Cocoa message box */
int Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
int
Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{ @autoreleasepool
{
@autoreleasepool {
__block int returnValue = 0;
__block int returnValue = 0;
if ([NSThread isMainThread]) {
Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
});
}
return returnValue;
if ([NSThread isMainThread]) {
Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
} else {
dispatch_sync(dispatch_get_main_queue(), ^{ Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); });
}
}
return returnValue;
}}
#endif /* SDL_VIDEO_DRIVER_COCOA */

View File

@ -39,6 +39,7 @@
#import <Metal/Metal.h>
#import <QuartzCore/CAMetalLayer.h>
@interface SDL_cocoametalview : NSView
- (instancetype)initWithFrame:(NSRect)frame
@ -49,20 +50,21 @@
- (NSView *)hitTest:(NSPoint)point;
/* Override superclass tag so this class can set it. */
@property(assign, readonly) NSInteger tag;
@property (assign, readonly) NSInteger tag;
@property(nonatomic) BOOL highDPI;
@property(nonatomic) Uint32 sdlWindowID;
@property (nonatomic) BOOL highDPI;
@property (nonatomic) Uint32 sdlWindowID;
@end
SDL_MetalView Cocoa_Metal_CreateView(_THIS, SDL_Window *window);
SDL_MetalView Cocoa_Metal_CreateView(_THIS, SDL_Window * window);
void Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view);
void *Cocoa_Metal_GetLayer(_THIS, SDL_MetalView view);
void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h);
void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h);
#endif /* SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */
#endif /* SDL_cocoametalview_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View File

@ -33,7 +33,9 @@
#include "SDL_events.h"
#include "SDL_syswm.h"
static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event)
static int SDLCALL
SDL_MetalViewEventWatch(void *userdata, SDL_Event *event)
{
/* Update the drawable size when SDL receives a size changed event for
* the window that contains the metal view. It would be nice to use
@ -70,7 +72,7 @@ static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event)
/* When the wantsLayer property is set to YES, this method will be invoked to
* return a layer instance.
*/
- (CALayer *)makeBackingLayer
- (CALayer*)makeBackingLayer
{
return [self.class.layerClass layer];
}
@ -91,7 +93,7 @@ static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event)
[self updateDrawableSize];
}
return self;
}
@ -122,78 +124,71 @@ static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event)
metalLayer.drawableSize = NSSizeToCGSize(backingSize);
}
- (NSView *)hitTest:(NSPoint)point
{
- (NSView *)hitTest:(NSPoint)point {
return nil;
}
@end
SDL_MetalView
Cocoa_Metal_CreateView(_THIS, SDL_Window *window)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
NSView *view = data.nswindow.contentView;
BOOL highDPI = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0;
Uint32 windowID = SDL_GetWindowID(window);
SDL_cocoametalview *newview;
SDL_MetalView metalview;
Cocoa_Metal_CreateView(_THIS, SDL_Window * window)
{ @autoreleasepool {
SDL_WindowData* data = (__bridge SDL_WindowData *)window->driverdata;
NSView *view = data.nswindow.contentView;
BOOL highDPI = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0;
Uint32 windowID = SDL_GetWindowID(window);
SDL_cocoametalview *newview;
SDL_MetalView metalview;
newview = [[SDL_cocoametalview alloc] initWithFrame:view.frame
highDPI:highDPI
windowID:windowID];
if (newview == nil) {
SDL_OutOfMemory();
return NULL;
}
[view addSubview:newview];
metalview = (SDL_MetalView)CFBridgingRetain(newview);
return metalview;
newview = [[SDL_cocoametalview alloc] initWithFrame:view.frame
highDPI:highDPI
windowID:windowID];
if (newview == nil) {
SDL_OutOfMemory();
return NULL;
}
}
void Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view)
{
@autoreleasepool {
SDL_cocoametalview *metalview = CFBridgingRelease(view);
[metalview removeFromSuperview];
}
}
[view addSubview:newview];
metalview = (SDL_MetalView)CFBridgingRetain(newview);
return metalview;
}}
void
Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view)
{ @autoreleasepool {
SDL_cocoametalview *metalview = CFBridgingRelease(view);
[metalview removeFromSuperview];
}}
void *
Cocoa_Metal_GetLayer(_THIS, SDL_MetalView view)
{
@autoreleasepool {
SDL_cocoametalview *cocoaview = (__bridge SDL_cocoametalview *)view;
return (__bridge void *)cocoaview.layer;
}
}
{ @autoreleasepool {
SDL_cocoametalview *cocoaview = (__bridge SDL_cocoametalview *)view;
return (__bridge void *)cocoaview.layer;
}}
void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
NSView *contentView = data.sdlContentView;
SDL_cocoametalview *metalview = [contentView viewWithTag:SDL_METALVIEW_TAG];
if (metalview) {
CAMetalLayer *layer = (CAMetalLayer *)metalview.layer;
SDL_assert(layer != NULL);
if (w) {
*w = layer.drawableSize.width;
}
if (h) {
*h = layer.drawableSize.height;
}
} else {
/* Fall back to the viewport size. */
SDL_GetWindowSizeInPixels(window, w, h);
void
Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h)
{ @autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
NSView *contentView = data.sdlContentView;
SDL_cocoametalview* metalview = [contentView viewWithTag:SDL_METALVIEW_TAG];
if (metalview) {
CAMetalLayer *layer = (CAMetalLayer*)metalview.layer;
SDL_assert(layer != NULL);
if (w) {
*w = layer.drawableSize.width;
}
if (h) {
*h = layer.drawableSize.height;
}
} else {
/* Fall back to the viewport size. */
SDL_GetWindowSizeInPixels(window, w, h);
}
}
}}
#endif /* SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */

View File

@ -34,11 +34,11 @@ typedef struct
} SDL_DisplayModeData;
extern void Cocoa_InitModes(_THIS);
extern int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect);
extern int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect);
extern void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display);
extern int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hpdi, float *vdpi);
extern int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode);
extern int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect);
extern int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect);
extern void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display);
extern int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hpdi, float * vdpi);
extern int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
extern void Cocoa_QuitModes(_THIS);
#endif /* SDL_cocoamodes_h_ */

View File

@ -41,7 +41,9 @@
#define kDisplayModeNativeFlag 0x02000000
#endif
static int CG_SetError(const char *prefix, CGDisplayErr result)
static int
CG_SetError(const char *prefix, CGDisplayErr result)
{
const char *error;
@ -83,22 +85,24 @@ static int CG_SetError(const char *prefix, CGDisplayErr result)
return SDL_SetError("%s: %s", prefix, error);
}
static int GetDisplayModeRefreshRate(CGDisplayModeRef vidmode, CVDisplayLinkRef link)
static int
GetDisplayModeRefreshRate(CGDisplayModeRef vidmode, CVDisplayLinkRef link)
{
int refreshRate = (int)(CGDisplayModeGetRefreshRate(vidmode) + 0.5);
int refreshRate = (int) (CGDisplayModeGetRefreshRate(vidmode) + 0.5);
/* CGDisplayModeGetRefreshRate can return 0 (eg for built-in displays). */
if (refreshRate == 0 && link != NULL) {
CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link);
if ((time.flags & kCVTimeIsIndefinite) == 0 && time.timeValue != 0) {
refreshRate = (int)((time.timeScale / (double)time.timeValue) + 0.5);
refreshRate = (int) ((time.timeScale / (double) time.timeValue) + 0.5);
}
}
return refreshRate;
}
static SDL_bool HasValidDisplayModeFlags(CGDisplayModeRef vidmode)
static SDL_bool
HasValidDisplayModeFlags(CGDisplayModeRef vidmode)
{
uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode);
@ -115,7 +119,8 @@ static SDL_bool HasValidDisplayModeFlags(CGDisplayModeRef vidmode)
return SDL_TRUE;
}
static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode)
static Uint32
GetDisplayModePixelFormat(CGDisplayModeRef vidmode)
{
/* This API is deprecated in 10.11 with no good replacement (as of 10.15). */
CFStringRef fmt = CGDisplayModeCopyPixelEncoding(vidmode);
@ -125,10 +130,10 @@ static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode)
kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
pixelformat = SDL_PIXELFORMAT_ARGB8888;
} else if (CFStringCompare(fmt, CFSTR(IO16BitDirectPixels),
kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
pixelformat = SDL_PIXELFORMAT_ARGB1555;
} else if (CFStringCompare(fmt, CFSTR(kIO30BitDirectPixels),
kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
pixelformat = SDL_PIXELFORMAT_ARGB2101010;
} else {
/* ignore 8-bit and such for now. */
@ -139,12 +144,13 @@ static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode)
return pixelformat;
}
static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmodeCurrent, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode)
static SDL_bool
GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmodeCurrent, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode)
{
SDL_DisplayModeData *data;
bool usableForGUI = CGDisplayModeIsUsableForDesktopGUI(vidmode);
int width = (int)CGDisplayModeGetWidth(vidmode);
int height = (int)CGDisplayModeGetHeight(vidmode);
int width = (int) CGDisplayModeGetWidth(vidmode);
int height = (int) CGDisplayModeGetHeight(vidmode);
uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode);
int refreshrate = GetDisplayModeRefreshRate(vidmode, link);
Uint32 format = GetDisplayModePixelFormat(vidmode);
@ -172,17 +178,17 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
* CGDisplayModeGetPixelWidth and friends are only available in 10.8+. */
#ifdef MAC_OS_X_VERSION_10_8
if (modelist != NULL && floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) {
int pixelW = (int)CGDisplayModeGetPixelWidth(vidmode);
int pixelH = (int)CGDisplayModeGetPixelHeight(vidmode);
int pixelW = (int) CGDisplayModeGetPixelWidth(vidmode);
int pixelH = (int) CGDisplayModeGetPixelHeight(vidmode);
CFIndex modescount = CFArrayGetCount(modelist);
int i;
int i;
for (i = 0; i < modescount; i++) {
int otherW, otherH, otherpixelW, otherpixelH, otherrefresh;
Uint32 otherformat;
bool otherGUI;
CGDisplayModeRef othermode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modelist, i);
CGDisplayModeRef othermode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modelist, i);
uint32_t otherioflags = CGDisplayModeGetIOFlags(othermode);
if (CFEqual(vidmode, othermode)) {
@ -193,10 +199,10 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
continue;
}
otherW = (int)CGDisplayModeGetWidth(othermode);
otherH = (int)CGDisplayModeGetHeight(othermode);
otherpixelW = (int)CGDisplayModeGetPixelWidth(othermode);
otherpixelH = (int)CGDisplayModeGetPixelHeight(othermode);
otherW = (int) CGDisplayModeGetWidth(othermode);
otherH = (int) CGDisplayModeGetHeight(othermode);
otherpixelW = (int) CGDisplayModeGetPixelWidth(othermode);
otherpixelH = (int) CGDisplayModeGetPixelHeight(othermode);
otherrefresh = GetDisplayModeRefreshRate(othermode, link);
otherformat = GetDisplayModePixelFormat(othermode);
otherGUI = CGDisplayModeIsUsableForDesktopGUI(othermode);
@ -204,7 +210,10 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
/* Ignore this mode if it's low-dpi (@1x) and we have a high-dpi
* mode in the list with the same size in points.
*/
if (width == pixelW && height == pixelH && width == otherW && height == otherH && refreshrate == otherrefresh && format == otherformat && (otherpixelW != otherW || otherpixelH != otherH)) {
if (width == pixelW && height == pixelH
&& width == otherW && height == otherH
&& refreshrate == otherrefresh && format == otherformat
&& (otherpixelW != otherW || otherpixelH != otherH)) {
CFRelease(modes);
return SDL_FALSE;
}
@ -212,7 +221,10 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
/* Ignore this mode if it's interlaced and there's a non-interlaced
* mode in the list with the same properties.
*/
if (interlaced && ((otherioflags & kDisplayModeInterlacedFlag) == 0) && width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && refreshrate == otherrefresh && format == otherformat && usableForGUI == otherGUI) {
if (interlaced && ((otherioflags & kDisplayModeInterlacedFlag) == 0)
&& width == otherW && height == otherH && pixelW == otherpixelW
&& pixelH == otherpixelH && refreshrate == otherrefresh
&& format == otherformat && usableForGUI == otherGUI) {
CFRelease(modes);
return SDL_FALSE;
}
@ -220,7 +232,9 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
/* Ignore this mode if it's not usable for desktop UI and its
* properties are equal to another GUI-capable mode in the list.
*/
if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && !usableForGUI && otherGUI && refreshrate == otherrefresh && format == otherformat) {
if (width == otherW && height == otherH && pixelW == otherpixelW
&& pixelH == otherpixelH && !usableForGUI && otherGUI
&& refreshrate == otherrefresh && format == otherformat) {
CFRelease(modes);
return SDL_FALSE;
}
@ -246,14 +260,16 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
* correct but it being filtered out by SDL_AddDisplayMode as being
* a duplicate.
*/
if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && usableForGUI == otherGUI && refreshrate == otherrefresh && format == otherformat) {
if (width == otherW && height == otherH && pixelW == otherpixelW
&& pixelH == otherpixelH && usableForGUI == otherGUI
&& refreshrate == otherrefresh && format == otherformat) {
CFArrayAppendValue(modes, othermode);
}
}
}
#endif
data = (SDL_DisplayModeData *)SDL_malloc(sizeof(*data));
data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data));
if (!data) {
CFRelease(modes);
return SDL_FALSE;
@ -267,13 +283,14 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode
return SDL_TRUE;
}
static const char *Cocoa_GetDisplayName(CGDirectDisplayID displayID)
static const char *
Cocoa_GetDisplayName(CGDirectDisplayID displayID)
{
/* This API is deprecated in 10.9 with no good replacement (as of 10.15). */
io_service_t servicePort = CGDisplayIOServicePort(displayID);
CFDictionaryRef deviceInfo = IODisplayCreateInfoDictionary(servicePort, kIODisplayOnlyPreferredName);
NSDictionary *localizedNames = [(__bridge NSDictionary *)deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
const char *displayName = NULL;
const char* displayName = NULL;
if ([localizedNames count] > 0) {
displayName = SDL_strdup([[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] UTF8String]);
@ -282,94 +299,95 @@ static const char *Cocoa_GetDisplayName(CGDirectDisplayID displayID)
return displayName;
}
void Cocoa_InitModes(_THIS)
void
Cocoa_InitModes(_THIS)
{ @autoreleasepool
{
@autoreleasepool {
CGDisplayErr result;
CGDirectDisplayID *displays;
CGDisplayCount numDisplays;
SDL_bool isstack;
int pass, i;
CGDisplayErr result;
CGDirectDisplayID *displays;
CGDisplayCount numDisplays;
SDL_bool isstack;
int pass, i;
result = CGGetOnlineDisplayList(0, NULL, &numDisplays);
if (result != kCGErrorSuccess) {
CG_SetError("CGGetOnlineDisplayList()", result);
return;
}
displays = SDL_small_alloc(CGDirectDisplayID, numDisplays, &isstack);
result = CGGetOnlineDisplayList(numDisplays, displays, &numDisplays);
if (result != kCGErrorSuccess) {
CG_SetError("CGGetOnlineDisplayList()", result);
SDL_small_free(displays, isstack);
return;
}
result = CGGetOnlineDisplayList(0, NULL, &numDisplays);
if (result != kCGErrorSuccess) {
CG_SetError("CGGetOnlineDisplayList()", result);
return;
}
displays = SDL_small_alloc(CGDirectDisplayID, numDisplays, &isstack);
result = CGGetOnlineDisplayList(numDisplays, displays, &numDisplays);
if (result != kCGErrorSuccess) {
CG_SetError("CGGetOnlineDisplayList()", result);
SDL_small_free(displays, isstack);
return;
}
/* Pick up the primary display in the first pass, then get the rest */
for (pass = 0; pass < 2; ++pass) {
for (i = 0; i < numDisplays; ++i) {
SDL_VideoDisplay display;
SDL_DisplayData *displaydata;
SDL_DisplayMode mode;
CGDisplayModeRef moderef = NULL;
CVDisplayLinkRef link = NULL;
/* Pick up the primary display in the first pass, then get the rest */
for (pass = 0; pass < 2; ++pass) {
for (i = 0; i < numDisplays; ++i) {
SDL_VideoDisplay display;
SDL_DisplayData *displaydata;
SDL_DisplayMode mode;
CGDisplayModeRef moderef = NULL;
CVDisplayLinkRef link = NULL;
if (pass == 0) {
if (!CGDisplayIsMain(displays[i])) {
continue;
}
} else {
if (CGDisplayIsMain(displays[i])) {
continue;
}
}
if (CGDisplayMirrorsDisplay(displays[i]) != kCGNullDirectDisplay) {
if (pass == 0) {
if (!CGDisplayIsMain(displays[i])) {
continue;
}
moderef = CGDisplayCopyDisplayMode(displays[i]);
if (!moderef) {
} else {
if (CGDisplayIsMain(displays[i])) {
continue;
}
}
displaydata = (SDL_DisplayData *)SDL_malloc(sizeof(*displaydata));
if (!displaydata) {
CGDisplayModeRelease(moderef);
continue;
}
displaydata->display = displays[i];
if (CGDisplayMirrorsDisplay(displays[i]) != kCGNullDirectDisplay) {
continue;
}
CVDisplayLinkCreateWithCGDisplay(displays[i], &link);
moderef = CGDisplayCopyDisplayMode(displays[i]);
SDL_zero(display);
/* this returns a stddup'ed string */
display.name = (char *)Cocoa_GetDisplayName(displays[i]);
if (!GetDisplayMode(_this, moderef, SDL_TRUE, NULL, link, &mode)) {
CVDisplayLinkRelease(link);
CGDisplayModeRelease(moderef);
SDL_free(display.name);
SDL_free(displaydata);
continue;
}
if (!moderef) {
continue;
}
displaydata = (SDL_DisplayData *) SDL_malloc(sizeof(*displaydata));
if (!displaydata) {
CGDisplayModeRelease(moderef);
continue;
}
displaydata->display = displays[i];
CVDisplayLinkCreateWithCGDisplay(displays[i], &link);
SDL_zero(display);
/* this returns a stddup'ed string */
display.name = (char *)Cocoa_GetDisplayName(displays[i]);
if (!GetDisplayMode(_this, moderef, SDL_TRUE, NULL, link, &mode)) {
CVDisplayLinkRelease(link);
CGDisplayModeRelease(moderef);
display.desktop_mode = mode;
display.current_mode = mode;
display.driverdata = displaydata;
SDL_AddVideoDisplay(&display, SDL_FALSE);
SDL_free(display.name);
SDL_free(displaydata);
continue;
}
}
SDL_small_free(displays, isstack);
}
}
int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect)
CVDisplayLinkRelease(link);
CGDisplayModeRelease(moderef);
display.desktop_mode = mode;
display.current_mode = mode;
display.driverdata = displaydata;
SDL_AddVideoDisplay(&display, SDL_FALSE);
SDL_free(display.name);
}
}
SDL_small_free(displays, isstack);
}}
int
Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
{
SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata;
CGRect cgrect;
cgrect = CGDisplayBounds(displaydata->display);
@ -380,23 +398,24 @@ int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect)
return 0;
}
int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect)
int
Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
{
SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata;
const CGDirectDisplayID cgdisplay = displaydata->display;
NSArray *screens = [NSScreen screens];
NSScreen *screen = nil;
/* !!! FIXME: maybe track the NSScreen in SDL_DisplayData? */
for (NSScreen *i in screens) {
const CGDirectDisplayID thisDisplay = (CGDirectDisplayID)[[[i deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
const CGDirectDisplayID thisDisplay = (CGDirectDisplayID) [[[i deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
if (thisDisplay == cgdisplay) {
screen = i;
break;
}
}
SDL_assert(screen != nil); /* didn't find it?! */
SDL_assert(screen != nil); /* didn't find it?! */
if (screen == nil) {
return -1;
}
@ -412,88 +431,89 @@ int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rec
return 0;
}
int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi)
int
Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi)
{ @autoreleasepool
{
@autoreleasepool {
const float MM_IN_INCH = 25.4f;
const float MM_IN_INCH = 25.4f;
SDL_DisplayData *data = (SDL_DisplayData *)display->driverdata;
SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
/* we need the backingScaleFactor for Retina displays, which is only exposed through NSScreen, not CGDisplay, afaik, so find our screen... */
CGFloat scaleFactor = 1.0f;
NSArray *screens = [NSScreen screens];
NSSize displayNativeSize;
displayNativeSize.width = (int)CGDisplayPixelsWide(data->display);
displayNativeSize.height = (int)CGDisplayPixelsHigh(data->display);
for (NSScreen *screen in screens) {
const CGDirectDisplayID dpyid = (const CGDirectDisplayID)[[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
if (dpyid == data->display) {
/* we need the backingScaleFactor for Retina displays, which is only exposed through NSScreen, not CGDisplay, afaik, so find our screen... */
CGFloat scaleFactor = 1.0f;
NSArray *screens = [NSScreen screens];
NSSize displayNativeSize;
displayNativeSize.width = (int) CGDisplayPixelsWide(data->display);
displayNativeSize.height = (int) CGDisplayPixelsHigh(data->display);
for (NSScreen *screen in screens) {
const CGDirectDisplayID dpyid = (const CGDirectDisplayID ) [[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
if (dpyid == data->display) {
#ifdef MAC_OS_X_VERSION_10_8
/* Neither CGDisplayScreenSize(description's NSScreenNumber) nor [NSScreen backingScaleFactor] can calculate the correct dpi in macOS. E.g. backingScaleFactor is always 2 in all display modes for rMBP 16" */
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) {
CFStringRef dmKeys[1] = { kCGDisplayShowDuplicateLowResolutionModes };
CFBooleanRef dmValues[1] = { kCFBooleanTrue };
CFDictionaryRef dmOptions = CFDictionaryCreate(kCFAllocatorDefault, (const void **)dmKeys, (const void **)dmValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFArrayRef allDisplayModes = CGDisplayCopyAllDisplayModes(dpyid, dmOptions);
CFIndex n = CFArrayGetCount(allDisplayModes);
for (CFIndex i = 0; i < n; ++i) {
CGDisplayModeRef m = (CGDisplayModeRef)CFArrayGetValueAtIndex(allDisplayModes, i);
CGFloat width = CGDisplayModeGetPixelWidth(m);
CGFloat height = CGDisplayModeGetPixelHeight(m);
CGFloat HiDPIWidth = CGDisplayModeGetWidth(m);
// Only check 1x mode
if (width == HiDPIWidth) {
if (CGDisplayModeGetIOFlags(m) & kDisplayModeNativeFlag) {
displayNativeSize.width = width;
displayNativeSize.height = height;
break;
}
// Get the largest size even if kDisplayModeNativeFlag is not present e.g. iMac 27-Inch with 5K Retina
if (width > displayNativeSize.width) {
displayNativeSize.width = width;
displayNativeSize.height = height;
}
/* Neither CGDisplayScreenSize(description's NSScreenNumber) nor [NSScreen backingScaleFactor] can calculate the correct dpi in macOS. E.g. backingScaleFactor is always 2 in all display modes for rMBP 16" */
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) {
CFStringRef dmKeys[1] = { kCGDisplayShowDuplicateLowResolutionModes };
CFBooleanRef dmValues[1] = { kCFBooleanTrue };
CFDictionaryRef dmOptions = CFDictionaryCreate(kCFAllocatorDefault, (const void**) dmKeys, (const void**) dmValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );
CFArrayRef allDisplayModes = CGDisplayCopyAllDisplayModes(dpyid, dmOptions);
CFIndex n = CFArrayGetCount(allDisplayModes);
for(CFIndex i = 0; i < n; ++i) {
CGDisplayModeRef m = (CGDisplayModeRef)CFArrayGetValueAtIndex(allDisplayModes, i);
CGFloat width = CGDisplayModeGetPixelWidth(m);
CGFloat height = CGDisplayModeGetPixelHeight(m);
CGFloat HiDPIWidth = CGDisplayModeGetWidth(m);
//Only check 1x mode
if(width == HiDPIWidth) {
if (CGDisplayModeGetIOFlags(m) & kDisplayModeNativeFlag) {
displayNativeSize.width = width;
displayNativeSize.height = height;
break;
}
//Get the largest size even if kDisplayModeNativeFlag is not present e.g. iMac 27-Inch with 5K Retina
if(width > displayNativeSize.width) {
displayNativeSize.width = width;
displayNativeSize.height = height;
}
}
CFRelease(allDisplayModes);
CFRelease(dmOptions);
} else
#endif
{
// fallback for 10.7
scaleFactor = [screen backingScaleFactor];
displayNativeSize.width = displayNativeSize.width * scaleFactor;
displayNativeSize.height = displayNativeSize.height * scaleFactor;
break;
}
CFRelease(allDisplayModes);
CFRelease(dmOptions);
} else
#endif
{
// fallback for 10.7
scaleFactor = [screen backingScaleFactor];
displayNativeSize.width = displayNativeSize.width * scaleFactor;
displayNativeSize.height = displayNativeSize.height * scaleFactor;
break;
}
}
{
const CGSize displaySize = CGDisplayScreenSize(data->display);
const int pixelWidth = displayNativeSize.width;
const int pixelHeight = displayNativeSize.height;
if (ddpi) {
*ddpi = (SDL_ComputeDiagonalDPI(pixelWidth, pixelHeight, displaySize.width / MM_IN_INCH, displaySize.height / MM_IN_INCH));
}
if (hdpi) {
*hdpi = (pixelWidth * MM_IN_INCH / displaySize.width);
}
if (vdpi) {
*vdpi = (pixelHeight * MM_IN_INCH / displaySize.height);
}
}
return 0;
}
}
void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
{
const CGSize displaySize = CGDisplayScreenSize(data->display);
const int pixelWidth = displayNativeSize.width;
const int pixelHeight = displayNativeSize.height;
if (ddpi) {
*ddpi = (SDL_ComputeDiagonalDPI(pixelWidth, pixelHeight, displaySize.width / MM_IN_INCH, displaySize.height / MM_IN_INCH));
}
if (hdpi) {
*hdpi = (pixelWidth * MM_IN_INCH / displaySize.width);
}
if (vdpi) {
*vdpi = (pixelHeight * MM_IN_INCH / displaySize.height);
}
}
return 0;
}}
void
Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
{
SDL_DisplayData *data = (SDL_DisplayData *)display->driverdata;
SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
CVDisplayLinkRef link = NULL;
CGDisplayModeRef desktopmoderef;
SDL_DisplayMode desktopmode;
@ -512,7 +532,7 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
*/
if (desktopmoderef && GetDisplayMode(_this, desktopmoderef, SDL_TRUE, NULL, link, &desktopmode)) {
if (!SDL_AddDisplayMode(display, &desktopmode)) {
CFRelease(((SDL_DisplayModeData *)desktopmode.driverdata)->modes);
CFRelease(((SDL_DisplayModeData*)desktopmode.driverdata)->modes);
SDL_free(desktopmode.driverdata);
}
}
@ -532,8 +552,8 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
*/
#ifdef MAC_OS_X_VERSION_10_8
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) {
const CFStringRef dictkeys[] = { kCGDisplayShowDuplicateLowResolutionModes };
const CFBooleanRef dictvalues[] = { kCFBooleanTrue };
const CFStringRef dictkeys[] = {kCGDisplayShowDuplicateLowResolutionModes};
const CFBooleanRef dictvalues[] = {kCFBooleanTrue};
dict = CFDictionaryCreate(NULL,
(const void **)dictkeys,
(const void **)dictvalues,
@ -554,12 +574,12 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
const CFIndex count = CFArrayGetCount(modes);
for (i = 0; i < count; i++) {
CGDisplayModeRef moderef = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
CGDisplayModeRef moderef = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i);
SDL_DisplayMode mode;
if (GetDisplayMode(_this, moderef, SDL_FALSE, modes, link, &mode)) {
if (!SDL_AddDisplayMode(display, &mode)) {
CFRelease(((SDL_DisplayModeData *)mode.driverdata)->modes);
CFRelease(((SDL_DisplayModeData*)mode.driverdata)->modes);
SDL_free(mode.driverdata);
}
}
@ -571,7 +591,8 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
CVDisplayLinkRelease(link);
}
static CGError SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayModeData *data)
static CGError
SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayModeData *data)
{
/* SDL_DisplayModeData can contain multiple CGDisplayModes to try (with
* identical properties), some of which might not work. See GetDisplayMode.
@ -589,10 +610,11 @@ static CGError SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayMo
return result;
}
int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode)
int
Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode)
{
SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata;
SDL_DisplayModeData *data = (SDL_DisplayModeData *)mode->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata;
SDL_DisplayModeData *data = (SDL_DisplayModeData *) mode->driverdata;
CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken;
CGError result;
@ -624,7 +646,7 @@ int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode
}
/* Do the physical switch */
result = SetDisplayModeForDisplay(displaydata->display, data);
result = SetDisplayModeForDisplay(displaydata->display, data);
if (result != kCGErrorSuccess) {
CG_SetError("CGDisplaySwitchToMode()", result);
goto ERR_NO_SWITCH;
@ -648,13 +670,14 @@ ERR_NO_SWITCH:
}
ERR_NO_CAPTURE:
if (fade_token != kCGDisplayFadeReservationInvalidToken) {
CGDisplayFade(fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
CGReleaseDisplayFadeReservation(fade_token);
}
return -1;
}
void Cocoa_QuitModes(_THIS)
void
Cocoa_QuitModes(_THIS)
{
int i, j;
@ -666,11 +689,11 @@ void Cocoa_QuitModes(_THIS)
Cocoa_SetDisplayMode(_this, display, &display->desktop_mode);
}
mode = (SDL_DisplayModeData *)display->desktop_mode.driverdata;
mode = (SDL_DisplayModeData *) display->desktop_mode.driverdata;
CFRelease(mode->modes);
for (j = 0; j < display->num_display_modes; j++) {
mode = (SDL_DisplayModeData *)display->display_modes[j].driverdata;
mode = (SDL_DisplayModeData*) display->display_modes[j].driverdata;
CFRelease(mode->modes);
}
}

View File

@ -26,13 +26,12 @@
#include "SDL_cocoavideo.h"
extern int Cocoa_InitMouse(_THIS);
extern void Cocoa_HandleMouseEvent(_THIS, NSEvent *event);
extern void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event);
extern void Cocoa_HandleMouseEvent(_THIS, NSEvent * event);
extern void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent * event);
extern void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y);
extern void Cocoa_QuitMouse(_THIS);
typedef struct
{
typedef struct {
/* Whether we've seen a cursor warp since the last move event. */
SDL_bool seenWarp;
/* What location our last cursor warp was to. */

View File

@ -33,9 +33,7 @@
#ifdef DEBUG_COCOAMOUSE
#define DLog(fmt, ...) printf("%s: " fmt "\n", __func__, ##__VA_ARGS__)
#else
#define DLog(...) \
do { \
} while (0)
#define DLog(...) do { } while (0)
#endif
@implementation NSCursor (InvisibleCursor)
@ -64,52 +62,54 @@
}
@end
static SDL_Cursor *Cocoa_CreateDefaultCursor()
static SDL_Cursor *
Cocoa_CreateDefaultCursor()
{ @autoreleasepool
{
@autoreleasepool {
NSCursor *nscursor;
SDL_Cursor *cursor = NULL;
NSCursor *nscursor;
SDL_Cursor *cursor = NULL;
nscursor = [NSCursor arrowCursor];
nscursor = [NSCursor arrowCursor];
if (nscursor) {
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
cursor->driverdata = (void *)CFBridgingRetain(nscursor);
}
if (nscursor) {
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
cursor->driverdata = (void *)CFBridgingRetain(nscursor);
}
return cursor;
}
}
static SDL_Cursor *Cocoa_CreateCursor(SDL_Surface *surface, int hot_x, int hot_y)
return cursor;
}}
static SDL_Cursor *
Cocoa_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
{ @autoreleasepool
{
@autoreleasepool {
NSImage *nsimage;
NSCursor *nscursor = NULL;
SDL_Cursor *cursor = NULL;
NSImage *nsimage;
NSCursor *nscursor = NULL;
SDL_Cursor *cursor = NULL;
nsimage = Cocoa_CreateImage(surface);
if (nsimage) {
nscursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(hot_x, hot_y)];
}
if (nscursor) {
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
cursor->driverdata = (void *)CFBridgingRetain(nscursor);
}
}
return cursor;
nsimage = Cocoa_CreateImage(surface);
if (nsimage) {
nscursor = [[NSCursor alloc] initWithImage: nsimage hotSpot: NSMakePoint(hot_x, hot_y)];
}
}
if (nscursor) {
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
cursor->driverdata = (void *)CFBridgingRetain(nscursor);
}
}
return cursor;
}}
/* there are .pdf files of some of the cursors we need, installed by default on macOS, but not available through NSCursor.
If we can load them ourselves, use them, otherwise fallback to something standard but not super-great.
Since these are under /System, they should be available even to sandboxed apps. */
static NSCursor *LoadHiddenSystemCursor(NSString *cursorName, SEL fallback)
static NSCursor *
LoadHiddenSystemCursor(NSString *cursorName, SEL fallback)
{
NSString *cursorPath = [@"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors" stringByAppendingPathComponent:cursorName];
NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:[cursorPath stringByAppendingPathComponent:@"info.plist"]];
@ -122,12 +122,12 @@ static NSCursor *LoadHiddenSystemCursor(NSString *cursorName, SEL fallback)
}
if (frames > 1) {
#ifdef MAC_OS_VERSION_12_0 /* same value as deprecated symbol. */
#ifdef MAC_OS_VERSION_12_0 /* same value as deprecated symbol. */
const NSCompositingOperation operation = NSCompositingOperationCopy;
#else
#else
const NSCompositingOperation operation = NSCompositeCopy;
#endif
const NSSize cropped_size = NSMakeSize(image.size.width, (int)(image.size.height / frames));
#endif
const NSSize cropped_size = NSMakeSize(image.size.width, (int) (image.size.height / frames));
NSImage *cropped = [[NSImage alloc] initWithSize:cropped_size];
if (cropped == nil) {
return [NSCursor performSelector:fallback];
@ -146,92 +146,93 @@ static NSCursor *LoadHiddenSystemCursor(NSString *cursorName, SEL fallback)
return cursor;
}
static SDL_Cursor *Cocoa_CreateSystemCursor(SDL_SystemCursor id)
static SDL_Cursor *
Cocoa_CreateSystemCursor(SDL_SystemCursor id)
{ @autoreleasepool
{
@autoreleasepool {
NSCursor *nscursor = NULL;
SDL_Cursor *cursor = NULL;
NSCursor *nscursor = NULL;
SDL_Cursor *cursor = NULL;
switch (id) {
case SDL_SYSTEM_CURSOR_ARROW:
nscursor = [NSCursor arrowCursor];
break;
case SDL_SYSTEM_CURSOR_IBEAM:
nscursor = [NSCursor IBeamCursor];
break;
case SDL_SYSTEM_CURSOR_CROSSHAIR:
nscursor = [NSCursor crosshairCursor];
break;
case SDL_SYSTEM_CURSOR_WAIT: /* !!! FIXME: this is more like WAITARROW */
nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor));
break;
case SDL_SYSTEM_CURSOR_WAITARROW: /* !!! FIXME: this is meant to be animated */
nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor));
break;
case SDL_SYSTEM_CURSOR_SIZENWSE:
nscursor = LoadHiddenSystemCursor(@"resizenorthwestsoutheast", @selector(closedHandCursor));
break;
case SDL_SYSTEM_CURSOR_SIZENESW:
nscursor = LoadHiddenSystemCursor(@"resizenortheastsouthwest", @selector(closedHandCursor));
break;
case SDL_SYSTEM_CURSOR_SIZEWE:
nscursor = LoadHiddenSystemCursor(@"resizeeastwest", @selector(resizeLeftRightCursor));
break;
case SDL_SYSTEM_CURSOR_SIZENS:
nscursor = LoadHiddenSystemCursor(@"resizenorthsouth", @selector(resizeUpDownCursor));
break;
case SDL_SYSTEM_CURSOR_SIZEALL:
nscursor = LoadHiddenSystemCursor(@"move", @selector(closedHandCursor));
break;
case SDL_SYSTEM_CURSOR_NO:
nscursor = [NSCursor operationNotAllowedCursor];
break;
case SDL_SYSTEM_CURSOR_HAND:
nscursor = [NSCursor pointingHandCursor];
break;
default:
SDL_assert(!"Unknown system cursor");
return NULL;
}
if (nscursor) {
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
/* We'll free it later, so retain it here */
cursor->driverdata = (void *)CFBridgingRetain(nscursor);
}
}
return cursor;
switch(id) {
case SDL_SYSTEM_CURSOR_ARROW:
nscursor = [NSCursor arrowCursor];
break;
case SDL_SYSTEM_CURSOR_IBEAM:
nscursor = [NSCursor IBeamCursor];
break;
case SDL_SYSTEM_CURSOR_CROSSHAIR:
nscursor = [NSCursor crosshairCursor];
break;
case SDL_SYSTEM_CURSOR_WAIT: /* !!! FIXME: this is more like WAITARROW */
nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor));
break;
case SDL_SYSTEM_CURSOR_WAITARROW: /* !!! FIXME: this is meant to be animated */
nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor));
break;
case SDL_SYSTEM_CURSOR_SIZENWSE:
nscursor = LoadHiddenSystemCursor(@"resizenorthwestsoutheast", @selector(closedHandCursor));
break;
case SDL_SYSTEM_CURSOR_SIZENESW:
nscursor = LoadHiddenSystemCursor(@"resizenortheastsouthwest", @selector(closedHandCursor));
break;
case SDL_SYSTEM_CURSOR_SIZEWE:
nscursor = LoadHiddenSystemCursor(@"resizeeastwest", @selector(resizeLeftRightCursor));
break;
case SDL_SYSTEM_CURSOR_SIZENS:
nscursor = LoadHiddenSystemCursor(@"resizenorthsouth", @selector(resizeUpDownCursor));
break;
case SDL_SYSTEM_CURSOR_SIZEALL:
nscursor = LoadHiddenSystemCursor(@"move", @selector(closedHandCursor));
break;
case SDL_SYSTEM_CURSOR_NO:
nscursor = [NSCursor operationNotAllowedCursor];
break;
case SDL_SYSTEM_CURSOR_HAND:
nscursor = [NSCursor pointingHandCursor];
break;
default:
SDL_assert(!"Unknown system cursor");
return NULL;
}
}
static void Cocoa_FreeCursor(SDL_Cursor *cursor)
if (nscursor) {
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
/* We'll free it later, so retain it here */
cursor->driverdata = (void *)CFBridgingRetain(nscursor);
}
}
return cursor;
}}
static void
Cocoa_FreeCursor(SDL_Cursor * cursor)
{ @autoreleasepool
{
@autoreleasepool {
CFBridgingRelease(cursor->driverdata);
SDL_free(cursor);
}
}
CFBridgingRelease(cursor->driverdata);
SDL_free(cursor);
}}
static int Cocoa_ShowCursor(SDL_Cursor *cursor)
static int
Cocoa_ShowCursor(SDL_Cursor * cursor)
{ @autoreleasepool
{
@autoreleasepool {
SDL_VideoDevice *device = SDL_GetVideoDevice();
SDL_Window *window = (device ? device->windows : NULL);
for (; window != NULL; window = window->next) {
SDL_WindowData *driverdata = (__bridge SDL_WindowData *)window->driverdata;
if (driverdata) {
[driverdata.nswindow performSelectorOnMainThread:@selector(invalidateCursorRectsForView:)
withObject:[driverdata.nswindow contentView]
waitUntilDone:NO];
}
SDL_VideoDevice *device = SDL_GetVideoDevice();
SDL_Window *window = (device ? device->windows : NULL);
for (; window != NULL; window = window->next) {
SDL_WindowData *driverdata = (__bridge SDL_WindowData *)window->driverdata;
if (driverdata) {
[driverdata.nswindow performSelectorOnMainThread:@selector(invalidateCursorRectsForView:)
withObject:[driverdata.nswindow contentView]
waitUntilDone:NO];
}
return 0;
}
}
return 0;
}}
static SDL_Window *SDL_FindWindowAtPoint(const int x, const int y)
static SDL_Window *
SDL_FindWindowAtPoint(const int x, const int y)
{
const SDL_Point pt = { x, y };
SDL_Window *i;
@ -245,12 +246,13 @@ static SDL_Window *SDL_FindWindowAtPoint(const int x, const int y)
return NULL;
}
static int Cocoa_WarpMouseGlobal(int x, int y)
static int
Cocoa_WarpMouseGlobal(int x, int y)
{
CGPoint point;
SDL_Mouse *mouse = SDL_GetMouse();
if (mouse->focus) {
SDL_WindowData *data = (__bridge SDL_WindowData *)mouse->focus->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) mouse->focus->driverdata;
if ([data.listener isMovingOrFocusClickPending]) {
DLog("Postponing warp, window being moved or focused.");
[data.listener setPendingMoveX:x Y:y];
@ -286,12 +288,14 @@ static int Cocoa_WarpMouseGlobal(int x, int y)
return 0;
}
static void Cocoa_WarpMouse(SDL_Window *window, int x, int y)
static void
Cocoa_WarpMouse(SDL_Window * window, int x, int y)
{
Cocoa_WarpMouseGlobal(window->x + x, window->y + y);
}
static int Cocoa_SetRelativeMouseMode(SDL_bool enabled)
static int
Cocoa_SetRelativeMouseMode(SDL_bool enabled)
{
CGError result;
SDL_Window *window;
@ -318,7 +322,7 @@ static int Cocoa_SetRelativeMouseMode(SDL_bool enabled)
/* We will re-apply the non-relative mode when the window finishes being moved,
* if it is being moved right now.
*/
data = (__bridge SDL_WindowData *)window->driverdata;
data = (__bridge SDL_WindowData *) window->driverdata;
if ([data.listener isMovingOrFocusClickPending]) {
return 0;
}
@ -334,21 +338,23 @@ static int Cocoa_SetRelativeMouseMode(SDL_bool enabled)
return 0;
}
static int Cocoa_CaptureMouse(SDL_Window *window)
static int
Cocoa_CaptureMouse(SDL_Window *window)
{
/* our Cocoa event code already tracks the mouse outside the window,
so all we have to do here is say "okay" and do what we always do. */
return 0;
}
static Uint32 Cocoa_GetGlobalMouseState(int *x, int *y)
static Uint32
Cocoa_GetGlobalMouseState(int *x, int *y)
{
const NSUInteger cocoaButtons = [NSEvent pressedMouseButtons];
const NSPoint cocoaLocation = [NSEvent mouseLocation];
Uint32 retval = 0;
*x = (int)cocoaLocation.x;
*y = (int)(CGDisplayPixelsHigh(kCGDirectMainDisplay) - cocoaLocation.y);
*x = (int) cocoaLocation.x;
*y = (int) (CGDisplayPixelsHigh(kCGDirectMainDisplay) - cocoaLocation.y);
retval |= (cocoaButtons & (1 << 0)) ? SDL_BUTTON_LMASK : 0;
retval |= (cocoaButtons & (1 << 1)) ? SDL_BUTTON_RMASK : 0;
@ -359,11 +365,12 @@ static Uint32 Cocoa_GetGlobalMouseState(int *x, int *y)
return retval;
}
int Cocoa_InitMouse(_THIS)
int
Cocoa_InitMouse(_THIS)
{
NSPoint location;
SDL_Mouse *mouse = SDL_GetMouse();
SDL_MouseData *driverdata = (SDL_MouseData *)SDL_calloc(1, sizeof(SDL_MouseData));
SDL_MouseData *driverdata = (SDL_MouseData*) SDL_calloc(1, sizeof(SDL_MouseData));
if (driverdata == NULL) {
return SDL_OutOfMemory();
}
@ -381,13 +388,14 @@ int Cocoa_InitMouse(_THIS)
SDL_SetDefaultCursor(Cocoa_CreateDefaultCursor());
location = [NSEvent mouseLocation];
location = [NSEvent mouseLocation];
driverdata->lastMoveX = location.x;
driverdata->lastMoveY = location.y;
return 0;
}
static void Cocoa_HandleTitleButtonEvent(_THIS, NSEvent *event)
static void
Cocoa_HandleTitleButtonEvent(_THIS, NSEvent *event)
{
SDL_Window *window;
NSWindow *nswindow = [event window];
@ -420,7 +428,8 @@ static void Cocoa_HandleTitleButtonEvent(_THIS, NSEvent *event)
}
}
void Cocoa_HandleMouseEvent(_THIS, NSEvent *event)
void
Cocoa_HandleMouseEvent(_THIS, NSEvent *event)
{
SDL_Mouse *mouse;
SDL_MouseData *driverdata;
@ -430,43 +439,43 @@ void Cocoa_HandleMouseEvent(_THIS, NSEvent *event)
float deltaX, deltaY;
SDL_bool seenWarp;
switch ([event type]) {
case NSEventTypeMouseMoved:
case NSEventTypeLeftMouseDragged:
case NSEventTypeRightMouseDragged:
case NSEventTypeOtherMouseDragged:
break;
case NSEventTypeMouseMoved:
case NSEventTypeLeftMouseDragged:
case NSEventTypeRightMouseDragged:
case NSEventTypeOtherMouseDragged:
break;
case NSEventTypeLeftMouseDown:
case NSEventTypeLeftMouseUp:
case NSEventTypeRightMouseDown:
case NSEventTypeRightMouseUp:
case NSEventTypeOtherMouseDown:
case NSEventTypeOtherMouseUp:
if ([event window]) {
NSRect windowRect = [[[event window] contentView] frame];
if (!NSMouseInRect([event locationInWindow], windowRect, NO)) {
Cocoa_HandleTitleButtonEvent(_this, event);
return;
case NSEventTypeLeftMouseDown:
case NSEventTypeLeftMouseUp:
case NSEventTypeRightMouseDown:
case NSEventTypeRightMouseUp:
case NSEventTypeOtherMouseDown:
case NSEventTypeOtherMouseUp:
if ([event window]) {
NSRect windowRect = [[[event window] contentView] frame];
if (!NSMouseInRect([event locationInWindow], windowRect, NO)) {
Cocoa_HandleTitleButtonEvent(_this, event);
return;
}
}
}
return;
return;
default:
/* Ignore any other events. */
return;
default:
/* Ignore any other events. */
return;
}
mouse = SDL_GetMouse();
driverdata = (SDL_MouseData *)mouse->driverdata;
driverdata = (SDL_MouseData*)mouse->driverdata;
if (!driverdata) {
return; /* can happen when returning from fullscreen Space on shutdown */
return; /* can happen when returning from fullscreen Space on shutdown */
}
mouseID = mouse ? mouse->mouseID : 0;
seenWarp = driverdata->seenWarp;
driverdata->seenWarp = NO;
location = [NSEvent mouseLocation];
location = [NSEvent mouseLocation];
lastMoveX = driverdata->lastMoveX;
lastMoveY = driverdata->lastMoveY;
driverdata->lastMoveX = location.x;
@ -499,7 +508,8 @@ void Cocoa_HandleMouseEvent(_THIS, NSEvent *event)
SDL_SendMouseMotion(mouse->focus, mouseID, 1, (int)deltaX, (int)deltaY);
}
void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event)
void
Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event)
{
SDL_MouseID mouseID;
SDL_MouseWheelDirection direction;
@ -536,12 +546,13 @@ void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event)
SDL_SendMouseWheel(window, mouseID, x, y, direction);
}
void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y)
void
Cocoa_HandleMouseWarp(CGFloat x, CGFloat y)
{
/* This makes Cocoa_HandleMouseEvent ignore the delta caused by the warp,
* since it gets included in the next movement event.
*/
SDL_MouseData *driverdata = (SDL_MouseData *)SDL_GetMouse()->driverdata;
SDL_MouseData *driverdata = (SDL_MouseData*)SDL_GetMouse()->driverdata;
driverdata->lastWarpX = x;
driverdata->lastWarpY = y;
driverdata->seenWarp = SDL_TRUE;
@ -549,7 +560,8 @@ void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y)
DLog("(%g, %g)", x, y);
}
void Cocoa_QuitMouse(_THIS)
void
Cocoa_QuitMouse(_THIS)
{
SDL_Mouse *mouse = SDL_GetMouse();
if (mouse) {

View File

@ -40,19 +40,14 @@ struct SDL_GLDriverData
int initialized;
};
@interface SDLOpenGLContext : NSOpenGLContext
{
@interface SDLOpenGLContext : NSOpenGLContext {
SDL_atomic_t dirty;
SDL_Window *window;
CVDisplayLinkRef displayLink;
@public
SDL_mutex *swapIntervalMutex;
@public
SDL_cond *swapIntervalCond;
@public
SDL_atomic_t swapIntervalSetting;
@public
SDL_atomic_t swapIntervalsPassed;
@public SDL_mutex *swapIntervalMutex;
@public SDL_cond *swapIntervalCond;
@public SDL_atomic_t swapIntervalSetting;
@public SDL_atomic_t swapIntervalsPassed;
}
- (id)initWithFormat:(NSOpenGLPixelFormat *)format
@ -61,11 +56,11 @@ struct SDL_GLDriverData
- (void)updateIfNeeded;
- (void)movedToNewScreen;
- (void)setWindow:(SDL_Window *)window;
- (SDL_Window *)window;
- (SDL_Window*)window;
- (void)explicitUpdate;
- (void)dealloc;
@property(retain, nonatomic) NSOpenGLPixelFormat *openglPixelFormat; // macOS 10.10 has -[NSOpenGLContext pixelFormat] but this handles older OS releases.
@property (retain, nonatomic) NSOpenGLPixelFormat* openglPixelFormat; // macOS 10.10 has -[NSOpenGLContext pixelFormat] but this handles older OS releases.
@end
@ -73,12 +68,12 @@ struct SDL_GLDriverData
extern int Cocoa_GL_LoadLibrary(_THIS, const char *path);
extern void *Cocoa_GL_GetProcAddress(_THIS, const char *proc);
extern void Cocoa_GL_UnloadLibrary(_THIS);
extern SDL_GLContext Cocoa_GL_CreateContext(_THIS, SDL_Window *window);
extern int Cocoa_GL_MakeCurrent(_THIS, SDL_Window *window,
extern SDL_GLContext Cocoa_GL_CreateContext(_THIS, SDL_Window * window);
extern int Cocoa_GL_MakeCurrent(_THIS, SDL_Window * window,
SDL_GLContext context);
extern int Cocoa_GL_SetSwapInterval(_THIS, int interval);
extern int Cocoa_GL_GetSwapInterval(_THIS);
extern int Cocoa_GL_SwapWindow(_THIS, SDL_Window *window);
extern int Cocoa_GL_SwapWindow(_THIS, SDL_Window * window);
extern void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context);
#ifdef __clang__

View File

@ -36,7 +36,7 @@
#include "SDL_opengl.h"
#include "../../SDL_hints_c.h"
#define DEFAULT_OPENGL "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"
#define DEFAULT_OPENGL "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"
/* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */
#ifdef __clang__
@ -56,14 +56,16 @@
static SDL_bool SDL_opengl_async_dispatch = SDL_FALSE;
static void SDLCALL SDL_OpenGLAsyncDispatchChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
static void SDLCALL
SDL_OpenGLAsyncDispatchChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
SDL_opengl_async_dispatch = SDL_GetStringBoolean(hint, SDL_FALSE);
}
static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext)
static CVReturn
DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext)
{
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)displayLinkContext;
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *) displayLinkContext;
/*printf("DISPLAY LINK! %u\n", (unsigned int) SDL_GetTicks()); */
const int setting = SDL_AtomicGet(&nscontext->swapIntervalSetting);
@ -97,7 +99,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
/* !!! FIXME: check return values. */
CVDisplayLinkCreateWithActiveCGDisplays(&self->displayLink);
CVDisplayLinkSetOutputCallback(self->displayLink, &DisplayLinkCallback, (__bridge void *_Nullable)self);
CVDisplayLinkSetOutputCallback(self->displayLink, &DisplayLinkCallback, (__bridge void * _Nullable) self);
CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(self->displayLink, [self CGLContextObj], [format CGLPixelFormatObj]);
CVDisplayLinkStart(displayLink);
}
@ -144,7 +146,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
/* Make sure to remove us from the old window's context list, or we'll get scheduled updates from it too. */
NSMutableArray *contexts = oldwindowdata.nscontexts;
@synchronized(contexts) {
@synchronized (contexts) {
[contexts removeObject:self];
}
}
@ -157,7 +159,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
/* Now sign up for scheduled updates for the new window. */
NSMutableArray *contexts = windowdata.nscontexts;
@synchronized(contexts) {
@synchronized (contexts) {
[contexts addObject:self];
}
@ -165,9 +167,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
if ([NSThread isMainThread]) {
[self setView:contentview];
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
[self setView:contentview];
});
dispatch_sync(dispatch_get_main_queue(), ^{ [self setView:contentview]; });
}
if (self == [NSOpenGLContext currentContext]) {
[self explicitUpdate];
@ -185,7 +185,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
}
}
- (SDL_Window *)window
- (SDL_Window*)window
{
return self->window;
}
@ -196,13 +196,9 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
[super update];
} else {
if (SDL_opengl_async_dispatch) {
dispatch_async(dispatch_get_main_queue(), ^{
[super update];
});
dispatch_async(dispatch_get_main_queue(), ^{ [super update]; });
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
[super update];
});
dispatch_sync(dispatch_get_main_queue(), ^{ [super update]; });
}
}
}
@ -223,7 +219,9 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
@end
int Cocoa_GL_LoadLibrary(_THIS, const char *path)
int
Cocoa_GL_LoadLibrary(_THIS, const char *path)
{
/* Load the OpenGL library */
if (path == NULL) {
@ -247,280 +245,280 @@ Cocoa_GL_GetProcAddress(_THIS, const char *proc)
return SDL_LoadFunction(_this->gl_config.dll_handle, proc);
}
void Cocoa_GL_UnloadLibrary(_THIS)
void
Cocoa_GL_UnloadLibrary(_THIS)
{
SDL_UnloadObject(_this->gl_config.dll_handle);
_this->gl_config.dll_handle = NULL;
}
SDL_GLContext
Cocoa_GL_CreateContext(_THIS, SDL_Window *window)
Cocoa_GL_CreateContext(_THIS, SDL_Window * window)
{ @autoreleasepool
{
@autoreleasepool {
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata;
NSOpenGLPixelFormatAttribute attr[32];
NSOpenGLPixelFormat *fmt;
SDLOpenGLContext *context;
SDL_GLContext sdlcontext;
NSOpenGLContext *share_context = nil;
int i = 0;
const char *glversion;
int glversion_major;
int glversion_minor;
NSOpenGLPixelFormatAttribute profile;
int interval;
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata;
NSOpenGLPixelFormatAttribute attr[32];
NSOpenGLPixelFormat *fmt;
SDLOpenGLContext *context;
SDL_GLContext sdlcontext;
NSOpenGLContext *share_context = nil;
int i = 0;
const char *glversion;
int glversion_major;
int glversion_minor;
NSOpenGLPixelFormatAttribute profile;
int interval;
if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) {
if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) {
#if SDL_VIDEO_OPENGL_EGL
/* Switch to EGL based functions */
Cocoa_GL_UnloadLibrary(_this);
_this->GL_LoadLibrary = Cocoa_GLES_LoadLibrary;
_this->GL_GetProcAddress = Cocoa_GLES_GetProcAddress;
_this->GL_UnloadLibrary = Cocoa_GLES_UnloadLibrary;
_this->GL_CreateContext = Cocoa_GLES_CreateContext;
_this->GL_MakeCurrent = Cocoa_GLES_MakeCurrent;
_this->GL_SetSwapInterval = Cocoa_GLES_SetSwapInterval;
_this->GL_GetSwapInterval = Cocoa_GLES_GetSwapInterval;
_this->GL_SwapWindow = Cocoa_GLES_SwapWindow;
_this->GL_DeleteContext = Cocoa_GLES_DeleteContext;
if (Cocoa_GLES_LoadLibrary(_this, NULL) != 0) {
return NULL;
}
return Cocoa_GLES_CreateContext(_this, window);
/* Switch to EGL based functions */
Cocoa_GL_UnloadLibrary(_this);
_this->GL_LoadLibrary = Cocoa_GLES_LoadLibrary;
_this->GL_GetProcAddress = Cocoa_GLES_GetProcAddress;
_this->GL_UnloadLibrary = Cocoa_GLES_UnloadLibrary;
_this->GL_CreateContext = Cocoa_GLES_CreateContext;
_this->GL_MakeCurrent = Cocoa_GLES_MakeCurrent;
_this->GL_SetSwapInterval = Cocoa_GLES_SetSwapInterval;
_this->GL_GetSwapInterval = Cocoa_GLES_GetSwapInterval;
_this->GL_SwapWindow = Cocoa_GLES_SwapWindow;
_this->GL_DeleteContext = Cocoa_GLES_DeleteContext;
if (Cocoa_GLES_LoadLibrary(_this, NULL) != 0) {
return NULL;
}
return Cocoa_GLES_CreateContext(_this, window);
#else
SDL_SetError("SDL not configured with EGL support");
return NULL;
SDL_SetError("SDL not configured with EGL support");
return NULL;
#endif
}
attr[i++] = NSOpenGLPFAAllowOfflineRenderers;
profile = NSOpenGLProfileVersionLegacy;
if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_CORE) {
profile = NSOpenGLProfileVersion3_2Core;
}
attr[i++] = NSOpenGLPFAOpenGLProfile;
attr[i++] = profile;
attr[i++] = NSOpenGLPFAColorSize;
attr[i++] = SDL_BYTESPERPIXEL(display->current_mode.format)*8;
attr[i++] = NSOpenGLPFADepthSize;
attr[i++] = _this->gl_config.depth_size;
if (_this->gl_config.double_buffer) {
attr[i++] = NSOpenGLPFADoubleBuffer;
}
if (_this->gl_config.stereo) {
attr[i++] = NSOpenGLPFAStereo;
}
if (_this->gl_config.stencil_size) {
attr[i++] = NSOpenGLPFAStencilSize;
attr[i++] = _this->gl_config.stencil_size;
}
if ((_this->gl_config.accum_red_size +
_this->gl_config.accum_green_size +
_this->gl_config.accum_blue_size +
_this->gl_config.accum_alpha_size) > 0) {
attr[i++] = NSOpenGLPFAAccumSize;
attr[i++] = _this->gl_config.accum_red_size + _this->gl_config.accum_green_size + _this->gl_config.accum_blue_size + _this->gl_config.accum_alpha_size;
}
if (_this->gl_config.multisamplebuffers) {
attr[i++] = NSOpenGLPFASampleBuffers;
attr[i++] = _this->gl_config.multisamplebuffers;
}
if (_this->gl_config.multisamplesamples) {
attr[i++] = NSOpenGLPFASamples;
attr[i++] = _this->gl_config.multisamplesamples;
attr[i++] = NSOpenGLPFANoRecovery;
}
if (_this->gl_config.floatbuffers) {
attr[i++] = NSOpenGLPFAColorFloat;
}
if (_this->gl_config.accelerated >= 0) {
if (_this->gl_config.accelerated) {
attr[i++] = NSOpenGLPFAAccelerated;
} else {
attr[i++] = NSOpenGLPFARendererID;
attr[i++] = kCGLRendererGenericFloatID;
}
}
attr[i++] = NSOpenGLPFAAllowOfflineRenderers;
attr[i++] = NSOpenGLPFAScreenMask;
attr[i++] = CGDisplayIDToOpenGLDisplayMask(displaydata->display);
attr[i] = 0;
profile = NSOpenGLProfileVersionLegacy;
if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_CORE) {
profile = NSOpenGLProfileVersion3_2Core;
}
attr[i++] = NSOpenGLPFAOpenGLProfile;
attr[i++] = profile;
fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr];
if (fmt == nil) {
SDL_SetError("Failed creating OpenGL pixel format");
return NULL;
}
attr[i++] = NSOpenGLPFAColorSize;
attr[i++] = SDL_BYTESPERPIXEL(display->current_mode.format) * 8;
if (_this->gl_config.share_with_current_context) {
share_context = (__bridge NSOpenGLContext*)SDL_GL_GetCurrentContext();
}
attr[i++] = NSOpenGLPFADepthSize;
attr[i++] = _this->gl_config.depth_size;
context = [[SDLOpenGLContext alloc] initWithFormat:fmt shareContext:share_context];
if (_this->gl_config.double_buffer) {
attr[i++] = NSOpenGLPFADoubleBuffer;
}
if (context == nil) {
SDL_SetError("Failed creating OpenGL context");
return NULL;
}
if (_this->gl_config.stereo) {
attr[i++] = NSOpenGLPFAStereo;
}
sdlcontext = (SDL_GLContext)CFBridgingRetain(context);
if (_this->gl_config.stencil_size) {
attr[i++] = NSOpenGLPFAStencilSize;
attr[i++] = _this->gl_config.stencil_size;
}
/* vsync is handled separately by synchronizing with a display link. */
interval = 0;
[context setValues:&interval forParameter:NSOpenGLCPSwapInterval];
if ((_this->gl_config.accum_red_size +
_this->gl_config.accum_green_size +
_this->gl_config.accum_blue_size +
_this->gl_config.accum_alpha_size) > 0) {
attr[i++] = NSOpenGLPFAAccumSize;
attr[i++] = _this->gl_config.accum_red_size + _this->gl_config.accum_green_size + _this->gl_config.accum_blue_size + _this->gl_config.accum_alpha_size;
}
if ( Cocoa_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext)context) < 0 ) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError("Failed making OpenGL context current");
return NULL;
}
if (_this->gl_config.multisamplebuffers) {
attr[i++] = NSOpenGLPFASampleBuffers;
attr[i++] = _this->gl_config.multisamplebuffers;
}
if (_this->gl_config.major_version < 3 &&
_this->gl_config.profile_mask == 0 &&
_this->gl_config.flags == 0) {
/* This is a legacy profile, so to match other backends, we're done. */
} else {
const GLubyte *(APIENTRY * glGetStringFunc)(GLenum);
if (_this->gl_config.multisamplesamples) {
attr[i++] = NSOpenGLPFASamples;
attr[i++] = _this->gl_config.multisamplesamples;
attr[i++] = NSOpenGLPFANoRecovery;
}
if (_this->gl_config.floatbuffers) {
attr[i++] = NSOpenGLPFAColorFloat;
}
if (_this->gl_config.accelerated >= 0) {
if (_this->gl_config.accelerated) {
attr[i++] = NSOpenGLPFAAccelerated;
} else {
attr[i++] = NSOpenGLPFARendererID;
attr[i++] = kCGLRendererGenericFloatID;
}
}
attr[i++] = NSOpenGLPFAScreenMask;
attr[i++] = CGDisplayIDToOpenGLDisplayMask(displaydata->display);
attr[i] = 0;
fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr];
if (fmt == nil) {
SDL_SetError("Failed creating OpenGL pixel format");
return NULL;
}
if (_this->gl_config.share_with_current_context) {
share_context = (__bridge NSOpenGLContext *)SDL_GL_GetCurrentContext();
}
context = [[SDLOpenGLContext alloc] initWithFormat:fmt shareContext:share_context];
if (context == nil) {
SDL_SetError("Failed creating OpenGL context");
return NULL;
}
sdlcontext = (SDL_GLContext)CFBridgingRetain(context);
/* vsync is handled separately by synchronizing with a display link. */
interval = 0;
[context setValues:&interval forParameter:NSOpenGLCPSwapInterval];
if (Cocoa_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext)context) < 0) {
glGetStringFunc = (const GLubyte *(APIENTRY *)(GLenum)) SDL_GL_GetProcAddress("glGetString");
if (!glGetStringFunc) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError("Failed making OpenGL context current");
SDL_SetError ("Failed getting OpenGL glGetString entry point");
return NULL;
}
if (_this->gl_config.major_version < 3 &&
_this->gl_config.profile_mask == 0 &&
_this->gl_config.flags == 0) {
/* This is a legacy profile, so to match other backends, we're done. */
} else {
const GLubyte *(APIENTRY * glGetStringFunc)(GLenum);
glGetStringFunc = (const GLubyte *(APIENTRY *)(GLenum))SDL_GL_GetProcAddress("glGetString");
if (!glGetStringFunc) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError("Failed getting OpenGL glGetString entry point");
return NULL;
}
glversion = (const char *)glGetStringFunc(GL_VERSION);
if (glversion == NULL) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError("Failed getting OpenGL context version");
return NULL;
}
if (SDL_sscanf(glversion, "%d.%d", &glversion_major, &glversion_minor) != 2) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError("Failed parsing OpenGL context version");
return NULL;
}
if ((glversion_major < _this->gl_config.major_version) ||
((glversion_major == _this->gl_config.major_version) && (glversion_minor < _this->gl_config.minor_version))) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError("Failed creating OpenGL context at version requested");
return NULL;
}
/* In the future we'll want to do this, but to match other platforms
we'll leave the OpenGL version the way it is for now
*/
/*_this->gl_config.major_version = glversion_major;*/
/*_this->gl_config.minor_version = glversion_minor;*/
}
return sdlcontext;
}
}
int Cocoa_GL_MakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context)
{
@autoreleasepool {
if (context) {
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context;
if ([nscontext window] != window) {
[nscontext setWindow:window];
[nscontext updateIfNeeded];
}
[nscontext makeCurrentContext];
} else {
[NSOpenGLContext clearCurrentContext];
glversion = (const char *)glGetStringFunc(GL_VERSION);
if (glversion == NULL) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError ("Failed getting OpenGL context version");
return NULL;
}
return 0;
}
}
int Cocoa_GL_SetSwapInterval(_THIS, int interval)
{
@autoreleasepool {
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)SDL_GL_GetCurrentContext();
int status;
if (nscontext == nil) {
status = SDL_SetError("No current OpenGL context");
} else {
SDL_LockMutex(nscontext->swapIntervalMutex);
SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0);
SDL_AtomicSet(&nscontext->swapIntervalSetting, interval);
SDL_UnlockMutex(nscontext->swapIntervalMutex);
status = 0;
if (SDL_sscanf(glversion, "%d.%d", &glversion_major, &glversion_minor) != 2) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError ("Failed parsing OpenGL context version");
return NULL;
}
return status;
}
}
int Cocoa_GL_GetSwapInterval(_THIS)
{
@autoreleasepool {
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)SDL_GL_GetCurrentContext();
return nscontext ? SDL_AtomicGet(&nscontext->swapIntervalSetting) : 0;
}
}
int Cocoa_GL_SwapWindow(_THIS, SDL_Window *window)
{
@autoreleasepool {
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)SDL_GL_GetCurrentContext();
SDL_VideoData *videodata = (__bridge SDL_VideoData *)_this->driverdata;
const int setting = SDL_AtomicGet(&nscontext->swapIntervalSetting);
if (setting == 0) {
/* nothing to do if vsync is disabled, don't even lock */
} else if (setting < 0) { /* late swap tearing */
SDL_LockMutex(nscontext->swapIntervalMutex);
while (SDL_AtomicGet(&nscontext->swapIntervalsPassed) == 0) {
SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex);
}
SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0);
SDL_UnlockMutex(nscontext->swapIntervalMutex);
} else {
SDL_LockMutex(nscontext->swapIntervalMutex);
do { /* always wait here so we know we just hit a swap interval. */
SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex);
} while ((SDL_AtomicGet(&nscontext->swapIntervalsPassed) % setting) != 0);
SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0);
SDL_UnlockMutex(nscontext->swapIntervalMutex);
if ((glversion_major < _this->gl_config.major_version) ||
((glversion_major == _this->gl_config.major_version) && (glversion_minor < _this->gl_config.minor_version))) {
Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context);
SDL_SetError ("Failed creating OpenGL context at version requested");
return NULL;
}
/*{ static Uint64 prev = 0; const Uint64 now = SDL_GetTicks64(); const unsigned int diff = (unsigned int) (now - prev); prev = now; printf("GLSWAPBUFFERS TICKS %u\n", diff); }*/
/* on 10.14 ("Mojave") and later, this deadlocks if two contexts in two
threads try to swap at the same time, so put a mutex around it. */
SDL_LockMutex(videodata.swaplock);
[nscontext flushBuffer];
[nscontext updateIfNeeded];
SDL_UnlockMutex(videodata.swaplock);
return 0;
/* In the future we'll want to do this, but to match other platforms
we'll leave the OpenGL version the way it is for now
*/
/*_this->gl_config.major_version = glversion_major;*/
/*_this->gl_config.minor_version = glversion_minor;*/
}
}
return sdlcontext;
}}
void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context)
int
Cocoa_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
{ @autoreleasepool
{
@autoreleasepool {
SDLOpenGLContext *nscontext = (SDLOpenGLContext *)CFBridgingRelease(context);
[nscontext setWindow:NULL];
if (context) {
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context;
if ([nscontext window] != window) {
[nscontext setWindow:window];
[nscontext updateIfNeeded];
}
[nscontext makeCurrentContext];
} else {
[NSOpenGLContext clearCurrentContext];
}
}
return 0;
}}
int
Cocoa_GL_SetSwapInterval(_THIS, int interval)
{ @autoreleasepool
{
SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *) SDL_GL_GetCurrentContext();
int status;
if (nscontext == nil) {
status = SDL_SetError("No current OpenGL context");
} else {
SDL_LockMutex(nscontext->swapIntervalMutex);
SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0);
SDL_AtomicSet(&nscontext->swapIntervalSetting, interval);
SDL_UnlockMutex(nscontext->swapIntervalMutex);
status = 0;
}
return status;
}}
int
Cocoa_GL_GetSwapInterval(_THIS)
{ @autoreleasepool
{
SDLOpenGLContext* nscontext = (__bridge SDLOpenGLContext*)SDL_GL_GetCurrentContext();
return nscontext ? SDL_AtomicGet(&nscontext->swapIntervalSetting) : 0;
}}
int
Cocoa_GL_SwapWindow(_THIS, SDL_Window * window)
{ @autoreleasepool
{
SDLOpenGLContext* nscontext = (__bridge SDLOpenGLContext*)SDL_GL_GetCurrentContext();
SDL_VideoData *videodata = (__bridge SDL_VideoData *) _this->driverdata;
const int setting = SDL_AtomicGet(&nscontext->swapIntervalSetting);
if (setting == 0) {
/* nothing to do if vsync is disabled, don't even lock */
} else if (setting < 0) { /* late swap tearing */
SDL_LockMutex(nscontext->swapIntervalMutex);
while (SDL_AtomicGet(&nscontext->swapIntervalsPassed) == 0) {
SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex);
}
SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0);
SDL_UnlockMutex(nscontext->swapIntervalMutex);
} else {
SDL_LockMutex(nscontext->swapIntervalMutex);
do { /* always wait here so we know we just hit a swap interval. */
SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex);
} while ((SDL_AtomicGet(&nscontext->swapIntervalsPassed) % setting) != 0);
SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0);
SDL_UnlockMutex(nscontext->swapIntervalMutex);
}
/*{ static Uint64 prev = 0; const Uint64 now = SDL_GetTicks64(); const unsigned int diff = (unsigned int) (now - prev); prev = now; printf("GLSWAPBUFFERS TICKS %u\n", diff); }*/
/* on 10.14 ("Mojave") and later, this deadlocks if two contexts in two
threads try to swap at the same time, so put a mutex around it. */
SDL_LockMutex(videodata.swaplock);
[nscontext flushBuffer];
[nscontext updateIfNeeded];
SDL_UnlockMutex(videodata.swaplock);
return 0;
}}
void
Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context)
{ @autoreleasepool
{
SDLOpenGLContext *nscontext = (SDLOpenGLContext *)CFBridgingRelease(context);
[nscontext setWindow:NULL];
}}
/* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */
#ifdef __clang__

View File

@ -28,7 +28,8 @@
/* EGL implementation of SDL OpenGL support */
int Cocoa_GLES_LoadLibrary(_THIS, const char *path)
int
Cocoa_GLES_LoadLibrary(_THIS, const char *path)
{
/* If the profile requested is not GL ES, switch over to WIN_GL functions */
if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) {
@ -48,7 +49,7 @@ int Cocoa_GLES_LoadLibrary(_THIS, const char *path)
return SDL_SetError("SDL not configured with OpenGL/CGL support");
#endif
}
if (_this->egl_data == NULL) {
return SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0);
}
@ -57,11 +58,11 @@ int Cocoa_GLES_LoadLibrary(_THIS, const char *path)
}
SDL_GLContext
Cocoa_GLES_CreateContext(_THIS, SDL_Window *window)
Cocoa_GLES_CreateContext(_THIS, SDL_Window * window)
{ @autoreleasepool
{
@autoreleasepool {
SDL_GLContext context;
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_GLContext context;
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
#if SDL_VIDEO_OPENGL_CGL
if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) {
@ -77,12 +78,12 @@ Cocoa_GLES_CreateContext(_THIS, SDL_Window *window)
_this->GL_SwapWindow = Cocoa_GL_SwapWindow;
_this->GL_DeleteContext = Cocoa_GL_DeleteContext;
if (Cocoa_GL_LoadLibrary(_this, NULL) != 0) {
return NULL;
}
return Cocoa_GL_CreateContext(_this, window);
if (Cocoa_GL_LoadLibrary(_this, NULL) != 0) {
return NULL;
}
return Cocoa_GL_CreateContext(_this, window);
}
#endif
context = SDL_EGL_CreateContext(_this, data.egl_surface);
@ -114,18 +115,12 @@ Cocoa_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
int
Cocoa_GLES_SetupWindow(_THIS, SDL_Window * window)
{
@autoreleasepool {
SDL_EGL_DeleteContext(_this, context);
Cocoa_GLES_UnloadLibrary(_this);
}
}
NSView* v;
/* The current context is lost in here; save it and reset it. */
SDL_WindowData *windowdata = (__bridge SDL_WindowData *) window->driverdata;
SDL_Window *current_win = SDL_GL_GetCurrentWindow();
SDL_GLContext current_ctx = SDL_GL_GetCurrentContext();
int Cocoa_GLES_SwapWindow(_THIS, SDL_Window *window)
{
@autoreleasepool {
return SDL_EGL_SwapBuffers(_this, ((__bridge SDL_WindowData *)window->driverdata).egl_surface);
}
}
if (_this->egl_data == NULL) {
/* !!! FIXME: commenting out this assertion is (I think) incorrect; figure out why driver_loaded is wrong for ANGLE instead. --ryan. */
@ -136,12 +131,16 @@ int Cocoa_GLES_SwapWindow(_THIS, SDL_Window *window)
SDL_EGL_UnloadLibrary(_this);
return -1;
}
if (h) {
*h = height;
}
_this->gl_config.driver_loaded = 1;
}
/* Create the GLES window surface */
v = windowdata.nswindow.contentView;
windowdata.egl_surface = SDL_EGL_CreateSurface(_this, (__bridge NativeWindowType)[v layer]);
if (windowdata.egl_surface == EGL_NO_SURFACE) {
return SDL_SetError("Could not create GLES window surface");
}
}
return Cocoa_GLES_MakeCurrent(_this, current_win, current_ctx);
}

View File

@ -30,13 +30,13 @@
#include "../SDL_shape_internals.h"
@interface SDL_ShapeData : NSObject
@property(nonatomic) NSGraphicsContext *context;
@property(nonatomic) SDL_bool saved;
@property(nonatomic) SDL_ShapeTree *shape;
@property (nonatomic) NSGraphicsContext* context;
@property (nonatomic) SDL_bool saved;
@property (nonatomic) SDL_ShapeTree* shape;
@end
extern SDL_WindowShaper *Cocoa_CreateShaper(SDL_Window *window);
extern int Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode);
extern SDL_WindowShaper* Cocoa_CreateShaper(SDL_Window* window);
extern int Cocoa_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode);
extern int Cocoa_ResizeWindowShape(SDL_Window *window);
#endif /* SDL_cocoashape_h_ */

View File

@ -31,101 +31,100 @@
@end
@interface SDL_CocoaClosure : NSObject
@property(nonatomic) NSView *view;
@property(nonatomic) NSBezierPath *path;
@property(nonatomic) SDL_Window *window;
@property (nonatomic) NSView* view;
@property (nonatomic) NSBezierPath* path;
@property (nonatomic) SDL_Window* window;
@end
@implementation SDL_CocoaClosure
@end
SDL_WindowShaper *
Cocoa_CreateShaper(SDL_Window *window)
SDL_WindowShaper*
Cocoa_CreateShaper(SDL_Window* window)
{ @autoreleasepool
{
@autoreleasepool {
SDL_WindowShaper *result;
SDL_ShapeData *data;
int resized_properly;
SDL_WindowData *windata = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowShaper* result;
SDL_ShapeData* data;
int resized_properly;
SDL_WindowData* windata = (__bridge SDL_WindowData*)window->driverdata;
result = (SDL_WindowShaper *)SDL_malloc(sizeof(SDL_WindowShaper));
if (!result) {
SDL_OutOfMemory();
return NULL;
}
[windata.nswindow setOpaque:NO];
[windata.nswindow setStyleMask:NSWindowStyleMaskBorderless];
result->window = window;
result->mode.mode = ShapeModeDefault;
result->mode.parameters.binarizationCutoff = 1;
result->userx = result->usery = 0;
window->shaper = result;
data = [[SDL_ShapeData alloc] init];
data.context = [windata.nswindow graphicsContext];
data.saved = SDL_FALSE;
data.shape = NULL;
/* TODO: There's no place to release this... */
result->driverdata = (void *)CFBridgingRetain(data);
resized_properly = Cocoa_ResizeWindowShape(window);
SDL_assert(resized_properly == 0);
return result;
result = (SDL_WindowShaper *)SDL_malloc(sizeof(SDL_WindowShaper));
if (!result) {
SDL_OutOfMemory();
return NULL;
}
}
void ConvertRects(SDL_ShapeTree *tree, void *closure)
[windata.nswindow setOpaque:NO];
[windata.nswindow setStyleMask:NSWindowStyleMaskBorderless];
result->window = window;
result->mode.mode = ShapeModeDefault;
result->mode.parameters.binarizationCutoff = 1;
result->userx = result->usery = 0;
window->shaper = result;
data = [[SDL_ShapeData alloc] init];
data.context = [windata.nswindow graphicsContext];
data.saved = SDL_FALSE;
data.shape = NULL;
/* TODO: There's no place to release this... */
result->driverdata = (void*) CFBridgingRetain(data);
resized_properly = Cocoa_ResizeWindowShape(window);
SDL_assert(resized_properly == 0);
return result;
}}
void
ConvertRects(SDL_ShapeTree* tree, void* closure)
{
SDL_CocoaClosure *data = (__bridge SDL_CocoaClosure *)closure;
if (tree->kind == OpaqueShape) {
SDL_CocoaClosure* data = (__bridge SDL_CocoaClosure*)closure;
if(tree->kind == OpaqueShape) {
NSRect rect = NSMakeRect(tree->data.shape.x, data.window->h - tree->data.shape.y, tree->data.shape.w, tree->data.shape.h);
[data.path appendBezierPathWithRect:[data.view convertRect:rect toView:nil]];
}
}
int Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode)
int
Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode)
{ @autoreleasepool
{
@autoreleasepool {
SDL_ShapeData *data = (__bridge SDL_ShapeData *)shaper->driverdata;
SDL_WindowData *windata = (__bridge SDL_WindowData *)shaper->window->driverdata;
SDL_CocoaClosure *closure;
if (data.saved == SDL_TRUE) {
[data.context restoreGraphicsState];
data.saved = SDL_FALSE;
}
/*[data.context saveGraphicsState];*/
/*data.saved = SDL_TRUE;*/
[NSGraphicsContext setCurrentContext:data.context];
[[NSColor clearColor] set];
NSRectFill([windata.sdlContentView frame]);
data.shape = SDL_CalculateShapeTree(*shape_mode, shape);
closure = [[SDL_CocoaClosure alloc] init];
closure.view = windata.sdlContentView;
closure.path = [NSBezierPath bezierPath];
closure.window = shaper->window;
SDL_TraverseShapeTree(data.shape, &ConvertRects, (__bridge void *)closure);
[closure.path addClip];
return 0;
SDL_ShapeData* data = (__bridge SDL_ShapeData*)shaper->driverdata;
SDL_WindowData* windata = (__bridge SDL_WindowData*)shaper->window->driverdata;
SDL_CocoaClosure* closure;
if(data.saved == SDL_TRUE) {
[data.context restoreGraphicsState];
data.saved = SDL_FALSE;
}
}
int Cocoa_ResizeWindowShape(SDL_Window *window)
{
@autoreleasepool {
SDL_ShapeData *data = (__bridge SDL_ShapeData *)window->shaper->driverdata;
SDL_assert(data != NULL);
return 0;
}
}
/*[data.context saveGraphicsState];*/
/*data.saved = SDL_TRUE;*/
[NSGraphicsContext setCurrentContext:data.context];
[[NSColor clearColor] set];
NSRectFill([windata.sdlContentView frame]);
data.shape = SDL_CalculateShapeTree(*shape_mode, shape);
closure = [[SDL_CocoaClosure alloc] init];
closure.view = windata.sdlContentView;
closure.path = [NSBezierPath bezierPath];
closure.window = shaper->window;
SDL_TraverseShapeTree(data.shape, &ConvertRects, (__bridge void*)closure);
[closure.path addClip];
return 0;
}}
int
Cocoa_ResizeWindowShape(SDL_Window *window)
{ @autoreleasepool {
SDL_ShapeData* data = (__bridge SDL_ShapeData*)window->shaper->driverdata;
SDL_assert(data != NULL);
return 0;
}}
#endif /* SDL_VIDEO_DRIVER_COCOA */

View File

@ -98,18 +98,18 @@ DECLARE_ALERT_STYLE(Critical);
@class SDLTranslatorResponder;
@interface SDL_VideoData : NSObject
@property(nonatomic) int allow_spaces;
@property(nonatomic) int trackpad_is_touch_only;
@property(nonatomic) unsigned int modifierFlags;
@property(nonatomic) void *key_layout;
@property(nonatomic) SDLTranslatorResponder *fieldEdit;
@property(nonatomic) NSInteger clipboard_count;
@property(nonatomic) IOPMAssertionID screensaver_assertion;
@property(nonatomic) SDL_mutex *swaplock;
@property (nonatomic) int allow_spaces;
@property (nonatomic) int trackpad_is_touch_only;
@property (nonatomic) unsigned int modifierFlags;
@property (nonatomic) void *key_layout;
@property (nonatomic) SDLTranslatorResponder *fieldEdit;
@property (nonatomic) NSInteger clipboard_count;
@property (nonatomic) IOPMAssertionID screensaver_assertion;
@property (nonatomic) SDL_mutex *swaplock;
@end
/* Utility functions */
extern NSImage *Cocoa_CreateImage(SDL_Surface *surface);
extern NSImage * Cocoa_CreateImage(SDL_Surface * surface);
/* Fix build with the 10.11 SDK */
#if MAC_OS_X_VERSION_MAX_ALLOWED < 101200

View File

@ -44,22 +44,53 @@ static void Cocoa_VideoQuit(_THIS);
/* Cocoa driver bootstrap functions */
static void Cocoa_DeleteDevice(SDL_VideoDevice *device)
static void
Cocoa_DeleteDevice(SDL_VideoDevice * device)
{ @autoreleasepool
{
@autoreleasepool {
if (device->wakeup_lock) {
SDL_DestroyMutex(device->wakeup_lock);
}
CFBridgingRelease(device->driverdata);
SDL_free(device);
if (device->wakeup_lock) {
SDL_DestroyMutex(device->wakeup_lock);
}
}
CFBridgingRelease(device->driverdata);
SDL_free(device);
}}
static SDL_VideoDevice *Cocoa_CreateDevice(void)
static SDL_VideoDevice *
Cocoa_CreateDevice(void)
{ @autoreleasepool
{
@autoreleasepool {
SDL_VideoDevice *device;
SDL_VideoData *data;
SDL_VideoDevice *device;
SDL_VideoData *data;
Cocoa_RegisterApp();
/* Initialize all variables that we clean on shutdown */
device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
if (device) {
data = [[SDL_VideoData alloc] init];
} else {
data = nil;
}
if (!data) {
SDL_OutOfMemory();
SDL_free(device);
return NULL;
}
device->driverdata = (void *)CFBridgingRetain(data);
device->wakeup_lock = SDL_CreateMutex();
/* Set the function pointers */
device->VideoInit = Cocoa_VideoInit;
device->VideoQuit = Cocoa_VideoQuit;
device->GetDisplayBounds = Cocoa_GetDisplayBounds;
device->GetDisplayUsableBounds = Cocoa_GetDisplayUsableBounds;
device->GetDisplayDPI = Cocoa_GetDisplayDPI;
device->GetDisplayModes = Cocoa_GetDisplayModes;
device->SetDisplayMode = Cocoa_SetDisplayMode;
device->PumpEvents = Cocoa_PumpEvents;
device->WaitEventTimeout = Cocoa_WaitEventTimeout;
device->SendWakeupEvent = Cocoa_SendWakeupEvent;
device->SuspendScreenSaver = Cocoa_SuspendScreenSaver;
device->CreateSDLWindow = Cocoa_CreateWindow;
device->CreateSDLWindowFrom = Cocoa_CreateWindowFrom;
@ -94,68 +125,9 @@ static SDL_VideoDevice *Cocoa_CreateDevice(void)
device->AcceptDragAndDrop = Cocoa_AcceptDragAndDrop;
device->FlashWindow = Cocoa_FlashWindow;
/* Initialize all variables that we clean on shutdown */
device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice));
if (device) {
data = [[SDL_VideoData alloc] init];
} else {
data = nil;
}
if (!data) {
SDL_OutOfMemory();
SDL_free(device);
return NULL;
}
device->driverdata = (void *)CFBridgingRetain(data);
device->wakeup_lock = SDL_CreateMutex();
/* Set the function pointers */
device->VideoInit = Cocoa_VideoInit;
device->VideoQuit = Cocoa_VideoQuit;
device->GetDisplayBounds = Cocoa_GetDisplayBounds;
device->GetDisplayUsableBounds = Cocoa_GetDisplayUsableBounds;
device->GetDisplayDPI = Cocoa_GetDisplayDPI;
device->GetDisplayModes = Cocoa_GetDisplayModes;
device->SetDisplayMode = Cocoa_SetDisplayMode;
device->PumpEvents = Cocoa_PumpEvents;
device->WaitEventTimeout = Cocoa_WaitEventTimeout;
device->SendWakeupEvent = Cocoa_SendWakeupEvent;
device->SuspendScreenSaver = Cocoa_SuspendScreenSaver;
device->CreateSDLWindow = Cocoa_CreateWindow;
device->CreateSDLWindowFrom = Cocoa_CreateWindowFrom;
device->SetWindowTitle = Cocoa_SetWindowTitle;
device->SetWindowIcon = Cocoa_SetWindowIcon;
device->SetWindowPosition = Cocoa_SetWindowPosition;
device->SetWindowSize = Cocoa_SetWindowSize;
device->SetWindowMinimumSize = Cocoa_SetWindowMinimumSize;
device->SetWindowMaximumSize = Cocoa_SetWindowMaximumSize;
device->SetWindowOpacity = Cocoa_SetWindowOpacity;
device->GetWindowSizeInPixels = Cocoa_GetWindowSizeInPixels;
device->ShowWindow = Cocoa_ShowWindow;
device->HideWindow = Cocoa_HideWindow;
device->RaiseWindow = Cocoa_RaiseWindow;
device->MaximizeWindow = Cocoa_MaximizeWindow;
device->MinimizeWindow = Cocoa_MinimizeWindow;
device->RestoreWindow = Cocoa_RestoreWindow;
device->SetWindowBordered = Cocoa_SetWindowBordered;
device->SetWindowResizable = Cocoa_SetWindowResizable;
device->SetWindowAlwaysOnTop = Cocoa_SetWindowAlwaysOnTop;
device->SetWindowFullscreen = Cocoa_SetWindowFullscreen;
device->GetWindowICCProfile = Cocoa_GetWindowICCProfile;
device->GetWindowDisplayIndex = Cocoa_GetWindowDisplayIndex;
device->SetWindowMouseRect = Cocoa_SetWindowMouseRect;
device->SetWindowMouseGrab = Cocoa_SetWindowMouseGrab;
device->SetWindowKeyboardGrab = Cocoa_SetWindowKeyboardGrab;
device->DestroyWindow = Cocoa_DestroyWindow;
device->GetWindowWMInfo = Cocoa_GetWindowWMInfo;
device->SetWindowHitTest = Cocoa_SetWindowHitTest;
device->AcceptDragAndDrop = Cocoa_AcceptDragAndDrop;
device->FlashWindow = Cocoa_FlashWindow;
device->shape_driver.CreateShaper = Cocoa_CreateShaper;
device->shape_driver.SetWindowShape = Cocoa_SetWindowShape;
device->shape_driver.ResizeWindowShape = Cocoa_ResizeWindowShape;
device->shape_driver.CreateShaper = Cocoa_CreateShaper;
device->shape_driver.SetWindowShape = Cocoa_SetWindowShape;
device->shape_driver.ResizeWindowShape = Cocoa_ResizeWindowShape;
#if SDL_VIDEO_OPENGL_CGL
device->GL_LoadLibrary = Cocoa_GL_LoadLibrary;
@ -180,77 +152,77 @@ static SDL_VideoDevice *Cocoa_CreateDevice(void)
#endif
#if SDL_VIDEO_VULKAN
device->Vulkan_LoadLibrary = Cocoa_Vulkan_LoadLibrary;
device->Vulkan_UnloadLibrary = Cocoa_Vulkan_UnloadLibrary;
device->Vulkan_GetInstanceExtensions = Cocoa_Vulkan_GetInstanceExtensions;
device->Vulkan_CreateSurface = Cocoa_Vulkan_CreateSurface;
device->Vulkan_GetDrawableSize = Cocoa_Vulkan_GetDrawableSize;
device->Vulkan_LoadLibrary = Cocoa_Vulkan_LoadLibrary;
device->Vulkan_UnloadLibrary = Cocoa_Vulkan_UnloadLibrary;
device->Vulkan_GetInstanceExtensions = Cocoa_Vulkan_GetInstanceExtensions;
device->Vulkan_CreateSurface = Cocoa_Vulkan_CreateSurface;
device->Vulkan_GetDrawableSize = Cocoa_Vulkan_GetDrawableSize;
#endif
#if SDL_VIDEO_METAL
device->Metal_CreateView = Cocoa_Metal_CreateView;
device->Metal_DestroyView = Cocoa_Metal_DestroyView;
device->Metal_GetLayer = Cocoa_Metal_GetLayer;
device->Metal_GetDrawableSize = Cocoa_Metal_GetDrawableSize;
device->Metal_CreateView = Cocoa_Metal_CreateView;
device->Metal_DestroyView = Cocoa_Metal_DestroyView;
device->Metal_GetLayer = Cocoa_Metal_GetLayer;
device->Metal_GetDrawableSize = Cocoa_Metal_GetDrawableSize;
#endif
device->StartTextInput = Cocoa_StartTextInput;
device->StopTextInput = Cocoa_StopTextInput;
device->SetTextInputRect = Cocoa_SetTextInputRect;
device->StartTextInput = Cocoa_StartTextInput;
device->StopTextInput = Cocoa_StopTextInput;
device->SetTextInputRect = Cocoa_SetTextInputRect;
device->SetClipboardText = Cocoa_SetClipboardText;
device->GetClipboardText = Cocoa_GetClipboardText;
device->HasClipboardText = Cocoa_HasClipboardText;
device->SetClipboardText = Cocoa_SetClipboardText;
device->GetClipboardText = Cocoa_GetClipboardText;
device->HasClipboardText = Cocoa_HasClipboardText;
device->free = Cocoa_DeleteDevice;
device->free = Cocoa_DeleteDevice;
return device;
}
}
return device;
}}
VideoBootStrap COCOA_bootstrap = {
"cocoa", "SDL Cocoa video driver",
Cocoa_CreateDevice
};
int Cocoa_VideoInit(_THIS)
int
Cocoa_VideoInit(_THIS)
{ @autoreleasepool
{
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
Cocoa_InitModes(_this);
Cocoa_InitKeyboard(_this);
if (Cocoa_InitMouse(_this) < 0) {
return -1;
}
data.allow_spaces = SDL_GetHintBoolean(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, SDL_TRUE);
data.trackpad_is_touch_only = SDL_GetHintBoolean(SDL_HINT_TRACKPAD_IS_TOUCH_ONLY, SDL_FALSE);
data.swaplock = SDL_CreateMutex();
if (!data.swaplock) {
return -1;
}
return 0;
Cocoa_InitModes(_this);
Cocoa_InitKeyboard(_this);
if (Cocoa_InitMouse(_this) < 0) {
return -1;
}
}
void Cocoa_VideoQuit(_THIS)
data.allow_spaces = SDL_GetHintBoolean(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, SDL_TRUE);
data.trackpad_is_touch_only = SDL_GetHintBoolean(SDL_HINT_TRACKPAD_IS_TOUCH_ONLY, SDL_FALSE);
data.swaplock = SDL_CreateMutex();
if (!data.swaplock) {
return -1;
}
return 0;
}}
void
Cocoa_VideoQuit(_THIS)
{ @autoreleasepool
{
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
Cocoa_QuitModes(_this);
Cocoa_QuitKeyboard(_this);
Cocoa_QuitMouse(_this);
SDL_DestroyMutex(data.swaplock);
data.swaplock = NULL;
}
}
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
Cocoa_QuitModes(_this);
Cocoa_QuitKeyboard(_this);
Cocoa_QuitMouse(_this);
SDL_DestroyMutex(data.swaplock);
data.swaplock = NULL;
}}
/* This function assumes that it's called from within an autorelease pool */
NSImage *
Cocoa_CreateImage(SDL_Surface *surface)
Cocoa_CreateImage(SDL_Surface * surface)
{
SDL_Surface *converted;
NSBitmapImageRep *imgrep;
@ -263,16 +235,16 @@ Cocoa_CreateImage(SDL_Surface *surface)
return nil;
}
imgrep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:converted->w
pixelsHigh:converted->h
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bytesPerRow:converted->pitch
bitsPerPixel:converted->format->BitsPerPixel];
imgrep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
pixelsWide: converted->w
pixelsHigh: converted->h
bitsPerSample: 8
samplesPerPixel: 4
hasAlpha: YES
isPlanar: NO
colorSpaceName: NSDeviceRGBColorSpace
bytesPerRow: converted->pitch
bitsPerPixel: converted->format->BitsPerPixel];
if (imgrep == nil) {
SDL_FreeSurface(converted);
return nil;
@ -284,7 +256,7 @@ Cocoa_CreateImage(SDL_Surface *surface)
SDL_FreeSurface(converted);
/* Premultiply the alpha channel */
for (i = (surface->h * surface->w); i--;) {
for (i = (surface->h * surface->w); i--; ) {
Uint8 alpha = pixels[3];
pixels[0] = (Uint8)(((Uint16)pixels[0] * alpha) / 255);
pixels[1] = (Uint8)(((Uint16)pixels[1] * alpha) / 255);
@ -292,9 +264,9 @@ Cocoa_CreateImage(SDL_Surface *surface)
pixels += 4;
}
img = [[NSImage alloc] initWithSize:NSMakeSize(surface->w, surface->h)];
img = [[NSImage alloc] initWithSize: NSMakeSize(surface->w, surface->h)];
if (img != nil) {
[img addRepresentation:imgrep];
[img addRepresentation: imgrep];
}
return img;
}

View File

@ -38,13 +38,13 @@
int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path);
void Cocoa_Vulkan_UnloadLibrary(_THIS);
SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS,
SDL_Window *window,
unsigned *count,
const char **names);
SDL_Window *window,
unsigned *count,
const char **names);
SDL_bool Cocoa_Vulkan_CreateSurface(_THIS,
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface);
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface);
void Cocoa_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h);

View File

@ -37,7 +37,7 @@
#include <dlfcn.h>
const char *defaultPaths[] = {
const char* defaultPaths[] = {
"vulkan.framework/vulkan",
"libvulkan.1.dylib",
"libvulkan.dylib",
@ -69,14 +69,14 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path)
if (!path) {
/* Handle the case where Vulkan Portability is linked statically. */
vkGetInstanceProcAddr =
(PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE,
"vkGetInstanceProcAddr");
(PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE,
"vkGetInstanceProcAddr");
}
if (vkGetInstanceProcAddr) {
_this->vulkan_config.loader_handle = DEFAULT_HANDLE;
} else {
const char **paths;
const char** paths;
const char *foundPath = NULL;
int numPaths;
int i;
@ -110,7 +110,7 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path)
SDL_SetError("Failed to find %s in either executable or %s: %s",
"vkGetInstanceProcAddr",
_this->vulkan_config.loader_path,
(const char *)dlerror());
(const char *) dlerror());
goto fail;
}
@ -139,10 +139,13 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path)
}
SDL_free(extensions);
if (!hasSurfaceExtension) {
SDL_SetError("Installed Vulkan Portability library doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension");
SDL_SetError("Installed Vulkan Portability library doesn't implement the "
VK_KHR_SURFACE_EXTENSION_NAME " extension");
goto fail;
} else if (!hasMetalSurfaceExtension && !hasMacOSSurfaceExtension) {
SDL_SetError("Installed Vulkan Portability library doesn't implement the " VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " VK_MVK_MACOS_SURFACE_EXTENSION_NAME " extensions");
SDL_SetError("Installed Vulkan Portability library doesn't implement the "
VK_EXT_METAL_SURFACE_EXTENSION_NAME " or "
VK_MVK_MACOS_SURFACE_EXTENSION_NAME " extensions");
goto fail;
}
return 0;
@ -164,9 +167,9 @@ void Cocoa_Vulkan_UnloadLibrary(_THIS)
}
SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS,
SDL_Window *window,
unsigned *count,
const char **names)
SDL_Window *window,
unsigned *count,
const char **names)
{
static const char *const extensionsForCocoa[] = {
VK_KHR_SURFACE_EXTENSION_NAME, VK_EXT_METAL_SURFACE_EXTENSION_NAME
@ -176,8 +179,8 @@ SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS,
return SDL_FALSE;
}
return SDL_Vulkan_GetInstanceExtensions_Helper(
count, names, SDL_arraysize(extensionsForCocoa),
extensionsForCocoa);
count, names, SDL_arraysize(extensionsForCocoa),
extensionsForCocoa);
}
SDL_bool Cocoa_Vulkan_CreateSurface(_THIS,
@ -221,7 +224,7 @@ SDL_bool Cocoa_Vulkan_CreateSurface(_THIS,
createInfo.pNext = NULL;
createInfo.flags = 0;
createInfo.pLayer = (__bridge const CAMetalLayer *)
Cocoa_Metal_GetLayer(_this, metalview);
Cocoa_Metal_GetLayer(_this, metalview);
result = vkCreateMetalSurfaceEXT(instance, &createInfo, NULL, surface);
if (result != VK_SUCCESS) {
Cocoa_Metal_DestroyView(_this, metalview);
@ -236,7 +239,7 @@ SDL_bool Cocoa_Vulkan_CreateSurface(_THIS,
createInfo.flags = 0;
createInfo.pView = (const void *)metalview;
result = vkCreateMacOSSurfaceMVK(instance, &createInfo,
NULL, surface);
NULL, surface);
if (result != VK_SUCCESS) {
Cocoa_Metal_DestroyView(_this, metalview);
SDL_SetError("vkCreateMacOSSurfaceMVK failed: %s",

View File

@ -39,8 +39,7 @@ typedef enum
PENDING_OPERATION_MINIMIZE
} PendingWindowOperation;
@interface Cocoa_WindowListener : NSResponder <NSWindowDelegate>
{
@interface Cocoa_WindowListener : NSResponder <NSWindowDelegate> {
/* SDL_WindowData owns this Listener and has a strong reference to it.
* To avoid reference cycles, we could have either a weak or an
* unretained ref to the WindowData. */
@ -57,64 +56,64 @@ typedef enum
BOOL isDragAreaRunning;
}
- (BOOL)isTouchFromTrackpad:(NSEvent *)theEvent;
- (void)listen:(SDL_WindowData *)data;
- (void)pauseVisibleObservation;
- (void)resumeVisibleObservation;
- (BOOL)setFullscreenSpace:(BOOL)state;
- (BOOL)isInFullscreenSpace;
- (BOOL)isInFullscreenSpaceTransition;
- (void)addPendingWindowOperation:(PendingWindowOperation)operation;
- (void)close;
-(BOOL) isTouchFromTrackpad:(NSEvent *)theEvent;
-(void) listen:(SDL_WindowData *) data;
-(void) pauseVisibleObservation;
-(void) resumeVisibleObservation;
-(BOOL) setFullscreenSpace:(BOOL) state;
-(BOOL) isInFullscreenSpace;
-(BOOL) isInFullscreenSpaceTransition;
-(void) addPendingWindowOperation:(PendingWindowOperation) operation;
-(void) close;
- (BOOL)isMoving;
- (BOOL)isMovingOrFocusClickPending;
- (void)setFocusClickPending:(NSInteger)button;
- (void)clearFocusClickPending:(NSInteger)button;
- (void)setPendingMoveX:(int)x Y:(int)y;
- (void)windowDidFinishMoving;
- (void)onMovingOrFocusClickPendingStateCleared;
-(BOOL) isMoving;
-(BOOL) isMovingOrFocusClickPending;
-(void) setFocusClickPending:(NSInteger) button;
-(void) clearFocusClickPending:(NSInteger) button;
-(void) setPendingMoveX:(int)x Y:(int)y;
-(void) windowDidFinishMoving;
-(void) onMovingOrFocusClickPendingStateCleared;
/* Window delegate functionality */
- (BOOL)windowShouldClose:(id)sender;
- (void)windowDidExpose:(NSNotification *)aNotification;
- (void)windowDidMove:(NSNotification *)aNotification;
- (void)windowDidResize:(NSNotification *)aNotification;
- (void)windowDidMiniaturize:(NSNotification *)aNotification;
- (void)windowDidDeminiaturize:(NSNotification *)aNotification;
- (void)windowDidBecomeKey:(NSNotification *)aNotification;
- (void)windowDidResignKey:(NSNotification *)aNotification;
- (void)windowDidChangeBackingProperties:(NSNotification *)aNotification;
- (void)windowDidChangeScreenProfile:(NSNotification *)aNotification;
- (void)windowDidChangeScreen:(NSNotification *)aNotification;
- (void)windowWillEnterFullScreen:(NSNotification *)aNotification;
- (void)windowDidEnterFullScreen:(NSNotification *)aNotification;
- (void)windowWillExitFullScreen:(NSNotification *)aNotification;
- (void)windowDidExitFullScreen:(NSNotification *)aNotification;
- (NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions;
-(BOOL) windowShouldClose:(id) sender;
-(void) windowDidExpose:(NSNotification *) aNotification;
-(void) windowDidMove:(NSNotification *) aNotification;
-(void) windowDidResize:(NSNotification *) aNotification;
-(void) windowDidMiniaturize:(NSNotification *) aNotification;
-(void) windowDidDeminiaturize:(NSNotification *) aNotification;
-(void) windowDidBecomeKey:(NSNotification *) aNotification;
-(void) windowDidResignKey:(NSNotification *) aNotification;
-(void) windowDidChangeBackingProperties:(NSNotification *) aNotification;
-(void) windowDidChangeScreenProfile:(NSNotification *) aNotification;
-(void) windowDidChangeScreen:(NSNotification *) aNotification;
-(void) windowWillEnterFullScreen:(NSNotification *) aNotification;
-(void) windowDidEnterFullScreen:(NSNotification *) aNotification;
-(void) windowWillExitFullScreen:(NSNotification *) aNotification;
-(void) windowDidExitFullScreen:(NSNotification *) aNotification;
-(NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions;
/* See if event is in a drag area, toggle on window dragging. */
- (BOOL)processHitTest:(NSEvent *)theEvent;
-(BOOL) processHitTest:(NSEvent *)theEvent;
/* Window event handling */
- (void)mouseDown:(NSEvent *)theEvent;
- (void)rightMouseDown:(NSEvent *)theEvent;
- (void)otherMouseDown:(NSEvent *)theEvent;
- (void)mouseUp:(NSEvent *)theEvent;
- (void)rightMouseUp:(NSEvent *)theEvent;
- (void)otherMouseUp:(NSEvent *)theEvent;
- (void)mouseMoved:(NSEvent *)theEvent;
- (void)mouseDragged:(NSEvent *)theEvent;
- (void)rightMouseDragged:(NSEvent *)theEvent;
- (void)otherMouseDragged:(NSEvent *)theEvent;
- (void)scrollWheel:(NSEvent *)theEvent;
- (void)touchesBeganWithEvent:(NSEvent *)theEvent;
- (void)touchesMovedWithEvent:(NSEvent *)theEvent;
- (void)touchesEndedWithEvent:(NSEvent *)theEvent;
- (void)touchesCancelledWithEvent:(NSEvent *)theEvent;
-(void) mouseDown:(NSEvent *) theEvent;
-(void) rightMouseDown:(NSEvent *) theEvent;
-(void) otherMouseDown:(NSEvent *) theEvent;
-(void) mouseUp:(NSEvent *) theEvent;
-(void) rightMouseUp:(NSEvent *) theEvent;
-(void) otherMouseUp:(NSEvent *) theEvent;
-(void) mouseMoved:(NSEvent *) theEvent;
-(void) mouseDragged:(NSEvent *) theEvent;
-(void) rightMouseDragged:(NSEvent *) theEvent;
-(void) otherMouseDragged:(NSEvent *) theEvent;
-(void) scrollWheel:(NSEvent *) theEvent;
-(void) touchesBeganWithEvent:(NSEvent *) theEvent;
-(void) touchesMovedWithEvent:(NSEvent *) theEvent;
-(void) touchesEndedWithEvent:(NSEvent *) theEvent;
-(void) touchesCancelledWithEvent:(NSEvent *) theEvent;
/* Touch event handling */
- (void)handleTouches:(NSTouchPhase)phase withEvent:(NSEvent *)theEvent;
-(void) handleTouches:(NSTouchPhase) phase withEvent:(NSEvent*) theEvent;
@end
/* *INDENT-ON* */
@ -123,23 +122,23 @@ typedef enum
@class SDL_VideoData;
@interface SDL_WindowData : NSObject
@property(nonatomic) SDL_Window *window;
@property(nonatomic) NSWindow *nswindow;
@property(nonatomic) NSView *sdlContentView;
@property(nonatomic) NSMutableArray *nscontexts;
@property(nonatomic) SDL_bool created;
@property(nonatomic) SDL_bool inWindowFullscreenTransition;
@property(nonatomic) NSInteger window_number;
@property(nonatomic) NSInteger flash_request;
@property(nonatomic) Cocoa_WindowListener *listener;
@property(nonatomic) SDL_VideoData *videodata;
@property (nonatomic) SDL_Window *window;
@property (nonatomic) NSWindow *nswindow;
@property (nonatomic) NSView *sdlContentView;
@property (nonatomic) NSMutableArray *nscontexts;
@property (nonatomic) SDL_bool created;
@property (nonatomic) SDL_bool inWindowFullscreenTransition;
@property (nonatomic) NSInteger window_number;
@property (nonatomic) NSInteger flash_request;
@property (nonatomic) Cocoa_WindowListener *listener;
@property (nonatomic) SDL_VideoData *videodata;
#if SDL_VIDEO_OPENGL_EGL
@property(nonatomic) EGLSurface egl_surface;
@property (nonatomic) EGLSurface egl_surface;
#endif
@end
extern int Cocoa_CreateWindow(_THIS, SDL_Window *window);
extern int Cocoa_CreateWindowFrom(_THIS, SDL_Window *window,
extern int Cocoa_CreateWindow(_THIS, SDL_Window * window);
extern int Cocoa_CreateWindowFrom(_THIS, SDL_Window * window,
const void *data);
extern void Cocoa_SetWindowTitle(_THIS, SDL_Window * window);
extern void Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon);
@ -168,8 +167,8 @@ extern void Cocoa_SetWindowMouseGrab(_THIS, SDL_Window * window, SDL_bool grabbe
extern void Cocoa_DestroyWindow(_THIS, SDL_Window * window);
extern SDL_bool Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info);
extern int Cocoa_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
extern void Cocoa_AcceptDragAndDrop(SDL_Window *window, SDL_bool accept);
extern int Cocoa_FlashWindow(_THIS, SDL_Window *window, SDL_FlashOperation operation);
extern void Cocoa_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept);
extern int Cocoa_FlashWindow(_THIS, SDL_Window * window, SDL_FlashOperation operation);
#endif /* SDL_cocoawindow_h_ */

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,7 @@
@end
@interface SDLUIKitDelegate : NSObject <UIApplicationDelegate>
@interface SDLUIKitDelegate : NSObject<UIApplicationDelegate>
+ (id)sharedAppDelegate;
+ (NSString *)getAppDelegateClassName;
@ -40,7 +40,7 @@
* the app's UI is storyboard-based. SDL is not storyboard-based, however
* several major third-party ad APIs (e.g. Google admob) incorrectly assume this
* property always exists, and will crash if it doesn't. */
@property(nonatomic) UIWindow *window;
@property (nonatomic) UIWindow *window;
@end

View File

@ -36,9 +36,9 @@
#if !TARGET_OS_TV
#include <AvailabilityVersions.h>
#ifndef __IPHONE_13_0
#define __IPHONE_13_0 130000
#endif
# ifndef __IPHONE_13_0
# define __IPHONE_13_0 130000
# endif
#endif
#ifdef main
@ -57,9 +57,9 @@ int SDL_UIKitRunApp(int argc, char *argv[], SDL_main_func mainFunction)
/* store arguments */
forward_main = mainFunction;
forward_argc = argc;
forward_argv = (char **)malloc((argc + 1) * sizeof(char *));
forward_argv = (char **)malloc((argc+1) * sizeof(char *));
for (i = 0; i < argc; i++) {
forward_argv[i] = malloc((strlen(argv[i]) + 1) * sizeof(char));
forward_argv[i] = malloc( (strlen(argv[i])+1) * sizeof(char));
strcpy(forward_argv[i], argv[i]);
}
forward_argv[i] = NULL;
@ -87,7 +87,8 @@ SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldVa
#if !TARGET_OS_TV
/* Load a launch image using the old UILaunchImageFile-era naming rules. */
static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
static UIImage *
SDL_LoadLaunchImageNamed(NSString *name, int screenh)
{
UIInterfaceOrientation curorient = [UIApplication sharedApplication].statusBarOrientation;
UIUserInterfaceIdiom idiom = [UIDevice currentDevice].userInterfaceIdiom;
@ -125,21 +126,19 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
}
@interface SDLLaunchStoryboardViewController : UIViewController
@property(nonatomic, strong) UIViewController *storyboardViewController;
@property (nonatomic, strong) UIViewController *storyboardViewController;
- (instancetype)initWithStoryboardViewController:(UIViewController *)storyboardViewController;
@end
@implementation SDLLaunchStoryboardViewController
- (instancetype)initWithStoryboardViewController:(UIViewController *)storyboardViewController
{
- (instancetype)initWithStoryboardViewController:(UIViewController *)storyboardViewController {
self = [super init];
self.storyboardViewController = storyboardViewController;
return self;
}
- (void)viewDidLoad
{
- (void)viewDidLoad {
[super viewDidLoad];
[self addChildViewController:self.storyboardViewController];
@ -152,13 +151,11 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
UIApplication.sharedApplication.statusBarStyle = self.preferredStatusBarStyle;
}
- (BOOL)prefersStatusBarHidden
{
- (BOOL)prefersStatusBarHidden {
return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"UIStatusBarHidden"] boolValue];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
- (UIStatusBarStyle)preferredStatusBarStyle {
NSString *statusBarStyle = [NSBundle.mainBundle objectForInfoDictionaryKey:@"UIStatusBarStyle"];
if ([statusBarStyle isEqualToString:@"UIStatusBarStyleLightContent"]) {
return UIStatusBarStyleLightContent;
@ -347,8 +344,7 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
@end
@implementation SDLUIKitDelegate
{
@implementation SDLUIKitDelegate {
UIWindow *launchWindow;
}
@ -379,14 +375,12 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
launchWindow = nil;
/* Do a nice animated fade-out (roughly matches the real launch behavior.) */
[UIView animateWithDuration:0.2
animations:^{
window.alpha = 0.0;
}
completion:^(BOOL finished) {
window.hidden = YES;
UIKit_ForceUpdateHomeIndicator(); /* Wait for launch screen to hide so settings are applied to the actual view controller. */
}];
[UIView animateWithDuration:0.2 animations:^{
window.alpha = 0.0;
} completion:^(BOOL finished) {
window.hidden = YES;
UIKit_ForceUpdateHomeIndicator(); /* Wait for launch screen to hide so settings are applied to the actual view controller. */
}];
}
- (void)postFinishLaunch
@ -482,7 +476,7 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
if (_this) {
SDL_Window *window = NULL;
for (window = _this->windows; window != NULL; window = window->next) {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
if (data != nil) {
return data.uiwindow;
}
@ -509,7 +503,7 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh)
#if TARGET_OS_TV || (defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_9_0)
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
/* TODO: Handle options */
[self sendDropFileForURL:url];

View File

@ -27,7 +27,8 @@
#import <UIKit/UIPasteboard.h>
int UIKit_SetClipboardText(_THIS, const char *text)
int
UIKit_SetClipboardText(_THIS, const char *text)
{
#if TARGET_OS_TV
return SDL_SetError("The clipboard is not available on tvOS");
@ -71,29 +72,31 @@ UIKit_HasClipboardText(_THIS)
}
}
void UIKit_InitClipboard(_THIS)
void
UIKit_InitClipboard(_THIS)
{
#if !TARGET_OS_TV
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
id observer = [center addObserverForName:UIPasteboardChangedNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
SDL_SendClipboardUpdate();
}];
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
SDL_SendClipboardUpdate();
}];
data.pasteboardObserver = observer;
}
#endif
}
void UIKit_QuitClipboard(_THIS)
void
UIKit_QuitClipboard(_THIS)
{
@autoreleasepool {
SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
if (data.pasteboardObserver != nil) {
[[NSNotificationCenter defaultCenter] removeObserver:data.pasteboardObserver];

View File

@ -41,8 +41,9 @@
static BOOL UIKit_EventPumpEnabled = YES;
@interface SDL_LifecycleObserver : NSObject
@property(nonatomic, assign) BOOL isObservingNotifications;
@property (nonatomic, assign) BOOL isObservingNotifications;
@end
@implementation SDL_LifecycleObserver
@ -59,10 +60,7 @@ static BOOL UIKit_EventPumpEnabled = YES;
[notificationCenter addObserver:self selector:@selector(applicationWillTerminate) name:UIApplicationWillTerminateNotification object:nil];
[notificationCenter addObserver:self selector:@selector(applicationDidReceiveMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#if !TARGET_OS_TV
[notificationCenter addObserver:self
selector:@selector(applicationDidChangeStatusBarOrientation)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
[notificationCenter addObserver:self selector:@selector(applicationDidChangeStatusBarOrientation) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
#endif
} else if (!UIKit_EventPumpEnabled && self.isObservingNotifications) {
self.isObservingNotifications = NO;
@ -109,19 +107,22 @@ static BOOL UIKit_EventPumpEnabled = YES;
@end
void SDL_iPhoneSetEventPump(SDL_bool enabled)
void
SDL_iPhoneSetEventPump(SDL_bool enabled)
{
UIKit_EventPumpEnabled = enabled;
static SDL_LifecycleObserver *lifecycleObserver;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
lifecycleObserver = [SDL_LifecycleObserver new];
lifecycleObserver = [SDL_LifecycleObserver new];
});
[lifecycleObserver eventPumpChanged];
}
void UIKit_PumpEvents(_THIS)
void
UIKit_PumpEvents(_THIS)
{
if (!UIKit_EventPumpEnabled) {
return;
@ -144,7 +145,7 @@ void UIKit_PumpEvents(_THIS)
/* Make sure UIScrollView objects scroll properly. */
do {
result = CFRunLoopRunInMode((CFStringRef)UITrackingRunLoopMode, seconds, TRUE);
} while (result == kCFRunLoopRunHandledSource);
} while(result == kCFRunLoopRunHandledSource);
/* See the comment in the function definition. */
#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
@ -161,12 +162,13 @@ static id keyboard_disconnect_observer = nil;
static void OnGCKeyboardConnected(GCKeyboard *keyboard) API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
{
keyboard_connected = SDL_TRUE;
keyboard.keyboardInput.keyChangedHandler = ^(GCKeyboardInput *kbrd, GCControllerButtonInput *key, GCKeyCode keyCode, BOOL pressed) {
SDL_SendKeyboardKey(pressed ? SDL_PRESSED : SDL_RELEASED, (SDL_Scancode)keyCode);
keyboard.keyboardInput.keyChangedHandler = ^(GCKeyboardInput *kbrd, GCControllerButtonInput *key, GCKeyCode keyCode, BOOL pressed)
{
SDL_SendKeyboardKey(pressed ? SDL_PRESSED : SDL_RELEASED, (SDL_Scancode)keyCode);
};
dispatch_queue_t queue = dispatch_queue_create("org.libsdl.input.keyboard", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
dispatch_queue_t queue = dispatch_queue_create( "org.libsdl.input.keyboard", DISPATCH_QUEUE_SERIAL );
dispatch_set_target_queue( queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) );
keyboard.handlerQueue = queue;
}
@ -186,16 +188,16 @@ void SDL_InitGCKeyboard(void)
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
GCKeyboard *keyboard = note.object;
OnGCKeyboardConnected(keyboard);
GCKeyboard *keyboard = note.object;
OnGCKeyboardConnected(keyboard);
}];
keyboard_disconnect_observer = [center addObserverForName:GCKeyboardDidDisconnectNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
GCKeyboard *keyboard = note.object;
OnGCKeyboardDisconnected(keyboard);
GCKeyboard *keyboard = note.object;
OnGCKeyboardDisconnected(keyboard);
}];
if (GCKeyboard.coalescedKeyboard != nil) {
@ -250,6 +252,7 @@ void SDL_QuitGCKeyboard(void)
#endif /* ENABLE_GCKEYBOARD */
#ifdef ENABLE_GCMOUSE
static int mice_connected = 0;
@ -283,36 +286,42 @@ static void OnGCMouseConnected(GCMouse *mouse) API_AVAILABLE(macos(11.0), ios(14
{
SDL_MouseID mouseID = mice_connected;
mouse.mouseInput.leftButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) {
OnGCMouseButtonChanged(mouseID, SDL_BUTTON_LEFT, pressed);
mouse.mouseInput.leftButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed)
{
OnGCMouseButtonChanged(mouseID, SDL_BUTTON_LEFT, pressed);
};
mouse.mouseInput.middleButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) {
OnGCMouseButtonChanged(mouseID, SDL_BUTTON_MIDDLE, pressed);
mouse.mouseInput.middleButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed)
{
OnGCMouseButtonChanged(mouseID, SDL_BUTTON_MIDDLE, pressed);
};
mouse.mouseInput.rightButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) {
OnGCMouseButtonChanged(mouseID, SDL_BUTTON_RIGHT, pressed);
mouse.mouseInput.rightButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed)
{
OnGCMouseButtonChanged(mouseID, SDL_BUTTON_RIGHT, pressed);
};
int auxiliary_button = SDL_BUTTON_X1;
for (GCControllerButtonInput *btn in mouse.mouseInput.auxiliaryButtons) {
btn.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) {
OnGCMouseButtonChanged(mouseID, auxiliary_button, pressed);
btn.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed)
{
OnGCMouseButtonChanged(mouseID, auxiliary_button, pressed);
};
++auxiliary_button;
}
mouse.mouseInput.mouseMovedHandler = ^(GCMouseInput *mouseInput, float deltaX, float deltaY) {
if (SDL_GCMouseRelativeMode()) {
SDL_SendMouseMotion(SDL_GetMouseFocus(), mouseID, 1, (int)deltaX, -(int)deltaY);
}
mouse.mouseInput.mouseMovedHandler = ^(GCMouseInput *mouseInput, float deltaX, float deltaY)
{
if (SDL_GCMouseRelativeMode()) {
SDL_SendMouseMotion(SDL_GetMouseFocus(), mouseID, 1, (int)deltaX, -(int)deltaY);
}
};
mouse.mouseInput.scroll.valueChangedHandler = ^(GCControllerDirectionPad *dpad, float xValue, float yValue) {
SDL_SendMouseWheel(SDL_GetMouseFocus(), 0, xValue, yValue, SDL_MOUSEWHEEL_NORMAL);
mouse.mouseInput.scroll.valueChangedHandler = ^(GCControllerDirectionPad *dpad, float xValue, float yValue)
{
SDL_SendMouseWheel(SDL_GetMouseFocus(), 0, xValue, yValue, SDL_MOUSEWHEEL_NORMAL);
};
dispatch_queue_t queue = dispatch_queue_create("org.libsdl.input.mouse", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
dispatch_queue_t queue = dispatch_queue_create( "org.libsdl.input.mouse", DISPATCH_QUEUE_SERIAL );
dispatch_set_target_queue( queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) );
mouse.handlerQueue = queue;
++mice_connected;
@ -353,17 +362,17 @@ void SDL_InitGCMouse(void)
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
GCMouse *mouse = note.object;
OnGCMouseConnected(mouse);
GCMouse *mouse = note.object;
OnGCMouseConnected(mouse);
}];
mouse_disconnect_observer = [center addObserverForName:GCMouseDidDisconnectNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
GCMouse *mouse = note.object;
OnGCMouseDisconnected(mouse);
}];
GCMouse *mouse = note.object;
OnGCMouseDisconnected(mouse);
}];
for (GCMouse *mouse in [GCMouse mice]) {
OnGCMouseConnected(mouse);

View File

@ -36,7 +36,8 @@ UIKit_ShowingMessageBox(void)
return s_showingMessageBox;
}
static void UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messageboxdata, int *clickedindex)
static void
UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messageboxdata, int *clickedindex)
{
*clickedindex = messageboxdata->numbuttons;
@ -51,7 +52,8 @@ static void UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messagebox
}
}
static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messageboxdata, int *buttonid)
static BOOL
UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
int i;
int __block clickedindex = messageboxdata->numbuttons;
@ -83,10 +85,10 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag
}
action = [UIAlertAction actionWithTitle:@(sdlButton->text)
style:style
handler:^(UIAlertAction *alertAction) {
clickedindex = (int)(sdlButton - messageboxdata->buttons);
}];
style:style
handler:^(UIAlertAction *alertAction) {
clickedindex = (int)(sdlButton - messageboxdata->buttons);
}];
[alert addAction:action];
if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) {
@ -95,7 +97,7 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag
}
if (messageboxdata->window) {
SDL_WindowData *data = (__bridge SDL_WindowData *)messageboxdata->window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) messageboxdata->window->driverdata;
window = data.uiwindow;
}
@ -122,32 +124,30 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag
return YES;
}
static void UIKit_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue)
static void
UIKit_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue)
{ @autoreleasepool
{
@autoreleasepool {
if (UIKit_ShowMessageBoxAlertController(messageboxdata, buttonid)) {
*returnValue = 0;
} else {
*returnValue = SDL_SetError("Could not show message box.");
}
if (UIKit_ShowMessageBoxAlertController(messageboxdata, buttonid)) {
*returnValue = 0;
} else {
*returnValue = SDL_SetError("Could not show message box.");
}
}
}}
int UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
int
UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{ @autoreleasepool
{
@autoreleasepool {
__block int returnValue = 0;
__block int returnValue = 0;
if ([NSThread isMainThread]) {
UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
});
}
return returnValue;
if ([NSThread isMainThread]) {
UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
} else {
dispatch_sync(dispatch_get_main_queue(), ^{ UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); });
}
}
return returnValue;
}}
#endif /* SDL_VIDEO_DRIVER_UIKIT */

View File

@ -1,15 +1,15 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
@ -38,6 +38,7 @@
#import <Metal/Metal.h>
#import <QuartzCore/CAMetalLayer.h>
@interface SDL_uikitmetalview : SDL_uikitview
- (instancetype)initWithFrame:(CGRect)frame
@ -45,10 +46,10 @@
@end
SDL_MetalView UIKit_Metal_CreateView(_THIS, SDL_Window *window);
SDL_MetalView UIKit_Metal_CreateView(_THIS, SDL_Window * window);
void UIKit_Metal_DestroyView(_THIS, SDL_MetalView view);
void *UIKit_Metal_GetLayer(_THIS, SDL_MetalView view);
void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h);
void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h);
#endif /* SDL_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */

View File

@ -1,15 +1,15 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
@ -75,63 +75,59 @@
@end
SDL_MetalView
UIKit_Metal_CreateView(_THIS, SDL_Window *window)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
CGFloat scale = 1.0;
SDL_uikitmetalview *metalview;
UIKit_Metal_CreateView(_THIS, SDL_Window * window)
{ @autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
CGFloat scale = 1.0;
SDL_uikitmetalview *metalview;
if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
/* Set the scale to the natural scale factor of the screen - then
* the backing dimensions of the Metal view will match the pixel
* dimensions of the screen rather than the dimensions in points
* yielding high resolution on retine displays.
*/
scale = data.uiwindow.screen.nativeScale;
}
metalview = [[SDL_uikitmetalview alloc] initWithFrame:data.uiwindow.bounds
scale:scale];
if (metalview == nil) {
SDL_OutOfMemory();
return NULL;
}
[metalview setSDLWindow:window];
return (void *)CFBridgingRetain(metalview);
if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
/* Set the scale to the natural scale factor of the screen - then
* the backing dimensions of the Metal view will match the pixel
* dimensions of the screen rather than the dimensions in points
* yielding high resolution on retine displays.
*/
scale = data.uiwindow.screen.nativeScale;
}
}
void UIKit_Metal_DestroyView(_THIS, SDL_MetalView view)
{
@autoreleasepool {
SDL_uikitmetalview *metalview = CFBridgingRelease(view);
if ([metalview isKindOfClass:[SDL_uikitmetalview class]]) {
[metalview setSDLWindow:NULL];
}
metalview = [[SDL_uikitmetalview alloc] initWithFrame:data.uiwindow.bounds
scale:scale];
if (metalview == nil) {
SDL_OutOfMemory();
return NULL;
}
}
[metalview setSDLWindow:window];
return (void*)CFBridgingRetain(metalview);
}}
void
UIKit_Metal_DestroyView(_THIS, SDL_MetalView view)
{ @autoreleasepool {
SDL_uikitmetalview *metalview = CFBridgingRelease(view);
if ([metalview isKindOfClass:[SDL_uikitmetalview class]]) {
[metalview setSDLWindow:NULL];
}
}}
void *
UIKit_Metal_GetLayer(_THIS, SDL_MetalView view)
{
@autoreleasepool {
SDL_uikitview *uiview = (__bridge SDL_uikitview *)view;
return (__bridge void *)uiview.layer;
}
}
{ @autoreleasepool {
SDL_uikitview *uiview = (__bridge SDL_uikitview *)view;
return (__bridge void *)uiview.layer;
}}
void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
void
UIKit_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_uikitview *view = (SDL_uikitview *)data.uiwindow.rootViewController.view;
SDL_uikitmetalview *metalview = [view viewWithTag:SDL_METALVIEW_TAG];
SDL_uikitview *view = (SDL_uikitview*)data.uiwindow.rootViewController.view;
SDL_uikitmetalview* metalview = [view viewWithTag:SDL_METALVIEW_TAG];
if (metalview) {
CAMetalLayer *layer = (CAMetalLayer *)metalview.layer;
CAMetalLayer *layer = (CAMetalLayer*)metalview.layer;
assert(layer != NULL);
if (w) {
*w = layer.drawableSize.width;

View File

@ -27,16 +27,16 @@
@interface SDL_DisplayData : NSObject
- (instancetype)initWithScreen:(UIScreen *)screen;
- (instancetype)initWithScreen:(UIScreen*)screen;
@property(nonatomic, strong) UIScreen *uiscreen;
@property(nonatomic) float screenDPI;
@property (nonatomic, strong) UIScreen *uiscreen;
@property (nonatomic) float screenDPI;
@end
@interface SDL_DisplayModeData : NSObject
@property(nonatomic, strong) UIScreenMode *uiscreenmode;
@property (nonatomic, strong) UIScreenMode *uiscreenmode;
@end
@ -45,11 +45,11 @@ extern SDL_bool UIKit_IsDisplayLandscape(UIScreen *uiscreen);
extern int UIKit_InitModes(_THIS);
extern int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event);
extern void UIKit_DelDisplay(UIScreen *uiscreen);
extern void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display);
extern int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi);
extern int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode);
extern void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display);
extern int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi);
extern int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
extern void UIKit_QuitModes(_THIS);
extern int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect);
extern int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect);
#endif /* SDL_uikitmodes_h_ */

View File

@ -31,7 +31,7 @@
@implementation SDL_DisplayData
- (instancetype)initWithScreen:(UIScreen *)screen
- (instancetype)initWithScreen:(UIScreen*)screen
{
if (self = [super init]) {
self.uiscreen = screen;
@ -40,109 +40,108 @@
* A well up to date list of device info can be found here:
* https://github.com/lmirosevic/GBDeviceInfo/blob/master/GBDeviceInfo/GBDeviceInfo_iOS.m
*/
NSDictionary *devices = @{
@"iPhone1,1" : @163,
@"iPhone1,2" : @163,
@"iPhone2,1" : @163,
@"iPhone3,1" : @326,
@"iPhone3,2" : @326,
@"iPhone3,3" : @326,
@"iPhone4,1" : @326,
@"iPhone5,1" : @326,
@"iPhone5,2" : @326,
@"iPhone5,3" : @326,
@"iPhone5,4" : @326,
@"iPhone6,1" : @326,
@"iPhone6,2" : @326,
@"iPhone7,1" : @401,
@"iPhone7,2" : @326,
@"iPhone8,1" : @326,
@"iPhone8,2" : @401,
@"iPhone8,4" : @326,
@"iPhone9,1" : @326,
@"iPhone9,2" : @401,
@"iPhone9,3" : @326,
@"iPhone9,4" : @401,
@"iPhone10,1" : @326,
@"iPhone10,2" : @401,
@"iPhone10,3" : @458,
@"iPhone10,4" : @326,
@"iPhone10,5" : @401,
@"iPhone10,6" : @458,
@"iPhone11,2" : @458,
@"iPhone11,4" : @458,
@"iPhone11,6" : @458,
@"iPhone11,8" : @326,
@"iPhone12,1" : @326,
@"iPhone12,3" : @458,
@"iPhone12,5" : @458,
@"iPad1,1" : @132,
@"iPad2,1" : @132,
@"iPad2,2" : @132,
@"iPad2,3" : @132,
@"iPad2,4" : @132,
@"iPad2,5" : @163,
@"iPad2,6" : @163,
@"iPad2,7" : @163,
@"iPad3,1" : @264,
@"iPad3,2" : @264,
@"iPad3,3" : @264,
@"iPad3,4" : @264,
@"iPad3,5" : @264,
@"iPad3,6" : @264,
@"iPad4,1" : @264,
@"iPad4,2" : @264,
@"iPad4,3" : @264,
@"iPad4,4" : @326,
@"iPad4,5" : @326,
@"iPad4,6" : @326,
@"iPad4,7" : @326,
@"iPad4,8" : @326,
@"iPad4,9" : @326,
@"iPad5,1" : @326,
@"iPad5,2" : @326,
@"iPad5,3" : @264,
@"iPad5,4" : @264,
@"iPad6,3" : @264,
@"iPad6,4" : @264,
@"iPad6,7" : @264,
@"iPad6,8" : @264,
@"iPad6,11" : @264,
@"iPad6,12" : @264,
@"iPad7,1" : @264,
@"iPad7,2" : @264,
@"iPad7,3" : @264,
@"iPad7,4" : @264,
@"iPad7,5" : @264,
@"iPad7,6" : @264,
@"iPad7,11" : @264,
@"iPad7,12" : @264,
@"iPad8,1" : @264,
@"iPad8,2" : @264,
@"iPad8,3" : @264,
@"iPad8,4" : @264,
@"iPad8,5" : @264,
@"iPad8,6" : @264,
@"iPad8,7" : @264,
@"iPad8,8" : @264,
@"iPad11,1" : @326,
@"iPad11,2" : @326,
@"iPad11,3" : @326,
@"iPad11,4" : @326,
@"iPod1,1" : @163,
@"iPod2,1" : @163,
@"iPod3,1" : @163,
@"iPod4,1" : @326,
@"iPod5,1" : @326,
@"iPod7,1" : @326,
@"iPod9,1" : @326,
NSDictionary* devices = @{
@"iPhone1,1": @163,
@"iPhone1,2": @163,
@"iPhone2,1": @163,
@"iPhone3,1": @326,
@"iPhone3,2": @326,
@"iPhone3,3": @326,
@"iPhone4,1": @326,
@"iPhone5,1": @326,
@"iPhone5,2": @326,
@"iPhone5,3": @326,
@"iPhone5,4": @326,
@"iPhone6,1": @326,
@"iPhone6,2": @326,
@"iPhone7,1": @401,
@"iPhone7,2": @326,
@"iPhone8,1": @326,
@"iPhone8,2": @401,
@"iPhone8,4": @326,
@"iPhone9,1": @326,
@"iPhone9,2": @401,
@"iPhone9,3": @326,
@"iPhone9,4": @401,
@"iPhone10,1": @326,
@"iPhone10,2": @401,
@"iPhone10,3": @458,
@"iPhone10,4": @326,
@"iPhone10,5": @401,
@"iPhone10,6": @458,
@"iPhone11,2": @458,
@"iPhone11,4": @458,
@"iPhone11,6": @458,
@"iPhone11,8": @326,
@"iPhone12,1": @326,
@"iPhone12,3": @458,
@"iPhone12,5": @458,
@"iPad1,1": @132,
@"iPad2,1": @132,
@"iPad2,2": @132,
@"iPad2,3": @132,
@"iPad2,4": @132,
@"iPad2,5": @163,
@"iPad2,6": @163,
@"iPad2,7": @163,
@"iPad3,1": @264,
@"iPad3,2": @264,
@"iPad3,3": @264,
@"iPad3,4": @264,
@"iPad3,5": @264,
@"iPad3,6": @264,
@"iPad4,1": @264,
@"iPad4,2": @264,
@"iPad4,3": @264,
@"iPad4,4": @326,
@"iPad4,5": @326,
@"iPad4,6": @326,
@"iPad4,7": @326,
@"iPad4,8": @326,
@"iPad4,9": @326,
@"iPad5,1": @326,
@"iPad5,2": @326,
@"iPad5,3": @264,
@"iPad5,4": @264,
@"iPad6,3": @264,
@"iPad6,4": @264,
@"iPad6,7": @264,
@"iPad6,8": @264,
@"iPad6,11": @264,
@"iPad6,12": @264,
@"iPad7,1": @264,
@"iPad7,2": @264,
@"iPad7,3": @264,
@"iPad7,4": @264,
@"iPad7,5": @264,
@"iPad7,6": @264,
@"iPad7,11": @264,
@"iPad7,12": @264,
@"iPad8,1": @264,
@"iPad8,2": @264,
@"iPad8,3": @264,
@"iPad8,4": @264,
@"iPad8,5": @264,
@"iPad8,6": @264,
@"iPad8,7": @264,
@"iPad8,8": @264,
@"iPad11,1": @326,
@"iPad11,2": @326,
@"iPad11,3": @326,
@"iPad11,4": @326,
@"iPod1,1": @163,
@"iPod2,1": @163,
@"iPod3,1": @163,
@"iPod4,1": @326,
@"iPod5,1": @326,
@"iPod7,1": @326,
@"iPod9,1": @326,
};
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceName =
[NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];
NSString* deviceName =
[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
id foundDPI = devices[deviceName];
if (foundDPI) {
self.screenDPI = (float)[foundDPI integerValue];
@ -186,14 +185,10 @@
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(screenConnected:)
name:UIScreenDidConnectNotification
object:nil];
[center addObserver:self
selector:@selector(screenDisconnected:)
name:UIScreenDidDisconnectNotification
object:nil];
[center addObserver:self selector:@selector(screenConnected:)
name:UIScreenDidConnectNotification object:nil];
[center addObserver:self selector:@selector(screenDisconnected:)
name:UIScreenDidDisconnectNotification object:nil];
}
+ (void)stop
@ -201,20 +196,18 @@
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self
name:UIScreenDidConnectNotification
object:nil];
name:UIScreenDidConnectNotification object:nil];
[center removeObserver:self
name:UIScreenDidDisconnectNotification
object:nil];
name:UIScreenDidDisconnectNotification object:nil];
}
+ (void)screenConnected:(NSNotification *)notification
+ (void)screenConnected:(NSNotification*)notification
{
UIScreen *uiscreen = [notification object];
UIKit_AddDisplay(uiscreen, SDL_TRUE);
}
+ (void)screenDisconnected:(NSNotification *)notification
+ (void)screenDisconnected:(NSNotification*)notification
{
UIScreen *uiscreen = [notification object];
UIKit_DelDisplay(uiscreen);
@ -222,8 +215,9 @@
@end
static int UIKit_AllocateDisplayModeData(SDL_DisplayMode *mode,
UIScreenMode *uiscreenmode)
static int
UIKit_AllocateDisplayModeData(SDL_DisplayMode * mode,
UIScreenMode * uiscreenmode)
{
SDL_DisplayModeData *data = nil;
@ -237,12 +231,13 @@ static int UIKit_AllocateDisplayModeData(SDL_DisplayMode *mode,
data.uiscreenmode = uiscreenmode;
}
mode->driverdata = (void *)CFBridgingRetain(data);
mode->driverdata = (void *) CFBridgingRetain(data);
return 0;
}
static void UIKit_FreeDisplayModeData(SDL_DisplayMode *mode)
static void
UIKit_FreeDisplayModeData(SDL_DisplayMode * mode)
{
if (mode->driverdata != NULL) {
CFRelease(mode->driverdata);
@ -250,7 +245,8 @@ static void UIKit_FreeDisplayModeData(SDL_DisplayMode *mode)
}
}
static NSUInteger UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen)
static NSUInteger
UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen)
{
#ifdef __IPHONE_10_3
if ([uiscreen respondsToSelector:@selector(maximumFramesPerSecond)]) {
@ -260,8 +256,9 @@ static NSUInteger UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen)
return 0;
}
static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay *display, int w, int h,
UIScreen *uiscreen, UIScreenMode *uiscreenmode)
static int
UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h,
UIScreen * uiscreen, UIScreenMode * uiscreenmode)
{
SDL_DisplayMode mode;
SDL_zero(mode);
@ -271,7 +268,7 @@ static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay *display, int w, int h,
}
mode.format = SDL_PIXELFORMAT_ABGR8888;
mode.refresh_rate = (int)UIKit_GetDisplayModeRefreshRate(uiscreen);
mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen);
mode.w = w;
mode.h = h;
@ -283,8 +280,9 @@ static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay *display, int w, int h,
}
}
static int UIKit_AddDisplayMode(SDL_VideoDisplay *display, int w, int h, UIScreen *uiscreen,
UIScreenMode *uiscreenmode, SDL_bool addRotation)
static int
UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h, UIScreen * uiscreen,
UIScreenMode * uiscreenmode, SDL_bool addRotation)
{
if (UIKit_AddSingleDisplayMode(display, w, h, uiscreen, uiscreenmode) < 0) {
return -1;
@ -300,7 +298,8 @@ static int UIKit_AddDisplayMode(SDL_VideoDisplay *display, int w, int h, UIScree
return 0;
}
int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event)
int
UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event)
{
UIScreenMode *uiscreenmode = uiscreen.currentMode;
CGSize size = uiscreen.bounds.size;
@ -316,9 +315,9 @@ int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event)
}
mode.format = SDL_PIXELFORMAT_ABGR8888;
mode.refresh_rate = (int)UIKit_GetDisplayModeRefreshRate(uiscreen);
mode.w = (int)size.width;
mode.h = (int)size.height;
mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen);
mode.w = (int) size.width;
mode.h = (int) size.height;
if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) {
return -1;
@ -335,13 +334,14 @@ int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event)
return SDL_OutOfMemory();
}
display.driverdata = (void *)CFBridgingRetain(data);
display.driverdata = (void *) CFBridgingRetain(data);
SDL_AddVideoDisplay(&display, send_event);
return 0;
}
void UIKit_DelDisplay(UIScreen *uiscreen)
void
UIKit_DelDisplay(UIScreen *uiscreen)
{
int i;
@ -370,7 +370,8 @@ UIKit_IsDisplayLandscape(UIScreen *uiscreen)
}
}
int UIKit_InitModes(_THIS)
int
UIKit_InitModes(_THIS)
{
@autoreleasepool {
for (UIScreen *uiscreen in [UIScreen screens]) {
@ -388,10 +389,11 @@ int UIKit_InitModes(_THIS)
return 0;
}
void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
void
UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
{
@autoreleasepool {
SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata;
SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
SDL_bool isLandscape = UIKit_IsDisplayLandscape(data.uiscreen);
SDL_bool addRotation = (data.uiscreen == [UIScreen mainScreen]);
@ -400,7 +402,7 @@ void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
#if TARGET_OS_TV
addRotation = SDL_FALSE;
availableModes = @[ data.uiscreen.currentMode ];
availableModes = @[data.uiscreen.currentMode];
#else
availableModes = data.uiscreen.availableModes;
#endif
@ -432,10 +434,11 @@ void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display)
}
}
int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi)
int
UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi)
{
@autoreleasepool {
SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata;
SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
float dpi = data.screenDPI;
if (ddpi) {
@ -452,10 +455,11 @@ int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hd
return 0;
}
int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode)
int
UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode)
{
@autoreleasepool {
SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata;
SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
#if !TARGET_OS_TV
SDL_DisplayModeData *modedata = (__bridge SDL_DisplayModeData *)mode->driverdata;
@ -481,11 +485,12 @@ int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode
return 0;
}
int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect)
int
UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
{
@autoreleasepool {
int displayIndex = (int)(display - _this->displays);
SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata;
int displayIndex = (int) (display - _this->displays);
SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
CGRect frame = data.uiscreen.bounds;
/* the default function iterates displays to make a fake offset,
@ -503,7 +508,8 @@ int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rec
return 0;
}
void UIKit_QuitModes(_THIS)
void
UIKit_QuitModes(_THIS)
{
[SDL_DisplayWatch stop];

View File

@ -25,12 +25,12 @@
#include "../SDL_sysvideo.h"
extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window *window,
extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window,
SDL_GLContext context);
extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window *window,
int *w, int *h);
extern int UIKit_GL_SwapWindow(_THIS, SDL_Window *window);
extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window *window);
extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window,
int * w, int * h);
extern int UIKit_GL_SwapWindow(_THIS, SDL_Window * window);
extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window);
extern void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context);
extern void *UIKit_GL_GetProcAddress(_THIS, const char *proc);
extern int UIKit_GL_LoadLibrary(_THIS, const char *path);

View File

@ -37,7 +37,7 @@
@interface SDLEAGLContext : EAGLContext
/* The OpenGL ES context owns a view / drawable. */
@property(nonatomic, strong) SDL_uikitopenglview *sdlView;
@property (nonatomic, strong) SDL_uikitopenglview *sdlView;
@end
@ -64,10 +64,11 @@ UIKit_GL_GetProcAddress(_THIS, const char *proc)
/*
note that SDL_GL_DeleteContext makes it current without passing the window
*/
int UIKit_GL_MakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context)
int
UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
{
@autoreleasepool {
SDLEAGLContext *eaglcontext = (__bridge SDLEAGLContext *)context;
SDLEAGLContext *eaglcontext = (__bridge SDLEAGLContext *) context;
if (![EAGLContext setCurrentContext:eaglcontext]) {
return SDL_SetError("Could not make EAGL context current");
@ -81,13 +82,14 @@ int UIKit_GL_MakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context)
return 0;
}
void UIKit_GL_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
void
UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
UIView *view = data.viewcontroller.view;
if ([view isKindOfClass:[SDL_uikitopenglview class]]) {
SDL_uikitopenglview *glview = (SDL_uikitopenglview *)view;
SDL_uikitopenglview *glview = (SDL_uikitopenglview *) view;
if (w) {
*w = glview.backingWidth;
}
@ -100,7 +102,8 @@ void UIKit_GL_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
}
}
int UIKit_GL_LoadLibrary(_THIS, const char *path)
int
UIKit_GL_LoadLibrary(_THIS, const char *path)
{
/* We shouldn't pass a path to this function, since we've already loaded the
* library. */
@ -110,10 +113,10 @@ int UIKit_GL_LoadLibrary(_THIS, const char *path)
return 0;
}
int UIKit_GL_SwapWindow(_THIS, SDL_Window *window)
int UIKit_GL_SwapWindow(_THIS, SDL_Window * window)
{
@autoreleasepool {
SDLEAGLContext *context = (__bridge SDLEAGLContext *)SDL_GL_GetCurrentContext();
SDLEAGLContext *context = (__bridge SDLEAGLContext *) SDL_GL_GetCurrentContext();
#if SDL_POWER_UIKIT
/* Check once a frame to see if we should turn off the battery monitor. */
@ -130,12 +133,12 @@ int UIKit_GL_SwapWindow(_THIS, SDL_Window *window)
}
SDL_GLContext
UIKit_GL_CreateContext(_THIS, SDL_Window *window)
UIKit_GL_CreateContext(_THIS, SDL_Window * window)
{
@autoreleasepool {
SDLEAGLContext *context = nil;
SDL_uikitopenglview *view;
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
CGRect frame = UIKit_ComputeViewFrame(window, data.uiwindow.screen);
EAGLSharegroup *sharegroup = nil;
CGFloat scale = 1.0;
@ -158,7 +161,7 @@ UIKit_GL_CreateContext(_THIS, SDL_Window *window)
}
if (_this->gl_config.share_with_current_context) {
EAGLContext *currContext = (__bridge EAGLContext *)SDL_GL_GetCurrentContext();
EAGLContext *currContext = (__bridge EAGLContext *) SDL_GL_GetCurrentContext();
sharegroup = currContext.sharegroup;
}
@ -196,18 +199,19 @@ UIKit_GL_CreateContext(_THIS, SDL_Window *window)
/* The context owns the view / drawable. */
context.sdlView = view;
if (UIKit_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext)context) < 0) {
UIKit_GL_DeleteContext(_this, (SDL_GLContext)CFBridgingRetain(context));
if (UIKit_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext) context) < 0) {
UIKit_GL_DeleteContext(_this, (SDL_GLContext) CFBridgingRetain(context));
return NULL;
}
/* We return a +1'd context. The window's driverdata owns the view (via
* MakeCurrent.) */
return (SDL_GLContext)CFBridgingRetain(context);
return (SDL_GLContext) CFBridgingRetain(context);
}
}
void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context)
void
UIKit_GL_DeleteContext(_THIS, SDL_GLContext context)
{
@autoreleasepool {
/* The context was retained in SDL_GL_CreateContext, so we release it
@ -217,7 +221,8 @@ void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context)
}
}
void UIKit_GL_RestoreCurrentContext(void)
void
UIKit_GL_RestoreCurrentContext(void)
{
@autoreleasepool {
/* Some iOS system functionality (such as Dictation on the on-screen
@ -227,7 +232,7 @@ void UIKit_GL_RestoreCurrentContext(void)
finished running its own code for the frame. If this isn't done, the
app may crash or have other nasty symptoms when Dictation is used.
*/
EAGLContext *context = (__bridge EAGLContext *)SDL_GL_GetCurrentContext();
EAGLContext *context = (__bridge EAGLContext *) SDL_GL_GetCurrentContext();
if (context != NULL && [EAGLContext currentContext] != context) {
[EAGLContext setCurrentContext:context];
}

View File

@ -43,15 +43,15 @@
multisamples:(int)multisamples
context:(EAGLContext *)glcontext;
@property(nonatomic, readonly, weak) EAGLContext *context;
@property (nonatomic, readonly, weak) EAGLContext *context;
/* The width and height of the drawable in pixels (as opposed to points.) */
@property(nonatomic, readonly) int backingWidth;
@property(nonatomic, readonly) int backingHeight;
@property (nonatomic, readonly) int backingWidth;
@property (nonatomic, readonly) int backingHeight;
@property(nonatomic, readonly) GLuint drawableRenderbuffer;
@property(nonatomic, readonly) GLuint drawableFramebuffer;
@property(nonatomic, readonly) GLuint msaaResolveFramebuffer;
@property (nonatomic, readonly) GLuint drawableRenderbuffer;
@property (nonatomic, readonly) GLuint drawableFramebuffer;
@property (nonatomic, readonly) GLuint msaaResolveFramebuffer;
- (void)swapBuffers;

View File

@ -27,8 +27,7 @@
#import "SDL_uikitopenglview.h"
#include "SDL_uikitwindow.h"
@implementation SDL_uikitopenglview
{
@implementation SDL_uikitopenglview {
/* The renderbuffer and framebuffer used to render to this layer. */
GLuint viewRenderbuffer, viewFramebuffer;
@ -110,8 +109,8 @@
eaglLayer.opaque = YES;
eaglLayer.drawableProperties = @{
kEAGLDrawablePropertyRetainedBacking : @(retained),
kEAGLDrawablePropertyColorFormat : colorFormat
kEAGLDrawablePropertyRetainedBacking:@(retained),
kEAGLDrawablePropertyColorFormat:colorFormat
};
/* Set the appropriate scale (for retina display support) */
@ -280,7 +279,7 @@
- (void)swapBuffers
{
if (msaaFramebuffer) {
const GLenum attachments[] = { GL_COLOR_ATTACHMENT0 };
const GLenum attachments[] = {GL_COLOR_ATTACHMENT0};
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, viewFramebuffer);
@ -318,8 +317,8 @@
{
[super layoutSubviews];
int width = (int)(self.bounds.size.width * self.contentScaleFactor);
int height = (int)(self.bounds.size.height * self.contentScaleFactor);
int width = (int) (self.bounds.size.width * self.contentScaleFactor);
int height = (int) (self.bounds.size.height * self.contentScaleFactor);
/* Update the color and depth buffer storage if the layer size has changed. */
if (width != backingWidth || height != backingHeight) {

View File

@ -29,7 +29,7 @@
@interface SDL_VideoData : NSObject
@property(nonatomic, assign) id pasteboardObserver;
@property (nonatomic, assign) id pasteboardObserver;
@end

View File

@ -52,7 +52,7 @@ static void UIKit_VideoQuit(_THIS);
/* DUMMY driver bootstrap functions */
static void UIKit_DeleteDevice(SDL_VideoDevice *device)
static void UIKit_DeleteDevice(SDL_VideoDevice * device)
{
@autoreleasepool {
CFRelease(device->driverdata);
@ -60,14 +60,15 @@ static void UIKit_DeleteDevice(SDL_VideoDevice *device)
}
}
static SDL_VideoDevice *UIKit_CreateDevice(void)
static SDL_VideoDevice *
UIKit_CreateDevice(void)
{
@autoreleasepool {
SDL_VideoDevice *device;
SDL_VideoData *data;
/* Initialize all variables that we clean on shutdown */
device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice));
device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
if (device) {
data = [SDL_VideoData new];
} else {
@ -76,7 +77,7 @@ static SDL_VideoDevice *UIKit_CreateDevice(void)
return (0);
}
device->driverdata = (void *)CFBridgingRetain(data);
device->driverdata = (void *) CFBridgingRetain(data);
/* Set the function pointers */
device->VideoInit = UIKit_VideoInit;
@ -113,20 +114,21 @@ static SDL_VideoDevice *UIKit_CreateDevice(void)
/* OpenGL (ES) functions */
#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
device->GL_MakeCurrent = UIKit_GL_MakeCurrent;
device->GL_GetDrawableSize = UIKit_GL_GetDrawableSize;
device->GL_SwapWindow = UIKit_GL_SwapWindow;
device->GL_CreateContext = UIKit_GL_CreateContext;
device->GL_DeleteContext = UIKit_GL_DeleteContext;
device->GL_GetProcAddress = UIKit_GL_GetProcAddress;
device->GL_LoadLibrary = UIKit_GL_LoadLibrary;
device->GL_MakeCurrent = UIKit_GL_MakeCurrent;
device->GL_GetDrawableSize = UIKit_GL_GetDrawableSize;
device->GL_SwapWindow = UIKit_GL_SwapWindow;
device->GL_CreateContext = UIKit_GL_CreateContext;
device->GL_DeleteContext = UIKit_GL_DeleteContext;
device->GL_GetProcAddress = UIKit_GL_GetProcAddress;
device->GL_LoadLibrary = UIKit_GL_LoadLibrary;
#endif
device->free = UIKit_DeleteDevice;
#if SDL_VIDEO_VULKAN
device->Vulkan_LoadLibrary = UIKit_Vulkan_LoadLibrary;
device->Vulkan_UnloadLibrary = UIKit_Vulkan_UnloadLibrary;
device->Vulkan_GetInstanceExtensions = UIKit_Vulkan_GetInstanceExtensions;
device->Vulkan_GetInstanceExtensions
= UIKit_Vulkan_GetInstanceExtensions;
device->Vulkan_CreateSurface = UIKit_Vulkan_CreateSurface;
device->Vulkan_GetDrawableSize = UIKit_Vulkan_GetDrawableSize;
#endif
@ -149,7 +151,9 @@ VideoBootStrap UIKIT_bootstrap = {
UIKit_CreateDevice
};
int UIKit_VideoInit(_THIS)
int
UIKit_VideoInit(_THIS)
{
_this->gl_config.driver_loaded = 1;
@ -163,7 +167,8 @@ int UIKit_VideoInit(_THIS)
return 0;
}
void UIKit_VideoQuit(_THIS)
void
UIKit_VideoQuit(_THIS)
{
SDL_QuitGCKeyboard();
SDL_QuitGCMouse();
@ -171,7 +176,8 @@ void UIKit_VideoQuit(_THIS)
UIKit_QuitModes(_this);
}
void UIKit_SuspendScreenSaver(_THIS)
void
UIKit_SuspendScreenSaver(_THIS)
{
@autoreleasepool {
/* Ignore ScreenSaver API calls if the idle timer hint has been set. */
@ -194,7 +200,7 @@ UIKit_IsSystemVersionAtLeast(double version)
CGRect
UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen)
{
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
CGRect frame = screen.bounds;
/* Use the UIWindow bounds instead of the UIScreen bounds, when possible.
@ -229,13 +235,14 @@ UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen)
return frame;
}
void UIKit_ForceUpdateHomeIndicator()
void
UIKit_ForceUpdateHomeIndicator()
{
#if !TARGET_OS_TV
/* Force the main SDL window to re-evaluate home indicator state */
SDL_Window *focus = SDL_GetFocusWindow();
if (focus) {
SDL_WindowData *data = (__bridge SDL_WindowData *)focus->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) focus->driverdata;
if (data != nil) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"

View File

@ -37,7 +37,7 @@
#if !TARGET_OS_TV && defined(__IPHONE_13_4)
- (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4));
- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4));
- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4));
#endif
- (CGPoint)touchLocation:(UITouch *)touch shouldNormalize:(BOOL)normalize;

View File

@ -1,22 +1,22 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
/*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
@ -35,15 +35,14 @@
#include "SDL_uikitwindow.h"
/* The maximum number of mouse buttons we support */
#define MAX_MOUSE_BUTTONS 5
#define MAX_MOUSE_BUTTONS 5
/* This is defined in SDL_sysjoystick.m */
#if !SDL_JOYSTICK_DISABLED
extern int SDL_AppleTVRemoteOpenedAsJoystick;
#endif
@implementation SDL_uikitview
{
@implementation SDL_uikitview {
SDL_Window *sdlwindow;
SDL_TouchID directTouchId;
@ -104,7 +103,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
/* Remove ourself from the old window. */
if (sdlwindow) {
SDL_uikitview *view = nil;
data = (__bridge SDL_WindowData *)sdlwindow->driverdata;
data = (__bridge SDL_WindowData *) sdlwindow->driverdata;
[data.views removeObject:self];
@ -123,7 +122,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
/* Add ourself to the new window. */
if (window) {
data = (__bridge SDL_WindowData *)window->driverdata;
data = (__bridge SDL_WindowData *) window->driverdata;
/* Make sure the SDL window has a strong reference to this view. */
[data.views addObject:self];
@ -150,8 +149,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
}
#if !TARGET_OS_TV && defined(__IPHONE_13_4)
- (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4))
{
- (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4)){
if (request != nil && !SDL_GCMouseRelativeMode()) {
CGPoint origin = self.bounds.origin;
CGPoint point = request.location;
@ -164,8 +162,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
return [UIPointerRegion regionWithRect:self.bounds identifier:nil];
}
- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4))
{
- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)){
if (SDL_ShowCursor(-1)) {
return nil;
} else {
@ -190,11 +187,11 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
- (SDL_TouchID)touchIdForType:(SDL_TouchDeviceType)type
{
switch (type) {
case SDL_TOUCH_DEVICE_DIRECT:
default:
return directTouchId;
case SDL_TOUCH_DEVICE_INDIRECT_RELATIVE:
return indirectTouchId;
case SDL_TOUCH_DEVICE_DIRECT:
default:
return directTouchId;
case SDL_TOUCH_DEVICE_INDIRECT_RELATIVE:
return indirectTouchId;
}
}
@ -215,7 +212,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
{
#ifdef __IPHONE_9_0
if ([touch respondsToSelector:@selector(force)]) {
return (float)touch.force;
return (float) touch.force;
}
#endif
@ -367,7 +364,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
}
#if TARGET_OS_TV || defined(__IPHONE_9_1)
- (SDL_Scancode)scancodeFromPress:(UIPress *)press
- (SDL_Scancode)scancodeFromPress:(UIPress*)press
{
#ifdef __IPHONE_13_4
if ([press respondsToSelector:@selector((key))]) {
@ -449,7 +446,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick;
#endif /* TARGET_OS_TV || defined(__IPHONE_9_1) */
#if TARGET_OS_TV
- (void)swipeGesture:(UISwipeGestureRecognizer *)gesture
-(void)swipeGesture:(UISwipeGestureRecognizer *)gesture
{
/* Swipe gestures don't trigger begin states. */
if (gesture.state == UIGestureRecognizerStateEnded) {

View File

@ -39,18 +39,18 @@
@interface SDL_uikitviewcontroller : SDLRootViewController
#endif
@property(nonatomic, assign) SDL_Window *window;
@property (nonatomic, assign) SDL_Window *window;
- (instancetype)initWithSDLWindow:(SDL_Window *)_window;
- (void)setAnimationCallback:(int)interval
callback:(void (*)(void *))callback
callbackParam:(void *)callbackParam;
callback:(void (*)(void*))callback
callbackParam:(void*)callbackParam;
- (void)startAnimation;
- (void)stopAnimation;
- (void)doLoop:(CADisplayLink *)sender;
- (void)doLoop:(CADisplayLink*)sender;
- (void)loadView;
- (void)viewDidLayoutSubviews;
@ -61,7 +61,7 @@
- (BOOL)prefersHomeIndicatorAutoHidden;
- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures;
@property(nonatomic, assign) int homeIndicatorHidden;
@property (nonatomic, assign) int homeIndicatorHidden;
#endif
#if SDL_IPHONE_KEYBOARD
@ -75,9 +75,9 @@
- (void)updateKeyboard;
@property(nonatomic, assign, getter=isKeyboardVisible) BOOL keyboardVisible;
@property(nonatomic, assign) SDL_Rect textInputRect;
@property(nonatomic, assign) int keyboardHeight;
@property (nonatomic, assign, getter=isKeyboardVisible) BOOL keyboardVisible;
@property (nonatomic, assign) SDL_Rect textInputRect;
@property (nonatomic, assign) int keyboardHeight;
#endif
@end

View File

@ -36,20 +36,22 @@
#include "SDL_uikitopengles.h"
#if TARGET_OS_TV
static void SDLCALL SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
static void SDLCALL
SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
@autoreleasepool {
SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *)userdata;
SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *) userdata;
viewcontroller.controllerUserInteractionEnabled = hint && (*hint != '0');
}
}
#endif
#if !TARGET_OS_TV
static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
static void SDLCALL
SDL_HideHomeIndicatorHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
@autoreleasepool {
SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *)userdata;
SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *) userdata;
viewcontroller.homeIndicatorHidden = (hint && *hint) ? SDL_atoi(hint) : -1;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
@ -62,11 +64,10 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
}
#endif
@implementation SDL_uikitviewcontroller
{
@implementation SDL_uikitviewcontroller {
CADisplayLink *displayLink;
int animationInterval;
void (*animationCallback)(void *);
void (*animationCallback)(void*);
void *animationCallbackParam;
#if SDL_IPHONE_KEYBOARD
@ -96,13 +97,13 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
#if TARGET_OS_TV
SDL_AddHintCallback(SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS,
SDL_AppleTVControllerUIHintChanged,
(__bridge void *)self);
(__bridge void *) self);
#endif
#if !TARGET_OS_TV
SDL_AddHintCallback(SDL_HINT_IOS_HIDE_HOME_INDICATOR,
SDL_HideHomeIndicatorHintChanged,
(__bridge void *)self);
(__bridge void *) self);
#endif
}
return self;
@ -117,19 +118,19 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
#if TARGET_OS_TV
SDL_DelHintCallback(SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS,
SDL_AppleTVControllerUIHintChanged,
(__bridge void *)self);
(__bridge void *) self);
#endif
#if !TARGET_OS_TV
SDL_DelHintCallback(SDL_HINT_IOS_HIDE_HOME_INDICATOR,
SDL_HideHomeIndicatorHintChanged,
(__bridge void *)self);
(__bridge void *) self);
#endif
}
- (void)setAnimationCallback:(int)interval
callback:(void (*)(void *))callback
callbackParam:(void *)callbackParam
callback:(void (*)(void*))callback
callbackParam:(void*)callbackParam
{
[self stopAnimation];
@ -147,9 +148,11 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)];
#ifdef __IPHONE_10_3
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)] && data != nil && data.uiwindow != nil && [data.uiwindow.screen respondsToSelector:@selector(maximumFramesPerSecond)]) {
if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)]
&& data != nil && data.uiwindow != nil
&& [data.uiwindow.screen respondsToSelector:@selector(maximumFramesPerSecond)]) {
displayLink.preferredFramesPerSecond = data.uiwindow.screen.maximumFramesPerSecond / animationInterval;
} else
#endif
@ -168,7 +171,7 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
displayLink = nil;
}
- (void)doLoop:(CADisplayLink *)sender
- (void)doLoop:(CADisplayLink*)sender
{
/* Don't run the game loop while a messagebox is up */
if (!UIKit_ShowingMessageBox()) {
@ -189,8 +192,8 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
- (void)viewDidLayoutSubviews
{
const CGSize size = self.view.bounds.size;
int w = (int)size.width;
int h = (int)size.height;
int w = (int) size.width;
int h = (int) size.height;
SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, w, h);
}
@ -203,7 +206,7 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
- (BOOL)prefersStatusBarHidden
{
BOOL hidden = (window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) != 0;
BOOL hidden = (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0;
return hidden;
}
@ -227,7 +230,7 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
}
/* By default, fullscreen and borderless windows get all screen gestures */
if ((window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) != 0) {
if ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0) {
return UIRectEdgeAll;
} else {
return UIRectEdgeNone;
@ -274,16 +277,10 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
#if !TARGET_OS_TV
[center addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
#endif
[center addObserver:self
selector:@selector(textFieldTextDidChange:)
name:UITextFieldTextDidChangeNotification
object:nil];
[center addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
- (NSArray *)keyCommands
@ -334,26 +331,20 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
rotatingOrientation = YES;
[coordinator
animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
}
completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
self->rotatingOrientation = NO;
}];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {}
completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
self->rotatingOrientation = NO;
}];
}
- (void)deinitKeyboard
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
#if !TARGET_OS_TV
[center removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[center removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[center removeObserver:self name:UIKeyboardWillHideNotification object:nil];
#endif
[center removeObserver:self
name:UITextFieldTextDidChangeNotification
object:nil];
[center removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
/* reveal onscreen virtual keyboard */
@ -480,12 +471,12 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
}
/* Terminates the editing session */
- (BOOL)textFieldShouldReturn:(UITextField *)_textField
- (BOOL)textFieldShouldReturn:(UITextField*)_textField
{
SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_RETURN);
if (keyboardVisible &&
SDL_GetHintBoolean(SDL_HINT_RETURN_KEY_HIDES_IME, SDL_FALSE)) {
SDL_StopTextInput();
SDL_StopTextInput();
}
return YES;
}
@ -497,7 +488,8 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char
/* iPhone keyboard addition functions */
#if SDL_IPHONE_KEYBOARD
static SDL_uikitviewcontroller *GetWindowViewController(SDL_Window *window)
static SDL_uikitviewcontroller *
GetWindowViewController(SDL_Window * window)
{
if (!window || !window->driverdata) {
SDL_SetError("Invalid window");
@ -515,7 +507,8 @@ UIKit_HasScreenKeyboardSupport(_THIS)
return SDL_TRUE;
}
void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window)
void
UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window)
{
@autoreleasepool {
SDL_uikitviewcontroller *vc = GetWindowViewController(window);
@ -523,7 +516,8 @@ void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window)
}
}
void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window)
void
UIKit_HideScreenKeyboard(_THIS, SDL_Window *window)
{
@autoreleasepool {
SDL_uikitviewcontroller *vc = GetWindowViewController(window);
@ -543,7 +537,8 @@ UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window)
}
}
void UIKit_SetTextInputRect(_THIS, const SDL_Rect *rect)
void
UIKit_SetTextInputRect(_THIS, const SDL_Rect *rect)
{
if (!rect) {
SDL_InvalidParamError("rect");
@ -562,6 +557,7 @@ void UIKit_SetTextInputRect(_THIS, const SDL_Rect *rect)
}
}
#endif /* SDL_IPHONE_KEYBOARD */
#endif /* SDL_VIDEO_DRIVER_UIKIT */

View File

@ -37,13 +37,13 @@
int UIKit_Vulkan_LoadLibrary(_THIS, const char *path);
void UIKit_Vulkan_UnloadLibrary(_THIS);
SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS,
SDL_Window *window,
unsigned *count,
const char **names);
SDL_Window *window,
unsigned *count,
const char **names);
SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface);
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface);
void UIKit_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h);

View File

@ -38,7 +38,7 @@
#include <dlfcn.h>
const char *defaultPaths[] = {
const char* defaultPaths[] = {
"libvulkan.dylib",
};
@ -67,14 +67,14 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path)
if (!path) {
/* Handle the case where Vulkan Portability is linked statically. */
vkGetInstanceProcAddr =
(PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE,
"vkGetInstanceProcAddr");
(PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE,
"vkGetInstanceProcAddr");
}
if (vkGetInstanceProcAddr) {
_this->vulkan_config.loader_handle = DEFAULT_HANDLE;
} else {
const char **paths;
const char** paths;
const char *foundPath = NULL;
int numPaths;
int i;
@ -101,15 +101,15 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path)
SDL_arraysize(_this->vulkan_config.loader_path));
vkGetInstanceProcAddr =
(PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
_this->vulkan_config.loader_handle,
"vkGetInstanceProcAddr");
_this->vulkan_config.loader_handle,
"vkGetInstanceProcAddr");
}
if (!vkGetInstanceProcAddr) {
SDL_SetError("Failed to find %s in either executable or %s: %s",
"vkGetInstanceProcAddr",
"linked Vulkan Portability library",
(const char *)dlerror());
(const char *) dlerror());
goto fail;
}
@ -145,10 +145,13 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path)
SDL_free(extensions);
if (!hasSurfaceExtension) {
SDL_SetError("Installed Vulkan Portability doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension");
SDL_SetError("Installed Vulkan Portability doesn't implement the "
VK_KHR_SURFACE_EXTENSION_NAME " extension");
goto fail;
} else if (!hasMetalSurfaceExtension && !hasIOSSurfaceExtension) {
SDL_SetError("Installed Vulkan Portability doesn't implement the " VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " VK_MVK_IOS_SURFACE_EXTENSION_NAME " extensions");
SDL_SetError("Installed Vulkan Portability doesn't implement the "
VK_EXT_METAL_SURFACE_EXTENSION_NAME " or "
VK_MVK_IOS_SURFACE_EXTENSION_NAME " extensions");
goto fail;
}
@ -170,9 +173,9 @@ void UIKit_Vulkan_UnloadLibrary(_THIS)
}
SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS,
SDL_Window *window,
unsigned *count,
const char **names)
SDL_Window *window,
unsigned *count,
const char **names)
{
static const char *const extensionsForUIKit[] = {
VK_KHR_SURFACE_EXTENSION_NAME, VK_EXT_METAL_SURFACE_EXTENSION_NAME
@ -183,25 +186,25 @@ SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS,
}
return SDL_Vulkan_GetInstanceExtensions_Helper(
count, names, SDL_arraysize(extensionsForUIKit),
extensionsForUIKit);
count, names, SDL_arraysize(extensionsForUIKit),
extensionsForUIKit);
}
SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface)
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface)
{
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
(PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT =
(PFN_vkCreateMetalSurfaceEXT)vkGetInstanceProcAddr(
(VkInstance)instance,
"vkCreateMetalSurfaceEXT");
(VkInstance)instance,
"vkCreateMetalSurfaceEXT");
PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK =
(PFN_vkCreateIOSSurfaceMVK)vkGetInstanceProcAddr(
(VkInstance)instance,
"vkCreateIOSSurfaceMVK");
(VkInstance)instance,
"vkCreateIOSSurfaceMVK");
VkResult result;
SDL_MetalView metalview;
@ -211,8 +214,9 @@ SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
}
if (!vkCreateMetalSurfaceEXT && !vkCreateIOSSurfaceMVK) {
SDL_SetError(VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " VK_MVK_IOS_SURFACE_EXTENSION_NAME
" extensions are not enabled in the Vulkan instance.");
SDL_SetError(VK_EXT_METAL_SURFACE_EXTENSION_NAME " or "
VK_MVK_IOS_SURFACE_EXTENSION_NAME
" extensions are not enabled in the Vulkan instance.");
return SDL_FALSE;
}
@ -227,7 +231,7 @@ SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
createInfo.pNext = NULL;
createInfo.flags = 0;
createInfo.pLayer = (__bridge const CAMetalLayer *)
UIKit_Metal_GetLayer(_this, metalview);
UIKit_Metal_GetLayer(_this, metalview);
result = vkCreateMetalSurfaceEXT(instance, &createInfo, NULL, surface);
if (result != VK_SUCCESS) {
UIKit_Metal_DestroyView(_this, metalview);
@ -242,7 +246,7 @@ SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
createInfo.flags = 0;
createInfo.pView = (const void *)metalview;
result = vkCreateIOSSurfaceMVK(instance, &createInfo,
NULL, surface);
NULL, surface);
if (result != VK_SUCCESS) {
UIKit_Metal_DestroyView(_this, metalview);
SDL_SetError("vkCreateIOSSurfaceMVK failed: %s",

View File

@ -40,17 +40,17 @@ extern void UIKit_GetWindowSizeInPixels(_THIS, SDL_Window * window, int *w, int
extern SDL_bool UIKit_GetWindowWMInfo(_THIS, SDL_Window * window,
struct SDL_SysWMinfo * info);
extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window *window);
extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window * window);
@class UIWindow;
@interface SDL_WindowData : NSObject
@property(nonatomic, strong) UIWindow *uiwindow;
@property(nonatomic, strong) SDL_uikitviewcontroller *viewcontroller;
@property (nonatomic, strong) UIWindow *uiwindow;
@property (nonatomic, strong) SDL_uikitviewcontroller *viewcontroller;
/* Array of SDL_uikitviews owned by this window. */
@property(nonatomic, copy) NSMutableArray *views;
@property (nonatomic, copy) NSMutableArray *views;
@end

View File

@ -83,22 +83,24 @@
@end
static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bool created)
static int
SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bool created)
{
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *)display->driverdata;
SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata;
SDL_uikitview *view;
CGRect frame = UIKit_ComputeViewFrame(window, displaydata.uiscreen);
int width = (int)frame.size.width;
int height = (int)frame.size.height;
int width = (int) frame.size.width;
int height = (int) frame.size.height;
SDL_WindowData *data = [[SDL_WindowData alloc] init];
if (!data) {
return SDL_OutOfMemory();
}
window->driverdata = (void *)CFBridgingRetain(data);
window->driverdata = (void *) CFBridgingRetain(data);
data.uiwindow = uiwindow;
@ -106,9 +108,9 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo
window->flags &= ~SDL_WINDOW_HIDDEN;
if (displaydata.uiscreen != [UIScreen mainScreen]) {
window->flags &= ~SDL_WINDOW_RESIZABLE; /* window is NEVER resizable */
window->flags &= ~SDL_WINDOW_INPUT_FOCUS; /* never has input focus */
window->flags |= SDL_WINDOW_BORDERLESS; /* never has a status bar. */
window->flags &= ~SDL_WINDOW_RESIZABLE; /* window is NEVER resizable */
window->flags &= ~SDL_WINDOW_INPUT_FOCUS; /* never has input focus */
window->flags |= SDL_WINDOW_BORDERLESS; /* never has a status bar. */
}
#if !TARGET_OS_TV
@ -123,7 +125,7 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo
NSUInteger orients = UIKit_GetSupportedOrientations(window);
BOOL supportsLandscape = (orients & UIInterfaceOrientationMaskLandscape) != 0;
BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown)) != 0;
BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskPortraitUpsideDown)) != 0;
/* Make sure the width/height are oriented correctly */
if ((width > height && !supportsLandscape) || (height > width && !supportsPortrait)) {
@ -156,11 +158,12 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo
return 0;
}
int UIKit_CreateWindow(_THIS, SDL_Window *window)
int
UIKit_CreateWindow(_THIS, SDL_Window *window)
{
@autoreleasepool {
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata;
SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
SDL_Window *other;
/* We currently only handle a single window per display on iOS */
@ -201,7 +204,7 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window)
}
if (data.uiscreen == [UIScreen mainScreen]) {
if (window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) {
if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) {
[UIApplication sharedApplication].statusBarHidden = YES;
} else {
[UIApplication sharedApplication].statusBarHidden = NO;
@ -226,23 +229,25 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window)
return 1;
}
void UIKit_SetWindowTitle(_THIS, SDL_Window *window)
void
UIKit_SetWindowTitle(_THIS, SDL_Window * window)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
data.viewcontroller.title = @(window->title);
}
}
void UIKit_ShowWindow(_THIS, SDL_Window *window)
void
UIKit_ShowWindow(_THIS, SDL_Window * window)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
[data.uiwindow makeKeyAndVisible];
/* Make this window the current mouse focus for touch input */
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *)display->driverdata;
SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata;
if (displaydata.uiscreen == [UIScreen mainScreen]) {
SDL_SetMouseFocus(window);
SDL_SetKeyboardFocus(window);
@ -250,15 +255,17 @@ void UIKit_ShowWindow(_THIS, SDL_Window *window)
}
}
void UIKit_HideWindow(_THIS, SDL_Window *window)
void
UIKit_HideWindow(_THIS, SDL_Window * window)
{
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
data.uiwindow.hidden = YES;
}
}
void UIKit_RaiseWindow(_THIS, SDL_Window *window)
void
UIKit_RaiseWindow(_THIS, SDL_Window * window)
{
/* We don't currently offer a concept of "raising" the SDL window, since
* we only allow one per display, in the iOS fashion.
@ -267,9 +274,10 @@ void UIKit_RaiseWindow(_THIS, SDL_Window *window)
_this->GL_MakeCurrent(_this, _this->current_glwin, _this->current_glctx);
}
static void UIKit_UpdateWindowBorder(_THIS, SDL_Window *window)
static void
UIKit_UpdateWindowBorder(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
SDL_uikitviewcontroller *viewcontroller = data.viewcontroller;
#if !TARGET_OS_TV
@ -296,31 +304,35 @@ static void UIKit_UpdateWindowBorder(_THIS, SDL_Window *window)
[viewcontroller.view layoutIfNeeded];
}
void UIKit_SetWindowBordered(_THIS, SDL_Window *window, SDL_bool bordered)
void
UIKit_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered)
{
@autoreleasepool {
UIKit_UpdateWindowBorder(_this, window);
}
}
void UIKit_SetWindowFullscreen(_THIS, SDL_Window *window, SDL_VideoDisplay *display, SDL_bool fullscreen)
void
UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
{
@autoreleasepool {
UIKit_UpdateWindowBorder(_this, window);
}
}
void UIKit_SetWindowMouseGrab(_THIS, SDL_Window *window, SDL_bool grabbed)
void
UIKit_SetWindowMouseGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
{
/* There really isn't a concept of window grab or cursor confinement on iOS */
}
void UIKit_UpdatePointerLock(_THIS, SDL_Window *window)
void
UIKit_UpdatePointerLock(_THIS, SDL_Window * window)
{
#if !TARGET_OS_TV
#if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
SDL_uikitviewcontroller *viewcontroller = data.viewcontroller;
if (@available(iOS 14.0, *)) {
[viewcontroller setNeedsUpdateOfPrefersPointerLocked];
@ -330,11 +342,12 @@ void UIKit_UpdatePointerLock(_THIS, SDL_Window *window)
#endif /* !TARGET_OS_TV */
}
void UIKit_DestroyWindow(_THIS, SDL_Window *window)
void
UIKit_DestroyWindow(_THIS, SDL_Window * window)
{
@autoreleasepool {
if (window->driverdata != NULL) {
SDL_WindowData *data = (SDL_WindowData *)CFBridgingRelease(window->driverdata);
SDL_WindowData *data = (SDL_WindowData *) CFBridgingRelease(window->driverdata);
NSArray *views = nil;
[data.viewcontroller stopAnimation];
@ -358,24 +371,18 @@ void UIKit_DestroyWindow(_THIS, SDL_Window *window)
window->driverdata = NULL;
}
void UIKit_GetWindowSizeInPixels(_THIS, SDL_Window *window, int *w, int *h)
void
UIKit_GetWindowSizeInPixels(_THIS, SDL_Window * window, int *w, int *h)
{ @autoreleasepool
{
@autoreleasepool {
SDL_WindowData *windata = (__bridge SDL_WindowData *)window->driverdata;
UIView *view = windata.viewcontroller.view;
CGSize size = view.bounds.size;
CGFloat scale = 1.0;
SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata;
UIView *view = windata.viewcontroller.view;
CGSize size = view.bounds.size;
CGFloat scale = 1.0;
if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
scale = windata.uiwindow.screen.nativeScale;
}
/* Integer truncation of fractional values matches SDL_uikitmetalview and
* SDL_uikitopenglview. */
*w = size.width * scale;
*h = size.height * scale;
if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
scale = windata.uiwindow.screen.nativeScale;
}
}
/* Integer truncation of fractional values matches SDL_uikitmetalview and
* SDL_uikitopenglview. */
@ -424,14 +431,14 @@ UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
#if !TARGET_OS_TV
NSUInteger
UIKit_GetSupportedOrientations(SDL_Window *window)
UIKit_GetSupportedOrientations(SDL_Window * window)
{
const char *hint = SDL_GetHint(SDL_HINT_ORIENTATIONS);
NSUInteger validOrientations = UIInterfaceOrientationMaskAll;
NSUInteger orientationMask = 0;
@autoreleasepool {
SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
UIApplication *app = [UIApplication sharedApplication];
/* Get all possible valid orientations. If the app delegate doesn't tell
@ -490,7 +497,8 @@ UIKit_GetSupportedOrientations(SDL_Window *window)
}
#endif /* !TARGET_OS_TV */
int SDL_iPhoneSetAnimationCallback(SDL_Window *window, int interval, void (*callback)(void *), void *callbackParam)
int
SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam)
{
if (!window || !window->driverdata) {
return SDL_SetError("Invalid window");