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);
289 attr[i++] = NSOpenGLPFADoubleBuffer; // double buffered
290 attr[i] = (NSOpenGLPixelFormatAttribute)0;
292 s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attr] autorelease];
293 s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
297 [s->window setContentView:glView];
299 [s->window setAcceptsMouseMovedEvents:YES];
300 [s->glContext setView:glView];
301 [s->glContext makeCurrentContext];
303 [NSApp setDelegate:s->window];
304 [s->window setDelegate:s->window];
305 [s->window setContentSize:s->current_video_size];
306 [s->window setContentAspectRatio:s->current_video_size];
309 if (flags & VOFLAG_HIDDEN) {
310 [s->window orderOut:nil];
312 [s->window makeKeyAndOrderFront:nil];
313 [NSApp activateIgnoringOtherApps:YES];
316 if (flags & VOFLAG_FULLSCREEN)
317 vo_cocoa_fullscreen(vo);
319 vo_set_level(opts->vo_ontop);
321 if (s->current_video_size.width != s->previous_video_size.width ||
322 s->current_video_size.height != s->previous_video_size.height) {
324 // we will resize as soon as we get out of fullscreen
325 s->out_fs_resize = YES;
327 // only if we are not in fullscreen and the video size did change
328 // we actually resize the window and set a new aspect ratio
329 [s->window setContentSize:s->current_video_size keepCentered:YES];
330 [s->window setContentAspectRatio:s->current_video_size];
338 [s->window_title release];
340 s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
341 [s->window setTitle: s->window_title];
346 void vo_cocoa_swap_buffers()
348 [s->glContext flushBuffer];
351 void vo_cocoa_display_cursor(int requested_state)
353 if (requested_state) {
354 if (!vo_fs || s->cursor_autohide_delay > -2) {
355 s->display_cursor = requested_state;
356 CGDisplayShowCursor(kCGDirectMainDisplay);
359 if (s->cursor_autohide_delay != -1) {
360 s->display_cursor = requested_state;
361 CGDisplayHideCursor(kCGDirectMainDisplay);
366 int vo_cocoa_check_events(struct vo *vo)
369 float curTime = TickCount()/60;
370 int msCurTime = (int) (curTime * 1000);
372 // automatically hide mouse cursor
373 if (vo_fs && s->display_cursor &&
374 (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
375 vo_cocoa_display_cursor(0);
376 s->cursor_timer = msCurTime;
379 //update activity every 30 seconds to prevent
380 //screensaver from starting up.
381 if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
383 UpdateSystemActivity(UsrActivity);
384 s->last_screensaver_update = (int)curTime;
387 event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
388 inMode:NSEventTrackingRunLoopMode dequeue:YES];
392 [NSApp sendEvent:event];
397 return VO_EVENT_RESIZE;
399 // Without SDL's bootstrap code (include SDL.h in mplayer.c),
400 // on Leopard, we have trouble to get the play window automatically focused
401 // when the app is actived. The Following code fix this problem.
403 if ([event type] == NSAppKitDefined
404 && [event subtype] == NSApplicationActivatedEventType) {
405 [s->window makeMainWindow];
406 [s->window makeKeyAndOrderFront:nil];
412 void vo_cocoa_fullscreen(struct vo *vo)
414 [s->window fullscreen];
418 int vo_cocoa_swap_interval(int enabled)
420 [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
424 void *vo_cocoa_cgl_context(void)
426 return [s->glContext CGLContextObj];
429 void *vo_cocoa_cgl_pixel_format(void)
431 return [s->pixelFormat CGLPixelFormatObj];
434 static NSMenuItem *new_menu_item(NSMenu *parent_menu, NSString *title,
435 SEL action, NSString *key_equivalent)
437 NSMenuItem *new_item = [[NSMenuItem alloc]
440 keyEquivalent:key_equivalent];
441 [parent_menu addItem:new_item];
442 return [new_item autorelease];
445 static NSMenuItem *new_main_menu_item(NSMenu *parent_menu, NSMenu *child_menu,
448 NSMenuItem *new_item = [[NSMenuItem alloc]
452 [new_item setSubmenu:child_menu];
453 [parent_menu addItem:new_item];
454 return [new_item autorelease];
459 NSAutoreleasePool *pool = [NSAutoreleasePool new];
460 NSMenu *main_menu, *m_menu, *w_menu;
461 NSMenuItem *app_menu_item;
463 main_menu = [[NSMenu new] autorelease];
464 app_menu_item = [[NSMenuItem new] autorelease];
465 [main_menu addItem:app_menu_item];
466 [NSApp setMainMenu: main_menu];
468 m_menu = [[[NSMenu alloc] initWithTitle:@"Movie"] autorelease];
469 new_menu_item(m_menu, @"Half Size", @selector(halfSize), @"0");
470 new_menu_item(m_menu, @"Normal Size", @selector(normalSize), @"1");
471 new_menu_item(m_menu, @"Double Size", @selector(doubleSize), @"2");
473 new_main_menu_item(main_menu, m_menu, @"Movie");
475 w_menu = [[[NSMenu alloc] initWithTitle:@"Window"] autorelease];
476 new_menu_item(w_menu, @"Minimize", @selector(performMiniaturize:), @"m");
477 new_menu_item(w_menu, @"Zoom", @selector(performZoom:), @"z");
479 new_main_menu_item(main_menu, w_menu, @"Window");
483 @implementation GLMPlayerWindow
485 - (void) windowDidResize:(NSNotification *) notification
494 update_screen_info();
495 if (current_screen_has_dock_or_menubar())
496 [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
497 s->windowed_frame = [self frame];
498 [self setHasShadow:NO];
499 [self setStyleMask:s->fullscreen_mask];
500 [self setFrame:s->screen_frame display:YES animate:NO];
501 [self setLevel:s->fullscreen_window_level];
503 vo_cocoa_display_cursor(0);
504 [self setMovableByWindowBackground: NO];
506 [NSApp setPresentationOptions:NSApplicationPresentationDefault];
507 [self setHasShadow:YES];
508 [self setStyleMask:s->windowed_mask];
509 [self setTitle:s->window_title];
510 [self setFrame:s->windowed_frame display:YES animate:NO];
511 if (s->out_fs_resize) {
512 [self setContentSize:s->current_video_size keepCentered:YES];
513 s->out_fs_resize = NO;
515 [self setContentAspectRatio:s->current_video_size];
516 [self setLevel:s->windowed_window_level];
518 vo_cocoa_display_cursor(1);
519 [self setMovableByWindowBackground: YES];
523 - (BOOL) canBecomeMainWindow { return YES; }
524 - (BOOL) canBecomeKeyWindow { return YES; }
525 - (BOOL) acceptsFirstResponder { return YES; }
526 - (BOOL) becomeFirstResponder { return YES; }
527 - (BOOL) resignFirstResponder { return YES; }
528 - (BOOL) windowShouldClose:(id)sender
530 mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
531 // We have to wait for MPlayer to handle this,
532 // otherwise we are in trouble if the
533 // KEY_CLOSE_WIN handler is disabled
537 - (BOOL) isMovableByWindowBackground
539 // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
543 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
545 mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
548 - (void) keyDown:(NSEvent *)theEvent
550 unsigned char charcode;
551 if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
552 charcode = *[[theEvent characters] UTF8String];
554 charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
556 int key = convert_key([theEvent keyCode], charcode);
559 if ([theEvent modifierFlags] & NSShiftKeyMask)
560 key |= KEY_MODIFIER_SHIFT;
561 if ([theEvent modifierFlags] & NSControlKeyMask)
562 key |= KEY_MODIFIER_CTRL;
563 if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
564 key |= KEY_MODIFIER_ALT;
565 if ([theEvent modifierFlags] & NSCommandKeyMask)
566 key |= KEY_MODIFIER_META;
567 mplayer_put_key(l_vo->key_fifo, key);
571 - (void) mouseMoved: (NSEvent *) theEvent
574 vo_cocoa_display_cursor(1);
577 - (void) mouseDragged:(NSEvent *)theEvent
579 [self mouseEvent: theEvent];
582 - (void) mouseDown:(NSEvent *)theEvent
584 [self mouseEvent: theEvent];
587 - (void) mouseUp:(NSEvent *)theEvent
589 [self mouseEvent: theEvent];
592 - (void) rightMouseDown:(NSEvent *)theEvent
594 [self mouseEvent: theEvent];
597 - (void) rightMouseUp:(NSEvent *)theEvent
599 [self mouseEvent: theEvent];
602 - (void) otherMouseDown:(NSEvent *)theEvent
604 [self mouseEvent: theEvent];
607 - (void) otherMouseUp:(NSEvent *)theEvent
609 [self mouseEvent: theEvent];
612 - (void) scrollWheel:(NSEvent *)theEvent
614 if ([theEvent deltaY] > 0)
615 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
617 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
620 - (void) mouseEvent:(NSEvent *)theEvent
622 if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
623 int buttonNumber = [theEvent buttonNumber];
624 // Fix to mplayer defined button order: left, middle, right
625 if (buttonNumber == 1) buttonNumber = 2;
626 else if (buttonNumber == 2) buttonNumber = 1;
627 switch ([theEvent type]) {
628 case NSLeftMouseDown:
629 case NSRightMouseDown:
630 case NSOtherMouseDown:
631 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
632 // Looks like Cocoa doesn't create MouseUp events when we are
633 // doing the second click in a double click. Put in the key_fifo
634 // the key that would be put from the MouseUp handling code.
635 if([theEvent clickCount] == 2)
636 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
641 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
647 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
650 [s->window makeKeyAndOrderFront:s->window];
651 [s->window setLevel:s->fullscreen_window_level];
652 if (current_screen_has_dock_or_menubar())
653 [NSApp setPresentationOptions:NSApplicationPresentationHideDock|
654 NSApplicationPresentationHideMenuBar];
658 - (void) applicationWillResignActive:(NSNotification *)aNotification
661 [NSApp setPresentationOptions:NSApplicationPresentationDefault];
662 [s->window setLevel:s->windowed_window_level];
663 [s->window orderBack:s->window];
667 - (void) applicationDidFinishLaunching:(NSNotification*)notification
669 // Install an event handler so the Quit menu entry works
670 // The proper way using NSApp setDelegate: and
671 // applicationShouldTerminate: does not work,
672 // probably NSApplication never installs its handler.
673 [[NSAppleEventManager sharedAppleEventManager]
675 andSelector:@selector(handleQuitEvent:withReplyEvent:)
676 forEventClass:kCoreEventClass
677 andEventID:kAEQuitApplication];
683 [self setContentSize:s->current_video_size keepCentered:YES];
686 - (void) halfSize { [self mulSize:0.5f];}
688 - (void) doubleSize { [self mulSize:2.0f];}
690 - (void) mulSize:(float)multiplier
693 NSSize size = [[self contentView] frame].size;
694 size.width = s->current_video_size.width * (multiplier);
695 size.height = s->current_video_size.height * (multiplier);
696 [self setContentSize:size keepCentered:YES];
700 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
703 NSRect nf = [self frame];
704 NSRect vf = [[self screen] visibleFrame];
705 int title_height = nf.size.height - [[self contentView] bounds].size.height;
706 double ratio = (double)ns.width / (double)ns.height;
708 // clip the new size to the visibleFrame's size if needed
709 if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
711 ns.height -= title_height; // make space for the title bar
713 if (ns.width > ns.height) {
714 ns.height = ((double)ns.width * 1/ratio + 0.5);
716 ns.width = ((double)ns.height * ratio + 0.5);
720 int dw = nf.size.width - ns.width;
721 int dh = nf.size.height - ns.height - title_height;
723 nf.origin.x += dw / 2;
724 nf.origin.y += dh / 2;
726 [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
728 [self setContentSize:ns];
733 @implementation GLMPlayerOpenGLView
734 - (void) drawRect: (NSRect)rect
736 [[NSColor clearColor] set];
737 NSRectFill([self bounds]);