Hide Mouse Timeout on mac.
[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     unsigned int i_mouse_hide_timeout =
855         var_GetInteger(p_vout, "mouse-hide-timeout") * 1000;
856     if( p_vout->b_fullscreen )
857     {
858         if( mdate() - i_time_mouse_last_moved > i_mouse_hide_timeout )
859         {
860             [self hideMouse: YES];
861         }
862     }
863     else
864     {
865         [self hideMouse: NO];
866     }
867 }
868
869 @end
870
871 /*****************************************************************************
872  * VLCEmbeddedVoutView implementation
873  *****************************************************************************/
874
875 @implementation VLCEmbeddedVoutView
876
877 - (id)initWithFrame: (NSRect)frameRect
878 {
879     [super initWithFrame: frameRect];
880     b_used = NO;
881     [[[VLCMain sharedInstance] getEmbeddedList] addEmbeddedVout: self];
882     return self;
883 }
884
885 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
886                  frame: (NSRect *)s_arg_frame showWindow: (BOOL)b_show_window
887 {
888     BOOL b_return;
889     b_return = [super setVout: p_arg_vout subView: view frame: s_arg_frame];
890     if( b_return )
891     {
892         o_window = [self window];
893         if (b_show_window)
894             [o_window makeKeyAndOrderFront: self];
895         [o_window setAcceptsMouseMovedEvents: TRUE];
896
897         if( var_GetBool( p_real_vout, "video-on-top" ) )
898         {
899             [o_window setLevel: NSStatusWindowLevel];
900         }
901
902         [view setFrameSize: [self frame].size];
903     }
904     return b_return;
905 }
906
907 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
908                      frame: (NSRect *) s_arg_frame
909
910 {
911     return [self setVout: p_arg_vout subView: view frame:s_arg_frame showWindow: YES];
912 }
913
914 - (void)setUsed: (BOOL)b_new_used
915 {
916     b_used = b_new_used;
917 }
918
919 - (BOOL)isUsed
920 {
921     return b_used;
922 }
923
924 - (void)closeVout
925 {
926     [super closeVout];
927     [o_window setAcceptsMouseMovedEvents: NO];
928     [[[VLCMain sharedInstance] getEmbeddedList] releaseEmbeddedVout: self];
929 }
930
931
932 @end
933
934 @implementation VLCDetachedEmbeddedVoutView
935 - (void)awakeFromNib
936 {
937     o_embeddedwindow = [self window];
938 }
939
940 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
941                      frame: (NSRect *) s_arg_frame
942 {
943     BOOL b_return = [super setVout: p_arg_vout subView: view frame: s_arg_frame showWindow: NO];
944
945     /* o_window needs to point to our o_embeddedwindow, super might have set it
946      * to the fullscreen window that o_embeddedwindow setups during fullscreen */
947     o_window = o_embeddedwindow;
948  
949     if( b_return )
950     {
951         [o_window lockFullscreenAnimation];
952
953         [o_window setAlphaValue: var_GetFloat( p_vout, "macosx-opaqueness" )];
954
955         [self updateTitle];
956
957         /* Make the window the front and key window before animating */
958         if ([o_window isVisible] && (![o_window isFullscreen]))
959             [o_window makeKeyAndOrderFront: self];
960
961         [self scaleWindowWithFactor: 1.0 animate: [o_window isVisible] && (![o_window isFullscreen])];
962
963         [o_window setAspectRatio:NSMakeSize([o_window frame].size.width, [o_window frame].size.height)];
964
965         /* Make sure our window is visible, if we are not in fullscreen */
966         if (![o_window isFullscreen])
967             [o_window makeKeyAndOrderFront: self];
968         [o_window unlockFullscreenAnimation];
969
970     }
971     return b_return;
972 }
973
974 - (void)closeVout
975 {
976     playlist_t * p_playlist = pl_Yield( VLCIntf );
977
978     if(!playlist_IsPlaying( p_playlist ))
979         [o_window performSelectorOnMainThread: @selector(orderOut:) withObject: self waitUntilDone: YES];
980  
981     vlc_object_release( p_playlist );
982
983     [super closeVout];
984 }
985
986 - (void)enterFullscreen
987 {
988     /* We are in a VLCEmbeddedWindow */
989     [o_embeddedwindow performSelectorOnMainThread: @selector(enterFullscreen) withObject: NULL waitUntilDone: YES];
990 }
991
992 - (void)leaveFullscreen
993 {
994     /* We are in a VLCEmbeddedWindow */
995     [o_embeddedwindow performSelectorOnMainThread: @selector(leaveFullscreen) withObject: NULL waitUntilDone: YES];
996 }
997 @end
998
999 /*****************************************************************************
1000  * VLCVoutWindow implementation
1001  *****************************************************************************/
1002 @implementation VLCVoutWindow
1003
1004 - (id) initWithVout: (vout_thread_t *) vout view: (VLCVoutView *) view
1005                      frame: (NSRect *) frame
1006 {
1007     p_vout  = vout;
1008     o_view  = view;
1009     s_frame = frame;
1010
1011     [self performSelectorOnMainThread: @selector(initReal:)
1012         withObject: NULL waitUntilDone: YES];
1013
1014     if( !b_init_ok )
1015     {
1016         return NULL;
1017     }
1018
1019     return self;
1020 }
1021
1022 - (id)initReal: (id) sender
1023 {
1024     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1025     NSArray *o_screens = [NSScreen screens];
1026     NSScreen *o_screen;
1027     vlc_bool_t b_menubar_screen = VLC_FALSE;
1028     int i_device;
1029
1030     b_init_ok = VLC_FALSE;
1031
1032     p_real_vout = [VLCVoutView getRealVout: p_vout];
1033     i_device = var_GetInteger( p_real_vout->p_libvlc, "video-device" );
1034     b_black = NO;
1035     b_embedded = var_GetBool( p_vout, "embedded-video" );
1036
1037     /* Find out on which screen to open the window */
1038     o_screen = [NSScreen screenWithDisplayID: (CGDirectDisplayID)i_device];
1039
1040     if( !o_screen )
1041         o_screen = [NSScreen mainScreen];
1042
1043     if( [o_screen isMainScreen] )
1044         b_menubar_screen = VLC_TRUE;
1045
1046     if( p_vout->b_fullscreen )
1047     {
1048         CGDisplayFadeReservationToken token;
1049         NSRect screen_rect = [o_screen frame];
1050         screen_rect.origin.x = screen_rect.origin.y = 0;
1051
1052         b_black = var_GetBool( p_vout, "macosx-black" );
1053
1054         /* move the FSPanel to front in case that it is currently shown
1055          * this won't and is not supposed to work when it's fading right now */
1056         if( [[[[VLCMain sharedInstance] getControls] getFSPanel] isDisplayed] )
1057             [[[[VLCMain sharedInstance] getControls] getFSPanel] setActive: nil];
1058  
1059         /* tell the fspanel to move itself to front next time it's triggered */
1060         [[[[VLCMain sharedInstance] getControls] getFSPanel] setVoutWasUpdated: i_device];
1061
1062         /* Creates a window with size: screen_rect on o_screen */
1063         [self initWithContentRect: screen_rect
1064               styleMask: NSBorderlessWindowMask
1065               backing: NSBackingStoreBuffered
1066               defer: YES screen: o_screen];
1067  
1068         if( b_menubar_screen )
1069         {
1070             SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
1071         }
1072         if( b_black == VLC_TRUE )
1073         {
1074             CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
1075             CGDisplayFade( token, 0.6 , kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES );
1076
1077             [o_screen blackoutOtherScreens];
1078
1079             CGDisplayFade( token, 0.3 , kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO );
1080             CGReleaseDisplayFadeReservation( token);
1081         }
1082     }
1083     else if( var_GetBool( p_vout, "macosx-background" ) )
1084     {
1085         NSRect screen_rect = [o_screen frame];
1086         screen_rect.origin.x = screen_rect.origin.y = 0;
1087
1088         /* Creates a window with size: screen_rect on o_screen */
1089         [self initWithContentRect: screen_rect
1090               styleMask: NSBorderlessWindowMask
1091               backing: NSBackingStoreBuffered
1092               defer: YES screen: o_screen];
1093
1094         [self setLevel: CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
1095     }
1096     else
1097     {
1098         unsigned int i_stylemask = NSTitledWindowMask |
1099                                    NSMiniaturizableWindowMask |
1100                                    NSClosableWindowMask |
1101                                    NSResizableWindowMask;
1102
1103         NSRect s_rect;
1104         if( !s_frame )
1105         {
1106             s_rect.size.width  = p_vout->i_window_width;
1107             s_rect.size.height = p_vout->i_window_height;
1108         }
1109         else
1110         {
1111             s_rect = *s_frame;
1112         }
1113
1114         [self initWithContentRect: s_rect
1115               styleMask: i_stylemask
1116               backing: NSBackingStoreBuffered
1117               defer: YES screen: o_screen];
1118
1119         [self setAlphaValue: var_GetFloat( p_vout, "macosx-opaqueness" )];
1120
1121         if( !s_frame )
1122         {
1123             [self center];
1124         }
1125     }
1126
1127     [self makeKeyAndOrderFront: nil];
1128     [self setReleasedWhenClosed: YES];
1129
1130     /* We'll catch mouse events */
1131     [self makeFirstResponder: o_view];
1132
1133     /* Add the view. It's automatically resized to fit the window */
1134     [self setContentView: o_view];
1135
1136     [o_pool release];
1137
1138     b_init_ok = VLC_TRUE;
1139     return self;
1140 }
1141
1142 - (void)close
1143 {
1144     [o_view closeVout];
1145 }
1146
1147 - (void)closeWindow
1148 {
1149     /* XXX waitUntilDone = NO to avoid a possible deadlock when hitting
1150        Command-Q */
1151     [self performSelectorOnMainThread: @selector(closeReal:)
1152         withObject: NULL waitUntilDone: NO];
1153 }
1154
1155 - (id)closeReal:(id)sender
1156 {
1157     if( b_black == VLC_TRUE )
1158     {
1159         CGDisplayFadeReservationToken token;
1160         CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
1161         CGDisplayFade( token, 0.3 , kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES );
1162  
1163         [self disableScreenUpdatesUntilFlush];
1164         [self orderOut: self];
1165
1166         CGDisplayFade( token, 0.6 , kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, YES );
1167         CGReleaseDisplayFadeReservation( token);
1168         CGDisplayRestoreColorSyncSettings();
1169     }
1170     [NSScreen unblackoutScreens];
1171
1172     SetSystemUIMode( kUIModeNormal, 0);
1173     [super close];
1174     /* this does only work in embedded mode */
1175     if( b_embedded == VLC_TRUE )
1176         [[[[VLCMain sharedInstance] getControls] getFSPanel] orderOut: self];
1177
1178     return NULL;
1179 }
1180
1181 - (id)getVoutView
1182 {
1183     return o_view;
1184 }
1185
1186 - (BOOL)canBecomeKeyWindow
1187 {
1188     return YES;
1189 }
1190
1191 /* Sometimes crashes VLC....
1192 - (BOOL)performKeyEquivalent:(NSEvent *)o_event
1193 {
1194         return [[VLCMain sharedInstance] hasDefinedShortcutKey:o_event];
1195 }*/
1196
1197 /* This is actually the same as VLCControls::stop. */
1198
1199 - (BOOL)windowShouldClose:(id)sender
1200 {
1201     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
1202                                                        FIND_ANYWHERE );
1203     if( p_playlist == NULL )
1204     {
1205         return NO;
1206     }
1207
1208     playlist_Stop( p_playlist );
1209     vlc_object_release( p_playlist );
1210
1211     /* The window will be closed by the intf later. */
1212     return NO;
1213 }
1214
1215
1216 @end