osd: rewrite OSD rendering to use libass
[mplayer.git] / libvo / cocoa_common.m
blobcbb8b79e8b25fdd046ed1d1a3872e148c2293a2c
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 "config.h"
30 #include "options.h"
31 #include "video_out.h"
32 #include "aspect.h"
34 #include "mp_fifo.h"
35 #include "talloc.h"
37 #include "input/input.h"
38 #include "input/keycodes.h"
39 #include "osx_common.h"
40 #include "mp_msg.h"
42 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
43 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
45 // add methods not available on OSX versions prior to 10.7
46 #ifndef MAC_OS_X_VERSION_10_7
47 @interface NSView (IntroducedInLion)
48 - (NSRect)convertRectToBacking:(NSRect)aRect;
49 - (void)setWantsBestResolutionOpenGLSurface:(BOOL)aBool;
50 @end
51 #endif
53 @interface GLMPlayerWindow : NSWindow <NSWindowDelegate>
54 - (BOOL) canBecomeKeyWindow;
55 - (BOOL) canBecomeMainWindow;
56 - (void) fullscreen;
57 - (void) mouseEvent:(NSEvent *)theEvent;
58 - (void) mulSize:(float)multiplier;
59 - (void) setContentSize:(NSSize)newSize keepCentered:(BOOL)keepCentered;
60 @end
62 @interface GLMPlayerOpenGLView : NSView
63 @end
65 struct vo_cocoa_state {
66     NSAutoreleasePool *pool;
67     GLMPlayerWindow *window;
68     NSOpenGLContext *glContext;
69     NSOpenGLPixelFormat *pixelFormat;
71     NSSize current_video_size;
72     NSSize previous_video_size;
74     NSRect screen_frame;
75     NSScreen *screen_handle;
76     NSArray *screen_array;
78     NSInteger windowed_mask;
79     NSInteger fullscreen_mask;
81     NSRect windowed_frame;
83     NSString *window_title;
85     NSInteger windowed_window_level;
86     NSInteger fullscreen_window_level;
88     int last_screensaver_update;
90     int display_cursor;
91     int cursor_timer;
92     int cursor_autohide_delay;
94     bool did_resize;
95     bool out_fs_resize;
98 struct vo_cocoa_state *s;
100 struct vo *l_vo;
102 // local function definitions
103 struct vo_cocoa_state *vo_cocoa_init_state(void);
104 void vo_set_level(int ontop);
105 void update_screen_info(void);
106 void resize_window(struct vo *vo);
107 void vo_cocoa_display_cursor(int requested_state);
108 void create_menu(void);
110 struct vo_cocoa_state *vo_cocoa_init_state(void)
112     struct vo_cocoa_state *s = talloc_ptrtype(NULL, s);
113     *s = (struct vo_cocoa_state){
114         .did_resize = NO,
115         .current_video_size = {0,0},
116         .previous_video_size = {0,0},
117         .windowed_mask = NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask,
118         .fullscreen_mask = NSBorderlessWindowMask,
119         .fullscreen_window_level = NSNormalWindowLevel + 1,
120         .windowed_frame = {{0,0},{0,0}},
121         .out_fs_resize = NO,
122         .display_cursor = 1,
123     };
124     return s;
127 static bool supports_hidpi(NSView *view)
129     SEL hdpi_selector = @selector(setWantsBestResolutionOpenGLSurface:);
130     return is_osx_version_at_least(10, 7, 0) && view &&
131            [view respondsToSelector:hdpi_selector];
134 bool vo_cocoa_gui_running(void)
136     return !!s;
139 void *vo_cocoa_glgetaddr(const char *s)
141     void *ret = NULL;
142     void *handle = dlopen(
143         "/System/Library/Frameworks/OpenGL.framework/OpenGL",
144         RTLD_LAZY | RTLD_LOCAL);
145     if (!handle)
146         return NULL;
147     ret = dlsym(handle, s);
148     dlclose(handle);
149     return ret;
152 int vo_cocoa_init(struct vo *vo)
154     s = vo_cocoa_init_state();
155     s->pool = [[NSAutoreleasePool alloc] init];
156     s->cursor_autohide_delay = vo->opts->cursor_autohide_delay;
157     NSApplicationLoad();
158     NSApp = [NSApplication sharedApplication];
159     [NSApp setActivationPolicy: NSApplicationActivationPolicyRegular];
161     return 1;
164 void vo_cocoa_uninit(struct vo *vo)
166     CGDisplayShowCursor(kCGDirectMainDisplay);
167     [NSApp setPresentationOptions:NSApplicationPresentationDefault];
169     [s->window release];
170     s->window = nil;
171     [s->glContext release];
172     s->glContext = nil;
173     [s->pool release];
174     s->pool = nil;
176     talloc_free(s);
177     s = nil;
180 static int current_screen_has_dock_or_menubar(void)
182     NSRect f  = s->screen_frame;
183     NSRect vf = [s->screen_handle visibleFrame];
184     return f.size.height > vf.size.height || f.size.width > vf.size.width;
187 void update_screen_info(void)
189     s->screen_array = [NSScreen screens];
190     if (xinerama_screen >= (int)[s->screen_array count]) {
191         mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
192         xinerama_screen = -1;
193     }
195     if (xinerama_screen < 0) { // default behaviour
196         if (! (s->screen_handle = [s->window screen]) )
197             s->screen_handle = [s->screen_array objectAtIndex:0];
198     } else {
199         s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
200     }
202     s->screen_frame = [s->screen_handle frame];
205 void vo_cocoa_update_xinerama_info(struct vo *vo)
207     update_screen_info();
208     aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
211 int vo_cocoa_change_attributes(struct vo *vo)
213     return 0;
216 void resize_window(struct vo *vo)
218     NSView *view = [s->window contentView];
219     NSRect frame;
221     if (supports_hidpi(view)) {
222         frame = [view convertRectToBacking: [view frame]];
223     } else {
224         frame = [view frame];
225     }
227     vo->dwidth  = frame.size.width;
228     vo->dheight = frame.size.height;
229     [s->glContext update];
232 void vo_set_level(int ontop)
234     if (ontop) {
235         s->windowed_window_level = NSNormalWindowLevel + 1;
236     } else {
237         s->windowed_window_level = NSNormalWindowLevel;
238     }
240     if (!vo_fs)
241         [s->window setLevel:s->windowed_window_level];
244 void vo_cocoa_ontop(struct vo *vo)
246     struct MPOpts *opts = vo->opts;
247     opts->vo_ontop = !opts->vo_ontop;
248     vo_set_level(opts->vo_ontop);
251 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
252                            uint32_t d_height, uint32_t flags)
254     struct MPOpts *opts = vo->opts;
255     if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
256         s->previous_video_size = s->current_video_size;
257     s->current_video_size = NSMakeSize(d_width, d_height);
259     if (!(s->window || s->glContext)) { // keep using the same window
260         s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
261                                              styleMask:s->windowed_mask
262                                              backing:NSBackingStoreBuffered defer:NO];
264         GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
266         // check for HiDPI support and enable it (available on 10.7 +)
267         if (supports_hidpi(glView))
268             [glView setWantsBestResolutionOpenGLSurface:YES];
270         NSOpenGLPixelFormatAttribute attrs[] = {
271             NSOpenGLPFADoubleBuffer, // double buffered
272             (NSOpenGLPixelFormatAttribute)0
273         };
275         s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
276         s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
278         create_menu();
280         [s->window setContentView:glView];
281         [glView release];
282         [s->window setAcceptsMouseMovedEvents:YES];
283         [s->glContext setView:glView];
284         [s->glContext makeCurrentContext];
286         [NSApp setDelegate:s->window];
287         [s->window setDelegate:s->window];
288         [s->window setContentSize:s->current_video_size];
289         [s->window setContentAspectRatio:s->current_video_size];
290         [s->window center];
292         if (flags & VOFLAG_HIDDEN) {
293             [s->window orderOut:nil];
294         } else {
295             [s->window makeKeyAndOrderFront:nil];
296             [NSApp activateIgnoringOtherApps:YES];
297         }
299         if (flags & VOFLAG_FULLSCREEN)
300             vo_cocoa_fullscreen(vo);
302         vo_set_level(opts->vo_ontop);
303     } else {
304         if (s->current_video_size.width  != s->previous_video_size.width ||
305             s->current_video_size.height != s->previous_video_size.height) {
306             if (vo_fs) {
307                 // we will resize as soon as we get out of fullscreen
308                 s->out_fs_resize = YES;
309             } else {
310                 // only if we are not in fullscreen and the video size did change
311                 // we actually resize the window and set a new aspect ratio
312                 [s->window setContentSize:s->current_video_size keepCentered:YES];
313                 [s->window setContentAspectRatio:s->current_video_size];
314             }
315         }
316     }
318     resize_window(vo);
320     if (s->window_title)
321         [s->window_title release];
323     s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
324     [s->window setTitle: s->window_title];
326     return 0;
329 void vo_cocoa_swap_buffers()
331     [s->glContext flushBuffer];
334 void vo_cocoa_display_cursor(int requested_state)
336     if (requested_state) {
337         if (!vo_fs || s->cursor_autohide_delay > -2) {
338             s->display_cursor = requested_state;
339             CGDisplayShowCursor(kCGDirectMainDisplay);
340         }
341     } else {
342         if (s->cursor_autohide_delay != -1) {
343             s->display_cursor = requested_state;
344             CGDisplayHideCursor(kCGDirectMainDisplay);
345         }
346     }
349 int vo_cocoa_check_events(struct vo *vo)
351     NSEvent *event;
352     float curTime = TickCount()/60;
353     int msCurTime = (int) (curTime * 1000);
355     // automatically hide mouse cursor
356     if (vo_fs && s->display_cursor &&
357         (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
358         vo_cocoa_display_cursor(0);
359         s->cursor_timer = msCurTime;
360     }
362     //update activity every 30 seconds to prevent
363     //screensaver from starting up.
364     if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
365     {
366         UpdateSystemActivity(UsrActivity);
367         s->last_screensaver_update = (int)curTime;
368     }
370     event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
371                    inMode:NSEventTrackingRunLoopMode dequeue:YES];
372     if (event == nil)
373         return 0;
374     l_vo = vo;
375     [NSApp sendEvent:event];
377     if (s->did_resize) {
378         s->did_resize = NO;
379         resize_window(vo);
380         return VO_EVENT_RESIZE;
381     }
382     // Without SDL's bootstrap code (include SDL.h in mplayer.c),
383     // on Leopard, we have trouble to get the play window automatically focused
384     // when the app is actived. The Following code fix this problem.
385 #ifndef CONFIG_SDL
386     if ([event type] == NSAppKitDefined
387             && [event subtype] == NSApplicationActivatedEventType) {
388         [s->window makeMainWindow];
389         [s->window makeKeyAndOrderFront:nil];
390     }
391 #endif
392     return 0;
395 void vo_cocoa_fullscreen(struct vo *vo)
397     [s->window fullscreen];
398     resize_window(vo);
401 int vo_cocoa_swap_interval(int enabled)
403     [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
404     return 0;
407 void *vo_cocoa_cgl_context(void)
409     return [s->glContext CGLContextObj];
412 void *vo_cocoa_cgl_pixel_format(void)
414     return [s->pixelFormat CGLPixelFormatObj];
417 static NSMenuItem *new_menu_item(NSMenu *parent_menu, NSString *title,
418                                  SEL action, NSString *key_equivalent)
420     NSMenuItem *new_item = [[NSMenuItem alloc]
421                                 initWithTitle:title
422                                        action:action
423                                 keyEquivalent:key_equivalent];
424     [parent_menu addItem:new_item];
425     return [new_item autorelease];
428 static NSMenuItem *new_main_menu_item(NSMenu *parent_menu, NSMenu *child_menu,
429                                       NSString *title)
431     NSMenuItem *new_item = [[NSMenuItem alloc]
432                                 initWithTitle:title
433                                        action:nil
434                                 keyEquivalent:@""];
435     [new_item setSubmenu:child_menu];
436     [parent_menu addItem:new_item];
437     return [new_item autorelease];
440 void create_menu()
442     NSAutoreleasePool *pool = [NSAutoreleasePool new];
443     NSMenu *main_menu, *m_menu, *w_menu;
444     NSMenuItem *app_menu_item;
446     main_menu = [[NSMenu new] autorelease];
447     app_menu_item = [[NSMenuItem new] autorelease];
448     [main_menu addItem:app_menu_item];
449     [NSApp setMainMenu: main_menu];
451     m_menu = [[[NSMenu alloc] initWithTitle:@"Movie"] autorelease];
452     new_menu_item(m_menu, @"Half Size", @selector(halfSize), @"0");
453     new_menu_item(m_menu, @"Normal Size", @selector(normalSize), @"1");
454     new_menu_item(m_menu, @"Double Size", @selector(doubleSize), @"2");
456     new_main_menu_item(main_menu, m_menu, @"Movie");
458     w_menu = [[[NSMenu alloc] initWithTitle:@"Window"] autorelease];
459     new_menu_item(w_menu, @"Minimize", @selector(performMiniaturize:), @"m");
460     new_menu_item(w_menu, @"Zoom", @selector(performZoom:), @"z");
462     new_main_menu_item(main_menu, w_menu, @"Window");
463     [pool release];
466 @implementation GLMPlayerWindow
468 - (void) windowDidResize:(NSNotification *) notification
470     if (l_vo)
471         s->did_resize = YES;
474 - (void) fullscreen
476     if (!vo_fs) {
477         update_screen_info();
478         if (current_screen_has_dock_or_menubar())
479             [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
480         s->windowed_frame = [self frame];
481         [self setHasShadow:NO];
482         [self setStyleMask:s->fullscreen_mask];
483         [self setFrame:s->screen_frame display:YES animate:NO];
484         [self setLevel:s->fullscreen_window_level];
485         vo_fs = VO_TRUE;
486         vo_cocoa_display_cursor(0);
487         [self setMovableByWindowBackground: NO];
488     } else {
489         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
490         [self setHasShadow:YES];
491         [self setStyleMask:s->windowed_mask];
492         [self setTitle:s->window_title];
493         [self setFrame:s->windowed_frame display:YES animate:NO];
494         if (s->out_fs_resize) {
495             [self setContentSize:s->current_video_size keepCentered:YES];
496             s->out_fs_resize = NO;
497         }
498         [self setContentAspectRatio:s->current_video_size];
499         [self setLevel:s->windowed_window_level];
500         vo_fs = VO_FALSE;
501         vo_cocoa_display_cursor(1);
502         [self setMovableByWindowBackground: YES];
503     }
506 - (BOOL) canBecomeMainWindow { return YES; }
507 - (BOOL) canBecomeKeyWindow { return YES; }
508 - (BOOL) acceptsFirstResponder { return YES; }
509 - (BOOL) becomeFirstResponder { return YES; }
510 - (BOOL) resignFirstResponder { return YES; }
511 - (BOOL) windowShouldClose:(id)sender
513     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
514     // We have to wait for MPlayer to handle this,
515     // otherwise we are in trouble if the
516     // KEY_CLOSE_WIN handler is disabled
517     return NO;
520 - (BOOL) isMovableByWindowBackground
522     // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
523     return !vo_fs;
526 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
528     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
531 - (void) keyDown:(NSEvent *)theEvent
533     unsigned char charcode;
534     if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
535         charcode = *[[theEvent characters] UTF8String];
536     else
537         charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
539     int key = convert_key([theEvent keyCode], charcode);
541     if (key > -1) {
542         if ([theEvent modifierFlags] & NSShiftKeyMask)
543             key |= KEY_MODIFIER_SHIFT;
544         if ([theEvent modifierFlags] & NSControlKeyMask)
545             key |= KEY_MODIFIER_CTRL;
546         if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
547             key |= KEY_MODIFIER_ALT;
548         if ([theEvent modifierFlags] & NSCommandKeyMask)
549             key |= KEY_MODIFIER_META;
550         mplayer_put_key(l_vo->key_fifo, key);
551     }
554 - (void) mouseMoved: (NSEvent *) theEvent
556     if (vo_fs)
557         vo_cocoa_display_cursor(1);
560 - (void) mouseDragged:(NSEvent *)theEvent
562     [self mouseEvent: theEvent];
565 - (void) mouseDown:(NSEvent *)theEvent
567     [self mouseEvent: theEvent];
570 - (void) mouseUp:(NSEvent *)theEvent
572     [self mouseEvent: theEvent];
575 - (void) rightMouseDown:(NSEvent *)theEvent
577     [self mouseEvent: theEvent];
580 - (void) rightMouseUp:(NSEvent *)theEvent
582     [self mouseEvent: theEvent];
585 - (void) otherMouseDown:(NSEvent *)theEvent
587     [self mouseEvent: theEvent];
590 - (void) otherMouseUp:(NSEvent *)theEvent
592     [self mouseEvent: theEvent];
595 - (void) scrollWheel:(NSEvent *)theEvent
597     if ([theEvent deltaY] > 0)
598         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
599     else
600         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
603 - (void) mouseEvent:(NSEvent *)theEvent
605     if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
606         int buttonNumber = [theEvent buttonNumber];
607         // Fix to mplayer defined button order: left, middle, right
608         if (buttonNumber == 1)  buttonNumber = 2;
609         else if (buttonNumber == 2) buttonNumber = 1;
610         switch ([theEvent type]) {
611             case NSLeftMouseDown:
612             case NSRightMouseDown:
613             case NSOtherMouseDown:
614                 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
615                 // Looks like Cocoa doesn't create MouseUp events when we are
616                 // doing the second click in a double click. Put in the key_fifo
617                 // the key that would be put from the MouseUp handling code.
618                 if([theEvent clickCount] == 2)
619                    mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
620                 break;
621             case NSLeftMouseUp:
622             case NSRightMouseUp:
623             case NSOtherMouseUp:
624                 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
625                 break;
626         }
627     }
630 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
632     if (vo_fs) {
633         [s->window makeKeyAndOrderFront:s->window];
634         [s->window setLevel:s->fullscreen_window_level];
635         if (current_screen_has_dock_or_menubar())
636             [NSApp setPresentationOptions:NSApplicationPresentationHideDock|
637                                           NSApplicationPresentationHideMenuBar];
638     }
641 - (void) applicationWillResignActive:(NSNotification *)aNotification
643     if (vo_fs) {
644         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
645         [s->window setLevel:s->windowed_window_level];
646         [s->window orderBack:s->window];
647     }
650 - (void) applicationDidFinishLaunching:(NSNotification*)notification
652     // Install an event handler so the Quit menu entry works
653     // The proper way using NSApp setDelegate: and
654     // applicationShouldTerminate: does not work,
655     // probably NSApplication never installs its handler.
656     [[NSAppleEventManager sharedAppleEventManager]
657         setEventHandler:self
658         andSelector:@selector(handleQuitEvent:withReplyEvent:)
659         forEventClass:kCoreEventClass
660         andEventID:kAEQuitApplication];
663 - (void) normalSize
665     if (!vo_fs)
666       [self setContentSize:s->current_video_size keepCentered:YES];
669 - (void) halfSize { [self mulSize:0.5f];}
671 - (void) doubleSize { [self mulSize:2.0f];}
673 - (void) mulSize:(float)multiplier
675     if (!vo_fs) {
676         NSSize size = [[self contentView] frame].size;
677         size.width  = s->current_video_size.width  * (multiplier);
678         size.height = s->current_video_size.height * (multiplier);
679         [self setContentSize:size keepCentered:YES];
680     }
683 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
685     if (keepCentered) {
686         NSRect nf = [self frame];
687         NSRect vf = [[self screen] visibleFrame];
688         int title_height = nf.size.height - [[self contentView] bounds].size.height;
689         double ratio = (double)ns.width / (double)ns.height;
691         // clip the new size to the visibleFrame's size if needed
692         if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
693             ns = vf.size;
694             ns.height -= title_height; // make space for the title bar
696             if (ns.width > ns.height) {
697                 ns.height = ((double)ns.width * 1/ratio + 0.5);
698             } else {
699                 ns.width = ((double)ns.height * ratio + 0.5);
700             }
701         }
703         int dw = nf.size.width - ns.width;
704         int dh = nf.size.height - ns.height - title_height;
706         nf.origin.x += dw / 2;
707         nf.origin.y += dh / 2;
709         [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
710     } else {
711         [self setContentSize:ns];
712     }
714 @end
716 @implementation GLMPlayerOpenGLView
717 - (void) drawRect: (NSRect)rect
719     [[NSColor clearColor] set];
720     NSRectFill([self bounds]);
722 @end