vo_corevideo: restructure this video output
[mplayer.git] / libvo / cocoa_common.m
blob71a8072b7c0910aa4792b9111611834fc070b67a
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     [NSApp setPresentationOptions:NSApplicationPresentationDefault];
132     [s->window release];
133     s->window = nil;
134     [s->glContext release];
135     s->glContext = nil;
136     [s->pool release];
137     s->pool = nil;
139     talloc_free(s);
142 void update_screen_info(void)
144     s->screen_array = [NSScreen screens];
145     if (xinerama_screen >= (int)[s->screen_array count]) {
146         mp_msg(MSGT_VO, MSGL_INFO, "[cocoa] Device ID %d does not exist, falling back to main device\n", xinerama_screen);
147         xinerama_screen = -1;
148     }
150     if (xinerama_screen < 0) { // default behaviour
151         if (! (s->screen_handle = [s->window screen]) )
152             s->screen_handle = [s->screen_array objectAtIndex:0];
153     } else {
154         s->screen_handle = [s->screen_array objectAtIndex:(xinerama_screen)];
155     }
157     s->screen_frame = [s->screen_handle frame];
160 void vo_cocoa_update_xinerama_info(struct vo *vo)
162     update_screen_info();
163     aspect_save_screenres(vo, s->screen_frame.size.width, s->screen_frame.size.height);
166 int vo_cocoa_change_attributes(struct vo *vo)
168     return 0;
171 void resize_window(struct vo *vo)
173     vo->dwidth = [[s->window contentView] frame].size.width;
174     vo->dheight = [[s->window contentView] frame].size.height;
175     [s->glContext update];
178 void vo_set_level(int ontop)
180     if (ontop) {
181         s->windowed_window_level = NSNormalWindowLevel + 1;
182     } else {
183         s->windowed_window_level = NSNormalWindowLevel;
184     }
186     if (!vo_fs)
187         [s->window setLevel:s->windowed_window_level];
190 void vo_cocoa_ontop(struct vo *vo)
192     struct MPOpts *opts = vo->opts;
193     opts->vo_ontop = !opts->vo_ontop;
194     vo_set_level(opts->vo_ontop);
197 int vo_cocoa_create_window(struct vo *vo, uint32_t d_width,
198                            uint32_t d_height, uint32_t flags)
200     struct MPOpts *opts = vo->opts;
201     if (s->current_video_size.width > 0 || s->current_video_size.height > 0)
202         s->previous_video_size = s->current_video_size;
203     s->current_video_size = NSMakeSize(d_width, d_height);
205     if (!(s->window || s->glContext)) { // keep using the same window
206         s->window = [[GLMPlayerWindow alloc] initWithContentRect:NSMakeRect(0, 0, d_width, d_height)
207                                              styleMask:s->windowed_mask
208                                              backing:NSBackingStoreBuffered defer:NO];
210         GLMPlayerOpenGLView *glView = [[GLMPlayerOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
212         NSOpenGLPixelFormatAttribute attrs[] = {
213             NSOpenGLPFADoubleBuffer, // double buffered
214             NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)16, // 16 bit depth buffer
215             (NSOpenGLPixelFormatAttribute)0
216         };
218         s->pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
219         s->glContext = [[NSOpenGLContext alloc] initWithFormat:s->pixelFormat shareContext:nil];
221         create_menu();
223         [s->window setContentView:glView];
224         [glView release];
225         [s->window setAcceptsMouseMovedEvents:YES];
226         [s->glContext setView:glView];
227         [s->glContext makeCurrentContext];
229         [NSApp setDelegate:s->window];
230         [s->window setDelegate:s->window];
231         [s->window setContentSize:s->current_video_size];
232         [s->window setContentAspectRatio:s->current_video_size];
233         [s->window center];
235         if (flags & VOFLAG_HIDDEN) {
236             [s->window orderOut:nil];
237         } else {
238             [s->window makeKeyAndOrderFront:nil];
239             [NSApp activateIgnoringOtherApps:YES];
240         }
242         if (flags & VOFLAG_FULLSCREEN)
243             vo_cocoa_fullscreen(vo);
245         vo_set_level(opts->vo_ontop);
246     } else {
247         if (s->current_video_size.width  != s->previous_video_size.width ||
248             s->current_video_size.height != s->previous_video_size.height) {
249             if (vo_fs) {
250                 // we will resize as soon as we get out of fullscreen
251                 s->out_fs_resize = YES;
252             } else {
253                 // only if we are not in fullscreen and the video size did change
254                 // we actually resize the window and set a new aspect ratio
255                 [s->window setContentSize:s->current_video_size keepCentered:YES];
256                 [s->window setContentAspectRatio:s->current_video_size];
257             }
258         }
259     }
261     resize_window(vo);
263     if (s->window_title)
264         [s->window_title release];
266     s->window_title = [[NSString alloc] initWithUTF8String:vo_get_window_title(vo)];
267     [s->window setTitle: s->window_title];
269     return 0;
272 void vo_cocoa_swap_buffers()
274     [s->glContext flushBuffer];
277 void vo_cocoa_display_cursor(int requested_state)
279     if (requested_state) {
280         if (!vo_fs || s->cursor_autohide_delay > -2) {
281             s->display_cursor = requested_state;
282             CGDisplayShowCursor(kCGDirectMainDisplay);
283         }
284     } else {
285         if (s->cursor_autohide_delay != -1) {
286             s->display_cursor = requested_state;
287             CGDisplayHideCursor(kCGDirectMainDisplay);
288         }
289     }
292 int vo_cocoa_check_events(struct vo *vo)
294     NSEvent *event;
295     float curTime = TickCount()/60;
296     int msCurTime = (int) (curTime * 1000);
298     // automatically hide mouse cursor
299     if (vo_fs && s->display_cursor &&
300         (msCurTime - s->cursor_timer >= s->cursor_autohide_delay)) {
301         vo_cocoa_display_cursor(0);
302         s->cursor_timer = msCurTime;
303     }
305     //update activity every 30 seconds to prevent
306     //screensaver from starting up.
307     if ((int)curTime - s->last_screensaver_update >= 30 || s->last_screensaver_update == 0)
308     {
309         UpdateSystemActivity(UsrActivity);
310         s->last_screensaver_update = (int)curTime;
311     }
313     event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
314                    inMode:NSEventTrackingRunLoopMode dequeue:YES];
315     if (event == nil)
316         return 0;
317     l_vo = vo;
318     [NSApp sendEvent:event];
319     l_vo = nil;
321     if (s->did_resize) {
322         s->did_resize = NO;
323         resize_window(vo);
324         return VO_EVENT_RESIZE;
325     }
326     // Without SDL's bootstrap code (include SDL.h in mplayer.c),
327     // on Leopard, we have trouble to get the play window automatically focused
328     // when the app is actived. The Following code fix this problem.
329 #ifndef CONFIG_SDL
330     if ([event type] == NSAppKitDefined
331             && [event subtype] == NSApplicationActivatedEventType) {
332         [s->window makeMainWindow];
333         [s->window makeKeyAndOrderFront:nil];
334     }
335 #endif
336     return 0;
339 void vo_cocoa_fullscreen(struct vo *vo)
341     [s->window fullscreen];
342     resize_window(vo);
345 int vo_cocoa_swap_interval(int enabled)
347     [s->glContext setValues:&enabled forParameter:NSOpenGLCPSwapInterval];
348     return 0;
351 void *vo_cocoa_cgl_context(void)
353     return [s->glContext CGLContextObj];
356 void *vo_cocoa_cgl_pixel_format(void)
358     return [s->pixelFormat CGLPixelFormatObj];
361 void create_menu()
363     NSMenu *menu;
364     NSMenuItem *menuItem;
366     menu = [[NSMenu new] autorelease];
367     menuItem = [[NSMenuItem new] autorelease];
368     [menu addItem: menuItem];
369     [NSApp setMainMenu: menu];
371     menu = [[NSMenu alloc] initWithTitle:@"Movie"];
372     menuItem = [[NSMenuItem alloc] initWithTitle:@"Half Size" action:@selector(halfSize) keyEquivalent:@"0"]; [menu addItem:menuItem];
373     menuItem = [[NSMenuItem alloc] initWithTitle:@"Normal Size" action:@selector(normalSize) keyEquivalent:@"1"]; [menu addItem:menuItem];
374     menuItem = [[NSMenuItem alloc] initWithTitle:@"Double Size" action:@selector(doubleSize) keyEquivalent:@"2"]; [menu addItem:menuItem];
376     menuItem = [[NSMenuItem alloc] initWithTitle:@"Movie" action:nil keyEquivalent:@""];
377     [menuItem setSubmenu:menu];
378     [[NSApp mainMenu] addItem:menuItem];
380     [menu release];
381     [menuItem release];
384 @implementation GLMPlayerWindow
386 - (void) windowDidResize:(NSNotification *) notification
388     if (l_vo)
389         s->did_resize = YES;
392 - (void) fullscreen
394     if (!vo_fs) {
395         update_screen_info();
396         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
397         s->windowed_frame = [self frame];
398         [self setHasShadow:NO];
399         [self setStyleMask:s->fullscreen_mask];
400         [self setFrame:s->screen_frame display:YES animate:NO];
401         [self setLevel:s->fullscreen_window_level];
402         vo_fs = VO_TRUE;
403         vo_cocoa_display_cursor(0);
404         [self setMovableByWindowBackground: NO];
405     } else {
406         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
407         [self setHasShadow:YES];
408         [self setStyleMask:s->windowed_mask];
409         [self setTitle:s->window_title];
410         [self setFrame:s->windowed_frame display:YES animate:NO];
411         if (s->out_fs_resize) {
412             [self setContentSize:s->current_video_size keepCentered:YES];
413             s->out_fs_resize = NO;
414         }
415         [self setContentAspectRatio:s->current_video_size];
416         [self setLevel:s->windowed_window_level];
417         vo_fs = VO_FALSE;
418         vo_cocoa_display_cursor(1);
419         [self setMovableByWindowBackground: YES];
420     }
423 - (BOOL) canBecomeMainWindow { return YES; }
424 - (BOOL) canBecomeKeyWindow { return YES; }
425 - (BOOL) acceptsFirstResponder { return YES; }
426 - (BOOL) becomeFirstResponder { return YES; }
427 - (BOOL) resignFirstResponder { return YES; }
428 - (BOOL) windowShouldClose:(id)sender
430     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
431     // We have to wait for MPlayer to handle this,
432     // otherwise we are in trouble if the
433     // KEY_CLOSE_WIN handler is disabled
434     return NO;
437 - (BOOL) isMovableByWindowBackground
439     // this is only valid as a starting value. it will be rewritten in the -fullscreen method.
440     return !vo_fs;
443 - (void) handleQuitEvent:(NSAppleEventDescriptor*)e withReplyEvent:(NSAppleEventDescriptor*)r
445     mplayer_put_key(l_vo->key_fifo, KEY_CLOSE_WIN);
448 - (void) keyDown:(NSEvent *)theEvent
450     unsigned char charcode;
451     if (([theEvent modifierFlags] & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
452         charcode = *[[theEvent characters] UTF8String];
453     else
454         charcode = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
456     int key = convert_key([theEvent keyCode], charcode);
458     if (key > -1) {
459         if ([theEvent modifierFlags] & NSShiftKeyMask)
460             key |= KEY_MODIFIER_SHIFT;
461         if ([theEvent modifierFlags] & NSControlKeyMask)
462             key |= KEY_MODIFIER_CTRL;
463         if (([theEvent modifierFlags] & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask)
464             key |= KEY_MODIFIER_ALT;
465         if ([theEvent modifierFlags] & NSCommandKeyMask)
466             key |= KEY_MODIFIER_META;
467         mplayer_put_key(l_vo->key_fifo, key);
468     }
471 - (void) mouseMoved: (NSEvent *) theEvent
473     if (vo_fs)
474         vo_cocoa_display_cursor(1);
477 - (void) mouseDragged:(NSEvent *)theEvent
479     [self mouseEvent: theEvent];
482 - (void) mouseDown:(NSEvent *)theEvent
484     [self mouseEvent: theEvent];
487 - (void) mouseUp:(NSEvent *)theEvent
489     [self mouseEvent: theEvent];
492 - (void) rightMouseDown:(NSEvent *)theEvent
494     [self mouseEvent: theEvent];
497 - (void) rightMouseUp:(NSEvent *)theEvent
499     [self mouseEvent: theEvent];
502 - (void) otherMouseDown:(NSEvent *)theEvent
504     [self mouseEvent: theEvent];
507 - (void) otherMouseUp:(NSEvent *)theEvent
509     [self mouseEvent: theEvent];
512 - (void) scrollWheel:(NSEvent *)theEvent
514     if ([theEvent deltaY] > 0)
515         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN3);
516     else
517         mplayer_put_key(l_vo->key_fifo, MOUSE_BTN4);
520 - (void) mouseEvent:(NSEvent *)theEvent
522     if ([theEvent buttonNumber] >= 0 && [theEvent buttonNumber] <= 9) {
523         int buttonNumber = [theEvent buttonNumber];
524         // Fix to mplayer defined button order: left, middle, right
525         if (buttonNumber == 1)  buttonNumber = 2;
526         else if (buttonNumber == 2) buttonNumber = 1;
527         switch ([theEvent type]) {
528             case NSLeftMouseDown:
529             case NSRightMouseDown:
530             case NSOtherMouseDown:
531                 mplayer_put_key(l_vo->key_fifo, (MOUSE_BTN0 + buttonNumber) | MP_KEY_DOWN);
532                 // Looks like Cocoa doesn't create MouseUp events when we are
533                 // doing the second click in a double click. Put in the key_fifo
534                 // the key that would be put from the MouseUp handling code.
535                 if([theEvent clickCount] == 2)
536                    mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
537                 break;
538             case NSLeftMouseUp:
539             case NSRightMouseUp:
540             case NSOtherMouseUp:
541                 mplayer_put_key(l_vo->key_fifo, MOUSE_BTN0 + buttonNumber);
542                 break;
543         }
544     }
547 - (void) applicationWillBecomeActive:(NSNotification *)aNotification
549     if (vo_fs) {
550         [s->window setLevel:s->fullscreen_window_level];
551         [NSApp setPresentationOptions:NSApplicationPresentationHideDock|NSApplicationPresentationHideMenuBar];
552         [s->window makeKeyAndOrderFront:nil];
553         [NSApp activateIgnoringOtherApps: YES];
554     }
557 - (void) applicationWillResignActive:(NSNotification *)aNotification
559     if (vo_fs) {
560         [s->window setLevel:s->windowed_window_level];
561         [NSApp setPresentationOptions:NSApplicationPresentationDefault];
562     }
565 - (void) applicationDidFinishLaunching:(NSNotification*)notification
567     // Install an event handler so the Quit menu entry works
568     // The proper way using NSApp setDelegate: and
569     // applicationShouldTerminate: does not work,
570     // probably NSApplication never installs its handler.
571     [[NSAppleEventManager sharedAppleEventManager]
572         setEventHandler:self
573         andSelector:@selector(handleQuitEvent:withReplyEvent:)
574         forEventClass:kCoreEventClass
575         andEventID:kAEQuitApplication];
578 - (void) normalSize
580     if (!vo_fs)
581       [self setContentSize:s->current_video_size keepCentered:YES];
584 - (void) halfSize { [self mulSize:0.5f];}
586 - (void) doubleSize { [self mulSize:2.0f];}
588 - (void) mulSize:(float)multiplier
590     if (!vo_fs) {
591         NSSize size = [[self contentView] frame].size;
592         size.width  = s->current_video_size.width  * (multiplier);
593         size.height = s->current_video_size.height * (multiplier);
594         [self setContentSize:size keepCentered:YES];
595     }
598 - (void) setContentSize:(NSSize)ns keepCentered:(BOOL)keepCentered
600     if (keepCentered) {
601         NSRect nf = [self frame];
602         NSRect vf = [[self screen] visibleFrame];
603         int title_height = nf.size.height - [[self contentView] bounds].size.height;
604         double ratio = (double)ns.width / (double)ns.height;
606         // clip the new size to the visibleFrame's size if needed
607         if (ns.width > vf.size.width || ns.height + title_height > vf.size.height) {
608             ns = vf.size;
609             ns.height -= title_height; // make space for the title bar
611             if (ns.width > ns.height) {
612                 ns.height = ((double)ns.width * 1/ratio + 0.5);
613             } else {
614                 ns.width = ((double)ns.height * ratio + 0.5);
615             }
616         }
618         int dw = nf.size.width - ns.width;
619         int dh = nf.size.height - ns.height - title_height;
621         nf.origin.x += dw / 2;
622         nf.origin.y += dh / 2;
624         [self setFrame: NSMakeRect(nf.origin.x, nf.origin.y, ns.width, ns.height + title_height) display:YES animate:NO];
625     } else {
626         [self setContentSize:ns];
627     }
629 @end
631 @implementation GLMPlayerOpenGLView
632 - (void) drawRect: (NSRect)rect
634     [[NSColor clearColor] set];
635     NSRectFill([self bounds]);
637 @end