cocoa_common: refactor menu generation
[mplayer.git] / libvo / cocoa_common.m
blob556466fce3e3f39fe219f572401449dd94c94649
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 static int current_screen_has_dock_or_menubar(void)
165     NSRect f  = s->screen_frame;
166     NSRect vf = [s->screen_handle visibleFrame];
167     return f.size.height > vf.size.height || f.size.width > vf.size.width;
170 void update_screen_info(void)
172     s->screen_array = [NSScreen screens];
173     if (xinerama_screen >= (int)[s->screen_array count]) {
174         mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
175         xinerama_screen = -1;
176     }
178     if (xinerama_screen < 0) { // default behaviour
179         if (! (s->screen_handle = [s->window screen]) )
180             s->screen_handle = [s->screen_array objectAtIndex:0];
181     } else {
182         s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
183     }
185     s->screen_frame = [s->screen_handle frame];
188 void vo_cocoa_update_xinerama_info(struct vo *vo)
190     update_screen_info();
191     aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
194 int vo_cocoa_change_attributes(struct vo *vo)
196     return 0;
199 void resize_window(struct vo *vo)
201     vo->dwidth = [[s->window contentView] frame].size.width;
202     vo->dheight = [[s->window contentView] frame].size.height;
203     [s->glContext update];
206 void vo_set_level(int ontop)
208     if (ontop) {
209         s->windowed_window_level = NSNormalWindowLevel + 1;
210     } else {
211         s->windowed_window_level = NSNormalWindowLevel;
212     }
214     if (!vo_fs)
215         [s->window setLevel:s->windowed_window_level];
218 void vo_cocoa_ontop(struct vo *vo)
220     struct MPOpts *opts = vo->opts;
221     opts->vo_ontop = !opts->vo_ontop;
222     vo_set_level(opts->vo_ontop);
225 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
226                            uint32_t d_height, uint32_t flags)
228     struct MPOpts *opts = vo->opts;
229     if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
230         s->previous_video_size = s->current_video_size;
231     s->current_video_size = NSMakeSize(d_width, d_height);
233     if (!(s->window || s->glContext)) { // keep using the same window
234         s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
235                                              styleMask:s->windowed_mask
236                                              backing:NSBackingStoreBuffered defer:NO];
238         GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
240         NSOpenGLPixelFormatAttribute attrs[] = {
241             NSOpenGLPFADoubleBuffer, // double buffered
242             NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)16, // 16 bit depth buffer
243             (NSOpenGLPixelFormatAttribute)0
244         };
246         s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
247         s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
249         create_menu();
251         [s->window setContentView:glView];
252         [glView release];
253         [s->window setAcceptsMouseMovedEvents:YES];
254         [s->glContext setView:glView];
255         [s->glContext makeCurrentContext];
257         [NSApp setDelegate:s->window];
258         [s->window setDelegate:s->window];
259         [s->window setContentSize:s->current_video_size];
260         [s->window setContentAspectRatio:s->current_video_size];
261         [s->window center];
263         if (flags & VOFLAG_HIDDEN) {
264             [s->window orderOut:nil];
265         } else {
266             [s->window makeKeyAndOrderFront:nil];
267             [NSApp activateIgnoringOtherApps:YES];
268         }
270         if (flags & VOFLAG_FULLSCREEN)
271             vo_cocoa_fullscreen(vo);
273         vo_set_level(opts->vo_ontop);
274     } else {
275         if (s->current_video_size.width  != s->previous_video_size.width ||
276             s->current_video_size.height != s->previous_video_size.height) {
277             if (vo_fs) {
278                 // we will resize as soon as we get out of fullscreen
279                 s->out_fs_resize = YES;
280             } else {
281                 // only if we are not in fullscreen and the video size did change
282                 // we actually resize the window and set a new aspect ratio
283                 [s->window setContentSize:s->current_video_size keepCentered:YES];
284                 [s->window setContentAspectRatio:s->current_video_size];
285             }
286         }
287     }
289     resize_window(vo);
291     if (s->window_title)
292         [s->window_title release];
294     s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
295     [s->window setTitle: s->window_title];
297     return 0;
300 void vo_cocoa_swap_buffers()
302     [s->glContext flushBuffer];
305 void vo_cocoa_display_cursor(int requested_state)
307     if (requested_state) {
308         if (!vo_fs || s->cursor_autohide_delay > -2) {
309             s->display_cursor = requested_state;
310             CGDisplayShowCursor(kCGDirectMainDisplay);
311         }
312     } else {
313         if (s->cursor_autohide_delay != -1) {
314             s->display_cursor = requested_state;
315             CGDisplayHideCursor(kCGDirectMainDisplay);
316         }
317     }
320 int vo_cocoa_check_events(struct vo *vo)
322     NSEvent *event;
323     float curTime = TickCount()/60;
324     int msCurTime = (int) (curTime * 1000);
326     // automatically hide mouse cursor
327     if (vo_fs && s->display_cursor &&
328         (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
329         vo_cocoa_display_cursor(0);
330         s->cursor_timer = msCurTime;
331     }
333     //update activity every 30 seconds to prevent
334     //screensaver from starting up.
335     if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
336     {
337         UpdateSystemActivity(UsrActivity);
338         s->last_screensaver_update = (int)curTime;
339     }
341     event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
342                    inMode:NSEventTrackingRunLoopMode dequeue:YES];
343     if (event == nil)
344         return 0;
345     l_vo = vo;
346     [NSApp sendEvent:event];
348     if (s->did_resize) {
349         s->did_resize = NO;
350         resize_window(vo);
351         return VO_EVENT_RESIZE;
352     }
353     // Without SDL's bootstrap code (include SDL.h in mplayer.c),
354     // on Leopard, we have trouble to get the play window automatically focused
355     // when the app is actived. The Following code fix this problem.
356 #ifndef CONFIG_SDL
357     if ([event type] == NSAppKitDefined
358             && [event subtype] == NSApplicationActivatedEventType) {
359         [s->window makeMainWindow];
360         [s->window makeKeyAndOrderFront:nil];
361     }
362 #endif
363     return 0;
366 void vo_cocoa_fullscreen(struct vo *vo)
368     [s->window fullscreen];
369     resize_window(vo);
372 int vo_cocoa_swap_interval(int enabled)
374     [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
375     return 0;
378 void *vo_cocoa_cgl_context(void)
380     return [s->glContext CGLContextObj];
383 void *vo_cocoa_cgl_pixel_format(void)
385     return [s->pixelFormat CGLPixelFormatObj];
388 static NSMenuItem *new_menu_item(NSMenu *parent_menu, NSString *title,
389                                  SEL action, NSString *key_equivalent)
391     NSMenuItem *new_item = [[NSMenuItem alloc]
392                                 initWithTitle:title
393                                        action:action
394                                 keyEquivalent:key_equivalent];
395     [parent_menu addItem:new_item];
396     return [new_item autorelease];
399 static NSMenuItem *new_main_menu_item(NSMenu *parent_menu, NSMenu *child_menu,
400                                       NSString *title)
402     NSMenuItem *new_item = [[NSMenuItem alloc]
403                                 initWithTitle:title
404                                        action:nil
405                                 keyEquivalent:@""];
406     [new_item setSubmenu:child_menu];
407     [parent_menu addItem:new_item];
408     return [new_item autorelease];
411 void create_menu()
413     NSAutoreleasePool *pool = [NSAutoreleasePool new];
414     NSMenu *main_menu, *m_menu, *w_menu;
415     NSMenuItem *app_menu_item;
417     main_menu = [[NSMenu new] autorelease];
418     app_menu_item = [[NSMenuItem new] autorelease];
419     [main_menu addItem:app_menu_item];
420     [NSApp setMainMenu: main_menu];
422     m_menu = [[[NSMenu alloc] initWithTitle:@"Movie"] autorelease];
423     new_menu_item(m_menu, @"Half Size", @selector(halfSize), @"0");
424     new_menu_item(m_menu, @"Normal Size", @selector(normalSize), @"1");
425     new_menu_item(m_menu, @"Double Size", @selector(doubleSize), @"2");
427     new_main_menu_item(main_menu, m_menu, @"Movie");
429     w_menu = [[[NSMenu alloc] initWithTitle:@"Window"] autorelease];
430     new_menu_item(w_menu, @"Minimize", @selector(performMiniaturize:), @"m");
431     new_menu_item(w_menu, @"Zoom", @selector(performZoom:), @"z");
433     new_main_menu_item(main_menu, w_menu, @"Window");
434     [pool release];
437 @implementation GLMPlayerWindow
439 - (void) windowDidResize:(NSNotification *) notification
441     if (l_vo)
442         s->did_resize = YES;
445 - (void) fullscreen
447     if (!vo_fs) {
448         update_screen_info();
449         if (current_screen_has_dock_or_menubar())
450             [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
451         s->windowed_frame = [self frame];
452         [self setHasShadow:NO];
453         [self setStyleMask:s->fullscreen_mask];
454         [self setFrame:s->screen_frame display:YES animate:NO];
455         [self setLevel:s->fullscreen_window_level];
456         vo_fs = VO_TRUE;
457         vo_cocoa_display_cursor(0);
458         [self setMovableByWindowBackground: NO];
459     } else {
460         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
461         [self setHasShadow:YES];
462         [self setStyleMask:s->windowed_mask];
463         [self setTitle:s->window_title];
464         [self setFrame:s->windowed_frame display:YES animate:NO];
465         if (s->out_fs_resize) {
466             [self setContentSize:s->current_video_size keepCentered:YES];
467             s->out_fs_resize = NO;
468         }
469         [self setContentAspectRatio:s->current_video_size];
470         [self setLevel:s->windowed_window_level];
471         vo_fs = VO_FALSE;
472         vo_cocoa_display_cursor(1);
473         [self setMovableByWindowBackground: YES];
474     }
477 - (BOOL) canBecomeMainWindow { return YES; }
478 - (BOOL) canBecomeKeyWindow { return YES; }
479 - (BOOL) acceptsFirstResponder { return YES; }
480 - (BOOL) becomeFirstResponder { return YES; }
481 - (BOOL) resignFirstResponder { return YES; }
482 - (BOOL) windowShouldClose:(id)sender
484     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
485     // We have to wait for MPlayer to handle this,
486     // otherwise we are in trouble if the
487     // KEY_CLOSE_WIN handler is disabled
488     return NO;
491 - (BOOL) isMovableByWindowBackground
493     // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
494     return !vo_fs;
497 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
499     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
502 - (void) keyDown:(NSEvent *)theEvent
504     unsigned char charcode;
505     if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
506         charcode = *[[theEvent characters] UTF8String];
507     else
508         charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
510     int key = convert_key([theEvent keyCode], charcode);
512     if (key > -1) {
513         if ([theEvent modifierFlags] & NSShiftKeyMask)
514             key |= KEY_MODIFIER_SHIFT;
515         if ([theEvent modifierFlags] & NSControlKeyMask)
516             key |= KEY_MODIFIER_CTRL;
517         if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
518             key |= KEY_MODIFIER_ALT;
519         if ([theEvent modifierFlags] & NSCommandKeyMask)
520             key |= KEY_MODIFIER_META;
521         mplayer_put_key(l_vo->key_fifo, key);
522     }
525 - (void) mouseMoved: (NSEvent *) theEvent
527     if (vo_fs)
528         vo_cocoa_display_cursor(1);
531 - (void) mouseDragged:(NSEvent *)theEvent
533     [self mouseEvent: theEvent];
536 - (void) mouseDown:(NSEvent *)theEvent
538     [self mouseEvent: theEvent];
541 - (void) mouseUp:(NSEvent *)theEvent
543     [self mouseEvent: theEvent];
546 - (void) rightMouseDown:(NSEvent *)theEvent
548     [self mouseEvent: theEvent];
551 - (void) rightMouseUp:(NSEvent *)theEvent
553     [self mouseEvent: theEvent];
556 - (void) otherMouseDown:(NSEvent *)theEvent
558     [self mouseEvent: theEvent];
561 - (void) otherMouseUp:(NSEvent *)theEvent
563     [self mouseEvent: theEvent];
566 - (void) scrollWheel:(NSEvent *)theEvent
568     if ([theEvent deltaY] > 0)
569         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
570     else
571         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
574 - (void) mouseEvent:(NSEvent *)theEvent
576     if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
577         int buttonNumber = [theEvent buttonNumber];
578         // Fix to mplayer defined button order: left, middle, right
579         if (buttonNumber == 1)  buttonNumber = 2;
580         else if (buttonNumber == 2) buttonNumber = 1;
581         switch ([theEvent type]) {
582             case NSLeftMouseDown:
583             case NSRightMouseDown:
584             case NSOtherMouseDown:
585                 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
586                 // Looks like Cocoa doesn't create MouseUp events when we are
587                 // doing the second click in a double click. Put in the key_fifo
588                 // the key that would be put from the MouseUp handling code.
589                 if([theEvent clickCount] == 2)
590                    mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
591                 break;
592             case NSLeftMouseUp:
593             case NSRightMouseUp:
594             case NSOtherMouseUp:
595                 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
596                 break;
597         }
598     }
601 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
603     if (vo_fs) {
604         [s->window makeKeyAndOrderFront:s->window];
605         [s->window setLevel:s->fullscreen_window_level];
606         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|
607                                       NSApplicationPresentationHideMenuBar];
608     }
611 - (void) applicationWillResignActive:(NSNotification *)aNotification
613     if (vo_fs) {
614         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
615         [s->window setLevel:s->windowed_window_level];
616         [s->window orderBack:s->window];
617     }
620 - (void) applicationDidFinishLaunching:(NSNotification*)notification
622     // Install an event handler so the Quit menu entry works
623     // The proper way using NSApp setDelegate: and
624     // applicationShouldTerminate: does not work,
625     // probably NSApplication never installs its handler.
626     [[NSAppleEventManager sharedAppleEventManager]
627         setEventHandler:self
628         andSelector:@selector(handleQuitEvent:withReplyEvent:)
629         forEventClass:kCoreEventClass
630         andEventID:kAEQuitApplication];
633 - (void) normalSize
635     if (!vo_fs)
636       [self setContentSize:s->current_video_size keepCentered:YES];
639 - (void) halfSize { [self mulSize:0.5f];}
641 - (void) doubleSize { [self mulSize:2.0f];}
643 - (void) mulSize:(float)multiplier
645     if (!vo_fs) {
646         NSSize size = [[self contentView] frame].size;
647         size.width  = s->current_video_size.width  * (multiplier);
648         size.height = s->current_video_size.height * (multiplier);
649         [self setContentSize:size keepCentered:YES];
650     }
653 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
655     if (keepCentered) {
656         NSRect nf = [self frame];
657         NSRect vf = [[self screen] visibleFrame];
658         int title_height = nf.size.height - [[self contentView] bounds].size.height;
659         double ratio = (double)ns.width / (double)ns.height;
661         // clip the new size to the visibleFrame's size if needed
662         if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
663             ns = vf.size;
664             ns.height -= title_height; // make space for the title bar
666             if (ns.width > ns.height) {
667                 ns.height = ((double)ns.width * 1/ratio + 0.5);
668             } else {
669                 ns.width = ((double)ns.height * ratio + 0.5);
670             }
671         }
673         int dw = nf.size.width - ns.width;
674         int dh = nf.size.height - ns.height - title_height;
676         nf.origin.x += dw / 2;
677         nf.origin.y += dh / 2;
679         [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
680     } else {
681         [self setContentSize:ns];
682     }
684 @end
686 @implementation GLMPlayerOpenGLView
687 - (void) drawRect: (NSRect)rect
689     [[NSColor clearColor] set];
690     NSRectFill([self bounds]);
692 @end