src/video/cocoa/SDL_cocoawindow.m
author Sam Lantinga <slouken@libsdl.org>
Thu, 29 Sep 2016 13:34:49 -0700
changeset 10378 cb7f88c92a2e
parent 10366 e1b52e69578b
child 10385 ad12658bc7ae
permissions -rw-r--r--
Generalized the hint for whether the application gets a mouse event when clicking on the window to activate it, and is now named SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH.
The behavior is defined to not receive the click event, and this hint allows you to override that.
     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_MOUSE_FOCUS_CLICKTHROUGH);
  1122     if (!hint) {
  1123         /* Check older hint for backwards compatibility */
  1124         hint = SDL_GetHint("SDL_MAC_MOUSE_FOCUS_CLICKTHROUGH");
  1125     }
  1126     return hint && *hint != '0';
  1127 }
  1128 @end
  1129 
  1130 static int
  1131 SetupWindowData(_THIS, SDL_Window * window, NSWindow *nswindow, SDL_bool created)
  1132 { @autoreleasepool
  1133 {
  1134     SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
  1135     SDL_WindowData *data;
  1136 
  1137     /* Allocate the window data */
  1138     window->driverdata = data = (SDL_WindowData *) SDL_calloc(1, sizeof(*data));
  1139     if (!data) {
  1140         return SDL_OutOfMemory();
  1141     }
  1142     data->window = window;
  1143     data->nswindow = nswindow;
  1144     data->created = created;
  1145     data->videodata = videodata;
  1146     data->nscontexts = [[NSMutableArray alloc] init];
  1147 
  1148     /* Create an event listener for the window */
  1149     data->listener = [[Cocoa_WindowListener alloc] init];
  1150 
  1151     /* Fill in the SDL window with the window data */
  1152     {
  1153         NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]];
  1154         ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
  1155         window->x = (int)rect.origin.x;
  1156         window->y = (int)rect.origin.y;
  1157         window->w = (int)rect.size.width;
  1158         window->h = (int)rect.size.height;
  1159     }
  1160 
  1161     /* Set up the listener after we create the view */
  1162     [data->listener listen:data];
  1163 
  1164     if ([nswindow isVisible]) {
  1165         window->flags |= SDL_WINDOW_SHOWN;
  1166     } else {
  1167         window->flags &= ~SDL_WINDOW_SHOWN;
  1168     }
  1169 
  1170     {
  1171         unsigned long style = [nswindow styleMask];
  1172 
  1173         if (style == NSBorderlessWindowMask) {
  1174             window->flags |= SDL_WINDOW_BORDERLESS;
  1175         } else {
  1176             window->flags &= ~SDL_WINDOW_BORDERLESS;
  1177         }
  1178         if (style & NSResizableWindowMask) {
  1179             window->flags |= SDL_WINDOW_RESIZABLE;
  1180         } else {
  1181             window->flags &= ~SDL_WINDOW_RESIZABLE;
  1182         }
  1183     }
  1184 
  1185     /* isZoomed always returns true if the window is not resizable */
  1186     if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) {
  1187         window->flags |= SDL_WINDOW_MAXIMIZED;
  1188     } else {
  1189         window->flags &= ~SDL_WINDOW_MAXIMIZED;
  1190     }
  1191 
  1192     if ([nswindow isMiniaturized]) {
  1193         window->flags |= SDL_WINDOW_MINIMIZED;
  1194     } else {
  1195         window->flags &= ~SDL_WINDOW_MINIMIZED;
  1196     }
  1197 
  1198     if ([nswindow isKeyWindow]) {
  1199         window->flags |= SDL_WINDOW_INPUT_FOCUS;
  1200         SDL_SetKeyboardFocus(data->window);
  1201     }
  1202 
  1203     /* Prevents the window's "window device" from being destroyed when it is
  1204      * hidden. See http://www.mikeash.com/pyblog/nsopenglcontext-and-one-shot.html
  1205      */
  1206     [nswindow setOneShot:NO];
  1207 
  1208     /* All done! */
  1209     window->driverdata = data;
  1210     return 0;
  1211 }}
  1212 
  1213 int
  1214 Cocoa_CreateWindow(_THIS, SDL_Window * window)
  1215 { @autoreleasepool
  1216 {
  1217     SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
  1218     NSWindow *nswindow;
  1219     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
  1220     NSRect rect;
  1221     SDL_Rect bounds;
  1222     NSUInteger style;
  1223     NSArray *screens = [NSScreen screens];
  1224 
  1225     Cocoa_GetDisplayBounds(_this, display, &bounds);
  1226     rect.origin.x = window->x;
  1227     rect.origin.y = window->y;
  1228     rect.size.width = window->w;
  1229     rect.size.height = window->h;
  1230     ConvertNSRect([screens objectAtIndex:0], (window->flags & FULLSCREEN_MASK), &rect);
  1231 
  1232     style = GetWindowStyle(window);
  1233 
  1234     /* Figure out which screen to place this window */
  1235     NSScreen *screen = nil;
  1236     for (NSScreen *candidate in screens) {
  1237         NSRect screenRect = [candidate frame];
  1238         if (rect.origin.x >= screenRect.origin.x &&
  1239             rect.origin.x < screenRect.origin.x + screenRect.size.width &&
  1240             rect.origin.y >= screenRect.origin.y &&
  1241             rect.origin.y < screenRect.origin.y + screenRect.size.height) {
  1242             screen = candidate;
  1243             rect.origin.x -= screenRect.origin.x;
  1244             rect.origin.y -= screenRect.origin.y;
  1245         }
  1246     }
  1247 
  1248     @try {
  1249         nswindow = [[SDLWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:NO screen:screen];
  1250     }
  1251     @catch (NSException *e) {
  1252         return SDL_SetError("%s", [[e reason] UTF8String]);
  1253     }
  1254     [nswindow setBackgroundColor:[NSColor blackColor]];
  1255 
  1256     if (videodata->allow_spaces) {
  1257         SDL_assert(floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6);
  1258         SDL_assert([nswindow respondsToSelector:@selector(toggleFullScreen:)]);
  1259         /* we put FULLSCREEN_DESKTOP windows in their own Space, without a toggle button or menubar, later */
  1260         if (window->flags & SDL_WINDOW_RESIZABLE) {
  1261             /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */
  1262             [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1263         }
  1264     }
  1265 
  1266     /* Create a default view for this window */
  1267     rect = [nswindow contentRectForFrameRect:[nswindow frame]];
  1268     SDLView *contentView = [[SDLView alloc] initWithFrame:rect];
  1269     [contentView setSDLWindow:window];
  1270 
  1271     if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
  1272         if ([contentView respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) {
  1273             [contentView setWantsBestResolutionOpenGLSurface:YES];
  1274         }
  1275     }
  1276 
  1277     [nswindow setContentView:contentView];
  1278     [contentView release];
  1279 
  1280     /* Allow files and folders to be dragged onto the window by users */
  1281     [nswindow registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]];
  1282 
  1283     if (SetupWindowData(_this, window, nswindow, SDL_TRUE) < 0) {
  1284         [nswindow release];
  1285         return -1;
  1286     }
  1287     return 0;
  1288 }}
  1289 
  1290 int
  1291 Cocoa_CreateWindowFrom(_THIS, SDL_Window * window, const void *data)
  1292 { @autoreleasepool
  1293 {
  1294     NSWindow *nswindow = (NSWindow *) data;
  1295     NSString *title;
  1296 
  1297     /* Query the title from the existing window */
  1298     title = [nswindow title];
  1299     if (title) {
  1300         window->title = SDL_strdup([title UTF8String]);
  1301     }
  1302 
  1303     return SetupWindowData(_this, window, nswindow, SDL_FALSE);
  1304 }}
  1305 
  1306 void
  1307 Cocoa_SetWindowTitle(_THIS, SDL_Window * window)
  1308 { @autoreleasepool
  1309 {
  1310     const char *title = window->title ? window->title : "";
  1311     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1312     NSString *string = [[NSString alloc] initWithUTF8String:title];
  1313     [nswindow setTitle:string];
  1314     [string release];
  1315 }}
  1316 
  1317 void
  1318 Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
  1319 { @autoreleasepool
  1320 {
  1321     NSImage *nsimage = Cocoa_CreateImage(icon);
  1322 
  1323     if (nsimage) {
  1324         [NSApp setApplicationIconImage:nsimage];
  1325     }
  1326 }}
  1327 
  1328 void
  1329 Cocoa_SetWindowPosition(_THIS, SDL_Window * window)
  1330 { @autoreleasepool
  1331 {
  1332     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1333     NSWindow *nswindow = windata->nswindow;
  1334     NSRect rect;
  1335     Uint32 moveHack;
  1336 
  1337     rect.origin.x = window->x;
  1338     rect.origin.y = window->y;
  1339     rect.size.width = window->w;
  1340     rect.size.height = window->h;
  1341     ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
  1342 
  1343     moveHack = s_moveHack;
  1344     s_moveHack = 0;
  1345     [nswindow setFrameOrigin:rect.origin];
  1346     s_moveHack = moveHack;
  1347 
  1348     ScheduleContextUpdates(windata);
  1349 }}
  1350 
  1351 void
  1352 Cocoa_SetWindowSize(_THIS, SDL_Window * window)
  1353 { @autoreleasepool
  1354 {
  1355     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1356     NSWindow *nswindow = windata->nswindow;
  1357     NSRect rect;
  1358     Uint32 moveHack;
  1359 
  1360     /* Cocoa will resize the window from the bottom-left rather than the
  1361      * top-left when -[nswindow setContentSize:] is used, so we must set the
  1362      * entire frame based on the new size, in order to preserve the position.
  1363      */
  1364     rect.origin.x = window->x;
  1365     rect.origin.y = window->y;
  1366     rect.size.width = window->w;
  1367     rect.size.height = window->h;
  1368     ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect);
  1369 
  1370     moveHack = s_moveHack;
  1371     s_moveHack = 0;
  1372     [nswindow setFrame:[nswindow frameRectForContentRect:rect] display:YES];
  1373     s_moveHack = moveHack;
  1374 
  1375     ScheduleContextUpdates(windata);
  1376 }}
  1377 
  1378 void
  1379 Cocoa_SetWindowMinimumSize(_THIS, SDL_Window * window)
  1380 { @autoreleasepool
  1381 {
  1382     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1383 
  1384     NSSize minSize;
  1385     minSize.width = window->min_w;
  1386     minSize.height = window->min_h;
  1387 
  1388     [windata->nswindow setContentMinSize:minSize];
  1389 }}
  1390 
  1391 void
  1392 Cocoa_SetWindowMaximumSize(_THIS, SDL_Window * window)
  1393 { @autoreleasepool
  1394 {
  1395     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1396 
  1397     NSSize maxSize;
  1398     maxSize.width = window->max_w;
  1399     maxSize.height = window->max_h;
  1400 
  1401     [windata->nswindow setContentMaxSize:maxSize];
  1402 }}
  1403 
  1404 void
  1405 Cocoa_ShowWindow(_THIS, SDL_Window * window)
  1406 { @autoreleasepool
  1407 {
  1408     SDL_WindowData *windowData = ((SDL_WindowData *) window->driverdata);
  1409     NSWindow *nswindow = windowData->nswindow;
  1410 
  1411     if (![nswindow isMiniaturized]) {
  1412         [windowData->listener pauseVisibleObservation];
  1413         [nswindow makeKeyAndOrderFront:nil];
  1414         [windowData->listener resumeVisibleObservation];
  1415     }
  1416 }}
  1417 
  1418 void
  1419 Cocoa_HideWindow(_THIS, SDL_Window * window)
  1420 { @autoreleasepool
  1421 {
  1422     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1423 
  1424     [nswindow orderOut:nil];
  1425 }}
  1426 
  1427 void
  1428 Cocoa_RaiseWindow(_THIS, SDL_Window * window)
  1429 { @autoreleasepool
  1430 {
  1431     SDL_WindowData *windowData = ((SDL_WindowData *) window->driverdata);
  1432     NSWindow *nswindow = windowData->nswindow;
  1433 
  1434     /* makeKeyAndOrderFront: has the side-effect of deminiaturizing and showing
  1435        a minimized or hidden window, so check for that before showing it.
  1436      */
  1437     [windowData->listener pauseVisibleObservation];
  1438     if (![nswindow isMiniaturized] && [nswindow isVisible]) {
  1439         [NSApp activateIgnoringOtherApps:YES];
  1440         [nswindow makeKeyAndOrderFront:nil];
  1441     }
  1442     [windowData->listener resumeVisibleObservation];
  1443 }}
  1444 
  1445 void
  1446 Cocoa_MaximizeWindow(_THIS, SDL_Window * window)
  1447 { @autoreleasepool
  1448 {
  1449     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
  1450     NSWindow *nswindow = windata->nswindow;
  1451 
  1452     [nswindow zoom:nil];
  1453 
  1454     ScheduleContextUpdates(windata);
  1455 }}
  1456 
  1457 void
  1458 Cocoa_MinimizeWindow(_THIS, SDL_Window * window)
  1459 { @autoreleasepool
  1460 {
  1461     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1462     NSWindow *nswindow = data->nswindow;
  1463 
  1464     if ([data->listener isInFullscreenSpaceTransition]) {
  1465         [data->listener addPendingWindowOperation:PENDING_OPERATION_MINIMIZE];
  1466     } else {
  1467         [nswindow miniaturize:nil];
  1468     }
  1469 }}
  1470 
  1471 void
  1472 Cocoa_RestoreWindow(_THIS, SDL_Window * window)
  1473 { @autoreleasepool
  1474 {
  1475     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1476 
  1477     if ([nswindow isMiniaturized]) {
  1478         [nswindow deminiaturize:nil];
  1479     } else if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) {
  1480         [nswindow zoom:nil];
  1481     }
  1482 }}
  1483 
  1484 void
  1485 Cocoa_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered)
  1486 { @autoreleasepool
  1487 {
  1488     if (SetWindowStyle(window, GetWindowStyle(window))) {
  1489         if (bordered) {
  1490             Cocoa_SetWindowTitle(_this, window);  /* this got blanked out. */
  1491         }
  1492     }
  1493 }}
  1494 
  1495 
  1496 void
  1497 Cocoa_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
  1498 { @autoreleasepool
  1499 {
  1500     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1501     NSWindow *nswindow = data->nswindow;
  1502     NSRect rect;
  1503 
  1504     /* The view responder chain gets messed with during setStyleMask */
  1505     if ([[nswindow contentView] nextResponder] == data->listener) {
  1506         [[nswindow contentView] setNextResponder:nil];
  1507     }
  1508 
  1509     if (fullscreen) {
  1510         SDL_Rect bounds;
  1511 
  1512         Cocoa_GetDisplayBounds(_this, display, &bounds);
  1513         rect.origin.x = bounds.x;
  1514         rect.origin.y = bounds.y;
  1515         rect.size.width = bounds.w;
  1516         rect.size.height = bounds.h;
  1517         ConvertNSRect([nswindow screen], fullscreen, &rect);
  1518 
  1519         /* Hack to fix origin on Mac OS X 10.4 */
  1520         NSRect screenRect = [[nswindow screen] frame];
  1521         if (screenRect.size.height >= 1.0f) {
  1522             rect.origin.y += (screenRect.size.height - rect.size.height);
  1523         }
  1524 
  1525         [nswindow setStyleMask:NSBorderlessWindowMask];
  1526     } else {
  1527         rect.origin.x = window->windowed.x;
  1528         rect.origin.y = window->windowed.y;
  1529         rect.size.width = window->windowed.w;
  1530         rect.size.height = window->windowed.h;
  1531         ConvertNSRect([nswindow screen], fullscreen, &rect);
  1532 
  1533         [nswindow setStyleMask:GetWindowStyle(window)];
  1534 
  1535         /* Hack to restore window decorations on Mac OS X 10.10 */
  1536         NSRect frameRect = [nswindow frame];
  1537         [nswindow setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  1538         [nswindow setFrame:frameRect display:NO];
  1539     }
  1540 
  1541     /* The view responder chain gets messed with during setStyleMask */
  1542     if ([[nswindow contentView] nextResponder] != data->listener) {
  1543         [[nswindow contentView] setNextResponder:data->listener];
  1544     }
  1545 
  1546     s_moveHack = 0;
  1547     [nswindow setContentSize:rect.size];
  1548     [nswindow setFrameOrigin:rect.origin];
  1549     s_moveHack = SDL_GetTicks();
  1550 
  1551     /* When the window style changes the title is cleared */
  1552     if (!fullscreen) {
  1553         Cocoa_SetWindowTitle(_this, window);
  1554     }
  1555 
  1556     if (SDL_ShouldAllowTopmost() && fullscreen) {
  1557         /* OpenGL is rendering to the window, so make it visible! */
  1558         [nswindow setLevel:CGShieldingWindowLevel()];
  1559     } else {
  1560         [nswindow setLevel:kCGNormalWindowLevel];
  1561     }
  1562 
  1563     if ([nswindow isVisible] || fullscreen) {
  1564         [data->listener pauseVisibleObservation];
  1565         [nswindow makeKeyAndOrderFront:nil];
  1566         [data->listener resumeVisibleObservation];
  1567     }
  1568 
  1569     ScheduleContextUpdates(data);
  1570 }}
  1571 
  1572 int
  1573 Cocoa_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp)
  1574 {
  1575     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
  1576     CGDirectDisplayID display_id = ((SDL_DisplayData *)display->driverdata)->display;
  1577     const uint32_t tableSize = 256;
  1578     CGGammaValue redTable[tableSize];
  1579     CGGammaValue greenTable[tableSize];
  1580     CGGammaValue blueTable[tableSize];
  1581     uint32_t i;
  1582     float inv65535 = 1.0f / 65535.0f;
  1583 
  1584     /* Extract gamma values into separate tables, convert to floats between 0.0 and 1.0 */
  1585     for (i = 0; i < 256; i++) {
  1586         redTable[i] = ramp[0*256+i] * inv65535;
  1587         greenTable[i] = ramp[1*256+i] * inv65535;
  1588         blueTable[i] = ramp[2*256+i] * inv65535;
  1589     }
  1590 
  1591     if (CGSetDisplayTransferByTable(display_id, tableSize,
  1592                                     redTable, greenTable, blueTable) != CGDisplayNoErr) {
  1593         return SDL_SetError("CGSetDisplayTransferByTable()");
  1594     }
  1595     return 0;
  1596 }
  1597 
  1598 int
  1599 Cocoa_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp)
  1600 {
  1601     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
  1602     CGDirectDisplayID display_id = ((SDL_DisplayData *)display->driverdata)->display;
  1603     const uint32_t tableSize = 256;
  1604     CGGammaValue redTable[tableSize];
  1605     CGGammaValue greenTable[tableSize];
  1606     CGGammaValue blueTable[tableSize];
  1607     uint32_t i, tableCopied;
  1608 
  1609     if (CGGetDisplayTransferByTable(display_id, tableSize,
  1610                                     redTable, greenTable, blueTable, &tableCopied) != CGDisplayNoErr) {
  1611         return SDL_SetError("CGGetDisplayTransferByTable()");
  1612     }
  1613 
  1614     for (i = 0; i < tableCopied; i++) {
  1615         ramp[0*256+i] = (Uint16)(redTable[i] * 65535.0f);
  1616         ramp[1*256+i] = (Uint16)(greenTable[i] * 65535.0f);
  1617         ramp[2*256+i] = (Uint16)(blueTable[i] * 65535.0f);
  1618     }
  1619     return 0;
  1620 }
  1621 
  1622 void
  1623 Cocoa_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
  1624 {
  1625     /* Move the cursor to the nearest point in the window */
  1626     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1627     if (grabbed && data && ![data->listener isMoving]) {
  1628         int x, y;
  1629         CGPoint cgpoint;
  1630 
  1631         SDL_GetMouseState(&x, &y);
  1632         cgpoint.x = window->x + x;
  1633         cgpoint.y = window->y + y;
  1634 
  1635         Cocoa_HandleMouseWarp(cgpoint.x, cgpoint.y);
  1636 
  1637         DLog("Returning cursor to (%g, %g)", cgpoint.x, cgpoint.y);
  1638         CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, cgpoint);
  1639     }
  1640 
  1641     if ( data && (window->flags & SDL_WINDOW_FULLSCREEN) ) {
  1642         if (SDL_ShouldAllowTopmost() && (window->flags & SDL_WINDOW_INPUT_FOCUS)
  1643             && ![data->listener isInFullscreenSpace]) {
  1644             /* OpenGL is rendering to the window, so make it visible! */
  1645             /* Doing this in 10.11 while in a Space breaks things (bug #3152) */
  1646             [data->nswindow setLevel:CGShieldingWindowLevel()];
  1647         } else {
  1648             [data->nswindow setLevel:kCGNormalWindowLevel];
  1649         }
  1650     }
  1651 }
  1652 
  1653 void
  1654 Cocoa_DestroyWindow(_THIS, SDL_Window * window)
  1655 { @autoreleasepool
  1656 {
  1657     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1658 
  1659     if (data) {
  1660         if ([data->listener isInFullscreenSpace]) {
  1661             [NSMenu setMenuBarVisible:YES];
  1662         }
  1663         [data->listener close];
  1664         [data->listener release];
  1665         if (data->created) {
  1666             [data->nswindow close];
  1667         }
  1668 
  1669         NSArray *contexts = [[data->nscontexts copy] autorelease];
  1670         for (SDLOpenGLContext *context in contexts) {
  1671             /* Calling setWindow:NULL causes the context to remove itself from the context list. */            
  1672             [context setWindow:NULL];
  1673         }
  1674         [data->nscontexts release];
  1675 
  1676         SDL_free(data);
  1677     }
  1678     window->driverdata = NULL;
  1679 }}
  1680 
  1681 SDL_bool
  1682 Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
  1683 {
  1684     NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
  1685 
  1686     if (info->version.major <= SDL_MAJOR_VERSION) {
  1687         info->subsystem = SDL_SYSWM_COCOA;
  1688         info->info.cocoa.window = nswindow;
  1689         return SDL_TRUE;
  1690     } else {
  1691         SDL_SetError("Application not compiled with SDL %d.%d\n",
  1692                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
  1693         return SDL_FALSE;
  1694     }
  1695 }
  1696 
  1697 SDL_bool
  1698 Cocoa_IsWindowInFullscreenSpace(SDL_Window * window)
  1699 {
  1700     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1701 
  1702     if ([data->listener isInFullscreenSpace]) {
  1703         return SDL_TRUE;
  1704     } else {
  1705         return SDL_FALSE;
  1706     }
  1707 }
  1708 
  1709 SDL_bool
  1710 Cocoa_SetWindowFullscreenSpace(SDL_Window * window, SDL_bool state)
  1711 { @autoreleasepool
  1712 {
  1713     SDL_bool succeeded = SDL_FALSE;
  1714     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1715 
  1716     if ([data->listener setFullscreenSpace:(state ? YES : NO)]) {
  1717         const int maxattempts = 3;
  1718         int attempt = 0;
  1719         while (++attempt <= maxattempts) {
  1720             /* Wait for the transition to complete, so application changes
  1721              take effect properly (e.g. setting the window size, etc.)
  1722              */
  1723             const int limit = 10000;
  1724             int count = 0;
  1725             while ([data->listener isInFullscreenSpaceTransition]) {
  1726                 if ( ++count == limit ) {
  1727                     /* Uh oh, transition isn't completing. Should we assert? */
  1728                     break;
  1729                 }
  1730                 SDL_Delay(1);
  1731                 SDL_PumpEvents();
  1732             }
  1733             if ([data->listener isInFullscreenSpace] == (state ? YES : NO))
  1734                 break;
  1735             /* Try again, the last attempt was interrupted by user gestures */
  1736             if (![data->listener setFullscreenSpace:(state ? YES : NO)])
  1737                 break; /* ??? */
  1738         }
  1739         /* Return TRUE to prevent non-space fullscreen logic from running */
  1740         succeeded = SDL_TRUE;
  1741     }
  1742 
  1743     return succeeded;
  1744 }}
  1745 
  1746 int
  1747 Cocoa_SetWindowHitTest(SDL_Window * window, SDL_bool enabled)
  1748 {
  1749     return 0;  /* just succeed, the real work is done elsewhere. */
  1750 }
  1751 
  1752 int
  1753 Cocoa_SetWindowOpacity(_THIS, SDL_Window * window, float opacity)
  1754 {
  1755     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
  1756     [data->nswindow setAlphaValue:opacity];
  1757     return 0;
  1758 }
  1759 
  1760 #endif /* SDL_VIDEO_DRIVER_COCOA */
  1761 
  1762 /* vi: set ts=4 sw=4 expandtab: */