core: change initial sync with --delay, video stream switch
[mplayer.git] / libvo / cocoa_common.m
blobf5ad7a0943ab3107c3250a566267868d03fc6c3e
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 "cocoa_common.h"
26 #include "options.h"
27 #include "video_out.h"
28 #include "aspect.h"
30 #include "mp_fifo.h"
31 #include "talloc.h"
33 #include "input/input.h"
34 #include "input/keycodes.h"
35 #include "osx_common.h"
36 #include "mp_msg.h"
38 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
39 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
41 @interface GLMPlayerWindow : NSWindow <NSWindowDelegate>
42 - (BOOL) canBecomeKeyWindow;
43 - (BOOL) canBecomeMainWindow;
44 - (void) fullscreen;
45 - (void) mouseEvent:(NSEvent *)theEvent;
46 - (void) mulSize:(float)multiplier;
47 - (void) setContentSize:(NSSize)newSize keepCentered:(BOOL)keepCentered;
48 @end
50 @interface GLMPlayerOpenGLView : NSView
51 @end
53 struct vo_cocoa_state {
54     NSAutoreleasePool *pool;
55     GLMPlayerWindow *window;
56     NSOpenGLContext *glContext;
58     NSSize current_video_size;
59     NSSize previous_video_size;
61     NSRect screen_frame;
62     NSScreen *screen_handle;
63     NSArray *screen_array;
65     NSInteger windowed_mask;
66     NSInteger fullscreen_mask;
68     NSRect windowed_frame;
70     NSString *window_title;
72     NSInteger windowed_window_level;
73     NSInteger fullscreen_window_level;
75     int last_screensaver_update;
77     int display_cursor;
78     int cursor_timer;
79     int cursor_autohide_delay;
81     bool did_resize;
82     bool out_fs_resize;
85 struct vo_cocoa_state *s;
87 struct vo *l_vo;
89 // local function definitions
90 struct vo_cocoa_state *vo_cocoa_init_state(void);
91 void vo_set_level(int ontop);
92 void update_screen_info(void);
93 void resize_window(struct vo *vo);
94 void vo_cocoa_display_cursor(int requested_state);
95 void create_menu(void);
97 struct vo_cocoa_state *vo_cocoa_init_state(void)
99     struct vo_cocoa_state *s = talloc_ptrtype(NULL, s);
100     *s = (struct vo_cocoa_state){
101         .did_resize = NO,
102         .current_video_size = {0,0},
103         .previous_video_size = {0,0},
104         .windowed_mask = NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask,
105         .fullscreen_mask = NSBorderlessWindowMask,
106         .fullscreen_window_level = NSNormalWindowLevel + 1,
107         .windowed_frame = {{0,0},{0,0}},
108         .out_fs_resize = NO,
109         .display_cursor = 1,
110     };
111     return s;
114 int vo_cocoa_init(struct vo *vo)
116     s = vo_cocoa_init_state();
117     s->pool = [[NSAutoreleasePool alloc] init];
118     s->cursor_autohide_delay = vo->opts->cursor_autohide_delay;
119     NSApplicationLoad();
120     NSApp = [NSApplication sharedApplication];
121     [NSApp setActivationPolicy: NSApplicationActivationPolicyRegular];
123     return 1;
126 void vo_cocoa_uninit(struct vo *vo)
128     CGDisplayShowCursor(kCGDirectMainDisplay);
129     [s->window release];
130     s->window = nil;
131     [s->glContext release];
132     s->glContext = nil;
133     [s->pool release];
134     s->pool = nil;
136     talloc_free(s);
139 void update_screen_info(void)
141     s->screen_array = [NSScreen screens];
142     if (xinerama_screen >= (int)[s->screen_array count]) {
143         mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
144         xinerama_screen = -1;
145     }
147     if (xinerama_screen < 0) { // default behaviour
148         if (! (s->screen_handle = [s->window screen]) )
149             s->screen_handle = [s->screen_array objectAtIndex:0];
150     } else {
151         s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
152     }
154     s->screen_frame = [s->screen_handle frame];
157 void vo_cocoa_update_xinerama_info(struct vo *vo)
159     update_screen_info();
160     aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
163 int vo_cocoa_change_attributes(struct vo *vo)
165     return 0;
168 void resize_window(struct vo *vo)
170     vo->dwidth = [[s->window contentView] frame].size.width;
171     vo->dheight = [[s->window contentView] frame].size.height;
172     [s->glContext update];
175 void vo_set_level(int ontop)
177     if (ontop) {
178         s->windowed_window_level = NSNormalWindowLevel + 1;
179     } else {
180         s->windowed_window_level = NSNormalWindowLevel;
181     }
183     if (!vo_fs)
184         [s->window setLevel:s->windowed_window_level];
187 void vo_cocoa_ontop(struct vo *vo)
189     struct MPOpts *opts = vo->opts;
190     opts->vo_ontop = !opts->vo_ontop;
191     vo_set_level(opts->vo_ontop);
194 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
195                            uint32_t d_height, uint32_t flags)
197     struct MPOpts *opts = vo->opts;
198     if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
199         s->previous_video_size = s->current_video_size;
200     s->current_video_size = NSMakeSize(d_width, d_height);
202     if (!(s->window || s->glContext)) { // keep using the same window
203         s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
204                                              styleMask:s->windowed_mask
205                                              backing:NSBackingStoreBuffered defer:NO];
207         GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
209         NSOpenGLPixelFormatAttribute attrs[] = {
210             NSOpenGLPFADoubleBuffer, // double buffered
211             NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)16, // 16 bit depth buffer
212             (NSOpenGLPixelFormatAttribute)0
213         };
215         NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
216         s->glContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
218         create_menu();
220         [s->window setContentView:glView];
221         [glView release];
222         [s->window setAcceptsMouseMovedEvents:YES];
223         [s->glContext setView:glView];
224         [s->glContext makeCurrentContext];
226         [NSApp setDelegate:s->window];
227         [s->window setDelegate:s->window];
228         [s->window setContentSize:s->current_video_size];
229         [s->window setContentAspectRatio:s->current_video_size];
230         [s->window center];
232         if (flags & VOFLAG_HIDDEN) {
233             [s->window orderOut:nil];
234         } else {
235             [s->window makeKeyAndOrderFront:nil];
236             [NSApp activateIgnoringOtherApps:YES];
237         }
239         if (flags & VOFLAG_FULLSCREEN)
240             vo_cocoa_fullscreen(vo);
242         vo_set_level(opts->vo_ontop);
243     } else {
244         if (s->current_video_size.width  != s->previous_video_size.width ||
245             s->current_video_size.height != s->previous_video_size.height) {
246             if (vo_fs) {
247                 // we will resize as soon as we get out of fullscreen
248                 s->out_fs_resize = YES;
249             } else {
250                 // only if we are not in fullscreen and the video size did change
251                 // we actually resize the window and set a new aspect ratio
252                 [s->window setContentSize:s->current_video_size keepCentered:YES];
253                 [s->window setContentAspectRatio:s->current_video_size];
254             }
255         }
256     }
258     resize_window(vo);
260     if (s->window_title)
261         [s->window_title release];
263     s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
264     [s->window setTitle: s->window_title];
266     return 0;
269 void vo_cocoa_swap_buffers()
271     [s->glContext flushBuffer];
274 void vo_cocoa_display_cursor(int requested_state)
276     if (requested_state) {
277         if (!vo_fs || s->cursor_autohide_delay > -2) {
278             s->display_cursor = requested_state;
279             CGDisplayShowCursor(kCGDirectMainDisplay);
280         }
281     } else {
282         if (s->cursor_autohide_delay != -1) {
283             s->display_cursor = requested_state;
284             CGDisplayHideCursor(kCGDirectMainDisplay);
285         }
286     }
289 int vo_cocoa_check_events(struct vo *vo)
291     NSEvent *event;
292     float curTime = TickCount()/60;
293     int msCurTime = (int) (curTime * 1000);
295     // automatically hide mouse cursor
296     if (vo_fs && s->display_cursor &&
297         (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
298         vo_cocoa_display_cursor(0);
299         s->cursor_timer = msCurTime;
300     }
302     //update activity every 30 seconds to prevent
303     //screensaver from starting up.
304     if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
305     {
306         UpdateSystemActivity(UsrActivity);
307         s->last_screensaver_update = (int)curTime;
308     }
310     event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
311                    inMode:NSEventTrackingRunLoopMode dequeue:YES];
312     if (event == nil)
313         return 0;
314     l_vo = vo;
315     [NSApp sendEvent:event];
316     l_vo = nil;
318     if (s->did_resize) {
319         s->did_resize = NO;
320         resize_window(vo);
321         return VO_EVENT_RESIZE;
322     }
323     // Without SDL's bootstrap code (include SDL.h in mplayer.c),
324     // on Leopard, we have trouble to get the play window automatically focused
325     // when the app is actived. The Following code fix this problem.
326 #ifndef CONFIG_SDL
327     if ([event type] == NSAppKitDefined
328             && [event subtype] == NSApplicationActivatedEventType) {
329         [s->window makeMainWindow];
330         [s->window makeKeyAndOrderFront:nil];
331     }
332 #endif
333     return 0;
336 void vo_cocoa_fullscreen(struct vo *vo)
338     [s->window fullscreen];
339     resize_window(vo);
342 int vo_cocoa_swap_interval(int enabled)
344     [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
345     return 0;
348 void create_menu()
350     NSMenu *menu;
351     NSMenuItem *menuItem;
353     menu = [[NSMenu new] autorelease];
354     menuItem = [[NSMenuItem new] autorelease];
355     [menu addItem: menuItem];
356     [NSApp setMainMenu: menu];
358     menu = [[NSMenu alloc] initWithTitle:@"Movie"];
359     menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(halfSize) keyEquivalent:@"0"]; [menu addItem:menuItem];
360     menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(normalSize) keyEquivalent:@"1"]; [menu addItem:menuItem];
361     menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(doubleSize) keyEquivalent:@"2"]; [menu addItem:menuItem];
363     menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
364     [menuItem setSubmenu:menu];
365     [[NSApp mainMenu] addItem:menuItem];
367     [menu release];
368     [menuItem release];
371 @implementation GLMPlayerWindow
373 - (void) windowDidResize:(NSNotification *) notification
375     if (l_vo)
376         s->did_resize = YES;
379 - (void) fullscreen
381     if (!vo_fs) {
382         update_screen_info();
383         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
384         s->windowed_frame = [self frame];
385         [self setHasShadow:NO];
386         [self setStyleMask:s->fullscreen_mask];
387         [self setFrame:s->screen_frame display:YES animate:NO];
388         [self setLevel:s->fullscreen_window_level];
389         vo_fs = VO_TRUE;
390         vo_cocoa_display_cursor(0);
391         [self setMovableByWindowBackground: NO];
392     } else {
393         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
394         [self setHasShadow:YES];
395         [self setStyleMask:s->windowed_mask];
396         [self setTitle:s->window_title];
397         [self setFrame:s->windowed_frame display:YES animate:NO];
398         if (s->out_fs_resize) {
399             [self setContentSize:s->current_video_size keepCentered:YES];
400             s->out_fs_resize = NO;
401         }
402         [self setContentAspectRatio:s->current_video_size];
403         [self setLevel:s->windowed_window_level];
404         vo_fs = VO_FALSE;
405         vo_cocoa_display_cursor(1);
406         [self setMovableByWindowBackground: YES];
407     }
410 - (BOOL) canBecomeMainWindow { return YES; }
411 - (BOOL) canBecomeKeyWindow { return YES; }
412 - (BOOL) acceptsFirstResponder { return YES; }
413 - (BOOL) becomeFirstResponder { return YES; }
414 - (BOOL) resignFirstResponder { return YES; }
415 - (BOOL) windowShouldClose:(id)sender
417     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
418     // We have to wait for MPlayer to handle this,
419     // otherwise we are in trouble if the
420     // KEY_CLOSE_WIN handler is disabled
421     return NO;
424 - (BOOL) isMovableByWindowBackground
426     // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
427     return !vo_fs;
430 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
432     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
435 - (void) keyDown:(NSEvent *)theEvent
437     unsigned char charcode;
438     if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
439         charcode = *[[theEvent characters] UTF8String];
440     else
441         charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
443     int key = convert_key([theEvent keyCode], charcode);
445     if (key > -1) {
446         if ([theEvent modifierFlags] & NSShiftKeyMask)
447             key |= KEY_MODIFIER_SHIFT;
448         if ([theEvent modifierFlags] & NSControlKeyMask)
449             key |= KEY_MODIFIER_CTRL;
450         if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
451             key |= KEY_MODIFIER_ALT;
452         if ([theEvent modifierFlags] & NSCommandKeyMask)
453             key |= KEY_MODIFIER_META;
454         mplayer_put_key(l_vo->key_fifo, key);
455     }
458 - (void) mouseMoved: (NSEvent *) theEvent
460     if (vo_fs)
461         vo_cocoa_display_cursor(1);
464 - (void) mouseDragged:(NSEvent *)theEvent
466     [self mouseEvent: theEvent];
469 - (void) mouseDown:(NSEvent *)theEvent
471     [self mouseEvent: theEvent];
474 - (void) mouseUp:(NSEvent *)theEvent
476     [self mouseEvent: theEvent];
479 - (void) rightMouseDown:(NSEvent *)theEvent
481     [self mouseEvent: theEvent];
484 - (void) rightMouseUp:(NSEvent *)theEvent
486     [self mouseEvent: theEvent];
489 - (void) otherMouseDown:(NSEvent *)theEvent
491     [self mouseEvent: theEvent];
494 - (void) otherMouseUp:(NSEvent *)theEvent
496     [self mouseEvent: theEvent];
499 - (void) scrollWheel:(NSEvent *)theEvent
501     if ([theEvent deltaY] > 0)
502         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
503     else
504         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
507 - (void) mouseEvent:(NSEvent *)theEvent
509     if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
510         int buttonNumber = [theEvent buttonNumber];
511         // Fix to mplayer defined button order: left, middle, right
512         if (buttonNumber == 1)  buttonNumber = 2;
513         else if (buttonNumber == 2) buttonNumber = 1;
514         switch ([theEvent type]) {
515             case NSLeftMouseDown:
516             case NSRightMouseDown:
517             case NSOtherMouseDown:
518                 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
519                 // Looks like Cocoa doesn't create MouseUp events when we are
520                 // doing the second click in a double click. Put in the key_fifo
521                 // the key that would be put from the MouseUp handling code.
522                 if([theEvent clickCount] == 2)
523                    mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
524                 break;
525             case NSLeftMouseUp:
526             case NSRightMouseUp:
527             case NSOtherMouseUp:
528                 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
529                 break;
530         }
531     }
534 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
536     if (vo_fs) {
537         [s->window setLevel:s->fullscreen_window_level];
538         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
539         [s->window makeKeyAndOrderFront:nil];
540         [NSApp activateIgnoringOtherApps: YES];
541     }
544 - (void) applicationWillResignActive:(NSNotification *)aNotification
546     if (vo_fs) {
547         [s->window setLevel:s->windowed_window_level];
548         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
549     }
552 - (void) applicationDidFinishLaunching:(NSNotification*)notification
554     // Install an event handler so the Quit menu entry works
555     // The proper way using NSApp setDelegate: and
556     // applicationShouldTerminate: does not work,
557     // probably NSApplication never installs its handler.
558     [[NSAppleEventManager sharedAppleEventManager]
559         setEventHandler:self
560         andSelector:@selector(handleQuitEvent:withReplyEvent:)
561         forEventClass:kCoreEventClass
562         andEventID:kAEQuitApplication];
565 - (void) normalSize
567     if (!vo_fs)
568       [self setContentSize:s->current_video_size keepCentered:YES];
571 - (void) halfSize { [self mulSize:0.5f];}
573 - (void) doubleSize { [self mulSize:2.0f];}
575 - (void) mulSize:(float)multiplier
577     if (!vo_fs) {
578         NSSize size = [[self contentView] frame].size;
579         size.width  = s->current_video_size.width  * (multiplier);
580         size.height = s->current_video_size.height * (multiplier);
581         [self setContentSize:size keepCentered:YES];
582     }
585 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
587     if (keepCentered) {
588         NSRect nf = [self frame];
589         NSRect vf = [[self screen] visibleFrame];
590         int title_height = nf.size.height - [[self contentView] bounds].size.height;
591         double ratio = (double)ns.width / (double)ns.height;
593         // clip the new size to the visibleFrame's size if needed
594         if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
595             ns = vf.size;
596             ns.height -= title_height; // make space for the title bar
598             if (ns.width > ns.height) {
599                 ns.height = ((double)ns.width * 1/ratio + 0.5);
600             } else {
601                 ns.width = ((double)ns.height * ratio + 0.5);
602             }
603         }
605         int dw = nf.size.width - ns.width;
606         int dh = nf.size.height - ns.height - title_height;
608         nf.origin.x += dw / 2;
609         nf.origin.y += dh / 2;
611         [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
612     } else {
613         [self setContentSize:ns];
614     }
616 @end
618 @implementation GLMPlayerOpenGLView
619 - (void) drawRect: (NSRect)rect
621     [[NSColor clearColor] set];
622     NSRectFill([self bounds]);
624 @end