4 * This file is part of mplayer2.
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.
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.
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/>.
20 #import <Cocoa/Cocoa.h>
21 #import <OpenGL/OpenGL.h>
22 #import <QuartzCore/QuartzCore.h>
23 #import <CoreServices/CoreServices.h> // for CGDisplayHideCursor and Gestalt
26 #include "cocoa_common.h"
31 #include "video_out.h"
37 #include "input/input.h"
38 #include "input/keycodes.h"
39 #include "osx_common.h"
42 #ifndef NSOpenGLPFAOpenGLProfile
43 #define NSOpenGLPFAOpenGLProfile 99
46 #ifndef NSOpenGLProfileVersionLegacy
47 #define NSOpenGLProfileVersionLegacy 0x1000
50 #ifndef NSOpenGLProfileVersion3_2Core
51 #define NSOpenGLProfileVersion3_2Core 0x3200
54 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
55 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
57 // add methods not available on OSX versions prior to 10.7
58 #ifndef MAC_OS_X_VERSION_10_7
59 @interface NSView (IntroducedInLion)
60 - (NSRect)convertRectToBacking:(NSRect)aRect;
61 - (void)setWantsBestResolutionOpenGLSurface:(BOOL)aBool;
65 @interface GLMPlayerWindow : NSWindow <NSWindowDelegate>
66 - (BOOL) canBecomeKeyWindow;
67 - (BOOL) canBecomeMainWindow;
69 - (void) mouseEvent:(NSEvent *)theEvent;
70 - (void) mulSize:(float)multiplier;
71 - (void) setContentSize:(NSSize)newSize keepCentered:(BOOL)keepCentered;
74 @interface GLMPlayerOpenGLView : NSView
77 struct vo_cocoa_state {
78 NSAutoreleasePool *pool;
79 GLMPlayerWindow *window;
80 NSOpenGLContext *glContext;
81 NSOpenGLPixelFormat *pixelFormat;
83 NSSize current_video_size;
84 NSSize previous_video_size;
87 NSScreen *screen_handle;
88 NSArray *screen_array;
90 NSInteger windowed_mask;
91 NSInteger fullscreen_mask;
93 NSRect windowed_frame;
95 NSString *window_title;
97 NSInteger windowed_window_level;
98 NSInteger fullscreen_window_level;
100 int last_screensaver_update;
104 int cursor_autohide_delay;
110 struct vo_cocoa_state *s;
114 // local function definitions
115 struct vo_cocoa_state *vo_cocoa_init_state(void);
116 void vo_set_level(int ontop);
117 void update_screen_info(void);
118 void resize_window(struct vo *vo);
119 void vo_cocoa_display_cursor(int requested_state);
120 void create_menu(void);
122 struct vo_cocoa_state *vo_cocoa_init_state(void)
124 struct vo_cocoa_state *s = talloc_ptrtype(NULL, s);
125 *s = (struct vo_cocoa_state){
127 .current_video_size = {0,0},
128 .previous_video_size = {0,0},
129 .windowed_mask = NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask,
130 .fullscreen_mask = NSBorderlessWindowMask,
131 .fullscreen_window_level = NSNormalWindowLevel + 1,
132 .windowed_frame = {{0,0},{0,0}},
139 static bool supports_hidpi(NSView *view)
141 SEL hdpi_selector = @selector(setWantsBestResolutionOpenGLSurface:);
142 return is_osx_version_at_least(10, 7, 0) && view &&
143 [view respondsToSelector:hdpi_selector];
146 bool vo_cocoa_gui_running(void)
151 void *vo_cocoa_glgetaddr(const char *s)
154 void *handle = dlopen(
155 "/System/Library/Frameworks/OpenGL.framework/OpenGL",
156 RTLD_LAZY | RTLD_LOCAL);
159 ret = dlsym(handle, s);
164 int vo_cocoa_init(struct vo *vo)
166 s = vo_cocoa_init_state();
167 s->pool = [[NSAutoreleasePool alloc] init];
168 s->cursor_autohide_delay = vo->opts->cursor_autohide_delay;
170 NSApp = [NSApplication sharedApplication];
171 [NSApp setActivationPolicy: NSApplicationActivationPolicyRegular];
176 void vo_cocoa_uninit(struct vo *vo)
178 CGDisplayShowCursor(kCGDirectMainDisplay);
179 [NSApp setPresentationOptions:NSApplicationPresentationDefault];
183 [s->glContext release];
192 static int current_screen_has_dock_or_menubar(void)
194 NSRect f = s->screen_frame;
195 NSRect vf = [s->screen_handle visibleFrame];
196 return f.size.height > vf.size.height || f.size.width > vf.size.width;
199 void update_screen_info(void)
201 s->screen_array = [NSScreen screens];
202 if (xinerama_screen >= (int)[s->screen_array count]) {
203 mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
204 xinerama_screen = -1;
207 if (xinerama_screen < 0) { // default behaviour
208 if (! (s->screen_handle = [s->window screen]) )
209 s->screen_handle = [s->screen_array objectAtIndex:0];
211 s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
214 s->screen_frame = [s->screen_handle frame];
217 void vo_cocoa_update_xinerama_info(struct vo *vo)
219 update_screen_info();
220 aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
223 int vo_cocoa_change_attributes(struct vo *vo)
228 void resize_window(struct vo *vo)
230 NSView *view = [s->window contentView];
233 if (supports_hidpi(view)) {
234 frame = [view convertRectToBacking: [view frame]];
236 frame = [view frame];
239 vo->dwidth = frame.size.width;
240 vo->dheight = frame.size.height;
241 [s->glContext update];
244 void vo_set_level(int ontop)
247 s->windowed_window_level = NSNormalWindowLevel + 1;
249 s->windowed_window_level = NSNormalWindowLevel;
253 [s->window setLevel:s->windowed_window_level];
256 void vo_cocoa_ontop(struct vo *vo)
258 struct MPOpts *opts = vo->opts;
259 opts->vo_ontop = !opts->vo_ontop;
260 vo_set_level(opts->vo_ontop);
263 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
264 uint32_t d_height, uint32_t flags,
267 struct MPOpts *opts = vo->opts;
268 if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
269 s->previous_video_size = s->current_video_size;
270 s->current_video_size = NSMakeSize(d_width, d_height);
272 if (!(s->window || s->glContext)) { // keep using the same window
273 s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
274 styleMask:s->windowed_mask
275 backing:NSBackingStoreBuffered defer:NO];
277 GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
279 // check for HiDPI support and enable it (available on 10.7 +)
280 if (supports_hidpi(glView))
281 [glView setWantsBestResolutionOpenGLSurface:YES];
284 NSOpenGLPixelFormatAttribute attr[32];
285 if (is_osx_version_at_least(10, 7, 0)) {
286 attr[i++] = NSOpenGLPFAOpenGLProfile;
287 attr[i++] = (gl3profile ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy);
288 } else if(gl3profile) {
289 mp_msg(MSGT_VO, MSGL_ERR,
290 "[cocoa] Invalid pixel format attribute "
291 "(GL3 is not supported on OSX versions prior to 10.7)\n");
294 attr[i++] = NSOpenGLPFADoubleBuffer; // double buffered
295 attr[i] = (NSOpenGLPixelFormatAttribute)0;
297 s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attr] autorelease];
298 if (!s->pixelFormat) {
299 mp_msg(MSGT_VO, MSGL_ERR,
300 "[cocoa] Invalid pixel format attribute "
301 "(GL3 not supported?)\n");
304 s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
308 [s->window setContentView:glView];
310 [s->window setAcceptsMouseMovedEvents:YES];
311 [s->glContext setView:glView];
312 [s->glContext makeCurrentContext];
314 [NSApp setDelegate:s->window];
315 [s->window setDelegate:s->window];
316 [s->window setContentSize:s->current_video_size];
317 [s->window setContentAspectRatio:s->current_video_size];
320 if (flags & VOFLAG_HIDDEN) {
321 [s->window orderOut:nil];
323 [s->window makeKeyAndOrderFront:nil];
324 [NSApp activateIgnoringOtherApps:YES];
327 if (flags & VOFLAG_FULLSCREEN)
328 vo_cocoa_fullscreen(vo);
330 vo_set_level(opts->vo_ontop);
332 if (s->current_video_size.width != s->previous_video_size.width ||
333 s->current_video_size.height != s->previous_video_size.height) {
335 // we will resize as soon as we get out of fullscreen
336 s->out_fs_resize = YES;
338 // only if we are not in fullscreen and the video size did change
339 // we actually resize the window and set a new aspect ratio
340 [s->window setContentSize:s->current_video_size keepCentered:YES];
341 [s->window setContentAspectRatio:s->current_video_size];
349 [s->window_title release];
351 s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
352 [s->window setTitle: s->window_title];
357 void vo_cocoa_swap_buffers()
359 [s->glContext flushBuffer];
362 void vo_cocoa_display_cursor(int requested_state)
364 if (requested_state) {
365 if (!vo_fs || s->cursor_autohide_delay > -2) {
366 s->display_cursor = requested_state;
367 CGDisplayShowCursor(kCGDirectMainDisplay);
370 if (s->cursor_autohide_delay != -1) {
371 s->display_cursor = requested_state;
372 CGDisplayHideCursor(kCGDirectMainDisplay);
377 int vo_cocoa_check_events(struct vo *vo)
380 float curTime = TickCount()/60;
381 int msCurTime = (int) (curTime * 1000);
383 // automatically hide mouse cursor
384 if (vo_fs && s->display_cursor &&
385 (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
386 vo_cocoa_display_cursor(0);
387 s->cursor_timer = msCurTime;
390 //update activity every 30 seconds to prevent
391 //screensaver from starting up.
392 if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
394 UpdateSystemActivity(UsrActivity);
395 s->last_screensaver_update = (int)curTime;
398 event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
399 inMode:NSEventTrackingRunLoopMode dequeue:YES];
403 [NSApp sendEvent:event];
408 return VO_EVENT_RESIZE;
410 // Without SDL's bootstrap code (include SDL.h in mplayer.c),
411 // on Leopard, we have trouble to get the play window automatically focused
412 // when the app is actived. The Following code fix this problem.
414 if ([event type] == NSAppKitDefined
415 && [event subtype] == NSApplicationActivatedEventType) {
416 [s->window makeMainWindow];
417 [s->window makeKeyAndOrderFront:nil];
423 void vo_cocoa_fullscreen(struct vo *vo)
425 [s->window fullscreen];
429 int vo_cocoa_swap_interval(int enabled)
431 [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
435 void *vo_cocoa_cgl_context(void)
437 return [s->glContext CGLContextObj];
440 void *vo_cocoa_cgl_pixel_format(void)
442 return CGLGetPixelFormat(vo_cocoa_cgl_context());
445 int vo_cocoa_cgl_color_size(void)
448 CGLDescribePixelFormat(vo_cocoa_cgl_pixel_format(), 0,
449 kCGLPFAColorSize, &value);
461 static NSMenuItem *new_menu_item(NSMenu *parent_menu, NSString *title,
462 SEL action, NSString *key_equivalent)
464 NSMenuItem *new_item = [[NSMenuItem alloc]
467 keyEquivalent:key_equivalent];
468 [parent_menu addItem:new_item];
469 return [new_item autorelease];
472 static NSMenuItem *new_main_menu_item(NSMenu *parent_menu, NSMenu *child_menu,
475 NSMenuItem *new_item = [[NSMenuItem alloc]
479 [new_item setSubmenu:child_menu];
480 [parent_menu addItem:new_item];
481 return [new_item autorelease];
486 NSAutoreleasePool *pool = [NSAutoreleasePool new];
487 NSMenu *main_menu, *m_menu, *w_menu;
488 NSMenuItem *app_menu_item;
490 main_menu = [[NSMenu new] autorelease];
491 app_menu_item = [[NSMenuItem new] autorelease];
492 [main_menu addItem:app_menu_item];
493 [NSApp setMainMenu: main_menu];
495 m_menu = [[[NSMenu alloc] initWithTitle:@"Movie"] autorelease];
496 new_menu_item(m_menu, @"Half Size", @selector(halfSize), @"0");
497 new_menu_item(m_menu, @"Normal Size", @selector(normalSize), @"1");
498 new_menu_item(m_menu, @"Double Size", @selector(doubleSize), @"2");
500 new_main_menu_item(main_menu, m_menu, @"Movie");
502 w_menu = [[[NSMenu alloc] initWithTitle:@"Window"] autorelease];
503 new_menu_item(w_menu, @"Minimize", @selector(performMiniaturize:), @"m");
504 new_menu_item(w_menu, @"Zoom", @selector(performZoom:), @"z");
506 new_main_menu_item(main_menu, w_menu, @"Window");
510 @implementation GLMPlayerWindow
512 - (void) windowDidResize:(NSNotification *) notification
521 update_screen_info();
522 if (current_screen_has_dock_or_menubar())
523 [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
524 s->windowed_frame = [self frame];
525 [self setHasShadow:NO];
526 [self setStyleMask:s->fullscreen_mask];
527 [self setFrame:s->screen_frame display:YES animate:NO];
528 [self setLevel:s->fullscreen_window_level];
530 vo_cocoa_display_cursor(0);
531 [self setMovableByWindowBackground: NO];
533 [NSApp setPresentationOptions:NSApplicationPresentationDefault];
534 [self setHasShadow:YES];
535 [self setStyleMask:s->windowed_mask];
536 [self setTitle:s->window_title];
537 [self setFrame:s->windowed_frame display:YES animate:NO];
538 if (s->out_fs_resize) {
539 [self setContentSize:s->current_video_size keepCentered:YES];
540 s->out_fs_resize = NO;
542 [self setContentAspectRatio:s->current_video_size];
543 [self setLevel:s->windowed_window_level];
545 vo_cocoa_display_cursor(1);
546 [self setMovableByWindowBackground: YES];
550 - (BOOL) canBecomeMainWindow { return YES; }
551 - (BOOL) canBecomeKeyWindow { return YES; }
552 - (BOOL) acceptsFirstResponder { return YES; }
553 - (BOOL) becomeFirstResponder { return YES; }
554 - (BOOL) resignFirstResponder { return YES; }
555 - (BOOL) windowShouldClose:(id)sender
557 mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
558 // We have to wait for MPlayer to handle this,
559 // otherwise we are in trouble if the
560 // KEY_CLOSE_WIN handler is disabled
564 - (BOOL) isMovableByWindowBackground
566 // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
570 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
572 mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
575 - (void) keyDown:(NSEvent *)theEvent
577 unsigned char charcode;
578 if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
579 charcode = *[[theEvent characters] UTF8String];
581 charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
583 int key = convert_key([theEvent keyCode], charcode);
586 if ([theEvent modifierFlags] & NSShiftKeyMask)
587 key |= KEY_MODIFIER_SHIFT;
588 if ([theEvent modifierFlags] & NSControlKeyMask)
589 key |= KEY_MODIFIER_CTRL;
590 if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
591 key |= KEY_MODIFIER_ALT;
592 if ([theEvent modifierFlags] & NSCommandKeyMask)
593 key |= KEY_MODIFIER_META;
594 mplayer_put_key(l_vo->key_fifo, key);
598 - (void) mouseMoved: (NSEvent *) theEvent
601 vo_cocoa_display_cursor(1);
604 - (void) mouseDragged:(NSEvent *)theEvent
606 [self mouseEvent: theEvent];
609 - (void) mouseDown:(NSEvent *)theEvent
611 [self mouseEvent: theEvent];
614 - (void) mouseUp:(NSEvent *)theEvent
616 [self mouseEvent: theEvent];
619 - (void) rightMouseDown:(NSEvent *)theEvent
621 [self mouseEvent: theEvent];
624 - (void) rightMouseUp:(NSEvent *)theEvent
626 [self mouseEvent: theEvent];
629 - (void) otherMouseDown:(NSEvent *)theEvent
631 [self mouseEvent: theEvent];
634 - (void) otherMouseUp:(NSEvent *)theEvent
636 [self mouseEvent: theEvent];
639 - (void) scrollWheel:(NSEvent *)theEvent
641 if ([theEvent deltaY] > 0)
642 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
644 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
647 - (void) mouseEvent:(NSEvent *)theEvent
649 if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
650 int buttonNumber = [theEvent buttonNumber];
651 // Fix to mplayer defined button order: left, middle, right
652 if (buttonNumber == 1) buttonNumber = 2;
653 else if (buttonNumber == 2) buttonNumber = 1;
654 switch ([theEvent type]) {
655 case NSLeftMouseDown:
656 case NSRightMouseDown:
657 case NSOtherMouseDown:
658 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
659 // Looks like Cocoa doesn't create MouseUp events when we are
660 // doing the second click in a double click. Put in the key_fifo
661 // the key that would be put from the MouseUp handling code.
662 if([theEvent clickCount] == 2)
663 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
668 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
674 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
677 [s->window makeKeyAndOrderFront:s->window];
678 [s->window setLevel:s->fullscreen_window_level];
679 if (current_screen_has_dock_or_menubar())
680 [NSApp setPresentationOptions:NSApplicationPresentationHideDock|
681 NSApplicationPresentationHideMenuBar];
685 - (void) applicationWillResignActive:(NSNotification *)aNotification
688 [NSApp setPresentationOptions:NSApplicationPresentationDefault];
689 [s->window setLevel:s->windowed_window_level];
690 [s->window orderBack:s->window];
694 - (void) applicationDidFinishLaunching:(NSNotification*)notification
696 // Install an event handler so the Quit menu entry works
697 // The proper way using NSApp setDelegate: and
698 // applicationShouldTerminate: does not work,
699 // probably NSApplication never installs its handler.
700 [[NSAppleEventManager sharedAppleEventManager]
702 andSelector:@selector(handleQuitEvent:withReplyEvent:)
703 forEventClass:kCoreEventClass
704 andEventID:kAEQuitApplication];
710 [self setContentSize:s->current_video_size keepCentered:YES];
713 - (void) halfSize { [self mulSize:0.5f];}
715 - (void) doubleSize { [self mulSize:2.0f];}
717 - (void) mulSize:(float)multiplier
720 NSSize size = [[self contentView] frame].size;
721 size.width = s->current_video_size.width * (multiplier);
722 size.height = s->current_video_size.height * (multiplier);
723 [self setContentSize:size keepCentered:YES];
727 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
730 NSRect nf = [self frame];
731 NSRect vf = [[self screen] visibleFrame];
732 int title_height = nf.size.height - [[self contentView] bounds].size.height;
733 double ratio = (double)ns.width / (double)ns.height;
735 // clip the new size to the visibleFrame's size if needed
736 if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
738 ns.height -= title_height; // make space for the title bar
740 if (ns.width > ns.height) {
741 ns.height = ((double)ns.width * 1/ratio + 0.5);
743 ns.width = ((double)ns.height * ratio + 0.5);
747 int dw = nf.size.width - ns.width;
748 int dh = nf.size.height - ns.height - title_height;
750 nf.origin.x += dw / 2;
751 nf.origin.y += dh / 2;
753 [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
755 [self setContentSize:ns];
760 @implementation GLMPlayerOpenGLView
761 - (void) drawRect: (NSRect)rect
763 [[NSColor clearColor] set];
764 NSRectFill([self bounds]);