src/video/cocoa/SDL_cocoawindow.m
author Alex Szpakowski <slime73@gmail.com>
Sat, 24 Sep 2016 18:46:34 -0300
changeset 10366 e1b52e69578b
parent 10353 c0f4fe10d1b3
child 10378 cb7f88c92a2e
permissions -rw-r--r--
Use OS-provided click counts on macOS and iOS for mouse press and release events.
     1 /*
     2   Simple DirectMedia Layer
     3   Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
     4 
     5   This software is provided 'as-is', without any express or implied
     6   warranty.  In no event will the authors be held liable for any damages
     7   arising from the use of this software.
     8 
     9   Permission is granted to anyone to use this software for any purpose,
    10   including commercial applications, and to alter it and redistribute it
    11   freely, subject to the following restrictions:
    12 
    13   1. The origin of this software must not be misrepresented; you must not
    14      claim that you wrote the original software. If you use this software
    15      in a product, an acknowledgment in the product documentation would be
    16      appreciated but is not required.
    17   2. Altered source versions must be plainly marked as such, and must not be
    18      misrepresented as being the original software.
    19   3. This notice may not be removed or altered from any source distribution.
    20 */
    21 #include "../../SDL_internal.h"
    22 
    23 #if SDL_VIDEO_DRIVER_COCOA
    24 
    25 #if MAC_OS_X_VERSION_MAX_ALLOWED < 1070
    26 # error SDL for Mac OS X must be built with a 10.7 SDK or above.
    27 #endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1070 */
    28 
    29 #include "SDL_syswm.h"
    30 #include "SDL_timer.h"  /* For SDL_GetTicks() */
    31 #include "SDL_hints.h"
    32 #include "../SDL_sysvideo.h"
    33 #include "../../events/SDL_keyboard_c.h"
    34 #include "../../events/SDL_mouse_c.h"
    35 #include "../../events/SDL_touch_c.h"
    36 #include "../../events/SDL_windowevents_c.h"
    37 #include "../../events/SDL_dropevents_c.h"
    38 #include "SDL_cocoavideo.h"
    39 #include "SDL_cocoashape.h"
    40 #include "SDL_cocoamouse.h"
    41 #include "SDL_cocoaopengl.h"
    42 #include "SDL_assert.h"
    43 
    44 /* #define DEBUG_COCOAWINDOW */
    45 
    46 #ifdef DEBUG_COCOAWINDOW
    47 #define DLog(fmt, ...) printf("%s: " fmt "\n", __func__, ##__VA_ARGS__)
    48 #else
    49 #define DLog(...) do { } while (0)
    50 #endif
    51 
    52 
    53 #define FULLSCREEN_MASK (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN)
    54 
    55 
    56 @interface SDLWindow : NSWindow <NSDraggingDestination>
    57 /* These are needed for borderless/fullscreen windows */
    58 - (BOOL)canBecomeKeyWindow;
    59 - (BOOL)canBecomeMainWindow;
    60 - (void)sendEvent:(NSEvent *)event;
    61 - (void)doCommandBySelector:(SEL)aSelector;
    62 
    63 /* Handle drag-and-drop of files onto the SDL window. */
    64 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
    65 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
    66 - (BOOL)wantsPeriodicDraggingUpdates;
    67 @end
    68 
    69 @implementation SDLWindow
    70 
    71 - (BOOL)canBecomeKeyWindow
    72 {
    73     return YES;
    74 }
    75 
    76 - (BOOL)canBecomeMainWindow
    77 {
    78     return YES;
    79 }
    80 
    81 - (void)sendEvent:(NSEvent *)event
    82 {
    83     [super sendEvent:event];
    84 
    85     if ([event type] != NSLeftMouseUp) {
    86         return;
    87     }
    88 
    89     id delegate = [self delegate];
    90     if (![delegate isKindOfClass:[Cocoa_WindowListener class]]) {
    91         return;
    92     }
    93 
    94     if ([delegate isMoving]) {
    95         [delegate windowDidFinishMoving];
    96     }
    97 }
    98 
    99 /* We'll respond to selectors by doing nothing so we don't beep.
   100  * The escape key gets converted to a "cancel" selector, etc.
   101  */
   102 - (void)doCommandBySelector:(SEL)aSelector
   103 {
   104     /*NSLog(@"doCommandBySelector: %@\n", NSStringFromSelector(aSelector));*/
   105 }
   106 
   107 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
   108 {
   109     if (([sender draggingSourceOperationMask] & NSDragOperationGeneric) == NSDragOperationGeneric) {
   110         return NSDragOperationGeneric;
   111     }
   112 
   113     return NSDragOperationNone; /* no idea what to do with this, reject it. */
   114 }
   115 
   116 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
   117 { @autoreleasepool
   118 {
   119     SDL_VideoDevice *_this = SDL_GetVideoDevice();
   120     NSPasteboard *pasteboard = [sender draggingPasteboard];
   121     NSArray *types = [NSArray arrayWithObject:NSFilenamesPboardType];
   122     NSString *desiredType = [pasteboard availableTypeFromArray:types];
   123     SDL_Window *sdlwindow = nil;
   124 
   125     if (desiredType == nil) {
   126         return NO;  /* can't accept anything that's being dropped here. */
   127     }
   128 
   129     NSData *data = [pasteboard dataForType:desiredType];
   130     if (data == nil) {
   131         return NO;
   132     }
   133 
   134     SDL_assert([desiredType isEqualToString:NSFilenamesPboardType]);
   135     NSArray *array = [pasteboard propertyListForType:@"NSFilenamesPboardType"];
   136 
   137     for (NSString *path in array) {
   138         NSURL *fileURL = [NSURL fileURLWithPath:path];
   139         NSNumber *isAlias = nil;
   140 
   141         [fileURL getResourceValue:&isAlias forKey:NSURLIsAliasFileKey error:nil];
   142 
   143         /* If the URL is an alias, resolve it. */
   144         if ([isAlias boolValue]) {
   145             NSURLBookmarkResolutionOptions opts = NSURLBookmarkResolutionWithoutMounting | NSURLBookmarkResolutionWithoutUI;
   146             NSData *bookmark = [NSURL bookmarkDataWithContentsOfURL:fileURL error:nil];
   147             if (bookmark != nil) {
   148                 NSURL *resolvedURL = [NSURL URLByResolvingBookmarkData:bookmark
   149                                                                options:opts
   150                                                          relativeToURL:nil
   151                                                    bookmarkDataIsStale:nil
   152                                                                  error:nil];
   153 
   154                 if (resolvedURL != nil) {
   155                     fileURL = resolvedURL;
   156                 }
   157             }
   158         }
   159 
   160         /* !!! FIXME: is there a better way to do this? */
   161         if (_this) {
   162             for (sdlwindow = _this->windows; sdlwindow; sdlwindow = sdlwindow->next) {
   163                 NSWindow *nswindow = ((SDL_WindowData *) sdlwindow->driverdata)->nswindow;
   164                 if (nswindow == self) {
   165                     break;
   166                 }
   167             }
   168         }
   169 
   170         if (!SDL_SendDropFile(sdlwindow, [[fileURL path] UTF8String])) {
   171             return NO;
   172         }
   173     }
   174 
   175     SDL_SendDropComplete(sdlwindow);
   176     return YES;
   177 }}
   178 
   179 - (BOOL)wantsPeriodicDraggingUpdates
   180 {
   181     return NO;
   182 }
   183 
   184 @end
   185 
   186 
   187 static Uint32 s_moveHack;
   188 
   189 static void ConvertNSRect(NSScreen *screen, BOOL fullscreen, NSRect *r)
   190 {
   191     r->origin.y = CGDisplayPixelsHigh(kCGDirectMainDisplay) - r->origin.y - r->size.height;
   192 }
   193 
   194 static void
   195 ScheduleContextUpdates(SDL_WindowData *data)
   196 {
   197     NSOpenGLContext *currentContext = [NSOpenGLContext currentContext];
   198     NSMutableArray *contexts = data->nscontexts;
   199     @synchronized (contexts) {
   200         for (SDLOpenGLContext *context in contexts) {
   201             if (context == currentContext) {
   202                 [context update];
   203             } else {
   204                 [context scheduleUpdate];
   205             }
   206         }
   207     }
   208 }
   209 
   210 /* !!! FIXME: this should use a hint callback. */
   211 static int
   212 GetHintCtrlClickEmulateRightClick()
   213 {
   214 	const char *hint = SDL_GetHint( SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK );
   215 	return hint != NULL && *hint != '0';
   216 }
   217 
   218 static NSUInteger
   219 GetWindowStyle(SDL_Window * window)
   220 {
   221     NSUInteger style = 0;
   222 
   223     if (window->flags & SDL_WINDOW_FULLSCREEN) {
   224         style = NSBorderlessWindowMask;
   225     } else {
   226         if (window->flags & SDL_WINDOW_BORDERLESS) {
   227             style = NSBorderlessWindowMask;
   228         } else {
   229             style = (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask);
   230         }
   231         if (window->flags & SDL_WINDOW_RESIZABLE) {
   232             style |= NSResizableWindowMask;
   233         }
   234     }
   235     return style;
   236 }
   237 
   238 static SDL_bool
   239 SetWindowStyle(SDL_Window * window, NSUInteger style)
   240 {
   241     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
   242     NSWindow *nswindow = data->nswindow;
   243 
   244     /* The view responder chain gets messed with during setStyleMask */
   245     if ([[nswindow contentView] nextResponder] == data->listener) {
   246         [[nswindow contentView] setNextResponder:nil];
   247     }
   248 
   249     [nswindow setStyleMask:style];
   250 
   251     /* The view responder chain gets messed with during setStyleMask */
   252     if ([[nswindow contentView] nextResponder] != data->listener) {
   253         [[nswindow contentView] setNextResponder:data->listener];
   254     }
   255 
   256     return SDL_TRUE;
   257 }
   258 
   259 
   260 @implementation Cocoa_WindowListener
   261 
   262 - (void)listen:(SDL_WindowData *)data
   263 {
   264     NSNotificationCenter *center;
   265     NSWindow *window = data->nswindow;
   266     NSView *view = [window contentView];
   267 
   268     _data = data;
   269     observingVisible = YES;
   270     wasCtrlLeft = NO;
   271     wasVisible = [window isVisible];
   272     isFullscreenSpace = NO;
   273     inFullscreenTransition = NO;
   274     pendingWindowOperation = PENDING_OPERATION_NONE;
   275     isMoving = NO;
   276     isDragAreaRunning = NO;
   277 
   278     center = [NSNotificationCenter defaultCenter];
   279 
   280     if ([window delegate] != nil) {
   281         [center addObserver:self selector:@selector(windowDidExpose:) name:NSWindowDidExposeNotification object:window];
   282         [center addObserver:self selector:@selector(windowDidMove:) name:NSWindowDidMoveNotification object:window];
   283         [center addObserver:self selector:@selector(windowDidResize:) name:NSWindowDidResizeNotification object:window];
   284         [center addObserver:self selector:@selector(windowDidMiniaturize:) name:NSWindowDidMiniaturizeNotification object:window];
   285         [center addObserver:self selector:@selector(windowDidDeminiaturize:) name:NSWindowDidDeminiaturizeNotification object:window];
   286         [center addObserver:self selector:@selector(windowDidBecomeKey:) name:NSWindowDidBecomeKeyNotification object:window];
   287         [center addObserver:self selector:@selector(windowDidResignKey:) name:NSWindowDidResignKeyNotification object:window];
   288         [center addObserver:self selector:@selector(windowDidChangeBackingProperties:) name:NSWindowDidChangeBackingPropertiesNotification object:window];
   289         [center addObserver:self selector:@selector(windowWillEnterFullScreen:) name:NSWindowWillEnterFullScreenNotification object:window];
   290         [center addObserver:self selector:@selector(windowDidEnterFullScreen:) name:NSWindowDidEnterFullScreenNotification object:window];
   291         [center addObserver:self selector:@selector(windowWillExitFullScreen:) name:NSWindowWillExitFullScreenNotification object:window];
   292         [center addObserver:self selector:@selector(windowDidExitFullScreen:) name:NSWindowDidExitFullScreenNotification object:window];
   293         [center addObserver:self selector:@selector(windowDidFailToEnterFullScreen:) name:@"NSWindowDidFailToEnterFullScreenNotification" object:window];
   294         [center addObserver:self selector:@selector(windowDidFailToExitFullScreen:) name:@"NSWindowDidFailToExitFullScreenNotification" object:window];
   295     } else {
   296         [window setDelegate:self];
   297     }
   298 
   299     /* Haven't found a delegate / notification that triggers when the window is
   300      * ordered out (is not visible any more). You can be ordered out without
   301      * minimizing, so DidMiniaturize doesn't work. (e.g. -[NSWindow orderOut:])
   302      */
   303     [window addObserver:self
   304              forKeyPath:@"visible"
   305                 options:NSKeyValueObservingOptionNew
   306                 context:NULL];
   307 
   308     [window setNextResponder:self];
   309     [window setAcceptsMouseMovedEvents:YES];
   310 
   311     [view setNextResponder:self];
   312 
   313     [view setAcceptsTouchEvents:YES];
   314 }
   315 
   316 - (void)observeValueForKeyPath:(NSString *)keyPath
   317                       ofObject:(id)object
   318                         change:(NSDictionary *)change
   319                        context:(void *)context
   320 {
   321     if (!observingVisible) {
   322         return;
   323     }
   324 
   325     if (object == _data->nswindow && [keyPath isEqualToString:@"visible"]) {
   326         int newVisibility = [[change objectForKey:@"new"] intValue];
   327         if (newVisibility) {
   328             SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_SHOWN, 0, 0);
   329         } else {
   330             SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0);
   331         }
   332     }
   333 }
   334 
   335 -(void) pauseVisibleObservation
   336 {
   337     observingVisible = NO;
   338     wasVisible = [_data->nswindow isVisible];
   339 }
   340 
   341 -(void) resumeVisibleObservation
   342 {
   343     BOOL isVisible = [_data->nswindow isVisible];
   344     observingVisible = YES;
   345     if (wasVisible != isVisible) {
   346         if (isVisible) {
   347             SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_SHOWN, 0, 0);
   348         } else {
   349             SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0);
   350         }
   351 
   352         wasVisible = isVisible;
   353     }
   354 }
   355 
   356 -(BOOL) setFullscreenSpace:(BOOL) state
   357 {
   358     SDL_Window *window = _data->window;
   359     NSWindow *nswindow = _data->nswindow;
   360     SDL_VideoData *videodata = ((SDL_WindowData *) window->driverdata)->videodata;
   361 
   362     if (!videodata->allow_spaces) {
   363         return NO;  /* Spaces are forcibly disabled. */
   364     } else if (state && ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP)) {
   365         return NO;  /* we only allow you to make a Space on FULLSCREEN_DESKTOP windows. */
   366     } else if (!state && ((window->last_fullscreen_flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP)) {
   367         return NO;  /* we only handle leaving the Space on windows that were previously FULLSCREEN_DESKTOP. */
   368     } else if (state == isFullscreenSpace) {
   369         return YES;  /* already there. */
   370     }
   371 
   372     if (inFullscreenTransition) {
   373         if (state) {
   374             [self addPendingWindowOperation:PENDING_OPERATION_ENTER_FULLSCREEN];
   375         } else {
   376             [self addPendingWindowOperation:PENDING_OPERATION_LEAVE_FULLSCREEN];
   377         }
   378         return YES;
   379     }
   380     inFullscreenTransition = YES;
   381 
   382     /* you need to be FullScreenPrimary, or toggleFullScreen doesn't work. Unset it again in windowDidExitFullScreen. */
   383     [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
   384     [nswindow performSelectorOnMainThread: @selector(toggleFullScreen:) withObject:nswindow waitUntilDone:NO];
   385     return YES;
   386 }
   387 
   388 -(BOOL) isInFullscreenSpace
   389 {
   390     return isFullscreenSpace;
   391 }
   392 
   393 -(BOOL) isInFullscreenSpaceTransition
   394 {
   395     return inFullscreenTransition;
   396 }
   397 
   398 -(void) addPendingWindowOperation:(PendingWindowOperation) operation
   399 {
   400     pendingWindowOperation = operation;
   401 }
   402 
   403 - (void)close
   404 {
   405     NSNotificationCenter *center;
   406     NSWindow *window = _data->nswindow;
   407     NSView *view = [window contentView];
   408 
   409     center = [NSNotificationCenter defaultCenter];
   410 
   411     if ([window delegate] != self) {
   412         [center removeObserver:self name:NSWindowDidExposeNotification object:window];
   413         [center removeObserver:self name:NSWindowDidMoveNotification object:window];
   414         [center removeObserver:self name:NSWindowDidResizeNotification object:window];
   415         [center removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
   416         [center removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
   417         [center removeObserver:self name:NSWindowDidBecomeKeyNotification object:window];
   418         [center removeObserver:self name:NSWindowDidResignKeyNotification object:window];
   419         [center removeObserver:self name:NSWindowDidChangeBackingPropertiesNotification object:window];
   420         [center removeObserver:self name:NSWindowWillEnterFullScreenNotification object:window];
   421         [center removeObserver:self name:NSWindowDidEnterFullScreenNotification object:window];
   422         [center removeObserver:self name:NSWindowWillExitFullScreenNotification object:window];
   423         [center removeObserver:self name:NSWindowDidExitFullScreenNotification object:window];
   424         [center removeObserver:self name:@"NSWindowDidFailToEnterFullScreenNotification" object:window];
   425         [center removeObserver:self name:@"NSWindowDidFailToExitFullScreenNotification" object:window];
   426     } else {
   427         [window setDelegate:nil];
   428     }
   429 
   430     [window removeObserver:self forKeyPath:@"visible"];
   431 
   432     if ([window nextResponder] == self) {
   433         [window setNextResponder:nil];
   434     }
   435     if ([view nextResponder] == self) {
   436         [view setNextResponder:nil];
   437     }
   438 }
   439 
   440 - (BOOL)isMoving
   441 {
   442     return isMoving;
   443 }
   444 
   445 -(void) setPendingMoveX:(int)x Y:(int)y
   446 {
   447     pendingWindowWarpX = x;
   448     pendingWindowWarpY = y;
   449 }
   450 
   451 - (void)windowDidFinishMoving
   452 {
   453     if ([self isMoving]) {
   454         isMoving = NO;
   455 
   456         SDL_Mouse *mouse = SDL_GetMouse();
   457         if (pendingWindowWarpX != INT_MAX && pendingWindowWarpY != INT_MAX) {
   458             mouse->WarpMouseGlobal(pendingWindowWarpX, pendingWindowWarpY);
   459             pendingWindowWarpX = pendingWindowWarpY = INT_MAX;
   460         }
   461         if (mouse->relative_mode && !mouse->relative_mode_warp && mouse->focus == _data->window) {
   462             mouse->SetRelativeMouseMode(SDL_TRUE);
   463         }
   464     }
   465 }
   466 
   467 - (BOOL)windowShouldClose:(id)sender
   468 {
   469     SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_CLOSE, 0, 0);
   470     return NO;
   471 }
   472 
   473 - (void)windowDidExpose:(NSNotification *)aNotification
   474 {
   475     SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_EXPOSED, 0, 0);
   476 }
   477 
   478 - (void)windowWillMove:(NSNotification *)aNotification
   479 {
   480     if ([_data->nswindow isKindOfClass:[SDLWindow class]]) {
   481         pendingWindowWarpX = pendingWindowWarpY = INT_MAX;
   482         isMoving = YES;
   483     }
   484 }
   485 
   486 - (void)windowDidMove:(NSNotification *)aNotification
   487 {
   488     int x, y;
   489     SDL_Window *window = _data->window;
   490     NSWindow *nswindow = _data->nswindow;
   491     BOOL fullscreen = window->flags & FULLSCREEN_MASK;
   492     NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]];
   493     ConvertNSRect([nswindow screen], fullscreen, &rect);
   494 
   495     if (s_moveHack) {
   496         SDL_bool blockMove = ((SDL_GetTicks() - s_moveHack) < 500);
   497 
   498         s_moveHack = 0;
   499 
   500         if (blockMove) {
   501             /* Cocoa is adjusting the window in response to a mode change */
   502             rect.origin.x = window->x;
   503             rect.origin.y = window->y;
   504             ConvertNSRect([nswindow screen], fullscreen, &rect);
   505             [nswindow setFrameOrigin:rect.origin];
   506             return;
   507         }
   508     }
   509 
   510     x = (int)rect.origin.x;
   511     y = (int)rect.origin.y;
   512 
   513     ScheduleContextUpdates(_data);
   514 
   515     SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MOVED, x, y);
   516 }
   517 
   518 - (void)windowDidResize:(NSNotification *)aNotification
   519 {
   520     if (inFullscreenTransition) {
   521         /* We'll take care of this at the end of the transition */
   522         return;
   523     }
   524 
   525     SDL_Window *window = _data->window;
   526     NSWindow *nswindow = _data->nswindow;
   527     int x, y, w, h;
   528     NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]];
   529     ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
   530     x = (int)rect.origin.x;
   531     y = (int)rect.origin.y;
   532     w = (int)rect.size.width;
   533     h = (int)rect.size.height;
   534 
   535     if (SDL_IsShapedWindow(window)) {
   536         Cocoa_ResizeWindowShape(window);
   537     }
   538 
   539     ScheduleContextUpdates(_data);
   540 
   541     /* The window can move during a resize event, such as when maximizing
   542        or resizing from a corner */
   543     SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MOVED, x, y);
   544     SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, w, h);
   545 
   546     const BOOL zoomed = [nswindow isZoomed];
   547     if (!zoomed) {
   548         SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESTORED, 0, 0);
   549     } else if (zoomed) {
   550         SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MAXIMIZED, 0, 0);
   551     }
   552 }
   553 
   554 - (void)windowDidMiniaturize:(NSNotification *)aNotification
   555 {
   556     SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
   557 }
   558 
   559 - (void)windowDidDeminiaturize:(NSNotification *)aNotification
   560 {
   561     SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_RESTORED, 0, 0);
   562 }
   563 
   564 - (void)windowDidBecomeKey:(NSNotification *)aNotification
   565 {
   566     SDL_Window *window = _data->window;
   567     SDL_Mouse *mouse = SDL_GetMouse();
   568 
   569     /* We're going to get keyboard events, since we're key. */
   570     /* This needs to be done before restoring the relative mouse mode. */
   571     SDL_SetKeyboardFocus(window);
   572 
   573     if (mouse->relative_mode && !mouse->relative_mode_warp && ![self isMoving]) {
   574         mouse->SetRelativeMouseMode(SDL_TRUE);
   575     }
   576 
   577     /* If we just gained focus we need the updated mouse position */
   578     if (!mouse->relative_mode) {
   579         NSPoint point;
   580         int x, y;
   581 
   582         point = [_data->nswindow mouseLocationOutsideOfEventStream];
   583         x = (int)point.x;
   584         y = (int)(window->h - point.y);
   585 
   586         if (x >= 0 && x < window->w && y >= 0 && y < window->h) {
   587             SDL_SendMouseMotion(window, 0, 0, x, y);
   588         }
   589     }
   590 
   591     /* Check to see if someone updated the clipboard */
   592     Cocoa_CheckClipboardUpdate(_data->videodata);
   593 
   594     if ((isFullscreenSpace) && ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP)) {
   595         [NSMenu setMenuBarVisible:NO];
   596     }
   597 
   598     const unsigned int newflags = [NSEvent modifierFlags] & NSAlphaShiftKeyMask;
   599     _data->videodata->modifierFlags = (_data->videodata->modifierFlags & ~NSAlphaShiftKeyMask) | newflags;
   600     SDL_ToggleModState(KMOD_CAPS, newflags != 0);
   601 }
   602 
   603 - (void)windowDidResignKey:(NSNotification *)aNotification
   604 {
   605     SDL_Mouse *mouse = SDL_GetMouse();
   606     if (mouse->relative_mode && !mouse->relative_mode_warp) {
   607         mouse->SetRelativeMouseMode(SDL_FALSE);
   608     }
   609 
   610     /* Some other window will get mouse events, since we're not key. */
   611     if (SDL_GetMouseFocus() == _data->window) {
   612         SDL_SetMouseFocus(NULL);
   613     }
   614 
   615     /* Some other window will get keyboard events, since we're not key. */
   616     if (SDL_GetKeyboardFocus() == _data->window) {
   617         SDL_SetKeyboardFocus(NULL);
   618     }
   619 
   620     if (isFullscreenSpace) {
   621         [NSMenu setMenuBarVisible:YES];
   622     }
   623 }
   624 
   625 - (void)windowDidChangeBackingProperties:(NSNotification *)aNotification
   626 {
   627     NSNumber *oldscale = [[aNotification userInfo] objectForKey:NSBackingPropertyOldScaleFactorKey];
   628 
   629     if (inFullscreenTransition) {
   630         return;
   631     }
   632 
   633     if ([oldscale doubleValue] != [_data->nswindow backingScaleFactor]) {
   634         /* Force a resize event when the backing scale factor changes. */
   635         _data->window->w = 0;
   636         _data->window->h = 0;
   637         [self windowDidResize:aNotification];
   638     }
   639 }
   640 
   641 - (void)windowWillEnterFullScreen:(NSNotification *)aNotification
   642 {
   643     SDL_Window *window = _data->window;
   644 
   645     SetWindowStyle(window, (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask));
   646 
   647     isFullscreenSpace = YES;
   648     inFullscreenTransition = YES;
   649 }
   650 
   651 - (void)windowDidFailToEnterFullScreen:(NSNotification *)aNotification
   652 {
   653     SDL_Window *window = _data->window;
   654 
   655     if (window->is_destroying) {
   656         return;
   657     }
   658 
   659     SetWindowStyle(window, GetWindowStyle(window));
   660 
   661     isFullscreenSpace = NO;
   662     inFullscreenTransition = NO;
   663     
   664     [self windowDidExitFullScreen:nil];
   665 }
   666 
   667 - (void)windowDidEnterFullScreen:(NSNotification *)aNotification
   668 {
   669     SDL_Window *window = _data->window;
   670 
   671     inFullscreenTransition = NO;
   672 
   673     if (pendingWindowOperation == PENDING_OPERATION_LEAVE_FULLSCREEN) {
   674         pendingWindowOperation = PENDING_OPERATION_NONE;
   675         [self setFullscreenSpace:NO];
   676     } else {
   677         if ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) {
   678             [NSMenu setMenuBarVisible:NO];
   679         }
   680 
   681         pendingWindowOperation = PENDING_OPERATION_NONE;
   682         /* Force the size change event in case it was delivered earlier
   683            while the window was still animating into place.
   684          */
   685         window->w = 0;
   686         window->h = 0;
   687         [self windowDidResize:aNotification];
   688     }
   689 }
   690 
   691 - (void)windowWillExitFullScreen:(NSNotification *)aNotification
   692 {
   693     SDL_Window *window = _data->window;
   694 
   695     /* As of OS X 10.11, the window seems to need to be resizable when exiting
   696        a Space, in order for it to resize back to its windowed-mode size.
   697      */
   698     SetWindowStyle(window, GetWindowStyle(window) | NSResizableWindowMask);
   699 
   700     isFullscreenSpace = NO;
   701     inFullscreenTransition = YES;
   702 }
   703 
   704 - (void)windowDidFailToExitFullScreen:(NSNotification *)aNotification
   705 {
   706     SDL_Window *window = _data->window;
   707     
   708     if (window->is_destroying) {
   709         return;
   710     }
   711 
   712     SetWindowStyle(window, (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask));
   713     
   714     isFullscreenSpace = YES;
   715     inFullscreenTransition = NO;
   716     
   717     [self windowDidEnterFullScreen:nil];
   718 }
   719 
   720 - (void)windowDidExitFullScreen:(NSNotification *)aNotification
   721 {
   722     SDL_Window *window = _data->window;
   723     NSWindow *nswindow = _data->nswindow;
   724 
   725     inFullscreenTransition = NO;
   726 
   727     SetWindowStyle(window, GetWindowStyle(window));
   728 
   729     [nswindow setLevel:kCGNormalWindowLevel];
   730 
   731     if (pendingWindowOperation == PENDING_OPERATION_ENTER_FULLSCREEN) {
   732         pendingWindowOperation = PENDING_OPERATION_NONE;
   733         [self setFullscreenSpace:YES];
   734     } else if (pendingWindowOperation == PENDING_OPERATION_MINIMIZE) {
   735         pendingWindowOperation = PENDING_OPERATION_NONE;
   736         [nswindow miniaturize:nil];
   737     } else {
   738         /* Adjust the fullscreen toggle button and readd menu now that we're here. */
   739         if (window->flags & SDL_WINDOW_RESIZABLE) {
   740             /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */
   741             [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
   742         } else {
   743             [nswindow setCollectionBehavior:NSWindowCollectionBehaviorManaged];
   744         }
   745         [NSMenu setMenuBarVisible:YES];
   746 
   747         pendingWindowOperation = PENDING_OPERATION_NONE;
   748         /* Force the size change event in case it was delivered earlier
   749            while the window was still animating into place.
   750          */
   751         window->w = 0;
   752         window->h = 0;
   753         [self windowDidResize:aNotification];
   754 
   755         /* FIXME: Why does the window get hidden? */
   756         if (window->flags & SDL_WINDOW_SHOWN) {
   757             Cocoa_ShowWindow(SDL_GetVideoDevice(), window);
   758         }
   759     }
   760 }
   761 
   762 -(NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions
   763 {
   764     if ((_data->window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) {
   765         return NSApplicationPresentationFullScreen | NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
   766     } else {
   767         return proposedOptions;
   768     }
   769 }
   770 
   771 
   772 /* We'll respond to key events by doing nothing so we don't beep.
   773  * We could handle key messages here, but we lose some in the NSApp dispatch,
   774  * where they get converted to action messages, etc.
   775  */
   776 - (void)flagsChanged:(NSEvent *)theEvent
   777 {
   778     /*Cocoa_HandleKeyEvent(SDL_GetVideoDevice(), theEvent);*/
   779 }
   780 - (void)keyDown:(NSEvent *)theEvent
   781 {
   782     /*Cocoa_HandleKeyEvent(SDL_GetVideoDevice(), theEvent);*/
   783 }
   784 - (void)keyUp:(NSEvent *)theEvent
   785 {
   786     /*Cocoa_HandleKeyEvent(SDL_GetVideoDevice(), theEvent);*/
   787 }
   788 
   789 /* We'll respond to selectors by doing nothing so we don't beep.
   790  * The escape key gets converted to a "cancel" selector, etc.
   791  */
   792 - (void)doCommandBySelector:(SEL)aSelector
   793 {
   794     /*NSLog(@"doCommandBySelector: %@\n", NSStringFromSelector(aSelector));*/
   795 }
   796 
   797 - (BOOL)processHitTest:(NSEvent *)theEvent
   798 {
   799     SDL_assert(isDragAreaRunning == [_data->nswindow isMovableByWindowBackground]);
   800 
   801     if (_data->window->hit_test) {  /* if no hit-test, skip this. */
   802         const NSPoint location = [theEvent locationInWindow];
   803         const SDL_Point point = { (int) location.x, _data->window->h - (((int) location.y)-1) };
   804         const SDL_HitTestResult rc = _data->window->hit_test(_data->window, &point, _data->window->hit_test_data);
   805         if (rc == SDL_HITTEST_DRAGGABLE) {
   806             if (!isDragAreaRunning) {
   807                 isDragAreaRunning = YES;
   808                 [_data->nswindow setMovableByWindowBackground:YES];
   809             }
   810             return YES;  /* dragging! */
   811         }
   812     }
   813 
   814     if (isDragAreaRunning) {
   815         isDragAreaRunning = NO;
   816         [_data->nswindow setMovableByWindowBackground:NO];
   817         return YES;  /* was dragging, drop event. */
   818     }
   819 
   820     return NO;  /* not a special area, carry on. */
   821 }
   822 
   823 - (void)mouseDown:(NSEvent *)theEvent
   824 {
   825     int button;
   826     int clicks;
   827 
   828     /* Ignore events that aren't inside the client area (i.e. title bar.) */
   829     if ([theEvent window]) {
   830         NSRect windowRect = [[[theEvent window] contentView] frame];
   831         if (!NSMouseInRect([theEvent locationInWindow], windowRect, NO)) {
   832             return;
   833         }
   834     }
   835 
   836     if ([self processHitTest:theEvent]) {
   837         SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIT_TEST, 0, 0);
   838         return;  /* dragging, drop event. */
   839     }
   840 
   841     switch ([theEvent buttonNumber]) {
   842     case 0:
   843         if (([theEvent modifierFlags] & NSControlKeyMask) &&
   844 		    GetHintCtrlClickEmulateRightClick()) {
   845             wasCtrlLeft = YES;
   846             button = SDL_BUTTON_RIGHT;
   847         } else {
   848             wasCtrlLeft = NO;
   849             button = SDL_BUTTON_LEFT;
   850         }
   851         break;
   852     case 1:
   853         button = SDL_BUTTON_RIGHT;
   854         break;
   855     case 2:
   856         button = SDL_BUTTON_MIDDLE;
   857         break;
   858     default:
   859         button = (int) [theEvent buttonNumber] + 1;
   860         break;
   861     }
   862 
   863     clicks = (int) [theEvent clickCount];
   864     SDL_SendMouseButtonClicks(_data->window, 0, SDL_PRESSED, button, clicks);
   865 }
   866 
   867 - (void)rightMouseDown:(NSEvent *)theEvent
   868 {
   869     [self mouseDown:theEvent];
   870 }
   871 
   872 - (void)otherMouseDown:(NSEvent *)theEvent
   873 {
   874     [self mouseDown:theEvent];
   875 }
   876 
   877 - (void)mouseUp:(NSEvent *)theEvent
   878 {
   879     int button;
   880     int clicks;
   881 
   882     if ([self processHitTest:theEvent]) {
   883         SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIT_TEST, 0, 0);
   884         return;  /* stopped dragging, drop event. */
   885     }
   886 
   887     switch ([theEvent buttonNumber]) {
   888     case 0:
   889         if (wasCtrlLeft) {
   890             button = SDL_BUTTON_RIGHT;
   891             wasCtrlLeft = NO;
   892         } else {
   893             button = SDL_BUTTON_LEFT;
   894         }
   895         break;
   896     case 1:
   897         button = SDL_BUTTON_RIGHT;
   898         break;
   899     case 2:
   900         button = SDL_BUTTON_MIDDLE;
   901         break;
   902     default:
   903         button = (int) [theEvent buttonNumber] + 1;
   904         break;
   905     }
   906 
   907     clicks = (int) [theEvent clickCount];
   908     SDL_SendMouseButtonClicks(_data->window, 0, SDL_RELEASED, button, clicks);
   909 }
   910 
   911 - (void)rightMouseUp:(NSEvent *)theEvent
   912 {
   913     [self mouseUp:theEvent];
   914 }
   915 
   916 - (void)otherMouseUp:(NSEvent *)theEvent
   917 {
   918     [self mouseUp:theEvent];
   919 }
   920 
   921 - (void)mouseMoved:(NSEvent *)theEvent
   922 {
   923     SDL_Mouse *mouse = SDL_GetMouse();
   924     SDL_Window *window = _data->window;
   925     NSPoint point;
   926     int x, y;
   927 
   928     if ([self processHitTest:theEvent]) {
   929         SDL_SendWindowEvent(window, SDL_WINDOWEVENT_HIT_TEST, 0, 0);
   930         return;  /* dragging, drop event. */
   931     }
   932 
   933     if (mouse->relative_mode) {
   934         return;
   935     }
   936 
   937     point = [theEvent locationInWindow];
   938     x = (int)point.x;
   939     y = (int)(window->h - point.y);
   940 
   941     if (window->flags & SDL_WINDOW_INPUT_GRABBED) {
   942         if (x < 0 || x >= window->w || y < 0 || y >= window->h) {
   943             if (x < 0) {
   944                 x = 0;
   945             } else if (x >= window->w) {
   946                 x = window->w - 1;
   947             }
   948             if (y < 0) {
   949                 y = 0;
   950             } else if (y >= window->h) {
   951                 y = window->h - 1;
   952             }
   953 
   954 #if !SDL_MAC_NO_SANDBOX
   955             CGPoint cgpoint;
   956 
   957             /* When SDL_MAC_NO_SANDBOX is set, this is handled by
   958              * SDL_cocoamousetap.m.
   959              */
   960 
   961             cgpoint.x = window->x + x;
   962             cgpoint.y = window->y + y;
   963 
   964             CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, cgpoint);
   965             CGAssociateMouseAndMouseCursorPosition(YES);
   966 
   967             Cocoa_HandleMouseWarp(cgpoint.x, cgpoint.y);
   968 #endif
   969         }
   970     }
   971     SDL_SendMouseMotion(window, 0, 0, x, y);
   972 }
   973 
   974 - (void)mouseDragged:(NSEvent *)theEvent
   975 {
   976     [self mouseMoved:theEvent];
   977 }
   978 
   979 - (void)rightMouseDragged:(NSEvent *)theEvent
   980 {
   981     [self mouseMoved:theEvent];
   982 }
   983 
   984 - (void)otherMouseDragged:(NSEvent *)theEvent
   985 {
   986     [self mouseMoved:theEvent];
   987 }
   988 
   989 - (void)scrollWheel:(NSEvent *)theEvent
   990 {
   991     Cocoa_HandleMouseWheel(_data->window, theEvent);
   992 }
   993 
   994 - (void)touchesBeganWithEvent:(NSEvent *) theEvent
   995 {
   996     NSSet *touches = [theEvent touchesMatchingPhase:NSTouchPhaseAny inView:nil];
   997     int existingTouchCount = 0;
   998 
   999     for (NSTouch* touch in touches) {
  1000         if ([touch phase] != NSTouchPhaseBegan) {
  1001             existingTouchCount++;
  1002         }
  1003     }
  1004     if (existingTouchCount == 0) {
  1005         SDL_TouchID touchID = (SDL_TouchID)(intptr_t)[[touches anyObject] device];
  1006         int numFingers = SDL_GetNumTouchFingers(touchID);
  1007         DLog("Reset Lost Fingers: %d", numFingers);
  1008         for (--numFingers; numFingers >= 0; --numFingers) {
  1009             SDL_Finger* finger = SDL_GetTouchFinger(touchID, numFingers);
  1010             SDL_SendTouch(touchID, finger->id, SDL_FALSE, 0, 0, 0);
  1011         }
  1012     }
  1013 
  1014     DLog("Began Fingers: %lu .. existing: %d", (unsigned long)[touches count], existingTouchCount);
  1015     [self handleTouches:NSTouchPhaseBegan withEvent:theEvent];
  1016 }
  1017 
  1018 - (void)touchesMovedWithEvent:(NSEvent *) theEvent
  1019 {
  1020     [self handleTouches:NSTouchPhaseMoved withEvent:theEvent];
  1021 }
  1022 
  1023 - (void)touchesEndedWithEvent:(NSEvent *) theEvent
  1024 {
  1025     [self handleTouches:NSTouchPhaseEnded withEvent:theEvent];
  1026 }
  1027 
  1028 - (void)touchesCancelledWithEvent:(NSEvent *) theEvent
  1029 {
  1030     [self handleTouches:NSTouchPhaseCancelled withEvent:theEvent];
  1031 }
  1032 
  1033 - (void)handleTouches:(NSTouchPhase) phase withEvent:(NSEvent *) theEvent
  1034 {
  1035     NSSet *touches = [theEvent touchesMatchingPhase:phase inView:nil];
  1036 
  1037     for (NSTouch *touch in touches) {
  1038         const SDL_TouchID touchId = (SDL_TouchID)(intptr_t)[touch device];
  1039         if (SDL_AddTouch(touchId, "") < 0) {
  1040             return;
  1041         }
  1042 
  1043         const SDL_FingerID fingerId = (SDL_FingerID)(intptr_t)[touch identity];
  1044         float x = [touch normalizedPosition].x;
  1045         float y = [touch normalizedPosition].y;
  1046         /* Make the origin the upper left instead of the lower left */
  1047         y = 1.0f - y;
  1048 
  1049         switch (phase) {
  1050         case NSTouchPhaseBegan:
  1051             SDL_SendTouch(touchId, fingerId, SDL_TRUE, x, y, 1.0f);
  1052             break;
  1053         case NSTouchPhaseEnded:
  1054         case NSTouchPhaseCancelled:
  1055             SDL_SendTouch(touchId, fingerId, SDL_FALSE, x, y, 1.0f);
  1056             break;
  1057         case NSTouchPhaseMoved:
  1058             SDL_SendTouchMotion(touchId, fingerId, x, y, 1.0f);
  1059             break;
  1060         default:
  1061             break;
  1062         }
  1063     }
  1064 }
  1065 
  1066 @end
  1067 
  1068 @interface SDLView : NSView {
  1069     SDL_Window *_sdlWindow;
  1070 }
  1071 
  1072 - (void)setSDLWindow:(SDL_Window*)window;
  1073 
  1074 /* The default implementation doesn't pass rightMouseDown to responder chain */
  1075 - (void)rightMouseDown:(NSEvent *)theEvent;
  1076 - (BOOL)mouseDownCanMoveWindow;
  1077 - (void)drawRect:(NSRect)dirtyRect;
  1078 - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent;
  1079 @end
  1080 
  1081 @implementation SDLView
  1082 - (void)setSDLWindow:(SDL_Window*)window
  1083 {
  1084     _sdlWindow = window;
  1085 }
  1086 
  1087 - (void)drawRect:(NSRect)dirtyRect
  1088 {
  1089     SDL_SendWindowEvent(_sdlWindow, SDL_WINDOWEVENT_EXPOSED, 0, 0);
  1090 }
  1091 
  1092 - (void)rightMouseDown:(NSEvent *)theEvent
  1093 {
  1094     [[self nextResponder] rightMouseDown:theEvent];
  1095 }
  1096 
  1097 - (BOOL)mouseDownCanMoveWindow
  1098 {
  1099     /* Always say YES, but this doesn't do anything until we call
  1100        -[NSWindow setMovableByWindowBackground:YES], which we ninja-toggle
  1101        during mouse events when we're using a drag area. */
  1102     return YES;
  1103 }
  1104 
  1105 - (void)resetCursorRects
  1106 {
  1107     [super resetCursorRects];
  1108     SDL_Mouse *mouse = SDL_GetMouse();
  1109 
  1110     if (mouse->cursor_shown && mouse->cur_cursor && !mouse->relative_mode) {
  1111         [self addCursorRect:[self bounds]
  1112                      cursor:mouse->cur_cursor->driverdata];
  1113     } else {
  1114         [self addCursorRect:[self bounds]
  1115                      cursor:[NSCursor invisibleCursor]];
  1116     }
  1117 }
  1118 
  1119 - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
  1120 {
  1121     const char *hint = SDL_GetHint(SDL_HINT_MAC_MOUSE_FOCUS_CLICKTHROUGH);
  1122     return hint && *hint != '0';
  1123 }
  1124 @end
  1125 
  1126 static int
  1127 SetupWindowData(_THIS, SDL_Window * window, NSWindow *nswindow, SDL_bool created)
  1128 { @autoreleasepool
  1129 {
  1130     SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
  1131     SDL_WindowData *data;
  1132 
  1133     /* Allocate the window data */
  1134     window->driverdata = data = (SDL_WindowData *) SDL_calloc(1, sizeof(*data));
  1135     if (!data) {
  1136         return SDL_OutOfMemory();
  1137     }
  1138     data->window = window;
  1139     data->nswindow = nswindow;
  1140     data->created = created;
  1141     data->videodata = videodata;
  1142     data->nscontexts = [[NSMutableArray alloc] init];
  1143 
  1144     /* Create an event listener for the window */
  1145     data->listener = [[Cocoa_WindowListener alloc] init];
  1146 
  1147     /* Fill in the SDL window with the window data */
  1148     {
  1149         NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]];
  1150         ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
  1151         window->x = (int)rect.origin.x;
  1152         window->y = (int)rect.origin.y;
  1153         window->w = (int)rect.size.width;
  1154         window->h = (int)rect.size.height;
  1155     }
  1156 
  1157     /* Set up the listener after we create the view */
  1158     [data->listener listen:data];
  1159 
  1160     if ([nswindow isVisible]) {
  1161         window->flags |= SDL_WINDOW_SHOWN;
  1162     } else {
  1163         window->flags &= ~SDL_WINDOW_SHOWN;
  1164     }
  1165 
  1166     {
  1167         unsigned long style = [nswindow styleMask];
  1168 
  1169         if (style == NSBorderlessWindowMask) {
  1170             window->flags |= SDL_WINDOW_BORDERLESS;
  1171         } else {
  1172             window->flags &= ~SDL_WINDOW_BORDERLESS;
  1173         }
  1174         if (style & NSResizableWindowMask) {
  1175             window->flags |= SDL_WINDOW_RESIZABLE;
  1176         } else {
  1177             window->flags &= ~SDL_WINDOW_RESIZABLE;
  1178         }
  1179     }
  1180 
  1181     /* isZoomed always returns true if the window is not resizable */
  1182     if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) {
  1183         window->flags |= SDL_WINDOW_MAXIMIZED;
  1184     } else {
  1185         window->flags &= ~SDL_WINDOW_MAXIMIZED;
  1186     }
  1187 
  1188     if ([nswindow isMiniaturized]) {
  1189         window->flags |= SDL_WINDOW_MINIMIZED;
  1190     } else {
  1191         window->flags &= ~SDL_WINDOW_MINIMIZED;
  1192     }
  1193 
  1194     if ([nswindow isKeyWindow]) {
  1195         window->flags |= SDL_WINDOW_INPUT_FOCUS;
  1196         SDL_SetKeyboardFocus(data->window);
  1197     }
  1198 
  1199     /* Prevents the window's "window device" from being destroyed when it is
  1200      * hidden. See http://www.mikeash.com/pyblog/nsopenglcontext-and-one-shot.html
  1201      */
  1202     [nswindow setOneShot:NO];
  1203 
  1204     /* All done! */
  1205     window->driverdata = data;
  1206     return 0;
  1207 }}
  1208 
  1209 int
  1210 Cocoa_CreateWindow(_THIS, SDL_Window * window)
  1211 { @autoreleasepool
  1212 {
  1213     SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
  1214     NSWindow *nswindow;
  1215     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
  1216     NSRect rect;
  1217     SDL_Rect bounds;
  1218     NSUInteger style;
  1219     NSArray *screens = [NSScreen screens];
  1220 
  1221     Cocoa_GetDisplayBounds(_this, display, &bounds);
  1222     rect.origin.x = window->x;
  1223     rect.origin.y = window->y;
  1224     rect.size.width = window->w;
  1225     rect.size.height = window->h;
  1226     ConvertNSRect([screens objectAtIndex:0], (window->flags & FULLSCREEN_MASK), &rect);
  1227 
  1228     style = GetWindowStyle(window);
  1229 
  1230     /* Figure out which screen to place this window */
  1231     NSScreen *screen = nil;
  1232     for (NSScreen *candidate in screens) {
  1233         NSRect screenRect = [candidate frame];
  1234         if (rect.origin.x >= screenRect.origin.x &&
  1235             rect.origin.x < screenRect.origin.x + screenRect.size.width &&
  1236             rect.origin.y >= screenRect.origin.y &&
  1237             rect.origin.y < screenRect.origin.y + screenRect.size.height) {
  1238             screen = candidate;
  1239             rect.origin.x -= screenRect.origin.x;
  1240             rect.origin.y -= screenRect.origin.y;
  1241         }
  1242     }
  1243 
  1244     @try {
  1245         nswindow = [[SDLWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:NO screen:screen];
  1246     }
  1247     @catch (NSException *e) {
  1248         return SDL_SetError("%s", [[e reason] UTF8String]);
  1249     }
  1250     [nswindow setBackgroundColor:[NSColor blackColor]];
  1251 
  1252     if (videodata->allow_spaces) {
  1253         SDL_assert(floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6);
  1254         SDL_assert([nswindow respondsToSelector:@selector(toggleFullScreen:)]);
  1255         /* we put FULLSCREEN_DESKTOP windows in their own Space, without a toggle button or menubar, later */
  1256         if (window->flags & SDL_WINDOW_RESIZABLE) {
  1257             /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */
  1258             [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1259         }
  1260     }
  1261 
  1262     /* Create a default view for this window */
  1263     rect = [nswindow contentRectForFrameRect:[nswindow frame]];
  1264     SDLView *contentView = [[SDLView alloc] initWithFrame:rect];
  1265     [contentView setSDLWindow:window];
  1266 
  1267     if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
  1268         if ([contentView respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) {
  1269             [contentView setWantsBestResolutionOpenGLSurface:YES];
  1270         }
  1271     }
  1272 
  1273     [nswindow setContentView:contentView];
  1274     [contentView release];
  1275 
  1276     /* Allow files and folders to be dragged onto the window by users */
  1277     [nswindow registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]];
  1278 
  1279     if (SetupWindowData(_this, window, nswindow, SDL_TRUE) < 0) {
  1280         [nswindow release];
  1281         return -1;
  1282     }
  1283     return 0;
  1284 }}
  1285 
  1286 int
  1287 Cocoa_CreateWindowFrom(_THIS, SDL_Window * window, const void *data)
  1288 { @autoreleasepool
  1289 {
  1290     NSWindow *nswindow = (NSWindow *) data;
  1291     NSString *title;
  1292 
  1293     /* Query the title from the existing window */
  1294     title = [nswindow title];
  1295     if (title) {
  1296         window->title = SDL_strdup([title UTF8String]);
  1297     }
  1298 
  1299     return SetupWindowData(_this, window, nswindow, SDL_FALSE);
  1300 }}
  1301 
  1302 void
  1303 Cocoa_SetWindowTitle(_THIS, SDL_Window * window)
  1304 { @autoreleasepool
  1305 {
  1306     const char *title = window->title ? window->title : "";
  1307     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1308     NSString *string = [[NSString alloc] initWithUTF8String:title];
  1309     [nswindow setTitle:string];
  1310     [string release];
  1311 }}
  1312 
  1313 void
  1314 Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
  1315 { @autoreleasepool
  1316 {
  1317     NSImage *nsimage = Cocoa_CreateImage(icon);
  1318 
  1319     if (nsimage) {
  1320         [NSApp setApplicationIconImage:nsimage];
  1321     }
  1322 }}
  1323 
  1324 void
  1325 Cocoa_SetWindowPosition(_THIS, SDL_Window * window)
  1326 { @autoreleasepool
  1327 {
  1328     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1329     NSWindow *nswindow = windata->nswindow;
  1330     NSRect rect;
  1331     Uint32 moveHack;
  1332 
  1333     rect.origin.x = window->x;
  1334     rect.origin.y = window->y;
  1335     rect.size.width = window->w;
  1336     rect.size.height = window->h;
  1337     ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
  1338 
  1339     moveHack = s_moveHack;
  1340     s_moveHack = 0;
  1341     [nswindow setFrameOrigin:rect.origin];
  1342     s_moveHack = moveHack;
  1343 
  1344     ScheduleContextUpdates(windata);
  1345 }}
  1346 
  1347 void
  1348 Cocoa_SetWindowSize(_THIS, SDL_Window * window)
  1349 { @autoreleasepool
  1350 {
  1351     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1352     NSWindow *nswindow = windata->nswindow;
  1353     NSRect rect;
  1354     Uint32 moveHack;
  1355 
  1356     /* Cocoa will resize the window from the bottom-left rather than the
  1357      * top-left when -[nswindow setContentSize:] is used, so we must set the
  1358      * entire frame based on the new size, in order to preserve the position.
  1359      */
  1360     rect.origin.x = window->x;
  1361     rect.origin.y = window->y;
  1362     rect.size.width = window->w;
  1363     rect.size.height = window->h;
  1364     ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
  1365 
  1366     moveHack = s_moveHack;
  1367     s_moveHack = 0;
  1368     [nswindow setFrame:[nswindow frameRectForContentRect:rect] display:YES];
  1369     s_moveHack = moveHack;
  1370 
  1371     ScheduleContextUpdates(windata);
  1372 }}
  1373 
  1374 void
  1375 Cocoa_SetWindowMinimumSize(_THIS, SDL_Window * window)
  1376 { @autoreleasepool
  1377 {
  1378     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1379 
  1380     NSSize minSize;
  1381     minSize.width = window->min_w;
  1382     minSize.height = window->min_h;
  1383 
  1384     [windata->nswindow setContentMinSize:minSize];
  1385 }}
  1386 
  1387 void
  1388 Cocoa_SetWindowMaximumSize(_THIS, SDL_Window * window)
  1389 { @autoreleasepool
  1390 {
  1391     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1392 
  1393     NSSize maxSize;
  1394     maxSize.width = window->max_w;
  1395     maxSize.height = window->max_h;
  1396 
  1397     [windata->nswindow setContentMaxSize:maxSize];
  1398 }}
  1399 
  1400 void
  1401 Cocoa_ShowWindow(_THIS, SDL_Window * window)
  1402 { @autoreleasepool
  1403 {
  1404     SDL_WindowData *windowData = ((SDL_WindowData *) window->driverdata);
  1405     NSWindow *nswindow = windowData->nswindow;
  1406 
  1407     if (![nswindow isMiniaturized]) {
  1408         [windowData->listener pauseVisibleObservation];
  1409         [nswindow makeKeyAndOrderFront:nil];
  1410         [windowData->listener resumeVisibleObservation];
  1411     }
  1412 }}
  1413 
  1414 void
  1415 Cocoa_HideWindow(_THIS, SDL_Window * window)
  1416 { @autoreleasepool
  1417 {
  1418     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1419 
  1420     [nswindow orderOut:nil];
  1421 }}
  1422 
  1423 void
  1424 Cocoa_RaiseWindow(_THIS, SDL_Window * window)
  1425 { @autoreleasepool
  1426 {
  1427     SDL_WindowData *windowData = ((SDL_WindowData *) window->driverdata);
  1428     NSWindow *nswindow = windowData->nswindow;
  1429 
  1430     /* makeKeyAndOrderFront: has the side-effect of deminiaturizing and showing
  1431        a minimized or hidden window, so check for that before showing it.
  1432      */
  1433     [windowData->listener pauseVisibleObservation];
  1434     if (![nswindow isMiniaturized] && [nswindow isVisible]) {
  1435         [NSApp activateIgnoringOtherApps:YES];
  1436         [nswindow makeKeyAndOrderFront:nil];
  1437     }
  1438     [windowData->listener resumeVisibleObservation];
  1439 }}
  1440 
  1441 void
  1442 Cocoa_MaximizeWindow(_THIS, SDL_Window * window)
  1443 { @autoreleasepool
  1444 {
  1445     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1446     NSWindow *nswindow = windata->nswindow;
  1447 
  1448     [nswindow zoom:nil];
  1449 
  1450     ScheduleContextUpdates(windata);
  1451 }}
  1452 
  1453 void
  1454 Cocoa_MinimizeWindow(_THIS, SDL_Window * window)
  1455 { @autoreleasepool
  1456 {
  1457     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1458     NSWindow *nswindow = data->nswindow;
  1459 
  1460     if ([data->listener isInFullscreenSpaceTransition]) {
  1461         [data->listener addPendingWindowOperation:PENDING_OPERATION_MINIMIZE];
  1462     } else {
  1463         [nswindow miniaturize:nil];
  1464     }
  1465 }}
  1466 
  1467 void
  1468 Cocoa_RestoreWindow(_THIS, SDL_Window * window)
  1469 { @autoreleasepool
  1470 {
  1471     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1472 
  1473     if ([nswindow isMiniaturized]) {
  1474         [nswindow deminiaturize:nil];
  1475     } else if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) {
  1476         [nswindow zoom:nil];
  1477     }
  1478 }}
  1479 
  1480 void
  1481 Cocoa_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered)
  1482 { @autoreleasepool
  1483 {
  1484     if (SetWindowStyle(window, GetWindowStyle(window))) {
  1485         if (bordered) {
  1486             Cocoa_SetWindowTitle(_this, window);  /* this got blanked out. */
  1487         }
  1488     }
  1489 }}
  1490 
  1491 
  1492 void
  1493 Cocoa_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
  1494 { @autoreleasepool
  1495 {
  1496     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1497     NSWindow *nswindow = data->nswindow;
  1498     NSRect rect;
  1499 
  1500     /* The view responder chain gets messed with during setStyleMask */
  1501     if ([[nswindow contentView] nextResponder] == data->listener) {
  1502         [[nswindow contentView] setNextResponder:nil];
  1503     }
  1504 
  1505     if (fullscreen) {
  1506         SDL_Rect bounds;
  1507 
  1508         Cocoa_GetDisplayBounds(_this, display, &bounds);
  1509         rect.origin.x = bounds.x;
  1510         rect.origin.y = bounds.y;
  1511         rect.size.width = bounds.w;
  1512         rect.size.height = bounds.h;
  1513         ConvertNSRect([nswindow screen], fullscreen, &rect);
  1514 
  1515         /* Hack to fix origin on Mac OS X 10.4 */
  1516         NSRect screenRect = [[nswindow screen] frame];
  1517         if (screenRect.size.height >= 1.0f) {
  1518             rect.origin.y += (screenRect.size.height - rect.size.height);
  1519         }
  1520 
  1521         [nswindow setStyleMask:NSBorderlessWindowMask];
  1522     } else {
  1523         rect.origin.x = window->windowed.x;
  1524         rect.origin.y = window->windowed.y;
  1525         rect.size.width = window->windowed.w;
  1526         rect.size.height = window->windowed.h;
  1527         ConvertNSRect([nswindow screen], fullscreen, &rect);
  1528 
  1529         [nswindow setStyleMask:GetWindowStyle(window)];
  1530 
  1531         /* Hack to restore window decorations on Mac OS X 10.10 */
  1532         NSRect frameRect = [nswindow frame];
  1533         [nswindow setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  1534         [nswindow setFrame:frameRect display:NO];
  1535     }
  1536 
  1537     /* The view responder chain gets messed with during setStyleMask */
  1538     if ([[nswindow contentView] nextResponder] != data->listener) {
  1539         [[nswindow contentView] setNextResponder:data->listener];
  1540     }
  1541 
  1542     s_moveHack = 0;
  1543     [nswindow setContentSize:rect.size];
  1544     [nswindow setFrameOrigin:rect.origin];
  1545     s_moveHack = SDL_GetTicks();
  1546 
  1547     /* When the window style changes the title is cleared */
  1548     if (!fullscreen) {
  1549         Cocoa_SetWindowTitle(_this, window);
  1550     }
  1551 
  1552     if (SDL_ShouldAllowTopmost() && fullscreen) {
  1553         /* OpenGL is rendering to the window, so make it visible! */
  1554         [nswindow setLevel:CGShieldingWindowLevel()];
  1555     } else {
  1556         [nswindow setLevel:kCGNormalWindowLevel];
  1557     }
  1558 
  1559     if ([nswindow isVisible] || fullscreen) {
  1560         [data->listener pauseVisibleObservation];
  1561         [nswindow makeKeyAndOrderFront:nil];
  1562         [data->listener resumeVisibleObservation];
  1563     }
  1564 
  1565     ScheduleContextUpdates(data);
  1566 }}
  1567 
  1568 int
  1569 Cocoa_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp)
  1570 {
  1571     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
  1572     CGDirectDisplayID display_id = ((SDL_DisplayData *)display->driverdata)->display;
  1573     const uint32_t tableSize = 256;
  1574     CGGammaValue redTable[tableSize];
  1575     CGGammaValue greenTable[tableSize];
  1576     CGGammaValue blueTable[tableSize];
  1577     uint32_t i;
  1578     float inv65535 = 1.0f / 65535.0f;
  1579 
  1580     /* Extract gamma values into separate tables, convert to floats between 0.0 and 1.0 */
  1581     for (i = 0; i < 256; i++) {
  1582         redTable[i] = ramp[0*256+i] * inv65535;
  1583         greenTable[i] = ramp[1*256+i] * inv65535;
  1584         blueTable[i] = ramp[2*256+i] * inv65535;
  1585     }
  1586 
  1587     if (CGSetDisplayTransferByTable(display_id, tableSize,
  1588                                     redTable, greenTable, blueTable) != CGDisplayNoErr) {
  1589         return SDL_SetError("CGSetDisplayTransferByTable()");
  1590     }
  1591     return 0;
  1592 }
  1593 
  1594 int
  1595 Cocoa_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp)
  1596 {
  1597     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
  1598     CGDirectDisplayID display_id = ((SDL_DisplayData *)display->driverdata)->display;
  1599     const uint32_t tableSize = 256;
  1600     CGGammaValue redTable[tableSize];
  1601     CGGammaValue greenTable[tableSize];
  1602     CGGammaValue blueTable[tableSize];
  1603     uint32_t i, tableCopied;
  1604 
  1605     if (CGGetDisplayTransferByTable(display_id, tableSize,
  1606                                     redTable, greenTable, blueTable, &tableCopied) != CGDisplayNoErr) {
  1607         return SDL_SetError("CGGetDisplayTransferByTable()");
  1608     }
  1609 
  1610     for (i = 0; i < tableCopied; i++) {
  1611         ramp[0*256+i] = (Uint16)(redTable[i] * 65535.0f);
  1612         ramp[1*256+i] = (Uint16)(greenTable[i] * 65535.0f);
  1613         ramp[2*256+i] = (Uint16)(blueTable[i] * 65535.0f);
  1614     }
  1615     return 0;
  1616 }
  1617 
  1618 void
  1619 Cocoa_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
  1620 {
  1621     /* Move the cursor to the nearest point in the window */
  1622     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1623     if (grabbed && data && ![data->listener isMoving]) {
  1624         int x, y;
  1625         CGPoint cgpoint;
  1626 
  1627         SDL_GetMouseState(&x, &y);
  1628         cgpoint.x = window->x + x;
  1629         cgpoint.y = window->y + y;
  1630 
  1631         Cocoa_HandleMouseWarp(cgpoint.x, cgpoint.y);
  1632 
  1633         DLog("Returning cursor to (%g, %g)", cgpoint.x, cgpoint.y);
  1634         CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, cgpoint);
  1635     }
  1636 
  1637     if ( data && (window->flags & SDL_WINDOW_FULLSCREEN) ) {
  1638         if (SDL_ShouldAllowTopmost() && (window->flags & SDL_WINDOW_INPUT_FOCUS)
  1639             && ![data->listener isInFullscreenSpace]) {
  1640             /* OpenGL is rendering to the window, so make it visible! */
  1641             /* Doing this in 10.11 while in a Space breaks things (bug #3152) */
  1642             [data->nswindow setLevel:CGShieldingWindowLevel()];
  1643         } else {
  1644             [data->nswindow setLevel:kCGNormalWindowLevel];
  1645         }
  1646     }
  1647 }
  1648 
  1649 void
  1650 Cocoa_DestroyWindow(_THIS, SDL_Window * window)
  1651 { @autoreleasepool
  1652 {
  1653     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1654 
  1655     if (data) {
  1656         if ([data->listener isInFullscreenSpace]) {
  1657             [NSMenu setMenuBarVisible:YES];
  1658         }
  1659         [data->listener close];
  1660         [data->listener release];
  1661         if (data->created) {
  1662             [data->nswindow close];
  1663         }
  1664 
  1665         NSArray *contexts = [[data->nscontexts copy] autorelease];
  1666         for (SDLOpenGLContext *context in contexts) {
  1667             /* Calling setWindow:NULL causes the context to remove itself from the context list. */            
  1668             [context setWindow:NULL];
  1669         }
  1670         [data->nscontexts release];
  1671 
  1672         SDL_free(data);
  1673     }
  1674     window->driverdata = NULL;
  1675 }}
  1676 
  1677 SDL_bool
  1678 Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
  1679 {
  1680     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1681 
  1682     if (info->version.major <= SDL_MAJOR_VERSION) {
  1683         info->subsystem = SDL_SYSWM_COCOA;
  1684         info->info.cocoa.window = nswindow;
  1685         return SDL_TRUE;
  1686     } else {
  1687         SDL_SetError("Application not compiled with SDL %d.%d\n",
  1688                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
  1689         return SDL_FALSE;
  1690     }
  1691 }
  1692 
  1693 SDL_bool
  1694 Cocoa_IsWindowInFullscreenSpace(SDL_Window * window)
  1695 {
  1696     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1697 
  1698     if ([data->listener isInFullscreenSpace]) {
  1699         return SDL_TRUE;
  1700     } else {
  1701         return SDL_FALSE;
  1702     }
  1703 }
  1704 
  1705 SDL_bool
  1706 Cocoa_SetWindowFullscreenSpace(SDL_Window * window, SDL_bool state)
  1707 { @autoreleasepool
  1708 {
  1709     SDL_bool succeeded = SDL_FALSE;
  1710     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1711 
  1712     if ([data->listener setFullscreenSpace:(state ? YES : NO)]) {
  1713         const int maxattempts = 3;
  1714         int attempt = 0;
  1715         while (++attempt <= maxattempts) {
  1716             /* Wait for the transition to complete, so application changes
  1717              take effect properly (e.g. setting the window size, etc.)
  1718              */
  1719             const int limit = 10000;
  1720             int count = 0;
  1721             while ([data->listener isInFullscreenSpaceTransition]) {
  1722                 if ( ++count == limit ) {
  1723                     /* Uh oh, transition isn't completing. Should we assert? */
  1724                     break;
  1725                 }
  1726                 SDL_Delay(1);
  1727                 SDL_PumpEvents();
  1728             }
  1729             if ([data->listener isInFullscreenSpace] == (state ? YES : NO))
  1730                 break;
  1731             /* Try again, the last attempt was interrupted by user gestures */
  1732             if (![data->listener setFullscreenSpace:(state ? YES : NO)])
  1733                 break; /* ??? */
  1734         }
  1735         /* Return TRUE to prevent non-space fullscreen logic from running */
  1736         succeeded = SDL_TRUE;
  1737     }
  1738 
  1739     return succeeded;
  1740 }}
  1741 
  1742 int
  1743 Cocoa_SetWindowHitTest(SDL_Window * window, SDL_bool enabled)
  1744 {
  1745     return 0;  /* just succeed, the real work is done elsewhere. */
  1746 }
  1747 
  1748 int
  1749 Cocoa_SetWindowOpacity(_THIS, SDL_Window * window, float opacity)
  1750 {
  1751     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1752     [data->nswindow setAlphaValue:opacity];
  1753     return 0;
  1754 }
  1755 
  1756 #endif /* SDL_VIDEO_DRIVER_COCOA */
  1757 
  1758 /* vi: set ts=4 sw=4 expandtab: */