vo_corevideo: use cocoa_common to display the window
[mplayer.git] / libvo / cocoa_common.m
blobaf2f4adaafaa260a1f01de2d92b82076a7e572a4
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;
57     NSOpenGLPixelFormat *pixelFormat;
59     NSSize current_video_size;
60     NSSize previous_video_size;
62     NSRect screen_frame;
63     NSScreen *screen_handle;
64     NSArray *screen_array;
66     NSInteger windowed_mask;
67     NSInteger fullscreen_mask;
69     NSRect windowed_frame;
71     NSString *window_title;
73     NSInteger windowed_window_level;
74     NSInteger fullscreen_window_level;
76     int last_screensaver_update;
78     int display_cursor;
79     int cursor_timer;
80     int cursor_autohide_delay;
82     bool did_resize;
83     bool out_fs_resize;
86 struct vo_cocoa_state *s;
88 struct vo *l_vo;
90 // local function definitions
91 struct vo_cocoa_state *vo_cocoa_init_state(void);
92 void vo_set_level(int ontop);
93 void update_screen_info(void);
94 void resize_window(struct vo *vo);
95 void vo_cocoa_display_cursor(int requested_state);
96 void create_menu(void);
98 struct vo_cocoa_state *vo_cocoa_init_state(void)
100     struct vo_cocoa_state *s = talloc_ptrtype(NULL, s);
101     *s = (struct vo_cocoa_state){
102         .did_resize = NO,
103         .current_video_size = {0,0},
104         .previous_video_size = {0,0},
105         .windowed_mask = NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask,
106         .fullscreen_mask = NSBorderlessWindowMask,
107         .fullscreen_window_level = NSNormalWindowLevel + 1,
108         .windowed_frame = {{0,0},{0,0}},
109         .out_fs_resize = NO,
110         .display_cursor = 1,
111     };
112     return s;
115 int vo_cocoa_init(struct vo *vo)
117     s = vo_cocoa_init_state();
118     s->pool = [[NSAutoreleasePool alloc] init];
119     s->cursor_autohide_delay = vo->opts->cursor_autohide_delay;
120     NSApplicationLoad();
121     NSApp = [NSApplication sharedApplication];
122     [NSApp setActivationPolicy: NSApplicationActivationPolicyRegular];
124     return 1;
127 void vo_cocoa_uninit(struct vo *vo)
129     CGDisplayShowCursor(kCGDirectMainDisplay);
130     [s->window release];
131     s->window = nil;
132     [s->glContext release];
133     s->glContext = nil;
134     [s->pool release];
135     s->pool = nil;
137     talloc_free(s);
140 void update_screen_info(void)
142     s->screen_array = [NSScreen screens];
143     if (xinerama_screen >= (int)[s->screen_array count]) {
144         mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
145         xinerama_screen = -1;
146     }
148     if (xinerama_screen < 0) { // default behaviour
149         if (! (s->screen_handle = [s->window screen]) )
150             s->screen_handle = [s->screen_array objectAtIndex:0];
151     } else {
152         s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
153     }
155     s->screen_frame = [s->screen_handle frame];
158 void vo_cocoa_update_xinerama_info(struct vo *vo)
160     update_screen_info();
161     aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
164 int vo_cocoa_change_attributes(struct vo *vo)
166     return 0;
169 void resize_window(struct vo *vo)
171     vo->dwidth = [[s->window contentView] frame].size.width;
172     vo->dheight = [[s->window contentView] frame].size.height;
173     [s->glContext update];
176 void vo_set_level(int ontop)
178     if (ontop) {
179         s->windowed_window_level = NSNormalWindowLevel + 1;
180     } else {
181         s->windowed_window_level = NSNormalWindowLevel;
182     }
184     if (!vo_fs)
185         [s->window setLevel:s->windowed_window_level];
188 void vo_cocoa_ontop(struct vo *vo)
190     struct MPOpts *opts = vo->opts;
191     opts->vo_ontop = !opts->vo_ontop;
192     vo_set_level(opts->vo_ontop);
195 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
196                            uint32_t d_height, uint32_t flags)
198     struct MPOpts *opts = vo->opts;
199     if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
200         s->previous_video_size = s->current_video_size;
201     s->current_video_size = NSMakeSize(d_width, d_height);
203     if (!(s->window || s->glContext)) { // keep using the same window
204         s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
205                                              styleMask:s->windowed_mask
206                                              backing:NSBackingStoreBuffered defer:NO];
208         GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
210         NSOpenGLPixelFormatAttribute attrs[] = {
211             NSOpenGLPFADoubleBuffer, // double buffered
212             NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)16, // 16 bit depth buffer
213             (NSOpenGLPixelFormatAttribute)0
214         };
216         s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
217         s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
219         create_menu();
221         [s->window setContentView:glView];
222         [glView release];
223         [s->window setAcceptsMouseMovedEvents:YES];
224         [s->glContext setView:glView];
225         [s->glContext makeCurrentContext];
227         [NSApp setDelegate:s->window];
228         [s->window setDelegate:s->window];
229         [s->window setContentSize:s->current_video_size];
230         [s->window setContentAspectRatio:s->current_video_size];
231         [s->window center];
233         if (flags & VOFLAG_HIDDEN) {
234             [s->window orderOut:nil];
235         } else {
236             [s->window makeKeyAndOrderFront:nil];
237             [NSApp activateIgnoringOtherApps:YES];
238         }
240         if (flags & VOFLAG_FULLSCREEN)
241             vo_cocoa_fullscreen(vo);
243         vo_set_level(opts->vo_ontop);
244     } else {
245         if (s->current_video_size.width  != s->previous_video_size.width ||
246             s->current_video_size.height != s->previous_video_size.height) {
247             if (vo_fs) {
248                 // we will resize as soon as we get out of fullscreen
249                 s->out_fs_resize = YES;
250             } else {
251                 // only if we are not in fullscreen and the video size did change
252                 // we actually resize the window and set a new aspect ratio
253                 [s->window setContentSize:s->current_video_size keepCentered:YES];
254                 [s->window setContentAspectRatio:s->current_video_size];
255             }
256         }
257     }
259     resize_window(vo);
261     if (s->window_title)
262         [s->window_title release];
264     s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
265     [s->window setTitle: s->window_title];
267     return 0;
270 void vo_cocoa_swap_buffers()
272     [s->glContext flushBuffer];
275 void vo_cocoa_display_cursor(int requested_state)
277     if (requested_state) {
278         if (!vo_fs || s->cursor_autohide_delay > -2) {
279             s->display_cursor = requested_state;
280             CGDisplayShowCursor(kCGDirectMainDisplay);
281         }
282     } else {
283         if (s->cursor_autohide_delay != -1) {
284             s->display_cursor = requested_state;
285             CGDisplayHideCursor(kCGDirectMainDisplay);
286         }
287     }
290 int vo_cocoa_check_events(struct vo *vo)
292     NSEvent *event;
293     float curTime = TickCount()/60;
294     int msCurTime = (int) (curTime * 1000);
296     // automatically hide mouse cursor
297     if (vo_fs && s->display_cursor &&
298         (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
299         vo_cocoa_display_cursor(0);
300         s->cursor_timer = msCurTime;
301     }
303     //update activity every 30 seconds to prevent
304     //screensaver from starting up.
305     if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
306     {
307         UpdateSystemActivity(UsrActivity);
308         s->last_screensaver_update = (int)curTime;
309     }
311     event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
312                    inMode:NSEventTrackingRunLoopMode dequeue:YES];
313     if (event == nil)
314         return 0;
315     l_vo = vo;
316     [NSApp sendEvent:event];
317     l_vo = nil;
319     if (s->did_resize) {
320         s->did_resize = NO;
321         resize_window(vo);
322         return VO_EVENT_RESIZE;
323     }
324     // Without SDL's bootstrap code (include SDL.h in mplayer.c),
325     // on Leopard, we have trouble to get the play window automatically focused
326     // when the app is actived. The Following code fix this problem.
327 #ifndef CONFIG_SDL
328     if ([event type] == NSAppKitDefined
329             && [event subtype] == NSApplicationActivatedEventType) {
330         [s->window makeMainWindow];
331         [s->window makeKeyAndOrderFront:nil];
332     }
333 #endif
334     return 0;
337 void vo_cocoa_fullscreen(struct vo *vo)
339     [s->window fullscreen];
340     resize_window(vo);
343 int vo_cocoa_swap_interval(int enabled)
345     [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
346     return 0;
349 void *vo_cocoa_cgl_context(void)
351     return [s->glContext CGLContextObj];
354 void *vo_cocoa_cgl_pixel_format(void)
356     return [s->pixelFormat CGLPixelFormatObj];
359 void create_menu()
361     NSMenu *menu;
362     NSMenuItem *menuItem;
364     menu = [[NSMenu new] autorelease];
365     menuItem = [[NSMenuItem new] autorelease];
366     [menu addItem: menuItem];
367     [NSApp setMainMenu: menu];
369     menu = [[NSMenu alloc] initWithTitle:@"Movie"];
370     menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(halfSize) keyEquivalent:@"0"]; [menu addItem:menuItem];
371     menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(normalSize) keyEquivalent:@"1"]; [menu addItem:menuItem];
372     menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(doubleSize) keyEquivalent:@"2"]; [menu addItem:menuItem];
374     menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
375     [menuItem setSubmenu:menu];
376     [[NSApp mainMenu] addItem:menuItem];
378     [menu release];
379     [menuItem release];
382 @implementation GLMPlayerWindow
384 - (void) windowDidResize:(NSNotification *) notification
386     if (l_vo)
387         s->did_resize = YES;
390 - (void) fullscreen
392     if (!vo_fs) {
393         update_screen_info();
394         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
395         s->windowed_frame = [self frame];
396         [self setHasShadow:NO];
397         [self setStyleMask:s->fullscreen_mask];
398         [self setFrame:s->screen_frame display:YES animate:NO];
399         [self setLevel:s->fullscreen_window_level];
400         vo_fs = VO_TRUE;
401         vo_cocoa_display_cursor(0);
402         [self setMovableByWindowBackground: NO];
403     } else {
404         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
405         [self setHasShadow:YES];
406         [self setStyleMask:s->windowed_mask];
407         [self setTitle:s->window_title];
408         [self setFrame:s->windowed_frame display:YES animate:NO];
409         if (s->out_fs_resize) {
410             [self setContentSize:s->current_video_size keepCentered:YES];
411             s->out_fs_resize = NO;
412         }
413         [self setContentAspectRatio:s->current_video_size];
414         [self setLevel:s->windowed_window_level];
415         vo_fs = VO_FALSE;
416         vo_cocoa_display_cursor(1);
417         [self setMovableByWindowBackground: YES];
418     }
421 - (BOOL) canBecomeMainWindow { return YES; }
422 - (BOOL) canBecomeKeyWindow { return YES; }
423 - (BOOL) acceptsFirstResponder { return YES; }
424 - (BOOL) becomeFirstResponder { return YES; }
425 - (BOOL) resignFirstResponder { return YES; }
426 - (BOOL) windowShouldClose:(id)sender
428     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
429     // We have to wait for MPlayer to handle this,
430     // otherwise we are in trouble if the
431     // KEY_CLOSE_WIN handler is disabled
432     return NO;
435 - (BOOL) isMovableByWindowBackground
437     // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
438     return !vo_fs;
441 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
443     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
446 - (void) keyDown:(NSEvent *)theEvent
448     unsigned char charcode;
449     if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
450         charcode = *[[theEvent characters] UTF8String];
451     else
452         charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
454     int key = convert_key([theEvent keyCode], charcode);
456     if (key > -1) {
457         if ([theEvent modifierFlags] & NSShiftKeyMask)
458             key |= KEY_MODIFIER_SHIFT;
459         if ([theEvent modifierFlags] & NSControlKeyMask)
460             key |= KEY_MODIFIER_CTRL;
461         if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
462             key |= KEY_MODIFIER_ALT;
463         if ([theEvent modifierFlags] & NSCommandKeyMask)
464             key |= KEY_MODIFIER_META;
465         mplayer_put_key(l_vo->key_fifo, key);
466     }
469 - (void) mouseMoved: (NSEvent *) theEvent
471     if (vo_fs)
472         vo_cocoa_display_cursor(1);
475 - (void) mouseDragged:(NSEvent *)theEvent
477     [self mouseEvent: theEvent];
480 - (void) mouseDown:(NSEvent *)theEvent
482     [self mouseEvent: theEvent];
485 - (void) mouseUp:(NSEvent *)theEvent
487     [self mouseEvent: theEvent];
490 - (void) rightMouseDown:(NSEvent *)theEvent
492     [self mouseEvent: theEvent];
495 - (void) rightMouseUp:(NSEvent *)theEvent
497     [self mouseEvent: theEvent];
500 - (void) otherMouseDown:(NSEvent *)theEvent
502     [self mouseEvent: theEvent];
505 - (void) otherMouseUp:(NSEvent *)theEvent
507     [self mouseEvent: theEvent];
510 - (void) scrollWheel:(NSEvent *)theEvent
512     if ([theEvent deltaY] > 0)
513         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
514     else
515         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
518 - (void) mouseEvent:(NSEvent *)theEvent
520     if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
521         int buttonNumber = [theEvent buttonNumber];
522         // Fix to mplayer defined button order: left, middle, right
523         if (buttonNumber == 1)  buttonNumber = 2;
524         else if (buttonNumber == 2) buttonNumber = 1;
525         switch ([theEvent type]) {
526             case NSLeftMouseDown:
527             case NSRightMouseDown:
528             case NSOtherMouseDown:
529                 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
530                 // Looks like Cocoa doesn't create MouseUp events when we are
531                 // doing the second click in a double click. Put in the key_fifo
532                 // the key that would be put from the MouseUp handling code.
533                 if([theEvent clickCount] == 2)
534                    mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
535                 break;
536             case NSLeftMouseUp:
537             case NSRightMouseUp:
538             case NSOtherMouseUp:
539                 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
540                 break;
541         }
542     }
545 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
547     if (vo_fs) {
548         [s->window setLevel:s->fullscreen_window_level];
549         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
550         [s->window makeKeyAndOrderFront:nil];
551         [NSApp activateIgnoringOtherApps: YES];
552     }
555 - (void) applicationWillResignActive:(NSNotification *)aNotification
557     if (vo_fs) {
558         [s->window setLevel:s->windowed_window_level];
559         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
560     }
563 - (void) applicationDidFinishLaunching:(NSNotification*)notification
565     // Install an event handler so the Quit menu entry works
566     // The proper way using NSApp setDelegate: and
567     // applicationShouldTerminate: does not work,
568     // probably NSApplication never installs its handler.
569     [[NSAppleEventManager sharedAppleEventManager]
570         setEventHandler:self
571         andSelector:@selector(handleQuitEvent:withReplyEvent:)
572         forEventClass:kCoreEventClass
573         andEventID:kAEQuitApplication];
576 - (void) normalSize
578     if (!vo_fs)
579       [self setContentSize:s->current_video_size keepCentered:YES];
582 - (void) halfSize { [self mulSize:0.5f];}
584 - (void) doubleSize { [self mulSize:2.0f];}
586 - (void) mulSize:(float)multiplier
588     if (!vo_fs) {
589         NSSize size = [[self contentView] frame].size;
590         size.width  = s->current_video_size.width  * (multiplier);
591         size.height = s->current_video_size.height * (multiplier);
592         [self setContentSize:size keepCentered:YES];
593     }
596 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
598     if (keepCentered) {
599         NSRect nf = [self frame];
600         NSRect vf = [[self screen] visibleFrame];
601         int title_height = nf.size.height - [[self contentView] bounds].size.height;
602         double ratio = (double)ns.width / (double)ns.height;
604         // clip the new size to the visibleFrame's size if needed
605         if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
606             ns = vf.size;
607             ns.height -= title_height; // make space for the title bar
609             if (ns.width > ns.height) {
610                 ns.height = ((double)ns.width * 1/ratio + 0.5);
611             } else {
612                 ns.width = ((double)ns.height * ratio + 0.5);
613             }
614         }
616         int dw = nf.size.width - ns.width;
617         int dh = nf.size.height - ns.height - title_height;
619         nf.origin.x += dw / 2;
620         nf.origin.y += dh / 2;
622         [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
623     } else {
624         [self setContentSize:ns];
625     }
627 @end
629 @implementation GLMPlayerOpenGLView
630 - (void) drawRect: (NSRect)rect
632     [[NSColor clearColor] set];
633     NSRectFill([self bounds]);
635 @end