misc/events.c: Fix event sending, by properly supporting event_manager edition (event...
[vlc.git] / modules / gui / macosx / vout.m
1 /*****************************************************************************
2  * vout.m: MacOS X video output module
3  *****************************************************************************
4  * Copyright (C) 2001-2007 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     NSMutableString * o_title = nil, * o_mrl = nil;
275     input_thread_t * p_input;
276
277     if( p_vout == NULL )
278     {
279         return;
280     }
281
282     p_input = vlc_object_find( p_vout, VLC_OBJECT_INPUT, FIND_PARENT );
283
284     if( p_input == NULL )
285     {
286         return;
287     }
288
289     char *psz_name = input_item_GetName( input_GetItem( p_input ) );
290     char *psz_uri = input_item_GetURI( input_GetItem( p_input ) );
291     if( psz_name != NULL )
292         o_title = [NSMutableString stringWithUTF8String: psz_name];
293     if( psz_uri != NULL )
294         o_mrl = [NSMutableString stringWithUTF8String: psz_uri];
295     free( psz_name );
296     free( psz_uri );
297     if( o_title == nil )
298         o_title = o_mrl;
299
300     if( o_mrl != nil )
301     {
302         /* FIXME once psz_access is exported, we could check if we are
303          * reading from a file in a smarter way. */
304
305         NSRange prefix_range = [o_mrl rangeOfString: @"file:"];
306         if( prefix_range.location != NSNotFound )
307             [o_mrl deleteCharactersInRange: prefix_range];
308
309         if( [o_mrl characterAtIndex:0] == '/' )
310         {
311             /* it's a local file */
312             [o_window setRepresentedFilename: o_mrl];
313         }
314         else
315         {
316             /* it's from the network or somewhere else,
317              * we clear the previous path */
318             [o_window setRepresentedFilename: @""];
319         }
320         [o_window setTitle: o_title];
321     }
322     else
323     {
324         [o_window setTitle: [NSString stringWithUTF8String: VOUT_TITLE]];
325     }
326     vlc_object_release( p_input );
327 }
328
329
330 - (void)setOnTop:(BOOL)b_on_top
331 {
332     if( b_on_top )
333     {
334         [o_window setLevel: NSStatusWindowLevel];
335     }
336     else
337     {
338         [o_window setLevel: NSNormalWindowLevel];
339     }
340 }
341
342 - (void)scaleWindowWithFactor: (float)factor animate: (BOOL)animate
343 {
344     NSSize newsize;
345     int i_corrected_height, i_corrected_width;
346     NSPoint topleftbase;
347     NSPoint topleftscreen;
348
349     if ( !p_vout->b_fullscreen )
350     {
351         NSView *mainView;
352         NSRect new_frame;
353         topleftbase.x = 0;
354         topleftbase.y = [o_window frame].size.height;
355         topleftscreen = [o_window convertBaseToScreen: topleftbase];
356
357         if( p_vout->render.i_height * p_vout->render.i_aspect >
358                         p_vout->render.i_width * VOUT_ASPECT_FACTOR )
359         {
360             i_corrected_width = p_vout->render.i_height * p_vout->render.i_aspect /
361                                             VOUT_ASPECT_FACTOR;
362             newsize.width = (int) ( i_corrected_width * factor );
363             newsize.height = (int) ( p_vout->render.i_height * factor );
364         }
365         else
366         {
367             i_corrected_height = p_vout->render.i_width * VOUT_ASPECT_FACTOR /
368                                             p_vout->render.i_aspect;
369             newsize.width = (int) ( p_vout->render.i_width * factor );
370             newsize.height = (int) ( i_corrected_height * factor );
371         }
372
373         /* In fullscreen mode we need to use a view that is different from
374          * ourselves, with the VLCEmbeddedWindow */
375         if([o_window isKindOfClass:[VLCEmbeddedWindow class]])
376             mainView = [o_window mainView];
377         else
378             mainView = self;
379
380         /* Calculate the window's new size */
381         new_frame.size.width = [o_window frame].size.width -
382                                     [mainView frame].size.width + newsize.width;
383         new_frame.size.height = [o_window frame].size.height -
384                                     [mainView frame].size.height + newsize.height;
385
386         new_frame.origin.x = topleftscreen.x;
387         new_frame.origin.y = topleftscreen.y - new_frame.size.height;
388
389         [o_window setFrame: new_frame display: animate animate: animate];
390
391         p_vout->i_changes |= VOUT_SIZE_CHANGE;
392     }
393 }
394
395 - (void)toggleFloatOnTop
396 {
397     vlc_value_t val;
398
399     if( !p_real_vout ) return;
400     if( var_Get( p_real_vout, "video-on-top", &val )>=0 && val.b_bool)
401     {
402         val.b_bool = VLC_FALSE;
403     }
404     else
405     {
406         val.b_bool = VLC_TRUE;
407     }
408     var_Set( p_real_vout, "video-on-top", val );
409 }
410
411 - (void)toggleFullscreen
412 {
413     vlc_value_t val;
414     if( !p_real_vout ) return;
415     var_Get( p_real_vout, "fullscreen", &val );
416     val.b_bool = !val.b_bool;
417     var_Set( p_real_vout, "fullscreen", val );
418 }
419
420 - (BOOL)isFullscreen
421 {
422     vlc_value_t val;
423     if( !p_real_vout ) return NO;
424     var_Get( p_real_vout, "fullscreen", &val );
425     return( val.b_bool );
426 }
427
428 - (void)snapshot
429 {
430     vout_Control( p_real_vout, VOUT_SNAPSHOT );
431 }
432
433 - (void)manage
434 {
435     /* Disable Screensaver, when we're playing something, but allow it on pause */
436     if( VLCIntf->p_sys->i_play_status == PLAYING_S )
437         UpdateSystemActivity( UsrActivity );
438 }
439
440 - (id)getWindow
441 {
442     return o_window;
443 }
444
445 - (void)scrollWheel:(NSEvent *)theEvent
446 {
447     VLCControls * o_controls = (VLCControls *)[[NSApp delegate] getControls];
448     [o_controls scrollWheel: theEvent];
449 }
450
451 - (void)keyDown:(NSEvent *)o_event
452 {
453     unichar key = 0;
454     vlc_value_t val;
455     unsigned int i_pressed_modifiers = 0;
456     val.i_int = 0;
457
458     i_pressed_modifiers = [o_event modifierFlags];
459
460     if( i_pressed_modifiers & NSShiftKeyMask )
461         val.i_int |= KEY_MODIFIER_SHIFT;
462     if( i_pressed_modifiers & NSControlKeyMask )
463         val.i_int |= KEY_MODIFIER_CTRL;
464     if( i_pressed_modifiers & NSAlternateKeyMask )
465         val.i_int |= KEY_MODIFIER_ALT;
466     if( i_pressed_modifiers & NSCommandKeyMask )
467         val.i_int |= KEY_MODIFIER_COMMAND;
468
469     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
470
471     if( key )
472     {
473         /* Escape should always get you out of fullscreen */
474         if( key == (unichar) 0x1b )
475         {
476              if( p_real_vout && [self isFullscreen] )
477              {
478                  [self toggleFullscreen];
479              }
480         }
481         else if ( key == ' ' )
482         {
483             vlc_value_t val;
484             val.i_int = config_GetInt( p_vout, "key-play-pause" );
485             var_Set( p_vout->p_libvlc, "key-pressed", val );
486         }
487         else
488         {
489             val.i_int |= CocoaKeyToVLC( key );
490             var_Set( p_vout->p_libvlc, "key-pressed", val );
491         }
492     }
493     else
494     {
495         [super keyDown: o_event];
496     }
497 }
498
499 - (void)mouseDown:(NSEvent *)o_event
500 {
501     vlc_value_t val;
502
503     if( p_vout )
504     {
505         if( ( [o_event type] == NSLeftMouseDown ) &&
506           ( ! ( [o_event modifierFlags] &  NSControlKeyMask ) ) )
507         {
508             if( [o_event clickCount] <= 1 )
509             {
510                 /* single clicking */
511                 var_Get( p_vout, "mouse-button-down", &val );
512                 val.i_int |= 1;
513                 var_Set( p_vout, "mouse-button-down", val );
514             }
515             else
516             {
517                 /* multiple clicking */
518                 [self toggleFullscreen];
519             }
520         }
521         else if( ( [o_event type] == NSRightMouseDown ) ||
522                ( ( [o_event type] == NSLeftMouseDown ) &&
523                  ( [o_event modifierFlags] &  NSControlKeyMask ) ) )
524         {
525             msg_Dbg( p_vout, "received NSRightMouseDown (generic method) or Ctrl clic" );
526             [NSMenu popUpContextMenu: [[VLCMain sharedInstance] getVoutMenu] withEvent: o_event forView: [[[VLCMain sharedInstance] getControls] getVoutView]];
527         }
528     }
529
530     [super mouseDown: o_event];
531 }
532
533 - (void)otherMouseDown:(NSEvent *)o_event
534 {
535     vlc_value_t val;
536
537     if( p_vout && [o_event type] == NSOtherMouseDown )
538     {
539         var_Get( p_vout, "mouse-button-down", &val );
540         val.i_int |= 2;
541         var_Set( p_vout, "mouse-button-down", val );
542     }
543
544     [super mouseDown: o_event];
545 }
546
547 - (void)rightMouseDown:(NSEvent *)o_event
548 {
549     if( p_vout && [o_event type] == NSRightMouseDown )
550     {
551         msg_Dbg( p_vout, "received NSRightMouseDown (specific method)" );
552         [NSMenu popUpContextMenu: [[VLCMain sharedInstance] getVoutMenu] withEvent: o_event forView: [[[VLCMain sharedInstance] getControls] getVoutView]];
553     }
554
555     [super mouseDown: o_event];
556 }
557
558 - (void)mouseUp:(NSEvent *)o_event
559 {
560     vlc_value_t val;
561
562     if( p_vout && [o_event type] == NSLeftMouseUp )
563     {
564         vlc_value_t b_val;
565         b_val.b_bool = VLC_TRUE;
566         var_Set( p_vout, "mouse-clicked", b_val );
567
568         var_Get( p_vout, "mouse-button-down", &val );
569         val.i_int &= ~1;
570         var_Set( p_vout, "mouse-button-down", val );
571     }
572
573     [super mouseUp: o_event];
574 }
575
576 - (void)otherMouseUp:(NSEvent *)o_event
577 {
578     vlc_value_t val;
579
580     if( p_vout && [o_event type] == NSOtherMouseUp )
581     {
582         var_Get( p_vout, "mouse-button-down", &val );
583         val.i_int &= ~2;
584         var_Set( p_vout, "mouse-button-down", val );
585     }
586
587     [super mouseUp: o_event];
588 }
589
590 - (void)rightMouseUp:(NSEvent *)o_event
591 {
592     if( p_vout && [o_event type] == NSRightMouseUp )
593     {
594         /* FIXME: this isn't the appropriate place, but we can't receive
595          * NSRightMouseDown some how */
596         msg_Dbg( p_vout, "received NSRightMouseUp" );
597         [NSMenu popUpContextMenu: [[VLCMain sharedInstance] getVoutMenu] withEvent: o_event forView: [[[VLCMain sharedInstance] getControls] getVoutView]];
598     }
599
600     [super mouseUp: o_event];
601 }
602
603 - (void)mouseDragged:(NSEvent *)o_event
604 {
605     [self mouseMoved: o_event];
606 }
607
608 - (void)otherMouseDragged:(NSEvent *)o_event
609 {
610     [self mouseMoved: o_event];
611 }
612
613 - (void)rightMouseDragged:(NSEvent *)o_event
614 {
615     [self mouseMoved: o_event];
616 }
617
618 - (void)mouseMoved:(NSEvent *)o_event
619 {
620     NSPoint ml;
621     NSRect s_rect;
622     BOOL b_inside;
623
624     if( p_vout )
625     {
626         s_rect = [o_view bounds];
627         ml = [o_view convertPoint: [o_event locationInWindow] fromView: nil];
628         b_inside = [o_view mouse: ml inRect: s_rect];
629
630         if( b_inside )
631         {
632             vlc_value_t val;
633             unsigned int i_width, i_height, i_x, i_y;
634
635             vout_PlacePicture( p_vout, (unsigned int)s_rect.size.width,
636                                        (unsigned int)s_rect.size.height,
637                                        &i_x, &i_y, &i_width, &i_height );
638
639             val.i_int = ( ((int)ml.x) - i_x ) *
640                         p_vout->render.i_width / i_width;
641             var_Set( p_vout, "mouse-x", val );
642
643             if( [[o_view className] isEqualToString: @"VLCGLView"] )
644             {
645                 val.i_int = ( ((int)(s_rect.size.height - ml.y)) - i_y ) *
646                             p_vout->render.i_height / i_height;
647             }
648             else
649             {
650                 val.i_int = ( ((int)ml.y) - i_y ) *
651                             p_vout->render.i_height / i_height;
652             }
653             var_Set( p_vout, "mouse-y", val );
654
655             val.b_bool = VLC_TRUE;
656             var_Set( p_vout, "mouse-moved", val );
657         }
658         if( [self isFullscreen] )
659             [[[[VLCMain sharedInstance] getControls] getFSPanel] fadeIn];
660     }
661
662     [super mouseMoved: o_event];
663 }
664
665 - (BOOL)acceptsFirstResponder
666 {
667     return YES;
668 }
669
670 - (BOOL)becomeFirstResponder
671 {
672     return YES;
673 }
674
675 - (BOOL)resignFirstResponder
676 {
677     /* We need to stay the first responder or we'll miss some
678        events */
679     return NO;
680 }
681
682 /* Class methods used by the different vout modules */
683
684 + (vout_thread_t *)getRealVout: (vout_thread_t *)p_vout
685 {
686     /* p_real_vout: the vout we have to use to check for video-on-top
687        and a few other things. If we are the QuickTime output, it's us.
688        It we are the OpenGL provider, it is our parent. */
689     if( p_vout->i_object_type == VLC_OBJECT_OPENGL )
690     {
691         return (vout_thread_t *) p_vout->p_parent;
692     }
693     else
694     {
695         return p_vout;
696     }
697
698 }
699
700 + (id)getVoutView: (vout_thread_t *)p_vout subView: (NSView *)view
701                                     frame: (NSRect *)s_frame
702 {
703     vlc_value_t value_drawable;
704     int i_timeout;
705     id o_return = nil;
706
707     var_Get( p_vout->p_libvlc, "drawable", &value_drawable );
708
709     var_Create( p_vout, "macosx-vdev", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
710     var_Create( p_vout, "macosx-stretch", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
711     var_Create( p_vout, "macosx-opaqueness", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
712     var_Create( p_vout, "macosx-background", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
713     var_Create( p_vout, "macosx-black", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
714     var_Create( p_vout, "macosx-embedded", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
715
716
717     /* We only wait for NSApp to initialise if we're not embedded (as in the
718      * case of the Mozilla plugin).  We can tell whether we're embedded or not
719      * by examining the "drawable" value: if it's zero, we're running in the
720      * main Mac intf; if it's non-zero, we're embedded. */
721     if( value_drawable.i_int == 0 )
722     {
723         /* Wait for a MacOS X interface to appear. Timeout is 2 seconds. */
724         for( i_timeout = 20 ; i_timeout-- ; )
725         {
726             if( NSApp == NULL )
727             {
728                 msleep( INTF_IDLE_SLEEP );
729             }
730         }
731
732         if( NSApp == NULL )
733         {
734             /* No MacOS X intf, unable to communicate with MT */
735             msg_Err( p_vout, "no MacOS X interface present" );
736             return nil;
737         }
738         else
739         {
740             if ( VLCIntf && !(p_vout->b_fullscreen) &&
741                         !(var_GetBool( p_vout, "macosx-background" )) &&
742                         var_GetBool( p_vout, "macosx-embedded") )
743             {
744                 o_return = [[[VLCMain sharedInstance] getEmbeddedList]
745                                                             getEmbeddedVout];
746             }
747         }
748     }
749
750     /* No embedded vout is available */
751     if( o_return == nil )
752     {
753         NSRect null_rect;
754         bzero( &null_rect, sizeof( NSRect ) );
755         o_return = [[VLCDetachedVoutView alloc] initWithFrame: null_rect ];
756     }
757     [o_return setVout: p_vout subView: view frame: s_frame];
758     return o_return;
759 }
760
761 - (void)enterFullscreen
762 {
763     [[o_view class] performSelectorOnMainThread:@selector(resetVout:) withObject:[NSValue valueWithPointer:p_vout] waitUntilDone:YES];
764     [[[[VLCMain sharedInstance] getControls] getFSPanel] setActive: nil];
765 }
766
767 - (void)leaveFullscreen
768 {
769     [[o_view class] performSelectorOnMainThread:@selector(resetVout:) withObject:[NSValue valueWithPointer:p_vout] waitUntilDone:YES];
770     [[[[VLCMain sharedInstance] getControls] getFSPanel] setNonActive: nil];
771 }
772
773 @end
774
775 /*****************************************************************************
776  * VLCDetachedVoutView implementation
777  *****************************************************************************/
778 @implementation VLCDetachedVoutView
779
780 - (id)initWithFrame: (NSRect)frameRect
781 {
782     [super initWithFrame: frameRect];
783     i_time_mouse_last_moved = 0;
784     return self;
785 }
786
787 - (bool)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
788                      frame: (NSRect *) s_arg_frame
789 {
790     BOOL b_return = [super setVout: p_arg_vout subView: view frame:s_arg_frame];
791     i_time_mouse_last_moved = mdate();
792     o_window = [[VLCVoutWindow alloc] initWithVout: p_arg_vout view: self
793                                                     frame: s_arg_frame];
794     [self updateTitle];
795     [view setFrame: [self frame]];
796
797     if( var_GetBool( p_real_vout, "video-on-top" ) )
798     {
799         [o_window setLevel: NSStatusWindowLevel];
800     }
801
802
803     [o_window setAcceptsMouseMovedEvents: TRUE];
804     return b_return;
805 }
806
807 - (void)closeVout
808 {
809     [o_window closeWindow];
810     [o_window setAcceptsMouseMovedEvents: NO];
811     i_time_mouse_last_moved = 0;
812     [super closeVout];
813 }
814
815 - (void)mouseMoved:(NSEvent *)o_event
816 {
817     i_time_mouse_last_moved = mdate();
818     [super mouseMoved: o_event];
819 }
820
821 - (void)hideMouse:(BOOL)b_hide
822 {
823     BOOL b_inside;
824     NSPoint ml;
825     NSView *o_contents = [o_window contentView];
826
827     ml = [o_window convertScreenToBase:[NSEvent mouseLocation]];
828     ml = [o_contents convertPoint:ml fromView:nil];
829     b_inside = [o_contents mouse: ml inRect: [o_contents bounds]];
830
831     if( b_hide && b_inside )
832     {
833         [NSCursor setHiddenUntilMouseMoves: YES];
834     }
835     else if( !b_hide )
836     {
837         [NSCursor setHiddenUntilMouseMoves: NO];
838     }
839 }
840
841 - (void)manage
842 {
843     [super manage];
844     if( p_vout->b_fullscreen )
845     {
846         if( mdate() - i_time_mouse_last_moved > 3000000 )
847         {
848             [self hideMouse: YES];
849         }
850     }
851     else
852     {
853         [self hideMouse: NO];
854     }
855 }
856
857 @end
858
859 /*****************************************************************************
860  * VLCEmbeddedVoutView implementation
861  *****************************************************************************/
862
863 @implementation VLCEmbeddedVoutView
864
865 - (id)initWithFrame: (NSRect)frameRect
866 {
867     [super initWithFrame: frameRect];
868     b_used = NO;
869     [[[VLCMain sharedInstance] getEmbeddedList] addEmbeddedVout: self];
870     return self;
871 }
872
873 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
874                  frame: (NSRect *)s_arg_frame showWindow: (BOOL)b_show_window
875 {
876     BOOL b_return;
877     b_return = [super setVout: p_arg_vout subView: view frame: s_arg_frame];
878     if( b_return )
879     {
880         o_window = [self window];
881         if (b_show_window)
882             [o_window makeKeyAndOrderFront: self];
883         [o_window setAcceptsMouseMovedEvents: TRUE];
884
885         if( var_GetBool( p_real_vout, "video-on-top" ) )
886         {
887             [o_window setLevel: NSStatusWindowLevel];
888         }
889
890         [view setFrameSize: [self frame].size];
891     }
892     return b_return;
893 }
894
895 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
896                      frame: (NSRect *) s_arg_frame
897
898 {
899     return [self setVout: p_arg_vout subView: view frame:s_arg_frame showWindow: YES];
900 }
901
902 - (void)setUsed: (BOOL)b_new_used
903 {
904     b_used = b_new_used;
905 }
906
907 - (BOOL)isUsed
908 {
909     return b_used;
910 }
911
912 - (void)closeVout
913 {
914     [super closeVout];
915     [o_window setAcceptsMouseMovedEvents: NO];
916     [[[VLCMain sharedInstance] getEmbeddedList] releaseEmbeddedVout: self];
917 }
918
919
920 @end
921
922 @implementation VLCDetachedEmbeddedVoutView
923 - (void)awakeFromNib
924 {
925     o_embeddedwindow = [self window];
926 }
927
928 - (BOOL)setVout: (vout_thread_t *) p_arg_vout subView: (NSView *) view
929                      frame: (NSRect *) s_arg_frame
930 {
931     BOOL b_return = [super setVout: p_arg_vout subView: view frame: s_arg_frame showWindow: NO];
932
933     /* o_window needs to point to our o_embeddedwindow, super might have set it
934      * to the fullscreen window that o_embeddedwindow setups during fullscreen */
935     o_window = o_embeddedwindow;
936  
937     if( b_return )
938     {
939         [o_window lockFullscreenAnimation];
940
941         [o_window setAlphaValue: var_GetFloat( p_vout, "macosx-opaqueness" )];
942
943         [self updateTitle];
944
945         /* Make the window the front and key window before animating */
946         if ([o_window isVisible] && (![o_window isFullscreen]))
947             [o_window makeKeyAndOrderFront: self];
948
949         [self scaleWindowWithFactor: 1.0 animate: [o_window isVisible] && (![o_window isFullscreen])];
950
951         [o_window setAspectRatio:NSMakeSize([o_window frame].size.width, [o_window frame].size.height)];
952
953         /* Make sure our window is visible, if we are not in fullscreen */
954         if (![o_window isFullscreen])
955             [o_window makeKeyAndOrderFront: self];
956         [o_window unlockFullscreenAnimation];
957
958     }
959     return b_return;
960 }
961
962 - (void)closeVout
963 {
964     playlist_t * p_playlist = pl_Yield( VLCIntf );
965
966     if(!playlist_IsPlaying( p_playlist ))
967         [o_window performSelectorOnMainThread: @selector(orderOut:) withObject: self waitUntilDone: YES];
968  
969     vlc_object_release( p_playlist );
970
971     [super closeVout];
972 }
973
974 - (void)enterFullscreen
975 {
976     /* We are in a VLCEmbeddedWindow */
977     [o_embeddedwindow performSelectorOnMainThread: @selector(enterFullscreen) withObject: NULL waitUntilDone: YES];
978 }
979
980 - (void)leaveFullscreen
981 {
982     /* We are in a VLCEmbeddedWindow */
983     [o_embeddedwindow performSelectorOnMainThread: @selector(leaveFullscreen) withObject: NULL waitUntilDone: YES];
984 }
985 @end
986
987 /*****************************************************************************
988  * VLCVoutWindow implementation
989  *****************************************************************************/
990 @implementation VLCVoutWindow
991
992 - (id) initWithVout: (vout_thread_t *) vout view: (VLCVoutView *) view
993                      frame: (NSRect *) frame
994 {
995     p_vout  = vout;
996     o_view  = view;
997     s_frame = frame;
998
999     [self performSelectorOnMainThread: @selector(initReal:)
1000         withObject: NULL waitUntilDone: YES];
1001
1002     if( !b_init_ok )
1003     {
1004         return NULL;
1005     }
1006
1007     return self;
1008 }
1009
1010 - (id)initReal: (id) sender
1011 {
1012     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1013     NSArray *o_screens = [NSScreen screens];
1014     NSScreen *o_screen;
1015     vlc_bool_t b_menubar_screen = VLC_FALSE;
1016     int i_device;
1017
1018     b_init_ok = VLC_FALSE;
1019
1020     p_real_vout = [VLCVoutView getRealVout: p_vout];
1021     i_device = var_GetInteger( p_real_vout->p_libvlc, "video-device" );
1022     b_black = NO;
1023     b_embedded = var_GetBool( p_vout, "macosx-embedded" );
1024
1025     /* Find out on which screen to open the window */
1026     o_screen = [NSScreen screenWithDisplayID: (CGDirectDisplayID)i_device];
1027
1028     if( !o_screen )
1029         o_screen = [NSScreen mainScreen];
1030
1031     if( [o_screen isMainScreen] )
1032         b_menubar_screen = VLC_TRUE;
1033
1034     if( p_vout->b_fullscreen )
1035     {
1036         CGDisplayFadeReservationToken token;
1037         NSRect screen_rect = [o_screen frame];
1038         screen_rect.origin.x = screen_rect.origin.y = 0;
1039
1040         b_black = var_GetBool( p_vout, "macosx-black" );
1041
1042         /* move the FSPanel to front in case that it is currently shown
1043          * this won't and is not supposed to work when it's fading right now */
1044         if( [[[[VLCMain sharedInstance] getControls] getFSPanel] isDisplayed] )
1045             [[[[VLCMain sharedInstance] getControls] getFSPanel] setActive: nil];
1046  
1047         /* tell the fspanel to move itself to front next time it's triggered */
1048         [[[[VLCMain sharedInstance] getControls] getFSPanel] setVoutWasUpdated: i_device];
1049
1050         /* Creates a window with size: screen_rect on o_screen */
1051         [self initWithContentRect: screen_rect
1052               styleMask: NSBorderlessWindowMask
1053               backing: NSBackingStoreBuffered
1054               defer: YES screen: o_screen];
1055  
1056         if( b_menubar_screen )
1057         {
1058             SetSystemUIMode( kUIModeAllHidden, kUIOptionAutoShowMenuBar);
1059         }
1060         if( b_black == VLC_TRUE )
1061         {
1062             CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
1063             CGDisplayFade( token, 0.6 , kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES );
1064
1065             [o_screen blackoutOtherScreens];
1066
1067             CGDisplayFade( token, 0.3 , kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO );
1068             CGReleaseDisplayFadeReservation( token);
1069         }
1070     }
1071     else if( var_GetBool( p_vout, "macosx-background" ) )
1072     {
1073         NSRect screen_rect = [o_screen frame];
1074         screen_rect.origin.x = screen_rect.origin.y = 0;
1075
1076         /* Creates a window with size: screen_rect on o_screen */
1077         [self initWithContentRect: screen_rect
1078               styleMask: NSBorderlessWindowMask
1079               backing: NSBackingStoreBuffered
1080               defer: YES screen: o_screen];
1081
1082         [self setLevel: CGWindowLevelForKey(kCGDesktopWindowLevelKey)];
1083     }
1084     else
1085     {
1086         unsigned int i_stylemask = NSTitledWindowMask |
1087                                    NSMiniaturizableWindowMask |
1088                                    NSClosableWindowMask |
1089                                    NSResizableWindowMask;
1090
1091         NSRect s_rect;
1092         if( !s_frame )
1093         {
1094             s_rect.size.width  = p_vout->i_window_width;
1095             s_rect.size.height = p_vout->i_window_height;
1096         }
1097         else
1098         {
1099             s_rect = *s_frame;
1100         }
1101
1102         [self initWithContentRect: s_rect
1103               styleMask: i_stylemask
1104               backing: NSBackingStoreBuffered
1105               defer: YES screen: o_screen];
1106
1107         [self setAlphaValue: var_GetFloat( p_vout, "macosx-opaqueness" )];
1108
1109         if( !s_frame )
1110         {
1111             [self center];
1112         }
1113     }
1114
1115     [self makeKeyAndOrderFront: nil];
1116     [self setReleasedWhenClosed: YES];
1117
1118     /* We'll catch mouse events */
1119     [self makeFirstResponder: o_view];
1120
1121     /* Add the view. It's automatically resized to fit the window */
1122     [self setContentView: o_view];
1123
1124     [o_pool release];
1125
1126     b_init_ok = VLC_TRUE;
1127     return self;
1128 }
1129
1130 - (void)close
1131 {
1132     [o_view closeVout];
1133 }
1134
1135 - (void)closeWindow
1136 {
1137     /* XXX waitUntilDone = NO to avoid a possible deadlock when hitting
1138        Command-Q */
1139     [self performSelectorOnMainThread: @selector(closeReal:)
1140         withObject: NULL waitUntilDone: NO];
1141 }
1142
1143 - (id)closeReal:(id)sender
1144 {
1145     if( b_black == VLC_TRUE )
1146     {
1147         CGDisplayFadeReservationToken token;
1148         CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
1149         CGDisplayFade( token, 0.3 , kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES );
1150  
1151         [self disableScreenUpdatesUntilFlush];
1152         [self orderOut: self];
1153
1154         CGDisplayFade( token, 0.6 , kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, YES );
1155         CGReleaseDisplayFadeReservation( token);
1156         CGDisplayRestoreColorSyncSettings();
1157     }
1158     [NSScreen unblackoutScreens];
1159
1160     SetSystemUIMode( kUIModeNormal, 0);
1161     [super close];
1162     /* this does only work in embedded mode */
1163     if( b_embedded == VLC_TRUE )
1164         [[[[VLCMain sharedInstance] getControls] getFSPanel] orderOut: self];
1165
1166     return NULL;
1167 }
1168
1169 - (id)getVoutView
1170 {
1171     return o_view;
1172 }
1173
1174 - (BOOL)canBecomeKeyWindow
1175 {
1176     return YES;
1177 }
1178
1179 /* Sometimes crashes VLC....
1180 - (BOOL)performKeyEquivalent:(NSEvent *)o_event
1181 {
1182         return [[VLCMain sharedInstance] hasDefinedShortcutKey:o_event];
1183 }*/
1184
1185 /* This is actually the same as VLCControls::stop. */
1186
1187 - (BOOL)windowShouldClose:(id)sender
1188 {
1189     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
1190                                                        FIND_ANYWHERE );
1191     if( p_playlist == NULL )
1192     {
1193         return NO;
1194     }
1195
1196     playlist_Stop( p_playlist );
1197     vlc_object_release( p_playlist );
1198
1199     /* The window will be closed by the intf later. */
1200     return NO;
1201 }
1202
1203
1204 @end