]> git.sesse.net Git - vlc/blob - modules/video_output/macosx.m
vout_macosx: fixed typo
[vlc] / modules / video_output / macosx.m
1 /*****************************************************************************
2  * macosx.m: MacOS X OpenGL provider
3  *****************************************************************************
4  * Copyright (C) 2001-2012 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Colin Delacroix <colin@zoy.org>
8  *          Florian G. Pflug <fgp@phlo.org>
9  *          Jon Lech Johansen <jon-vl@nanocrew.net>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *          Eric Petit <titer@m0k.org>
12  *          Benjamin Pracht <bigben at videolan dot org>
13  *          Damien Fouilleul <damienf at videolan dot org>
14  *          Pierre d'Herbemont <pdherbemont at videolan dot org>
15  *          Felix Paul Kühne <fkuehne at videolan dot org>
16  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program; if not, write to the Free Software
30  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
31  *****************************************************************************/
32
33 /*****************************************************************************
34  * Preamble
35  *****************************************************************************/
36
37 #import <Cocoa/Cocoa.h>
38 #import <OpenGL/OpenGL.h>
39 #import <dlfcn.h>
40
41 #ifdef HAVE_CONFIG_H
42 # include "config.h"
43 #endif
44
45 #include <vlc_common.h>
46 #include <vlc_plugin.h>
47 #include <vlc_vout_display.h>
48 #include <vlc_opengl.h>
49 #include <vlc_dialog.h>
50 #include "opengl.h"
51
52 @interface NSWindow (VLCCustomCode)
53 - (BOOL)isFullscreen;
54 @end
55
56 /* compilation support for 10.5 and 10.6 */
57 #define OSX_LION NSAppKitVersionNumber >= 1115.2
58 #ifndef MAC_OS_X_VERSION_10_7
59
60 @interface NSView (IntroducedInLion)
61 - (NSRect)convertRectToBacking:(NSRect)aRect;
62 - (void)setWantsBestResolutionOpenGLSurface:(BOOL)aBool;
63 @end
64
65 #endif
66
67 /**
68  * Forward declarations
69  */
70 static int Open (vlc_object_t *);
71 static void Close (vlc_object_t *);
72
73 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count);
74 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
75 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture);
76 static int Control (vout_display_t *vd, int query, va_list ap);
77
78 static void *OurGetProcAddress(vlc_gl_t *, const char *);
79
80 static int OpenglLock (vlc_gl_t *gl);
81 static void OpenglUnlock (vlc_gl_t *gl);
82 static void OpenglSwap (vlc_gl_t *gl);
83
84 /**
85  * Module declaration
86  */
87 vlc_module_begin ()
88     /* Will be loaded even without interface module. see voutgl.m */
89     set_shortname ("Mac OS X")
90     set_description (N_("Mac OS X OpenGL video output (requires drawable-nsobject)"))
91     set_category (CAT_VIDEO)
92     set_subcategory (SUBCAT_VIDEO_VOUT )
93     set_capability ("vout display", 300)
94     set_callbacks (Open, Close)
95
96     add_shortcut ("macosx", "vout_macosx")
97 vlc_module_end ()
98
99 /**
100  * Obj-C protocol declaration that drawable-nsobject should follow
101  */
102 @protocol VLCOpenGLVideoViewEmbedding <NSObject>
103 - (void)addVoutSubview:(NSView *)view;
104 - (void)removeVoutSubview:(NSView *)view;
105 @end
106
107 @interface VLCOpenGLVideoView : NSOpenGLView
108 {
109     vout_display_t *vd;
110     BOOL _hasPendingReshape;
111 }
112 - (void)setVoutDisplay:(vout_display_t *)vd;
113 - (void)setVoutFlushing:(BOOL)flushing;
114 @end
115
116
117 struct vout_display_sys_t
118 {
119     VLCOpenGLVideoView *glView;
120     id<VLCOpenGLVideoViewEmbedding> container;
121
122     vout_window_t *embed;
123     vlc_gl_t gl;
124     vout_display_opengl_t *vgl;
125
126     picture_pool_t *pool;
127     picture_t *current;
128     bool has_first_frame;
129
130     vout_display_place_t place;
131 };
132
133
134 static void *OurGetProcAddress(vlc_gl_t *gl, const char *name)
135 {
136     VLC_UNUSED(gl);
137
138     return dlsym(RTLD_DEFAULT, name);
139 }
140
141 static int Open (vlc_object_t *this)
142 {
143     vout_display_t *vd = (vout_display_t *)this;
144     vout_display_sys_t *sys = calloc (1, sizeof(*sys));
145     NSAutoreleasePool *nsPool = nil;
146
147     if (!sys)
148         return VLC_ENOMEM;
149
150     if (!CGDisplayUsesOpenGLAcceleration (kCGDirectMainDisplay))
151     {
152         msg_Err (this, "no OpenGL hardware acceleration found. this can lead to slow output and unexpected results");
153         dialog_Fatal (this, _("OpenGL acceleration is not supported on your Mac"), _("Your Mac lacks Quartz Extreme acceleration, which is required for video output. It will still work, but much slower and with possibly unexpected results."));
154     }
155     else
156         msg_Dbg (this, "Quartz Extreme acceleration is active");
157
158     vd->sys = sys;
159     sys->pool = NULL;
160     sys->gl.sys = NULL;
161     sys->embed = NULL;
162
163     /* Get the drawable object */
164     id container = var_CreateGetAddress (vd, "drawable-nsobject");
165     if (container)
166     {
167         vout_display_DeleteWindow (vd, NULL);
168     }
169     else
170     {
171         vout_window_cfg_t wnd_cfg;
172
173         memset (&wnd_cfg, 0, sizeof (wnd_cfg));
174         wnd_cfg.type = VOUT_WINDOW_TYPE_NSOBJECT;
175         wnd_cfg.x = var_InheritInteger (vd, "video-x");
176         wnd_cfg.y = var_InheritInteger (vd, "video-y");
177         wnd_cfg.width  = vd->cfg->display.width;
178         wnd_cfg.height = vd->cfg->display.height;
179
180         sys->embed = vout_display_NewWindow (vd, &wnd_cfg);
181         if (sys->embed)
182             container = sys->embed->handle.nsobject;
183
184         if (!container)
185         {
186             msg_Dbg(vd, "No drawable-nsobject nor vout_window_t found, passing over.");
187             goto error;
188         }
189     }
190
191     /* This will be released in Close(), on
192      * main thread, after we are done using it. */
193     sys->container = [container retain];
194
195     /* Get our main view*/
196     nsPool = [[NSAutoreleasePool alloc] init];
197
198     [VLCOpenGLVideoView performSelectorOnMainThread:@selector(getNewView:) withObject:[NSValue valueWithPointer:&sys->glView] waitUntilDone:YES];
199     if (!sys->glView)
200         goto error;
201
202     [sys->glView setVoutDisplay:vd];
203
204     /* We don't wait, that means that we'll have to be careful about releasing
205      * container.
206      * That's why we'll release on main thread in Close(). */
207     if ([(id)container respondsToSelector:@selector(addVoutSubview:)])
208         [(id)container performSelectorOnMainThread:@selector(addVoutSubview:) withObject:sys->glView waitUntilDone:NO];
209     else if ([container isKindOfClass:[NSView class]])
210     {
211         NSView *parentView = container;
212         [parentView performSelectorOnMainThread:@selector(addSubview:) withObject:sys->glView waitUntilDone:NO];
213         [sys->glView performSelectorOnMainThread:@selector(setFrameToBoundsOfView:) withObject:[NSValue valueWithPointer:parentView] waitUntilDone:NO];
214     }
215     else
216     {
217         msg_Err(vd, "Invalid drawable-nsobject object. drawable-nsobject must either be an NSView or comply to the @protocol VLCOpenGLVideoViewEmbedding.");
218         goto error;
219     }
220
221
222     [nsPool release];
223     nsPool = nil;
224
225     /* Initialize common OpenGL video display */
226     sys->gl.lock = OpenglLock;
227     sys->gl.unlock = OpenglUnlock;
228     sys->gl.swap = OpenglSwap;
229     sys->gl.getProcAddress = OurGetProcAddress;
230     sys->gl.sys = sys;
231     const vlc_fourcc_t *subpicture_chromas;
232     video_format_t fmt = vd->fmt;
233
234     sys->vgl = vout_display_opengl_New (&vd->fmt, &subpicture_chromas, &sys->gl);
235     if (!sys->vgl)
236     {
237         sys->gl.sys = NULL;
238         goto error;
239     }
240
241     /* */
242     vout_display_info_t info = vd->info;
243     info.has_pictures_invalid = false;
244     info.has_event_thread = true;
245     info.subpicture_chromas = subpicture_chromas;
246
247     /* Setup vout_display_t once everything is fine */
248     vd->info = info;
249
250     vd->pool = Pool;
251     vd->prepare = PictureRender;
252     vd->display = PictureDisplay;
253     vd->control = Control;
254
255     /* */
256     vout_display_SendEventDisplaySize (vd, vd->source.i_visible_width, vd->source.i_visible_height, false);
257
258     return VLC_SUCCESS;
259
260 error:
261     [nsPool release];
262     Close(this);
263     return VLC_EGENERIC;
264 }
265
266 void Close (vlc_object_t *this)
267 {
268     vout_display_t *vd = (vout_display_t *)this;
269     vout_display_sys_t *sys = vd->sys;
270
271     if ([[sys->glView window] level] != NSNormalWindowLevel)
272         [[sys->glView window] setLevel: NSNormalWindowLevel];
273
274     [sys->glView setVoutDisplay:nil];
275
276     var_Destroy (vd, "drawable-nsobject");
277     if ([(id)sys->container respondsToSelector:@selector(removeVoutSubview:)])
278     {
279         /* This will retain sys->glView */
280         [(id)sys->container performSelectorOnMainThread:@selector(removeVoutSubview:) withObject:sys->glView waitUntilDone:NO];
281     }
282     /* release on main thread as explained in Open() */
283     [(id)sys->container performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
284     [sys->glView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
285
286     [sys->glView release];
287
288     if (sys->gl.sys != NULL)
289         vout_display_opengl_Delete (sys->vgl);
290
291     if (sys->embed)
292         vout_display_DeleteWindow (vd, sys->embed);
293     free (sys);
294 }
295
296 /*****************************************************************************
297  * vout display callbacks
298  *****************************************************************************/
299
300 static picture_pool_t *Pool (vout_display_t *vd, unsigned requested_count)
301 {
302     vout_display_sys_t *sys = vd->sys;
303
304     if (!sys->pool)
305         sys->pool = vout_display_opengl_GetPool (sys->vgl, requested_count);
306     assert(sys->pool);
307     return sys->pool;
308 }
309
310 static void PictureRender (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
311 {
312
313     vout_display_sys_t *sys = vd->sys;
314
315     vout_display_opengl_Prepare (sys->vgl, pic, subpicture);
316 }
317
318 static void PictureDisplay (vout_display_t *vd, picture_t *pic, subpicture_t *subpicture)
319 {
320     vout_display_sys_t *sys = vd->sys;
321     [sys->glView setVoutFlushing:YES];
322     vout_display_opengl_Display (sys->vgl, &vd->source);
323     [sys->glView setVoutFlushing:NO];
324     picture_Release (pic);
325     sys->has_first_frame = true;
326
327     if (subpicture)
328         subpicture_Delete(subpicture);
329 }
330
331 static int Control (vout_display_t *vd, int query, va_list ap)
332 {
333     vout_display_sys_t *sys = vd->sys;
334
335     switch (query)
336     {
337         case VOUT_DISPLAY_CHANGE_FULLSCREEN:
338         {
339             const vout_display_cfg_t *cfg = va_arg (ap, const vout_display_cfg_t *);
340             if (vout_window_SetFullScreen (sys->embed, cfg->is_fullscreen))
341                 return VLC_EGENERIC;
342
343             return VLC_SUCCESS;
344         }
345         case VOUT_DISPLAY_CHANGE_WINDOW_STATE:
346         {
347             NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
348             unsigned state = va_arg (ap, unsigned);
349             [sys->glView performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:state] waitUntilDone:NO];
350             [o_pool release];
351             return VLC_SUCCESS;
352         }
353         case VOUT_DISPLAY_CHANGE_DISPLAY_FILLED:
354         case VOUT_DISPLAY_CHANGE_ZOOM:
355         case VOUT_DISPLAY_CHANGE_SOURCE_ASPECT:
356         case VOUT_DISPLAY_CHANGE_SOURCE_CROP:
357         case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE:
358         {
359             if (!vd->sys)
360                 return VLC_EGENERIC;
361
362             NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
363
364             id o_window = [sys->glView window];
365             if (!o_window)
366                 return VLC_SUCCESS; // this is okay, since the event will occur again when we have a window
367
368             NSSize windowMinSize = [o_window minSize];
369
370             const vout_display_cfg_t *cfg;
371             const video_format_t *source;
372             bool is_forced = false;
373
374             if (query == VOUT_DISPLAY_CHANGE_SOURCE_ASPECT || query == VOUT_DISPLAY_CHANGE_SOURCE_CROP)
375             {
376                 source = (const video_format_t *)va_arg (ap, const video_format_t *);
377                 cfg = vd->cfg;
378             }
379             else
380             {
381                 source = &vd->source;
382                 cfg = (const vout_display_cfg_t*)va_arg (ap, const vout_display_cfg_t *);
383                 if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
384                     is_forced = (bool)va_arg (ap, int);
385             }
386
387             if (query == VOUT_DISPLAY_CHANGE_DISPLAY_SIZE && is_forced
388                 && (cfg->display.width != vd->cfg->display.width
389                     || cfg->display.height != vd->cfg->display.height)
390                 && vout_window_SetSize (sys->embed, cfg->display.width, cfg->display.height))
391                 return VLC_EGENERIC;
392  
393             /* for the case that the core wants to resize below minimum window size we correct the size here
394              to ensure a centered picture */
395             vout_display_cfg_t cfg_tmp = *cfg;
396             if (cfg_tmp.display.width < windowMinSize.width)
397                 cfg_tmp.display.width = windowMinSize.width;
398             if (cfg_tmp.display.height < 70)
399                 cfg_tmp.display.height = 70;
400
401             if (!config_GetInt(vd, "macosx-video-autoresize"))
402             {
403                 NSRect bounds;
404                 /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
405                 if (OSX_LION)
406                     bounds = [sys->glView convertRectToBacking:[sys->glView bounds]];
407                 else
408                     bounds = [sys->glView bounds];
409                 cfg_tmp.display.width = bounds.size.width;
410                 cfg_tmp.display.height = bounds.size.height;
411             }
412             vout_display_place_t place;
413             vout_display_PlacePicture (&place, source, &cfg_tmp, false);
414             @synchronized (sys->glView) {
415                 sys->place = place;
416             }
417
418             /* For resize, we call glViewport in reshape and not here.
419                This has the positive side effect that we avoid erratic sizing as we animate every resize. */
420             if (query != VOUT_DISPLAY_CHANGE_DISPLAY_SIZE)
421             {
422                 // x / y are top left corner, but we need the lower left one
423                 glViewport (place.x, cfg_tmp.display.height - (place.y + place.height), place.width, place.height);
424             }
425
426             [o_pool release];
427             return VLC_SUCCESS;
428         }
429
430         case VOUT_DISPLAY_HIDE_MOUSE:
431         {
432             [NSCursor setHiddenUntilMouseMoves: YES];
433             return VLC_SUCCESS;
434         }
435
436         case VOUT_DISPLAY_GET_OPENGL:
437         {
438             vlc_gl_t **gl = va_arg (ap, vlc_gl_t **);
439             *gl = &sys->gl;
440             return VLC_SUCCESS;
441         }
442
443         case VOUT_DISPLAY_RESET_PICTURES:
444             assert (0);
445         default:
446             msg_Err (vd, "Unknown request in Mac OS X vout display");
447             return VLC_EGENERIC;
448     }
449 }
450
451 /*****************************************************************************
452  * vout opengl callbacks
453  *****************************************************************************/
454 static int OpenglLock (vlc_gl_t *gl)
455 {
456     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
457     NSOpenGLContext *context = [sys->glView openGLContext];
458     CGLError err = CGLLockContext ([context CGLContextObj]);
459     if (kCGLNoError == err)
460     {
461         [context makeCurrentContext];
462         return 0;
463     }
464     return 1;
465 }
466
467 static void OpenglUnlock (vlc_gl_t *gl)
468 {
469     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
470     CGLUnlockContext ([[sys->glView openGLContext] CGLContextObj]);
471 }
472
473 static void OpenglSwap (vlc_gl_t *gl)
474 {
475     vout_display_sys_t *sys = (vout_display_sys_t *)gl->sys;
476     [[sys->glView openGLContext] flushBuffer];
477 }
478
479 /*****************************************************************************
480  * Our NSView object
481  *****************************************************************************/
482 @implementation VLCOpenGLVideoView
483
484 #define VLCAssertMainThread() assert([[NSThread currentThread] isMainThread])
485
486
487 + (void)getNewView:(NSValue *)value
488 {
489     id *ret = [value pointerValue];
490     *ret = [[self alloc] init];
491 }
492
493 /**
494  * Gets called by the Open() method.
495  */
496 - (id)init
497 {
498     VLCAssertMainThread();
499
500     /* Warning - this may be called on non main thread */
501
502     NSOpenGLPixelFormatAttribute attribs[] =
503     {
504         NSOpenGLPFADoubleBuffer,
505         NSOpenGLPFAAccelerated,
506         NSOpenGLPFANoRecovery,
507         NSOpenGLPFAColorSize, 24,
508         NSOpenGLPFAAlphaSize, 8,
509         NSOpenGLPFADepthSize, 24,
510         NSOpenGLPFAWindow,
511         0
512     };
513
514     NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
515
516     if (!fmt)
517         return nil;
518
519     self = [super initWithFrame:NSMakeRect(0,0,10,10) pixelFormat:fmt];
520     [fmt release];
521
522     if (!self)
523         return nil;
524
525     /* enable HiDPI support on OS X 10.7 and later */
526     if (OSX_LION)
527         [self setWantsBestResolutionOpenGLSurface:YES];
528
529     /* Swap buffers only during the vertical retrace of the monitor.
530      http://developer.apple.com/documentation/GraphicsImaging/
531      Conceptual/OpenGL/chap5/chapter_5_section_44.html */
532     GLint params[] = { 1 };
533     CGLSetParameter ([[self openGLContext] CGLContextObj], kCGLCPSwapInterval, params);
534
535     [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
536     return self;
537 }
538
539 /**
540  * Gets called by the Open() method.
541  */
542 - (void)setFrameToBoundsOfView:(NSValue *)value
543 {
544     NSView *parentView = [value pointerValue];
545     NSRect frame;
546     /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
547     if (OSX_LION)
548         frame = [parentView convertRectToBacking:[parentView bounds]];
549     else
550         frame = [parentView bounds];
551     [self setFrame:frame];
552 }
553
554 /**
555  * Gets called by the Close and Open methods.
556  * (Non main thread).
557  */
558 - (void)setVoutDisplay:(vout_display_t *)aVd
559 {
560     @synchronized(self) {
561         vd = aVd;
562     }
563 }
564
565 /**
566  * Gets called when the vout will aquire the lock and flush.
567  * (Non main thread).
568  */
569 - (void)setVoutFlushing:(BOOL)flushing
570 {
571     if (!flushing)
572         return;
573     @synchronized(self) {
574         _hasPendingReshape = NO;
575     }
576 }
577
578 /**
579  * Can -drawRect skip rendering?.
580  */
581 - (BOOL)canSkipRendering
582 {
583     VLCAssertMainThread();
584
585     @synchronized(self) {
586         BOOL hasFirstFrame = vd && vd->sys->has_first_frame;
587         return !_hasPendingReshape && hasFirstFrame;
588     }
589 }
590
591
592 /**
593  * Local method that locks the gl context.
594  */
595 - (BOOL)lockgl
596 {
597     VLCAssertMainThread();
598     NSOpenGLContext *context = [self openGLContext];
599     CGLError err = CGLLockContext ([context CGLContextObj]);
600     if (err == kCGLNoError)
601         [context makeCurrentContext];
602     return err == kCGLNoError;
603 }
604
605 /**
606  * Local method that unlocks the gl context.
607  */
608 - (void)unlockgl
609 {
610     VLCAssertMainThread();
611     CGLUnlockContext ([[self openGLContext] CGLContextObj]);
612 }
613
614 /**
615  * Local method that force a rendering of a frame.
616  * This will get called if Cocoa forces us to redraw (via -drawRect).
617  */
618 - (void)render
619 {
620     VLCAssertMainThread();
621
622     // We may have taken some times to take the opengl Lock.
623     // Check here to see if we can just skip the frame as well.
624     if ([self canSkipRendering])
625         return;
626
627     BOOL hasFirstFrame;
628     @synchronized(self) { // vd can be accessed from multiple threads
629         hasFirstFrame = vd && vd->sys->has_first_frame;
630     }
631
632     if (hasFirstFrame) {
633         // This will lock gl.
634         vout_display_opengl_Display (vd->sys->vgl, &vd->source);
635     }
636     else
637         glClear (GL_COLOR_BUFFER_BIT);
638 }
639
640 /**
641  * Method called by Cocoa when the view is resized.
642  */
643 - (void)reshape
644 {
645     VLCAssertMainThread();
646
647     NSRect bounds;
648     /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
649     if (OSX_LION)
650         bounds = [self convertRectToBacking:[self bounds]];
651     else
652         bounds = [self bounds];
653     vout_display_place_t place;
654     
655     @synchronized(self) {
656         if (vd) {
657             vout_display_cfg_t cfg_tmp = *(vd->cfg);
658             cfg_tmp.display.width  = bounds.size.width;
659             cfg_tmp.display.height = bounds.size.height;
660
661             vout_display_PlacePicture (&place, &vd->source, &cfg_tmp, false);
662             vd->sys->place = place;
663             vout_display_SendEventDisplaySize (vd, bounds.size.width, bounds.size.height, vd->cfg->is_fullscreen);
664         }
665     }
666
667     if ([self lockgl]) {
668         // x / y are top left corner, but we need the lower left one
669         glViewport (place.x, bounds.size.height - (place.y + place.height), place.width, place.height);
670
671         @synchronized(self) {
672             // This may be cleared before -drawRect is being called,
673             // in this case we'll skip the rendering.
674             // This will save us for rendering two frames (or more) for nothing
675             // (one by the vout, one (or more) by drawRect)
676             _hasPendingReshape = YES;
677         }
678
679         [self unlockgl];
680
681         [super reshape];
682     }
683 }
684
685 /**
686  * Method called by Cocoa when the view is resized or the location has changed.
687  * We just need to make sure we are locking here.
688  */
689 - (void)update
690 {
691     VLCAssertMainThread();
692     BOOL success = [self lockgl];
693     if (!success)
694         return;
695
696     [super update];
697
698     [self unlockgl];
699 }
700
701 /**
702  * Method called by Cocoa to force redraw.
703  */
704 - (void)drawRect:(NSRect) rect
705 {
706     VLCAssertMainThread();
707
708     if ([self canSkipRendering])
709         return;
710
711     BOOL success = [self lockgl];
712     if (!success)
713         return;
714
715     [self render];
716
717     [self unlockgl];
718 }
719
720 - (void)renewGState
721 {
722     NSWindow *window = [self window];
723
724     // Remove flashes with splitter view.
725     if ([window respondsToSelector:@selector(disableScreenUpdatesUntilFlush)])
726         [window disableScreenUpdatesUntilFlush];
727
728     [super renewGState];
729 }
730
731 - (BOOL)isOpaque
732 {
733     return YES;
734 }
735
736 - (void)setWindowLevel:(NSNumber*)state
737 {
738     if ([state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE)
739         [[self window] setLevel: NSStatusWindowLevel];
740     else
741         [[self window] setLevel: NSNormalWindowLevel];
742 }
743
744 #pragma mark -
745 #pragma mark Mouse handling
746
747 - (void)mouseDown:(NSEvent *)o_event
748 {
749     if ([o_event type] == NSLeftMouseDown && !([o_event modifierFlags] &  NSControlKeyMask))
750     {
751         if ([o_event clickCount] <= 1)
752             vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_LEFT);
753     }
754
755     [super mouseDown:o_event];
756 }
757
758 - (void)otherMouseDown:(NSEvent *)o_event
759 {
760     vout_display_SendEventMousePressed (vd, MOUSE_BUTTON_CENTER);
761
762     [super otherMouseDown: o_event];
763 }
764
765 - (void)mouseUp:(NSEvent *)o_event
766 {
767     if ([o_event type] == NSLeftMouseUp)
768         vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_LEFT);
769
770     [super mouseUp: o_event];
771 }
772
773 - (void)otherMouseUp:(NSEvent *)o_event
774 {
775     vout_display_SendEventMouseReleased (vd, MOUSE_BUTTON_CENTER);
776
777     [super otherMouseUp: o_event];
778 }
779
780 - (void)mouseMoved:(NSEvent *)o_event
781 {
782     NSPoint ml;
783     NSRect s_rect;
784     BOOL b_inside;
785
786     /* on HiDPI displays, the point bounds don't equal the actual pixel based bounds */
787     if (OSX_LION)
788         s_rect = [self convertRectToBacking:[self bounds]];
789     else
790         s_rect = [self bounds];
791     ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
792     b_inside = [self mouse: ml inRect: s_rect];
793     
794     if (b_inside)
795     {
796         @synchronized (self)
797         {
798             if (vd)
799             {
800                 vout_display_place_t place = vd->sys->place;
801
802                 if (place.width > 0 && place.height > 0)
803                 {
804                     const int x = vd->source.i_x_offset +
805                     (int64_t)(ml.x - place.x) * vd->source.i_visible_width / place.width;
806                     const int y = vd->source.i_y_offset +
807                     (int64_t)((int)s_rect.size.height - (int)ml.y - place.y) * vd->source.i_visible_height / place.height;
808
809                     vout_display_SendEventMouseMoved (vd, x, y);
810                 }
811             }
812         }
813     }
814
815     [super mouseMoved: o_event];
816 }
817
818 - (void)mouseDragged:(NSEvent *)o_event
819 {
820     [self mouseMoved: o_event];
821     [super mouseDragged: o_event];
822 }
823
824 - (void)otherMouseDragged:(NSEvent *)o_event
825 {
826     [self mouseMoved: o_event];
827     [super otherMouseDragged: o_event];
828 }
829
830 - (void)rightMouseDragged:(NSEvent *)o_event
831 {
832     [self mouseMoved: o_event];
833     [super rightMouseDragged: o_event];
834 }
835
836 - (BOOL)acceptsFirstResponder
837 {
838     return YES;
839 }
840
841 - (BOOL)mouseDownCanMoveWindow
842 {
843     return YES;
844 }
845
846 @end