11e7cc0f6105b58ea916565441ef1734f0e89d00
[vlc.git] / modules / gui / macosx / vout.m
1 /*****************************************************************************
2  * vout.m: MacOS X video output module
3  *****************************************************************************
4  * Copyright (C) 2001-2008 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  *          Felix K├╝hne <fkuehne at videolan dot org>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
28  *****************************************************************************/
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #include <errno.h>                                                 /* ENOMEM */
34 #include <stdlib.h>                                                /* free() */
35 #include <string.h>
36
37 /* BeginFullScreen, EndFullScreen */
38 #include <QuickTime/QuickTime.h>
39
40 #include <vlc_keys.h>
41
42 #include "intf.h"
43 #include "fspanel.h"
44 #include "vout.h"
45 #import "controls.h"
46 #import "embeddedwindow.h"
47
48 /*****************************************************************************
49  * DeviceCallback: Callback triggered when the video-device variable is changed
50  *****************************************************************************/
51 int DeviceCallback( vlc_object_t *p_this, const char *psz_variable,
52                      vlc_value_t old_val, vlc_value_t new_val, void *param )
53 {
54     vlc_value_t val;
55     vout_thread_t *p_vout = (vout_thread_t *)p_this;
56
57     msg_Dbg( p_vout, "set %d", new_val.i_int );
58     var_Create( p_vout->p_libvlc, "video-device", VLC_VAR_INTEGER );
59     var_Set( p_vout->p_libvlc, "video-device", new_val );
60
61     val.b_bool = VLC_TRUE;
62     var_Set( p_vout, "intf-change", val );
63     return VLC_SUCCESS;
64 }
65
66
67 /*****************************************************************************
68  * VLCEmbeddedList implementation
69  *****************************************************************************/
70 @implementation VLCEmbeddedList
71
72 - (id)init
73 {
74     [super init];
75     o_embedded_array = [NSMutableArray array];
76     return self;
77 }
78
79 - (id)getEmbeddedVout
80 {
81     unsigned int i;
82
83     for( i = 0; i < [o_embedded_array count]; i++ )
84     {
85         id o_vout_view = [o_embedded_array objectAtIndex: i];
86         if( ![o_vout_view isUsed] )
87         {
88             [o_vout_view setUsed: YES];
89             return o_vout_view;
90         }
91     }
92     return nil;
93 }
94
95 - (void)releaseEmbeddedVout: (id)o_vout_view
96 {
97     if( [o_embedded_array containsObject: o_vout_view] )
98     {
99         [o_vout_view setUsed: NO];
100     }
101     else
102     {
103         msg_Warn( VLCIntf, "cannot find Video Output");
104     }
105 }
106
107 - (void)addEmbeddedVout: (id)o_vout_view
108 {
109     if( ![o_embedded_array containsObject: o_vout_view] )
110     {
111         [o_embedded_array addObject: o_vout_view];
112     }
113 }
114
115 - (BOOL)windowContainsEmbedded: (id)o_window
116 {
117 /*    if( ![[o_window className] isEqualToString: @"VLCVoutWindow"] )
118     {
119         NSLog( @"We were not given a VLCVoutWindow" );
120     }*/
121     return ([self getViewForWindow: o_window] == nil ? NO : YES );
122 }
123
124 - (id)getViewForWindow: (id)o_window
125 {
126     id o_enumerator = [o_embedded_array objectEnumerator];
127     id o_current_embedded;
128
129     while( (o_current_embedded = [o_enumerator nextObject]) )
130     {
131         if( [o_current_embedded getWindow] == o_window )
132         {
133             return o_current_embedded;
134         }
135     }
136     return nil;
137 }
138
139 @end
140
141 /*****************************************************************************
142  * VLCVoutView implementation
143  *****************************************************************************/
144 @implementation VLCVoutView
145
146 - (id)initWithFrame: (NSRect)frameRect
147 {
148     [super initWithFrame: frameRect];
149     p_vout = NULL;
150     o_view = nil;
151     s_frame = &frameRect;
152
153     p_real_vout = NULL;
154     o_window = nil;
155     return self;
156 }
157
158 - (BOOL)setVout: (vout_thread_t *) vout
159         subView: (NSView *) view
160           frame: (NSRect *) frame
161 {
162     int i_device;
163     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
164     NSArray *o_screens = [NSScreen screens];
165
166     p_vout  = vout;
167     o_view  = view;
168     s_frame = frame;
169
170     if( [o_screens count] <= 0 )
171     {
172         msg_Err( p_vout, "no OSX screens available" );
173         return NO;
174     }
175
176     p_real_vout = [VLCVoutView getRealVout: p_vout];
177
178     /* Get the pref value when this is the first time, otherwise retrieve the device from the top level video-device var */
179     if( var_Type( p_real_vout->p_libvlc, "video-device" ) == 0 )
180     {
181         i_device = var_GetInteger( p_vout, "macosx-vdev" );
182     }
183     else
184     {
185         i_device = var_GetInteger( p_real_vout->p_libvlc, "video-device" );
186     }
187
188     /* Setup the menuitem for the multiple displays. */
189     if( var_Type( p_real_vout, "video-device" ) == 0 )
190     {
191         int i = 1;
192         vlc_value_t val2, text;
193         NSScreen * o_screen;
194
195         var_Create( p_real_vout, "video-device", VLC_VAR_INTEGER |
196                                             VLC_VAR_HASCHOICE );
197         text.psz_string = _("Video Device");
198         var_Change( p_real_vout, "video-device", VLC_VAR_SETTEXT, &text, NULL );
199
200         NSEnumerator * o_enumerator = [o_screens objectEnumerator];
201
202         val2.i_int = 0;
203         text.psz_string = _("Default");
204         var_Change( p_real_vout, "video-device",
205                         VLC_VAR_ADDCHOICE, &val2, &text );
206         var_Set( p_real_vout, "video-device", val2 );
207
208         while( (o_screen = [o_enumerator nextObject]) != NULL )
209         {
210             char psz_temp[255];
211             NSRect s_rect = [o_screen frame];
212
213             snprintf( psz_temp, sizeof(psz_temp)/sizeof(psz_temp[0])-1,
214                       "%s %d (%dx%d)", _("Screen"), i,
215                       (int)s_rect.size.width, (int)s_rect.size.height );
216
217             text.psz_string = psz_temp;
218             val2.i_int = (int)[o_screen displayID];
219             var_Change( p_real_vout, "video-device",
220                         VLC_VAR_ADDCHOICE, &val2, &text );
221             if( (int)[o_screen displayID] == i_device )
222             {
223                 var_Set( p_real_vout, "video-device", val2 );
224             }
225             i++;
226         }
227
228         var_AddCallback( p_real_vout, "video-device", DeviceCallback,
229                          NULL );
230
231         val2.b_bool = VLC_TRUE;
232         var_Set( p_real_vout, "intf-change", val2 );
233     }
234
235     /* Add the view. It's automatically resized to fit the window */
236     [self addSubview: o_view];
237     [self setAutoresizesSubviews: YES];
238     [o_pool release];
239
240     return YES;
241 }
242
243 - (void)resizeSubviewsWithOldSize:(NSSize)oldBoundsSize
244 {
245     [super resizeSubviewsWithOldSize: oldBoundsSize];
246     [o_view setFrameSize: [self frame].size];
247 }
248
249 - (void)drawRect:(NSRect)rect
250 {
251     /* When there is no subview we draw a black background */
252     [self lockFocus];
253     [[NSColor blackColor] set];
254     NSRectFill(rect);
255     [self unlockFocus];
256 }
257
258 - (void)closeVout
259 {
260     [[[[VLCMain sharedInstance] getControls] getFSPanel] fadeOut];
261
262     /* Make sure we don't see a white flash */
263     [[self window] disableScreenUpdatesUntilFlush];
264     [o_view removeFromSuperview];
265     o_view = nil;
266     p_vout = NULL;
267     s_frame = nil;
268     o_window = nil;
269     p_real_vout = NULL;
270 }
271
272 - (void)updateTitle
273 {
274     NSString * o_title = nil; 
275     NSMutableString * o_mrl = nil;
276     input_thread_t * p_input;
277
278     if( p_vout == NULL )
279     {
280         return;
281     }
282
283     p_input = vlc_object_find( p_vout, VLC_OBJECT_INPUT, FIND_PARENT );
284
285     if( p_input == NULL )
286     {
287         return;
288     }
289
290     char *psz_nowPlaying = input_item_GetNowPlaying ( input_GetItem( p_input ) );
291     char *psz_name = input_item_GetName( input_GetItem( p_input ) );
292     char *psz_uri = input_item_GetURI( input_GetItem( p_input ) );
293     if( psz_nowPlaying != NULL )
294         o_title = [NSString stringWithUTF8String: psz_nowPlaying];
295     else if( psz_name != NULL )
296         o_title = [NSString stringWithUTF8String: psz_name];
297
298     if( psz_uri != NULL )
299         o_mrl = [NSMutableString stringWithUTF8String: psz_uri];
300
301     FREENULL( psz_nowPlaying );
302     FREENULL( psz_name );
303     FREENULL( psz_uri );
304
305     if( o_title == nil )
306         o_title = o_mrl;
307
308     if( o_mrl != nil )
309     {
310         /* FIXME once psz_access is exported, we could check if we are
311          * reading from a file in a smarter way. */
312
313         NSRange prefix_range = [o_mrl rangeOfString: @"file:"];
314         if( prefix_range.location != NSNotFound )
315             [o_mrl deleteCharactersInRange: prefix_range];
316
317         if( [o_mrl characterAtIndex:0] == '/' )
318         {
319             /* it's a local file */
320             [o_window setRepresentedFilename: o_mrl];
321         }
322         else
323         {
324             /* it's from the network or somewhere else,
325              * we clear the previous path */
326             [o_window setRepresentedFilename: @""];
327         }
328         [o_window setTitle: o_title];
329     }
330     else
331     {
332         [o_window setTitle: [NSString stringWithUTF8String: VOUT_TITLE]];
333     }
334     vlc_object_release( p_input );
335 }
336
337
338 - (void)setOnTop:(BOOL)b_on_top
339 {
340     if( b_on_top )
341     {
342         [o_window setLevel: NSStatusWindowLevel];
343     }
344     else
345     {
346         [o_window setLevel: NSNormalWindowLevel];
347     }
348 }
349
350 - (void)scaleWindowWithFactor: (float)factor animate: (BOOL)animate
351 {
352     NSSize newsize;
353     int i_corrected_height, i_corrected_width;
354     NSPoint topleftbase;
355     NSPoint topleftscreen;
356
357     if ( !p_vout->b_fullscreen )
358     {
359         NSView *mainView;
360         NSRect new_frame;
361         topleftbase.x = 0;
362         topleftbase.y = [o_window frame].size.height;
363         topleftscreen = [o_window convertBaseToScreen: topleftbase];
364
365         if( p_vout->render.i_height * p_vout->render.i_aspect >
366                         p_vout->render.i_width * VOUT_ASPECT_FACTOR )
367         {
368             i_corrected_width = p_vout->render.i_height * p_vout->render.i_aspect /
369                                             VOUT_ASPECT_FACTOR;
370             newsize.width = (int) ( i_corrected_width * factor );
371             newsize.height = (int) ( p_vout->render.i_height * factor );
372         }
373         else
374         {
375             i_corrected_height = p_vout->render.i_width * VOUT_ASPECT_FACTOR /
376                                             p_vout->render.i_aspect;
377             newsize.width = (int) ( p_vout->render.i_width * factor );
378             newsize.height = (int) ( i_corrected_height * factor );
379         }
380
381         /* In fullscreen mode we need to use a view that is different from
382          * ourselves, with the VLCEmbeddedWindow */
383         if([o_window isKindOfClass:[VLCEmbeddedWindow class]])
384             mainView = [o_window mainView];
385         else
386             mainView = self;
387
388         /* Calculate the window's new size */
389         new_frame.size.width = [o_window frame].size.width -
390                                     [mainView frame].size.width + newsize.width;
391         new_frame.size.height = [o_window frame].size.height -
392                                     [mainView frame].size.height + newsize.height;
393
394         new_frame.origin.x = topleftscreen.x;
395         new_frame.origin.y = topleftscreen.y - new_frame.size.height;
396
397         [o_window setFrame: new_frame display: animate animate: animate];
398
399         p_vout->i_changes |= VOUT_SIZE_CHANGE;
400     }
401 }
402
403 - (void)toggleFloatOnTop
404 {
405     vlc_value_t val;
406
407     if( !p_real_vout ) return;
408     if( var_Get( p_real_vout, "video-on-top", &val )>=0 && val.b_bool)
409     {
410         val.b_bool = VLC_FALSE;
411     }
412     else
413     {
414         val.b_bool = VLC_TRUE;
415     }
416     var_Set( p_real_vout, "video-on-top", val );
417 }
418
419 - (void)toggleFullscreen
420 {
421     vlc_value_t val;
422     if( !p_real_vout ) return;
423     var_Get( p_real_vout, "fullscreen", &val );
424     val.b_bool = !val.b_bool;
425     var_Set( p_real_vout, "fullscreen", val );
426 }
427
428 - (BOOL)isFullscreen
429 {
430     vlc_value_t val;
431     if( !p_real_vout ) return NO;
432     var_Get( p_real_vout, "fullscreen", &val );
433     return( val.b_bool );
434 }
435
436 - (void)snapshot
437 {
438     vout_Control( p_real_vout, VOUT_SNAPSHOT );
439 }
440
441 - (void)manage
442 {
443     /* Disable Screensaver, when we're playing something, but allow it on pause */
444     if( !VLCIntf || !VLCIntf->p_sys || !VLCIntf->p_sys->i_play_status )
445         return;
446
447     if( VLCIntf->p_sys->i_play_status == PLAYING_S )
448         UpdateSystemActivity( UsrActivity );
449 }
450
451 - (id)getWindow
452 {
453     return o_window;
454 }
455
456 - (void)scrollWheel:(NSEvent *)theEvent
457 {
458     VLCControls * o_controls = (VLCControls *)[[NSApp delegate] getControls];
459     [o_controls scrollWheel: theEvent];
460 }
461
462 - (void)keyDown:(NSEvent *)o_event
463 {
464     unichar key = 0;
465     vlc_value_t val;
466     unsigned int i_pressed_modifiers = 0;
467     val.i_int = 0;
468
469     i_pressed_modifiers = [o_event modifierFlags];
470
471     if( i_pressed_modifiers & NSShiftKeyMask )
472         val.i_int |= KEY_MODIFIER_SHIFT;
473     if( i_pressed_modifiers & NSControlKeyMask )
474         val.i_int |= KEY_MODIFIER_CTRL;
475     if( i_pressed_modifiers & NSAlternateKeyMask )
476         val.i_int |= KEY_MODIFIER_ALT;
477     if( i_pressed_modifiers & NSCommandKeyMask )
478         val.i_int |= KEY_MODIFIER_COMMAND;
479
480     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
481
482     if( key )
483     {
484         /* Escape should always get you out of fullscreen */
485         if( key == (unichar) 0x1b )
486         {
487              if( p_real_vout && [self isFullscreen] )
488              {
489                  [self toggleFullscreen];
490              }
491         }
492         else if ( key == ' ' )
493         {
494             vlc_value_t val;
495             val.i_int = config_GetInt( p_vout, "key-play-pause" );
496             var_Set( p_vout->p_libvlc, "key-pressed", val );
497         }
498         else
499         {
500             val.i_int |= CocoaKeyToVLC( key );
501             var_Set( p_vout->p_libvlc, "key-pressed", val );
502         }
503     }
504     else
505     {
506         [super keyDown: o_event];
507     }
508 }
509
510 - (void)mouseDown:(NSEvent *)o_event
511 {
512     vlc_value_t val;
513
514     if( p_vout )
515     {
516         if( ( [o_event type] == NSLeftMouseDown ) &&
517           ( ! ( [o_event modifierFlags] &  NSControlKeyMask ) ) )
518         {
519             if( [o_event clickCount] <= 1 )
520             {
521                 /* single clicking */
522                 var_Get( p_vout, "mouse-button-down", &val );
523                 val.i_int |= 1;
524                 var_Set( p_vout, "mouse-button-down", val );
525             }
526             else
527             {
528                 /* multiple clicking */
529                 [self toggleFullscreen];
530             }
531         }
532         else if( ( [o_event type] == NSRightMouseDown ) ||
533                ( ( [o_event type] == NSLeftMouseDown ) &&
534                  ( [o_event modifierFlags] &  NSControlKeyMask ) ) )
535         {
536             msg_Dbg( p_vout, "received NSRightMouseDown (generic method) or Ctrl clic" );
537             [NSMenu popUpContextMenu: [[VLCMain sharedInstance] getVoutMenu] withEvent: o_event forView: [[[VLCMain sharedInstance] getControls] getVoutView]];
538         }
539     }
540
541     [super mouseDown: o_event];
542 }
543
544 - (void)otherMouseDown:(NSEvent *)o_event
545 {
546     vlc_value_t val;
547
548     if( p_vout && [o_event type] == NSOtherMouseDown )
549     {
550         var_Get( p_vout, "mouse-button-down", &val );
551         val.i_int |= 2;
552         var_Set( p_vout, "mouse-button-down", val );
553     }
554
555     [super mouseDown: o_event];
556 }
557
558 - (void)rightMouseDown:(NSEvent *)o_event
559 {
560     if( p_vout && [o_event type] == NSRightMouseDown )
561     {
562         msg_Dbg( p_vout, "received NSRightMouseDown (specific method)" );
563         [NSMenu popUpContextMenu: [[VLCMain sharedInstance] getVoutMenu] withEvent: o_event forView: [[[VLCMain sharedInstance] getControls] getVoutView]];
564     }
565
566     [super mouseDown: o_event];
567 }
568
569 - (void)mouseUp:(NSEvent *)o_event
570 {
571     vlc_value_t val;
572
573     if( p_vout && [o_event type] == NSLeftMouseUp )
574     {
575         vlc_value_t b_val;
576         b_val.b_bool = VLC_TRUE;
577         var_Set( p_vout, "mouse-clicked", b_val );
578
579         var_Get( p_vout, "mouse-button-down", &val );
580         val.i_int &= ~1;
581         var_Set( p_vout, "mouse-button-down", val );
582     }
583
584     [super mouseUp: o_event];
585 }
586
587 - (void)otherMouseUp:(NSEvent *)o_event
588 {
589     vlc_value_t val;
590
591     if( p_vout && [o_event type] == NSOtherMouseUp )
592     {
593         var_Get( p_vout, "mouse-button-down", &val );
594         val.i_int &= ~2;
595         var_Set( p_vout, "mouse-button-down", val );
596     }
597
598     [super mouseUp: o_event];
599 }
600
601 - (void)rightMouseUp:(NSEvent *)o_event
602 {
603     if( p_vout && [o_event type] == NSRightMouseUp )
604     {
605         /* FIXME: this isn't the appropriate place, but we can't receive
606          * NSRightMouseDown some how */
607         msg_Dbg( p_vout, "received NSRightMouseUp" );
608         [NSMenu popUpContextMenu: [[VLCMain sharedInstance] getVoutMenu] withEvent: o_event forView: [[[VLCMain sharedInstance] getControls] getVoutView]];
609     }
610
611     [super mouseUp: o_event];
612 }
613
614 - (void)mouseDragged:(NSEvent *)o_event
615 {
616     [self mouseMoved: o_event];
617 }
618
619 - (void)otherMouseDragged:(NSEvent *)o_event
620 {
621     [self mouseMoved: o_event];
622 }
623
624 - (void)rightMouseDragged:(NSEvent *)o_event
625 {
626     [self mouseMoved: o_event];
627 }
628
629 - (void)mouseMoved:(NSEvent *)o_event
630 {
631     NSPoint ml;
632     NSRect s_rect;
633     BOOL b_inside;
634
635     if( p_vout )
636     {
637         s_rect = [o_view bounds];
638         ml = [o_view convertPoint: [o_event locationInWindow] fromView: nil];
639         b_inside = [o_view mouse: ml inRect: s_rect];
640
641         if( b_inside )
642         {
643             vlc_value_t val;
644             unsigned int i_width, i_height, i_x, i_y;
645
646             vout_PlacePicture( p_vout, (unsigned int)s_rect.size.width,
647                                        (unsigned int)s_rect.size.height,
648                                        &i_x, &i_y, &i_width, &i_height );
649
650             val.i_int = ( ((int)ml.x) - i_x ) *
651                         p_vout->render.i_width / i_width;
652             var_Set( p_vout, "mouse-x", val );
653
654             if( [[o_view className] isEqualToString: @"VLCGLView"] )
655             {
656                 val.i_int = ( ((int)(s_rect.size.height - ml.y)) - i_y ) *
657                             p_vout->render.i_height / i_height;
658             }
659             else
660             {
661                 val.i_int = ( ((int)ml.y) - i_y ) *
662                             p_vout->render.i_height / i_height;
663             }
664             var_Set( p_vout, "mouse-y", val );
665
666             val.b_bool = VLC_TRUE;
667             var_Set( p_vout, "mouse-moved", val );
668         }
669         if( [self isFullscreen] )
670             [[[[VLCMain sharedInstance] getControls] getFSPanel] fadeIn];
671     }
672
673     [super mouseMoved: o_event];
674 }
675
676 - (BOOL)acceptsFirstResponder
677 {
678     return YES;
679 }
680
681 - (BOOL)becomeFirstResponder
682 {
683     return YES;
684 }
685
686 - (BOOL)resignFirstResponder
687 {
688     /* We need to stay the first responder or we'll miss some
689        events */
690     return NO;
691 }
692
693 /* Class methods used by the different vout modules */
694
695 + (vout_thread_t *)getRealVout: (vout_thread_t *)p_vout
696 {
697     /* p_real_vout: the vout we have to use to check for video-on-top
698        and a few other things. If we are the QuickTime output, it's us.
699        It we are the OpenGL provider, it is our parent. */
700     if( p_vout->i_object_type == VLC_OBJECT_OPENGL )
701     {
702         return (vout_thread_t *) p_vout->p_parent;
703     }
704     else
705     {
706         return p_vout;
707     }
708
709 }
710
711 + (id)getVoutView: (vout_thread_t *)p_vout subView: (NSView *)view
712                                     frame: (NSRect *)s_frame
713 {
714     vlc_value_t value_drawable;
715     int i_timeout;
716     id o_return = nil;
717
718     var_Get( p_vout->p_libvlc, "drawable", &value_drawable );
719
720     var_Create( p_vout, "macosx-vdev", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
721     var_Create( p_vout, "macosx-stretch", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
722     var_Create( p_vout, "macosx-opaqueness", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
723     var_Create( p_vout, "macosx-background", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
724     var_Create( p_vout, "macosx-black", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
725     var_Create( p_vout, "embedded-video", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
726
727     /* We only wait for NSApp to initialise if we're not embedded (as in the
728      * case of the Mozilla plugin).  We can tell whether we're embedded or not
729      * by examining the "drawable" value: if it's zero, we're running in the
730      * main Mac intf; if it's non-zero, we're embedded. */
731     if( value_drawable.i_int == 0 )
732     {
733         /* Wait for a MacOS X interface to appear. Timeout is 2 seconds. */
734         for( i_timeout = 20 ; i_timeout-- ; )
735         {
736             if( NSApp == NULL )
737             {
738                 msleep( INTF_IDLE_SLEEP );
739             }
740         }
741
742         if( NSApp == NULL )
743         {
744             /* No MacOS X intf, unable to communicate with MT */
745             msg_Err( p_vout, "no MacOS X interface present" );
746             return nil;
747         }
748         else
749         {
750             if ( VLCIntf && !(p_vout->b_fullscreen) &&
751                         !(var_GetBool( p_vout, "macosx-background" )) &&
752                         var_GetBool( p_vout, "embedded-video") )
753             {
754                 o_return = [[[VLCMain sharedInstance] getEmbeddedList]
755                                                             getEmbeddedVout];
756             }
757         }
758     }
759
760     /* No embedded vout is available */
761     if( o_return == nil )
762     {
763         NSRect null_rect;
764         bzero( &null_rect, sizeof( NSRect ) );
765         o_return = [[VLCDetachedVoutView alloc] initWithFrame: null_rect ];
766     }
767     [o_return setVout: p_vout subView: view frame: s_frame];
768     return o_return;
769 }
770
771 - (void)enterFullscreen
772 {
773     [[o_view class] performSelectorOnMainThread:@selector(resetVout:) withObject:[NSValue valueWithPointer:p_vout] waitUntilDone:YES];
774     [[[[VLCMain sharedInstance] getControls] getFSPanel] setActive: nil];
775 }
776
777 - (void)leaveFullscreen
778 {
779     [[o_view class] performSelectorOnMainThread:@selector(resetVout:) withObject:[NSValue valueWithPointer:p_vout] waitUntilDone:YES];
780     [[[[VLCMain sharedInstance] getControls] getFSPanel] setNonActive: nil];
781 }
782
783 @end
784
785 /*****************************************************************************
786  * VLCDetachedVoutView implementation
787  *****************************************************************************/
788 @implementation VLCDetachedVoutView
789
790 - (id)initWithFrame: (NSRect)frameRect
791 {
792     [super initWithFrame: frameRect];
793     i_time_mouse_last_moved = 0;
794     return self;
795 }
796
797 - (bool)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
798                      frame: (NSRect *) s_arg_frame
799 {
800     BOOL b_return = [super setVout: p_arg_vout subView: view frame:s_arg_frame];
801     i_time_mouse_last_moved = mdate();
802     o_window = [[VLCVoutWindow alloc] initWithVout: p_arg_vout view: self
803                                                     frame: s_arg_frame];
804     [self updateTitle];
805     [view setFrame: [self frame]];
806
807     if( var_GetBool( p_real_vout, "video-on-top" ) )
808     {
809         [o_window setLevel: NSStatusWindowLevel];
810     }
811
812
813     [o_window setAcceptsMouseMovedEvents: TRUE];
814     return b_return;
815 }
816
817 - (void)closeVout
818 {
819     [o_window closeWindow];
820     [o_window setAcceptsMouseMovedEvents: NO];
821     i_time_mouse_last_moved = 0;
822     [super closeVout];
823 }
824
825 - (void)mouseMoved:(NSEvent *)o_event
826 {
827     i_time_mouse_last_moved = mdate();
828     [super mouseMoved: o_event];
829 }
830
831 - (void)hideMouse:(BOOL)b_hide
832 {
833     BOOL b_inside;
834     NSPoint ml;
835     NSView *o_contents = [o_window contentView];
836
837     ml = [o_window convertScreenToBase:[NSEvent mouseLocation]];
838     ml = [o_contents convertPoint:ml fromView:nil];
839     b_inside = [o_contents mouse: ml inRect: [o_contents bounds]];
840
841     if( b_hide && b_inside )
842     {
843         [NSCursor setHiddenUntilMouseMoves: YES];
844     }
845     else if( !b_hide )
846     {
847         [NSCursor setHiddenUntilMouseMoves: NO];
848     }
849 }
850
851 - (void)manage
852 {
853     [super manage];
854     if( p_vout->b_fullscreen )
855     {
856         if( mdate() - i_time_mouse_last_moved > 3000000 )
857         {
858             [self hideMouse: YES];
859         }
860     }
861     else
862     {
863         [self hideMouse: NO];
864     }
865 }
866
867 @end
868
869 /*****************************************************************************
870  * VLCEmbeddedVoutView implementation
871  *****************************************************************************/
872
873 @implementation VLCEmbeddedVoutView
874
875 - (id)initWithFrame: (NSRect)frameRect
876 {
877     [super initWithFrame: frameRect];
878     b_used = NO;
879     [[[VLCMain sharedInstance] getEmbeddedList] addEmbeddedVout: self];
880     return self;
881 }
882
883 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
884                  frame: (NSRect *)s_arg_frame showWindow: (BOOL)b_show_window
885 {
886     BOOL b_return;
887     b_return = [super setVout: p_arg_vout subView: view frame: s_arg_frame];
888     if( b_return )
889     {
890         o_window = [self window];
891         if (b_show_window)
892             [o_window makeKeyAndOrderFront: self];
893         [o_window setAcceptsMouseMovedEvents: TRUE];
894
895         if( var_GetBool( p_real_vout, "video-on-top" ) )
896         {
897             [o_window setLevel: NSStatusWindowLevel];
898         }
899
900         [view setFrameSize: [self frame].size];
901     }
902     return b_return;
903 }
904
905 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
906                      frame: (NSRect *) s_arg_frame
907
908 {
909     return [self setVout: p_arg_vout subView: view frame:s_arg_frame showWindow: YES];
910 }
911
912 - (void)setUsed: (BOOL)b_new_used
913 {
914     b_used = b_new_used;
915 }
916
917 - (BOOL)isUsed
918 {
919     return b_used;
920 }
921
922 - (void)closeVout
923 {
924     [super closeVout];
925     [o_window setAcceptsMouseMovedEvents: NO];
926     [[[VLCMain sharedInstance] getEmbeddedList] releaseEmbeddedVout: self];
927 }
928
929
930 @end
931
932 @implementation VLCDetachedEmbeddedVoutView
933 - (void)awakeFromNib
934 {
935     o_embeddedwindow = [self window];
936 }
937
938 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
939                      frame: (NSRect *) s_arg_frame
940 {
941     BOOL b_return = [super setVout: p_arg_vout subView: view frame: s_arg_frame showWindow: NO];
942
943     /* o_window needs to point to our o_embeddedwindow, super might have set it
944      * to the fullscreen window that o_embeddedwindow setups during fullscreen */
945     o_window = o_embeddedwindow;
946  
947     if( b_return )
948     {
949         [o_window lockFullscreenAnimation];
950
951         [o_window setAlphaValue: var_GetFloat( p_vout, "macosx-opaqueness" )];
952
953         [self updateTitle];
954
955         /* Make the window the front and key window before animating */
956         if ([o_window isVisible] && (![o_window isFullscreen]))
957             [o_window makeKeyAndOrderFront: self];
958
959         [self scaleWindowWithFactor: 1.0 animate: [o_window isVisible] && (![o_window isFullscreen])];
960
961         [o_window setAspectRatio:NSMakeSize([o_window frame].size.width, [o_window frame].size.height)];
962
963         /* Make sure our window is visible, if we are not in fullscreen */
964         if (![o_window isFullscreen])
965             [o_window makeKeyAndOrderFront: self];
966         [o_window unlockFullscreenAnimation];
967
968     }
969     return b_return;
970 }
971
972 - (void)closeVout
973 {
974     playlist_t * p_playlist = pl_Yield( VLCIntf );
975
976     if(!playlist_IsPlaying( p_playlist ))
977         [o_window performSelectorOnMainThread: @selector(orderOut:) withObject: self waitUntilDone: YES];
978  
979     vlc_object_release( p_playlist );
980
981     [super closeVout];
982 }
983
984 - (void)enterFullscreen
985 {
986     /* We are in a VLCEmbeddedWindow */
987     [o_embeddedwindow performSelectorOnMainThread: @selector(enterFullscreen) withObject: NULL waitUntilDone: YES];
988 }
989
990 - (void)leaveFullscreen
991 {
992     /* We are in a VLCEmbeddedWindow */
993     [o_embeddedwindow performSelectorOnMainThread: @selector(leaveFullscreen) withObject: NULL waitUntilDone: YES];
994 }
995 @end
996
997 /*****************************************************************************
998  * VLCVoutWindow implementation
999  *****************************************************************************/
1000 @implementation VLCVoutWindow
1001
1002 - (id) initWithVout: (vout_thread_t *) vout view: (VLCVoutView *) view
1003                      frame: (NSRect *) frame
1004 {
1005     p_vout  = vout;
1006     o_view  = view;
1007     s_frame = frame;
1008
1009     [self performSelectorOnMainThread: @selector(initReal:)
1010         withObject: NULL waitUntilDone: YES];
1011
1012     if( !b_init_ok )
1013     {
1014         return NULL;
1015     }
1016
1017     return self;
1018 }
1019
1020 - (id)initReal: (id) sender
1021 {
1022     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1023     NSArray *o_screens = [NSScreen screens];
1024     NSScreen *o_screen;
1025     vlc_bool_t b_menubar_screen = VLC_FALSE;
1026     int i_device;
1027
1028     b_init_ok = VLC_FALSE;
1029
1030     p_real_vout = [VLCVoutView getRealVout: p_vout];
1031     i_device = var_GetInteger( p_real_vout->p_libvlc, "video-device" );
1032     b_black = NO;
1033     b_embedded = var_GetBool( p_vout, "embedded-video" );
1034
1035     /* Find out on which screen to open the window */
1036     o_screen = [NSScreen screenWithDisplayID: (CGDirectDisplayID)i_device];
1037
1038     if( !o_screen )
1039         o_screen = [NSScreen mainScreen];
1040
1041     if( [o_screen isMainScreen] )
1042         b_menubar_screen = VLC_TRUE;
1043
1044     if( p_vout->b_fullscreen )
1045     {
1046         CGDisplayFadeReservationToken token;
1047         NSRect screen_rect = [o_screen frame];
1048         screen_rect.origin.x = screen_rect.origin.y = 0;
1049
1050         b_black = var_GetBool( p_vout, "macosx-black" );
1051
1052         /* move the FSPanel to front in case that it is currently shown
1053          * this won't and is not supposed to work when it's fading right now */
1054         if( [[[[VLCMain sharedInstance] getControls] getFSPanel] isDisplayed] )
1055             [[[[VLCMain sharedInstance] getControls] getFSPanel] setActive: nil];
1056  
1057         /* tell the fspanel to move itself to front next time it's triggered */
1058         [[[[VLCMain sharedInstance] getControls] getFSPanel] setVoutWasUpdated: i_device];
1059
1060         /* Creates a window with size: screen_rect on o_screen */
1061         [self initWithContentRect: screen_rect
1062               styleMask: NSBorderlessWindowMask
1063               backing: NSBackingStoreBuffered
1064               defer: YES screen: o_screen];
1065  
1066         if( b_menubar_screen )
1067         {
1068             SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
1069         }
1070         if( b_black == VLC_TRUE )
1071         {
1072             CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
1073             CGDisplayFade( token, 0.6 , kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES );
1074
1075             [o_screen blackoutOtherScreens];
1076
1077             CGDisplayFade( token, 0.3 , kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO );
1078             CGReleaseDisplayFadeReservation( token);
1079         }
1080     }
1081     else if( var_GetBool( p_vout, "macosx-background" ) )
1082     {
1083         NSRect screen_rect = [o_screen frame];
1084         screen_rect.origin.x = screen_rect.origin.y = 0;
1085
1086         /* Creates a window with size: screen_rect on o_screen */
1087         [self initWithContentRect: screen_rect
1088               styleMask: NSBorderlessWindowMask
1089               backing: NSBackingStoreBuffered
1090               defer: YES screen: o_screen];
1091
1092         [self setLevel: CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
1093     }
1094     else
1095     {
1096         unsigned int i_stylemask = NSTitledWindowMask |
1097                                    NSMiniaturizableWindowMask |
1098                                    NSClosableWindowMask |
1099                                    NSResizableWindowMask;
1100
1101         NSRect s_rect;
1102         if( !s_frame )
1103         {
1104             s_rect.size.width  = p_vout->i_window_width;
1105             s_rect.size.height = p_vout->i_window_height;
1106         }
1107         else
1108         {
1109             s_rect = *s_frame;
1110         }
1111
1112         [self initWithContentRect: s_rect
1113               styleMask: i_stylemask
1114               backing: NSBackingStoreBuffered
1115               defer: YES screen: o_screen];
1116
1117         [self setAlphaValue: var_GetFloat( p_vout, "macosx-opaqueness" )];
1118
1119         if( !s_frame )
1120         {
1121             [self center];
1122         }
1123     }
1124
1125     [self makeKeyAndOrderFront: nil];
1126     [self setReleasedWhenClosed: YES];
1127
1128     /* We'll catch mouse events */
1129     [self makeFirstResponder: o_view];
1130
1131     /* Add the view. It's automatically resized to fit the window */
1132     [self setContentView: o_view];
1133
1134     [o_pool release];
1135
1136     b_init_ok = VLC_TRUE;
1137     return self;
1138 }
1139
1140 - (void)close
1141 {
1142     [o_view closeVout];
1143 }
1144
1145 - (void)closeWindow
1146 {
1147     /* XXX waitUntilDone = NO to avoid a possible deadlock when hitting
1148        Command-Q */
1149     [self performSelectorOnMainThread: @selector(closeReal:)
1150         withObject: NULL waitUntilDone: NO];
1151 }
1152
1153 - (id)closeReal:(id)sender
1154 {
1155     if( b_black == VLC_TRUE )
1156     {
1157         CGDisplayFadeReservationToken token;
1158         CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
1159         CGDisplayFade( token, 0.3 , kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES );
1160  
1161         [self disableScreenUpdatesUntilFlush];
1162         [self orderOut: self];
1163
1164         CGDisplayFade( token, 0.6 , kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, YES );
1165         CGReleaseDisplayFadeReservation( token);
1166         CGDisplayRestoreColorSyncSettings();
1167     }
1168     [NSScreen unblackoutScreens];
1169
1170     SetSystemUIMode( kUIModeNormal, 0);
1171     [super close];
1172     /* this does only work in embedded mode */
1173     if( b_embedded == VLC_TRUE )
1174         [[[[VLCMain sharedInstance] getControls] getFSPanel] orderOut: self];
1175
1176     return NULL;
1177 }
1178
1179 - (id)getVoutView
1180 {
1181     return o_view;
1182 }
1183
1184 - (BOOL)canBecomeKeyWindow
1185 {
1186     return YES;
1187 }
1188
1189 /* Sometimes crashes VLC....
1190 - (BOOL)performKeyEquivalent:(NSEvent *)o_event
1191 {
1192         return [[VLCMain sharedInstance] hasDefinedShortcutKey:o_event];
1193 }*/
1194
1195 /* This is actually the same as VLCControls::stop. */
1196
1197 - (BOOL)windowShouldClose:(id)sender
1198 {
1199     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
1200                                                        FIND_ANYWHERE );
1201     if( p_playlist == NULL )
1202     {
1203         return NO;
1204     }
1205
1206     playlist_Stop( p_playlist );
1207     vlc_object_release( p_playlist );
1208
1209     /* The window will be closed by the intf later. */
1210     return NO;
1211 }
1212
1213
1214 @end