cocoa_common: fix problems with alt-tab window changes
[mplayer.git] / libvo / cocoa_common.m
blobc3578d27c19d302d381b4dc3f736d8a5b87a5293
1 /*
2  * Cocoa OpenGL Backend
3  *
4  * This file is part of mplayer2.
5  *
6  * mplayer2 is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * mplayer2 is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with mplayer2.  If not, see <http://www.gnu.org/licenses/>.
18  */
20 #import <Cocoa/Cocoa.h>
21 #import <OpenGL/OpenGL.h>
22 #import <QuartzCore/QuartzCore.h>
23 #import <CoreServices/CoreServices.h> // for CGDisplayHideCursor
24 #include <dlfcn.h>
26 #include "cocoa_common.h"
28 #include "options.h"
29 #include "video_out.h"
30 #include "aspect.h"
32 #include "mp_fifo.h"
33 #include "talloc.h"
35 #include "input/input.h"
36 #include "input/keycodes.h"
37 #include "osx_common.h"
38 #include "mp_msg.h"
40 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
41 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
43 @interface GLMPlayerWindow : NSWindow <NSWindowDelegate>
44 - (BOOL) canBecomeKeyWindow;
45 - (BOOL) canBecomeMainWindow;
46 - (void) fullscreen;
47 - (void) mouseEvent:(NSEvent *)theEvent;
48 - (void) mulSize:(float)multiplier;
49 - (void) setContentSize:(NSSize)newSize keepCentered:(BOOL)keepCentered;
50 @end
52 @interface GLMPlayerOpenGLView : NSView
53 @end
55 struct vo_cocoa_state {
56     NSAutoreleasePool *pool;
57     GLMPlayerWindow *window;
58     NSOpenGLContext *glContext;
59     NSOpenGLPixelFormat *pixelFormat;
61     NSSize current_video_size;
62     NSSize previous_video_size;
64     NSRect screen_frame;
65     NSScreen *screen_handle;
66     NSArray *screen_array;
68     NSInteger windowed_mask;
69     NSInteger fullscreen_mask;
71     NSRect windowed_frame;
73     NSString *window_title;
75     NSInteger windowed_window_level;
76     NSInteger fullscreen_window_level;
78     int last_screensaver_update;
80     int display_cursor;
81     int cursor_timer;
82     int cursor_autohide_delay;
84     bool did_resize;
85     bool out_fs_resize;
88 struct vo_cocoa_state *s;
90 struct vo *l_vo;
92 // local function definitions
93 struct vo_cocoa_state *vo_cocoa_init_state(void);
94 void vo_set_level(int ontop);
95 void update_screen_info(void);
96 void resize_window(struct vo *vo);
97 void vo_cocoa_display_cursor(int requested_state);
98 void create_menu(void);
100 struct vo_cocoa_state *vo_cocoa_init_state(void)
102     struct vo_cocoa_state *s = talloc_ptrtype(NULL, s);
103     *s = (struct vo_cocoa_state){
104         .did_resize = NO,
105         .current_video_size = {0,0},
106         .previous_video_size = {0,0},
107         .windowed_mask = NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask,
108         .fullscreen_mask = NSBorderlessWindowMask,
109         .fullscreen_window_level = NSNormalWindowLevel + 1,
110         .windowed_frame = {{0,0},{0,0}},
111         .out_fs_resize = NO,
112         .display_cursor = 1,
113     };
114     return s;
117 bool vo_cocoa_gui_running(void)
119     return !!s;
122 void *vo_cocoa_glgetaddr(const char *s)
124     void *ret = NULL;
125     void *handle = dlopen(
126         "/System/Library/Frameworks/OpenGL.framework/OpenGL",
127         RTLD_LAZY | RTLD_LOCAL);
128     if (!handle)
129         return NULL;
130     ret = dlsym(handle, s);
131     dlclose(handle);
132     return ret;
135 int vo_cocoa_init(struct vo *vo)
137     s = vo_cocoa_init_state();
138     s->pool = [[NSAutoreleasePool alloc] init];
139     s->cursor_autohide_delay = vo->opts->cursor_autohide_delay;
140     NSApplicationLoad();
141     NSApp = [NSApplication sharedApplication];
142     [NSApp setActivationPolicy: NSApplicationActivationPolicyRegular];
144     return 1;
147 void vo_cocoa_uninit(struct vo *vo)
149     CGDisplayShowCursor(kCGDirectMainDisplay);
150     [NSApp setPresentationOptions:NSApplicationPresentationDefault];
152     [s->window release];
153     s->window = nil;
154     [s->glContext release];
155     s->glContext = nil;
156     [s->pool release];
157     s->pool = nil;
159     talloc_free(s);
160     s = nil;
163 void update_screen_info(void)
165     s->screen_array = [NSScreen screens];
166     if (xinerama_screen >= (int)[s->screen_array count]) {
167         mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
168         xinerama_screen = -1;
169     }
171     if (xinerama_screen < 0) { // default behaviour
172         if (! (s->screen_handle = [s->window screen]) )
173             s->screen_handle = [s->screen_array objectAtIndex:0];
174     } else {
175         s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
176     }
178     s->screen_frame = [s->screen_handle frame];
181 void vo_cocoa_update_xinerama_info(struct vo *vo)
183     update_screen_info();
184     aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
187 int vo_cocoa_change_attributes(struct vo *vo)
189     return 0;
192 void resize_window(struct vo *vo)
194     vo->dwidth = [[s->window contentView] frame].size.width;
195     vo->dheight = [[s->window contentView] frame].size.height;
196     [s->glContext update];
199 void vo_set_level(int ontop)
201     if (ontop) {
202         s->windowed_window_level = NSNormalWindowLevel + 1;
203     } else {
204         s->windowed_window_level = NSNormalWindowLevel;
205     }
207     if (!vo_fs)
208         [s->window setLevel:s->windowed_window_level];
211 void vo_cocoa_ontop(struct vo *vo)
213     struct MPOpts *opts = vo->opts;
214     opts->vo_ontop = !opts->vo_ontop;
215     vo_set_level(opts->vo_ontop);
218 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
219                            uint32_t d_height, uint32_t flags)
221     struct MPOpts *opts = vo->opts;
222     if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
223         s->previous_video_size = s->current_video_size;
224     s->current_video_size = NSMakeSize(d_width, d_height);
226     if (!(s->window || s->glContext)) { // keep using the same window
227         s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
228                                              styleMask:s->windowed_mask
229                                              backing:NSBackingStoreBuffered defer:NO];
231         GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
233         NSOpenGLPixelFormatAttribute attrs[] = {
234             NSOpenGLPFADoubleBuffer, // double buffered
235             NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)16, // 16 bit depth buffer
236             (NSOpenGLPixelFormatAttribute)0
237         };
239         s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
240         s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
242         create_menu();
244         [s->window setContentView:glView];
245         [glView release];
246         [s->window setAcceptsMouseMovedEvents:YES];
247         [s->glContext setView:glView];
248         [s->glContext makeCurrentContext];
250         [NSApp setDelegate:s->window];
251         [s->window setDelegate:s->window];
252         [s->window setContentSize:s->current_video_size];
253         [s->window setContentAspectRatio:s->current_video_size];
254         [s->window center];
256         if (flags & VOFLAG_HIDDEN) {
257             [s->window orderOut:nil];
258         } else {
259             [s->window makeKeyAndOrderFront:nil];
260             [NSApp activateIgnoringOtherApps:YES];
261         }
263         if (flags & VOFLAG_FULLSCREEN)
264             vo_cocoa_fullscreen(vo);
266         vo_set_level(opts->vo_ontop);
267     } else {
268         if (s->current_video_size.width  != s->previous_video_size.width ||
269             s->current_video_size.height != s->previous_video_size.height) {
270             if (vo_fs) {
271                 // we will resize as soon as we get out of fullscreen
272                 s->out_fs_resize = YES;
273             } else {
274                 // only if we are not in fullscreen and the video size did change
275                 // we actually resize the window and set a new aspect ratio
276                 [s->window setContentSize:s->current_video_size keepCentered:YES];
277                 [s->window setContentAspectRatio:s->current_video_size];
278             }
279         }
280     }
282     resize_window(vo);
284     if (s->window_title)
285         [s->window_title release];
287     s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
288     [s->window setTitle: s->window_title];
290     return 0;
293 void vo_cocoa_swap_buffers()
295     [s->glContext flushBuffer];
298 void vo_cocoa_display_cursor(int requested_state)
300     if (requested_state) {
301         if (!vo_fs || s->cursor_autohide_delay > -2) {
302             s->display_cursor = requested_state;
303             CGDisplayShowCursor(kCGDirectMainDisplay);
304         }
305     } else {
306         if (s->cursor_autohide_delay != -1) {
307             s->display_cursor = requested_state;
308             CGDisplayHideCursor(kCGDirectMainDisplay);
309         }
310     }
313 int vo_cocoa_check_events(struct vo *vo)
315     NSEvent *event;
316     float curTime = TickCount()/60;
317     int msCurTime = (int) (curTime * 1000);
319     // automatically hide mouse cursor
320     if (vo_fs && s->display_cursor &&
321         (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
322         vo_cocoa_display_cursor(0);
323         s->cursor_timer = msCurTime;
324     }
326     //update activity every 30 seconds to prevent
327     //screensaver from starting up.
328     if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
329     {
330         UpdateSystemActivity(UsrActivity);
331         s->last_screensaver_update = (int)curTime;
332     }
334     event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
335                    inMode:NSEventTrackingRunLoopMode dequeue:YES];
336     if (event == nil)
337         return 0;
338     l_vo = vo;
339     [NSApp sendEvent:event];
340     l_vo = nil;
342     if (s->did_resize) {
343         s->did_resize = NO;
344         resize_window(vo);
345         return VO_EVENT_RESIZE;
346     }
347     // Without SDL's bootstrap code (include SDL.h in mplayer.c),
348     // on Leopard, we have trouble to get the play window automatically focused
349     // when the app is actived. The Following code fix this problem.
350 #ifndef CONFIG_SDL
351     if ([event type] == NSAppKitDefined
352             && [event subtype] == NSApplicationActivatedEventType) {
353         [s->window makeMainWindow];
354         [s->window makeKeyAndOrderFront:nil];
355     }
356 #endif
357     return 0;
360 void vo_cocoa_fullscreen(struct vo *vo)
362     [s->window fullscreen];
363     resize_window(vo);
366 int vo_cocoa_swap_interval(int enabled)
368     [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
369     return 0;
372 void *vo_cocoa_cgl_context(void)
374     return [s->glContext CGLContextObj];
377 void *vo_cocoa_cgl_pixel_format(void)
379     return [s->pixelFormat CGLPixelFormatObj];
382 void create_menu()
384     NSMenu *menu;
385     NSMenuItem *menuItem;
387     menu = [[NSMenu new] autorelease];
388     menuItem = [[NSMenuItem new] autorelease];
389     [menu addItem: menuItem];
390     [NSApp setMainMenu: menu];
392     menu = [[NSMenu alloc] initWithTitle:@"Movie"];
393     menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(halfSize) keyEquivalent:@"0"]; [menu addItem:menuItem];
394     menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(normalSize) keyEquivalent:@"1"]; [menu addItem:menuItem];
395     menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(doubleSize) keyEquivalent:@"2"]; [menu addItem:menuItem];
397     menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
398     [menuItem setSubmenu:menu];
399     [[NSApp mainMenu] addItem:menuItem];
401     [menu release];
402     [menuItem release];
405 @implementation GLMPlayerWindow
407 - (void) windowDidResize:(NSNotification *) notification
409     if (l_vo)
410         s->did_resize = YES;
413 - (void) fullscreen
415     if (!vo_fs) {
416         update_screen_info();
417         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
418         s->windowed_frame = [self frame];
419         [self setHasShadow:NO];
420         [self setStyleMask:s->fullscreen_mask];
421         [self setFrame:s->screen_frame display:YES animate:NO];
422         [self setLevel:s->fullscreen_window_level];
423         vo_fs = VO_TRUE;
424         vo_cocoa_display_cursor(0);
425         [self setMovableByWindowBackground: NO];
426     } else {
427         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
428         [self setHasShadow:YES];
429         [self setStyleMask:s->windowed_mask];
430         [self setTitle:s->window_title];
431         [self setFrame:s->windowed_frame display:YES animate:NO];
432         if (s->out_fs_resize) {
433             [self setContentSize:s->current_video_size keepCentered:YES];
434             s->out_fs_resize = NO;
435         }
436         [self setContentAspectRatio:s->current_video_size];
437         [self setLevel:s->windowed_window_level];
438         vo_fs = VO_FALSE;
439         vo_cocoa_display_cursor(1);
440         [self setMovableByWindowBackground: YES];
441     }
444 - (BOOL) canBecomeMainWindow { return YES; }
445 - (BOOL) canBecomeKeyWindow { return YES; }
446 - (BOOL) acceptsFirstResponder { return YES; }
447 - (BOOL) becomeFirstResponder { return YES; }
448 - (BOOL) resignFirstResponder { return YES; }
449 - (BOOL) windowShouldClose:(id)sender
451     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
452     // We have to wait for MPlayer to handle this,
453     // otherwise we are in trouble if the
454     // KEY_CLOSE_WIN handler is disabled
455     return NO;
458 - (BOOL) isMovableByWindowBackground
460     // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
461     return !vo_fs;
464 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
466     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
469 - (void) keyDown:(NSEvent *)theEvent
471     unsigned char charcode;
472     if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
473         charcode = *[[theEvent characters] UTF8String];
474     else
475         charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
477     int key = convert_key([theEvent keyCode], charcode);
479     if (key > -1) {
480         if ([theEvent modifierFlags] & NSShiftKeyMask)
481             key |= KEY_MODIFIER_SHIFT;
482         if ([theEvent modifierFlags] & NSControlKeyMask)
483             key |= KEY_MODIFIER_CTRL;
484         if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
485             key |= KEY_MODIFIER_ALT;
486         if ([theEvent modifierFlags] & NSCommandKeyMask)
487             key |= KEY_MODIFIER_META;
488         mplayer_put_key(l_vo->key_fifo, key);
489     }
492 - (void) mouseMoved: (NSEvent *) theEvent
494     if (vo_fs)
495         vo_cocoa_display_cursor(1);
498 - (void) mouseDragged:(NSEvent *)theEvent
500     [self mouseEvent: theEvent];
503 - (void) mouseDown:(NSEvent *)theEvent
505     [self mouseEvent: theEvent];
508 - (void) mouseUp:(NSEvent *)theEvent
510     [self mouseEvent: theEvent];
513 - (void) rightMouseDown:(NSEvent *)theEvent
515     [self mouseEvent: theEvent];
518 - (void) rightMouseUp:(NSEvent *)theEvent
520     [self mouseEvent: theEvent];
523 - (void) otherMouseDown:(NSEvent *)theEvent
525     [self mouseEvent: theEvent];
528 - (void) otherMouseUp:(NSEvent *)theEvent
530     [self mouseEvent: theEvent];
533 - (void) scrollWheel:(NSEvent *)theEvent
535     if ([theEvent deltaY] > 0)
536         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
537     else
538         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
541 - (void) mouseEvent:(NSEvent *)theEvent
543     if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
544         int buttonNumber = [theEvent buttonNumber];
545         // Fix to mplayer defined button order: left, middle, right
546         if (buttonNumber == 1)  buttonNumber = 2;
547         else if (buttonNumber == 2) buttonNumber = 1;
548         switch ([theEvent type]) {
549             case NSLeftMouseDown:
550             case NSRightMouseDown:
551             case NSOtherMouseDown:
552                 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
553                 // Looks like Cocoa doesn't create MouseUp events when we are
554                 // doing the second click in a double click. Put in the key_fifo
555                 // the key that would be put from the MouseUp handling code.
556                 if([theEvent clickCount] == 2)
557                    mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
558                 break;
559             case NSLeftMouseUp:
560             case NSRightMouseUp:
561             case NSOtherMouseUp:
562                 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
563                 break;
564         }
565     }
568 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
570     if (vo_fs) {
571         [s->window makeKeyAndOrderFront:s->window];
572         [s->window setLevel:s->fullscreen_window_level];
573         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|
574                                       NSApplicationPresentationHideMenuBar];
575     }
578 - (void) applicationWillResignActive:(NSNotification *)aNotification
580     if (vo_fs) {
581         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
582         [s->window setLevel:s->windowed_window_level];
583         [s->window orderBack:s->window];
584     }
587 - (void) applicationDidFinishLaunching:(NSNotification*)notification
589     // Install an event handler so the Quit menu entry works
590     // The proper way using NSApp setDelegate: and
591     // applicationShouldTerminate: does not work,
592     // probably NSApplication never installs its handler.
593     [[NSAppleEventManager sharedAppleEventManager]
594         setEventHandler:self
595         andSelector:@selector(handleQuitEvent:withReplyEvent:)
596         forEventClass:kCoreEventClass
597         andEventID:kAEQuitApplication];
600 - (void) normalSize
602     if (!vo_fs)
603       [self setContentSize:s->current_video_size keepCentered:YES];
606 - (void) halfSize { [self mulSize:0.5f];}
608 - (void) doubleSize { [self mulSize:2.0f];}
610 - (void) mulSize:(float)multiplier
612     if (!vo_fs) {
613         NSSize size = [[self contentView] frame].size;
614         size.width  = s->current_video_size.width  * (multiplier);
615         size.height = s->current_video_size.height * (multiplier);
616         [self setContentSize:size keepCentered:YES];
617     }
620 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
622     if (keepCentered) {
623         NSRect nf = [self frame];
624         NSRect vf = [[self screen] visibleFrame];
625         int title_height = nf.size.height - [[self contentView] bounds].size.height;
626         double ratio = (double)ns.width / (double)ns.height;
628         // clip the new size to the visibleFrame's size if needed
629         if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
630             ns = vf.size;
631             ns.height -= title_height; // make space for the title bar
633             if (ns.width > ns.height) {
634                 ns.height = ((double)ns.width * 1/ratio + 0.5);
635             } else {
636                 ns.width = ((double)ns.height * ratio + 0.5);
637             }
638         }
640         int dw = nf.size.width - ns.width;
641         int dh = nf.size.height - ns.height - title_height;
643         nf.origin.x += dw / 2;
644         nf.origin.y += dh / 2;
646         [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
647     } else {
648         [self setContentSize:ns];
649     }
651 @end
653 @implementation GLMPlayerOpenGLView
654 - (void) drawRect: (NSRect)rect
656     [[NSColor clearColor] set];
657     NSRectFill([self bounds]);
659 @end