]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
Don't crash when using libgmalloc on Leopard (closes #1501)
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          Derk-Jan Hartman <hartman at videolan.org>
10  *          Felix Paul Kühne <fkuehne at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <stdlib.h>                                      /* malloc(), free() */
31 #include <sys/param.h>                                    /* for MAXPATHLEN */
32 #include <string.h>
33 #include <vlc_keys.h>
34
35 #ifdef HAVE_CONFIG_H
36 #   include "config.h"
37 #endif
38
39 #import "intf.h"
40 #import "fspanel.h"
41 #import "vout.h"
42 #import "prefs.h"
43 #import "playlist.h"
44 #import "controls.h"
45 #import "about.h"
46 #import "open.h"
47 #import "wizard.h"
48 #import "extended.h"
49 #import "bookmarks.h"
50 #import "sfilters.h"
51 #import "interaction.h"
52 #import "embeddedwindow.h"
53 #import "update.h"
54 #import "AppleRemote.h"
55 #import "eyetv.h"
56 #import "simple_prefs.h"
57
58 #import <vlc_input.h>
59 #import <vlc_interface.h>
60
61 /*****************************************************************************
62  * Local prototypes.
63  *****************************************************************************/
64 static void Run ( intf_thread_t *p_intf );
65
66 /* Quick hack */
67 /*****************************************************************************
68  * VLCApplication implementation (this hack is really disgusting now,
69  *                                feel free to fix.)
70  *****************************************************************************/
71 @interface VLCApplication : NSApplication
72 {
73    libvlc_int_t *o_libvlc;
74 }
75 - (void)setVLC: (libvlc_int_t *)p_libvlc;
76 @end
77
78
79 @implementation VLCApplication
80 - (void)setVLC: (libvlc_int_t *) p_libvlc
81 {
82     o_libvlc = p_libvlc;
83 }
84 - (void)terminate: (id)sender
85 {
86     vlc_object_kill( o_libvlc );
87     [super terminate: sender];
88 }
89 @end
90
91 /*****************************************************************************
92  * OpenIntf: initialize interface
93  *****************************************************************************/
94 int E_(OpenIntf) ( vlc_object_t *p_this )
95 {
96     intf_thread_t *p_intf = (intf_thread_t*) p_this;
97
98     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
99     if( p_intf->p_sys == NULL )
100     {
101         return( 1 );
102     }
103
104     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
105
106     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
107
108     p_intf->p_sys->o_sendport = [[NSPort port] retain];
109     p_intf->p_sys->p_sub = msg_Subscribe( p_intf, MSG_QUEUE_NORMAL );
110     p_intf->b_play = VLC_TRUE;
111     p_intf->pf_run = Run;
112     p_intf->b_should_run_on_first_thread = VLC_TRUE;
113
114     return( 0 );
115 }
116
117 /*****************************************************************************
118  * CloseIntf: destroy interface
119  *****************************************************************************/
120 void E_(CloseIntf) ( vlc_object_t *p_this )
121 {
122     intf_thread_t *p_intf = (intf_thread_t*) p_this;
123
124     msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
125
126     [p_intf->p_sys->o_sendport release];
127     [p_intf->p_sys->o_pool release];
128
129     free( p_intf->p_sys );
130 }
131
132 /*****************************************************************************
133  * KillerThread: Thread that kill the application
134  *****************************************************************************/
135 static void * KillerThread( void *user_data )
136 {
137     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
138
139     intf_thread_t *p_intf = user_data;
140     
141     vlc_object_lock ( p_intf );
142     while( vlc_object_alive( p_intf ) )
143         vlc_object_wait( p_intf );
144     vlc_object_unlock( p_intf );
145
146     msg_Dbg( p_intf, "Killing the Mac OS X module\n" );
147
148     /* We are dead, terminate */
149     [NSApp terminate: nil];
150     [o_pool release];
151     return NULL;
152 }
153 /*****************************************************************************
154  * Run: main loop
155  *****************************************************************************/
156 jmp_buf jmpbuffer;
157
158 static void Run( intf_thread_t *p_intf )
159 {
160     sigset_t set;
161
162     /* Do it again - for some unknown reason, vlc_thread_create() often
163      * fails to go to real-time priority with the first launched thread
164      * (???) --Meuuh */
165     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
166
167     /* Make sure the "force quit" menu item does quit instantly.
168      * VLC overrides SIGTERM which is sent by the "force quit"
169      * menu item to make sure deamon mode quits gracefully, so
170      * we un-override SIGTERM here. */
171     sigemptyset( &set );
172     sigaddset( &set, SIGTERM );
173     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
174
175     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
176
177     /* Install a jmpbuffer to where we can go back before the NSApp exit
178      * see applicationWillTerminate: */
179     /* We need that code to run on main thread */
180     [VLCApplication sharedApplication];
181     [NSApp setVLC: p_intf->p_libvlc];
182
183     [[VLCMain sharedInstance] setIntf: p_intf];
184     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
185
186     /* Setup a thread that will monitor the module killing */
187     pthread_t killer_thread;
188     pthread_create( &killer_thread, NULL, KillerThread, p_intf );
189
190     /* Install a jmpbuffer to where we can go back before the NSApp exit
191      * see applicationWillTerminate: */
192     if(setjmp(jmpbuffer) == 0)
193         [NSApp run];
194
195     [o_pool release];
196 }
197
198 int ExecuteOnMainThread( id target, SEL sel, void * p_arg )
199 {
200     int i_ret = 0;
201
202     //NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
203
204     if( [target respondsToSelector: @selector(performSelectorOnMainThread:
205                                              withObject:waitUntilDone:)] )
206     {
207         [target performSelectorOnMainThread: sel
208                 withObject: [NSValue valueWithPointer: p_arg]
209                 waitUntilDone: NO];
210     }
211     else if( NSApp != nil && [[VLCMain sharedInstance] respondsToSelector: @selector(getIntf)] )
212     {
213         NSValue * o_v1;
214         NSValue * o_v2;
215         NSArray * o_array;
216         NSPort * o_recv_port;
217         NSInvocation * o_inv;
218         NSPortMessage * o_msg;
219         intf_thread_t * p_intf;
220         NSConditionLock * o_lock;
221         NSMethodSignature * o_sig;
222
223         id * val[] = { &o_lock, &o_v2 };
224
225         p_intf = (intf_thread_t *)VLCIntf;
226
227         o_recv_port = [[NSPort port] retain];
228         o_v1 = [NSValue valueWithPointer: val];
229         o_v2 = [NSValue valueWithPointer: p_arg];
230
231         o_sig = [target methodSignatureForSelector: sel];
232         o_inv = [NSInvocation invocationWithMethodSignature: o_sig];
233         [o_inv setArgument: &o_v1 atIndex: 2];
234         [o_inv setTarget: target];
235         [o_inv setSelector: sel];
236
237         o_array = [NSArray arrayWithObject:
238             [NSData dataWithBytes: &o_inv length: sizeof(o_inv)]];
239         o_msg = [[NSPortMessage alloc]
240             initWithSendPort: p_intf->p_sys->o_sendport
241             receivePort: o_recv_port components: o_array];
242
243         o_lock = [[NSConditionLock alloc] initWithCondition: 0];
244         [o_msg sendBeforeDate: [NSDate distantPast]];
245         [o_lock lockWhenCondition: 1];
246         [o_lock unlock];
247         [o_lock release];
248
249         [o_msg release];
250         [o_recv_port release];
251     }
252     else
253     {
254         i_ret = 1;
255     }
256
257     //[o_pool release];
258
259     return( i_ret );
260 }
261
262 /*****************************************************************************
263  * playlistChanged: Callback triggered by the intf-change playlist
264  * variable, to let the intf update the playlist.
265  *****************************************************************************/
266 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
267                      vlc_value_t old_val, vlc_value_t new_val, void *param )
268 {
269     intf_thread_t * p_intf = VLCIntf;
270     p_intf->p_sys->b_playlist_update = VLC_TRUE;
271     p_intf->p_sys->b_intf_update = VLC_TRUE;
272     p_intf->p_sys->b_playmode_update = VLC_TRUE;
273     p_intf->p_sys->b_current_title_update = VLC_TRUE;
274     return VLC_SUCCESS;
275 }
276
277 /*****************************************************************************
278  * ShowController: Callback triggered by the show-intf playlist variable
279  * through the ShowIntf-control-intf, to let us show the controller-win;
280  * usually when in fullscreen-mode
281  *****************************************************************************/
282 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
283                      vlc_value_t old_val, vlc_value_t new_val, void *param )
284 {
285     intf_thread_t * p_intf = VLCIntf;
286     p_intf->p_sys->b_intf_show = VLC_TRUE;
287     return VLC_SUCCESS;
288 }
289
290 /*****************************************************************************
291  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
292  * variable, to let the intf update the controller.
293  *****************************************************************************/
294 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
295                      vlc_value_t old_val, vlc_value_t new_val, void *param )
296 {
297     intf_thread_t * p_intf = VLCIntf;
298     p_intf->p_sys->b_fullscreen_update = VLC_TRUE;
299     return VLC_SUCCESS;
300 }
301
302 /*****************************************************************************
303  * InteractCallback: Callback triggered by the interaction
304  * variable, to let the intf display error and interaction dialogs
305  *****************************************************************************/
306 static int InteractCallback( vlc_object_t *p_this, const char *psz_variable,
307                      vlc_value_t old_val, vlc_value_t new_val, void *param )
308 {
309     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
310     VLCMain *interface = (VLCMain *)param;
311     interaction_dialog_t *p_dialog = (interaction_dialog_t *)(new_val.p_address);
312     NSValue *o_value = [NSValue valueWithPointer:p_dialog];
313  
314     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewInteractionEventNotification" object:[interface getInteractionList]
315      userInfo:[NSDictionary dictionaryWithObject:o_value forKey:@"VLCDialogPointer"]];
316  
317     [o_pool release];
318     return VLC_SUCCESS;
319 }
320
321 static struct
322 {
323     unichar i_nskey;
324     unsigned int i_vlckey;
325 } nskeys_to_vlckeys[] =
326 {
327     { NSUpArrowFunctionKey, KEY_UP },
328     { NSDownArrowFunctionKey, KEY_DOWN },
329     { NSLeftArrowFunctionKey, KEY_LEFT },
330     { NSRightArrowFunctionKey, KEY_RIGHT },
331     { NSF1FunctionKey, KEY_F1 },
332     { NSF2FunctionKey, KEY_F2 },
333     { NSF3FunctionKey, KEY_F3 },
334     { NSF4FunctionKey, KEY_F4 },
335     { NSF5FunctionKey, KEY_F5 },
336     { NSF6FunctionKey, KEY_F6 },
337     { NSF7FunctionKey, KEY_F7 },
338     { NSF8FunctionKey, KEY_F8 },
339     { NSF9FunctionKey, KEY_F9 },
340     { NSF10FunctionKey, KEY_F10 },
341     { NSF11FunctionKey, KEY_F11 },
342     { NSF12FunctionKey, KEY_F12 },
343     { NSHomeFunctionKey, KEY_HOME },
344     { NSEndFunctionKey, KEY_END },
345     { NSPageUpFunctionKey, KEY_PAGEUP },
346     { NSPageDownFunctionKey, KEY_PAGEDOWN },
347     { NSTabCharacter, KEY_TAB },
348     { NSCarriageReturnCharacter, KEY_ENTER },
349     { NSEnterCharacter, KEY_ENTER },
350     { NSBackspaceCharacter, KEY_BACKSPACE },
351     { (unichar) ' ', KEY_SPACE },
352     { (unichar) 0x1b, KEY_ESC },
353     {0,0}
354 };
355
356 unichar VLCKeyToCocoa( unsigned int i_key )
357 {
358     unsigned int i;
359
360     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
361     {
362         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
363         {
364             return nskeys_to_vlckeys[i].i_nskey;
365         }
366     }
367     return (unichar)(i_key & ~KEY_MODIFIER);
368 }
369
370 unsigned int CocoaKeyToVLC( unichar i_key )
371 {
372     unsigned int i;
373
374     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
375     {
376         if( nskeys_to_vlckeys[i].i_nskey == i_key )
377         {
378             return nskeys_to_vlckeys[i].i_vlckey;
379         }
380     }
381     return (unsigned int)i_key;
382 }
383
384 unsigned int VLCModifiersToCocoa( unsigned int i_key )
385 {
386     unsigned int new = 0;
387     if( i_key & KEY_MODIFIER_COMMAND )
388         new |= NSCommandKeyMask;
389     if( i_key & KEY_MODIFIER_ALT )
390         new |= NSAlternateKeyMask;
391     if( i_key & KEY_MODIFIER_SHIFT )
392         new |= NSShiftKeyMask;
393     if( i_key & KEY_MODIFIER_CTRL )
394         new |= NSControlKeyMask;
395     return new;
396 }
397
398 /*****************************************************************************
399  * VLCMain implementation
400  *****************************************************************************/
401 @implementation VLCMain
402
403 static VLCMain *_o_sharedMainInstance = nil;
404
405 + (VLCMain *)sharedInstance
406 {
407     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
408 }
409
410 - (id)init
411 {
412     if( _o_sharedMainInstance) 
413     {
414         [self dealloc];
415         return _o_sharedMainInstance;
416     } 
417     else
418         _o_sharedMainInstance = [super init];
419
420     o_about = [[VLAboutBox alloc] init];
421     o_prefs = [[VLCPrefs alloc] init];
422     o_open = [[VLCOpen alloc] init];
423     o_wizard = [[VLCWizard alloc] init];
424     o_extended = nil;
425     o_bookmarks = [[VLCBookmarks alloc] init];
426     o_embedded_list = [[VLCEmbeddedList alloc] init];
427     o_interaction_list = [[VLCInteractionList alloc] init];
428     o_sfilters = nil;
429 #ifdef UPDATE_CHECK
430     o_update = [[VLCUpdate alloc] init];
431 #endif
432
433     i_lastShownVolume = -1;
434
435     o_remote = [[AppleRemote alloc] init];
436     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
437     [o_remote setDelegate: _o_sharedMainInstance];
438
439     o_eyetv = [[VLCEyeTVController alloc] init];
440
441     /* announce our launch to a potential eyetv plugin */
442     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
443                                                                    object: @"VLCEyeTVSupport"
444                                                                  userInfo: NULL
445                                                        deliverImmediately: YES];
446
447     return _o_sharedMainInstance;
448 }
449
450 - (void)setIntf: (intf_thread_t *)p_mainintf {
451     p_intf = p_mainintf;
452 }
453
454 - (intf_thread_t *)getIntf {
455     return p_intf;
456 }
457
458 - (void)awakeFromNib
459 {
460     unsigned int i_key = 0;
461     playlist_t *p_playlist;
462     vlc_value_t val;
463
464     /* Check if we already did this once. Opening the other nibs calls it too, because VLCMain is the owner */
465     if( nib_main_loaded ) return;
466
467     [self initStrings];
468     [o_window setExcludedFromWindowsMenu: TRUE];
469     [o_msgs_panel setExcludedFromWindowsMenu: TRUE];
470     [o_msgs_panel setDelegate: self];
471
472     i_key = config_GetInt( p_intf, "key-quit" );
473     [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
474     [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
475     i_key = config_GetInt( p_intf, "key-play-pause" );
476     [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
477     [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
478     i_key = config_GetInt( p_intf, "key-stop" );
479     [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
480     [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
481     i_key = config_GetInt( p_intf, "key-faster" );
482     [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
483     [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
484     i_key = config_GetInt( p_intf, "key-slower" );
485     [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
486     [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
487     i_key = config_GetInt( p_intf, "key-prev" );
488     [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
489     [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
490     i_key = config_GetInt( p_intf, "key-next" );
491     [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
492     [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
493     i_key = config_GetInt( p_intf, "key-jump+short" );
494     [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
495     [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
496     i_key = config_GetInt( p_intf, "key-jump-short" );
497     [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
498     [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
499     i_key = config_GetInt( p_intf, "key-jump+medium" );
500     [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
501     [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
502     i_key = config_GetInt( p_intf, "key-jump-medium" );
503     [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
504     [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
505     i_key = config_GetInt( p_intf, "key-jump+long" );
506     [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
507     [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
508     i_key = config_GetInt( p_intf, "key-jump-long" );
509     [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
510     [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
511     i_key = config_GetInt( p_intf, "key-vol-up" );
512     [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
513     [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
514     i_key = config_GetInt( p_intf, "key-vol-down" );
515     [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
516     [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
517     i_key = config_GetInt( p_intf, "key-vol-mute" );
518     [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
519     [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
520     i_key = config_GetInt( p_intf, "key-fullscreen" );
521     [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
522     [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
523     i_key = config_GetInt( p_intf, "key-snapshot" );
524     [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
525     [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
526
527     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
528
529     [self setSubmenusEnabled: FALSE];
530     [self manageVolumeSlider];
531     [o_window setDelegate: self];
532  
533     b_restore_size = false;
534     if( [o_window frame].size.height <= 200 )
535     {
536         b_small_window = YES;
537         [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
538             [o_window frame].origin.y, [o_window frame].size.width,
539             [o_window minSize].height ) display: YES animate:YES];
540         [o_playlist_view setAutoresizesSubviews: NO];
541     }
542     else
543     {
544         b_small_window = NO;
545         [o_playlist_view setFrame: NSMakeRect( 10, 10, [o_window frame].size.width - 20, [o_window frame].size.height - 105 )];
546         [o_playlist_view setNeedsDisplay:YES];
547         [o_playlist_view setAutoresizesSubviews: YES];
548         [[o_window contentView] addSubview: o_playlist_view];
549     }
550     [self updateTogglePlaylistState];
551
552     o_size_with_playlist = [o_window frame].size;
553
554     p_playlist = pl_Yield( p_intf );
555
556     /* Check if we need to start playing */
557     if( p_intf->b_play )
558     {
559         playlist_Control( p_playlist, PLAYLIST_PLAY, VLC_FALSE );
560     }
561     var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
562     val.b_bool = VLC_FALSE;
563
564     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
565     var_AddCallback( p_playlist, "intf-show", ShowController, self);
566
567     vlc_object_release( p_playlist );
568  
569     var_Create( p_intf, "interaction", VLC_VAR_ADDRESS );
570     var_AddCallback( p_intf, "interaction", InteractCallback, self );
571     p_intf->b_interaction = VLC_TRUE;
572
573     /* update the playmode stuff */
574     p_intf->p_sys->b_playmode_update = VLC_TRUE;
575
576     [[NSNotificationCenter defaultCenter] addObserver: self
577                                              selector: @selector(refreshVoutDeviceMenu:)
578                                                  name: NSApplicationDidChangeScreenParametersNotification
579                                                object: nil];
580
581     o_img_play = [NSImage imageNamed: @"play"];
582     o_img_pause = [NSImage imageNamed: @"pause"];    
583     
584     [self controlTintChanged];
585
586     [[NSNotificationCenter defaultCenter] addObserver: self
587                                              selector: @selector( controlTintChanged )
588                                                  name: NSControlTintDidChangeNotification
589                                                object: nil];
590     
591     nib_main_loaded = TRUE;
592 }
593
594 - (void)controlTintChanged
595 {
596     BOOL b_playing = NO;
597     
598     if( [o_btn_play alternateImage] == o_img_play_pressed )
599         b_playing = YES;
600     
601     if( [NSColor currentControlTint] == NSGraphiteControlTint )
602     {
603         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
604         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
605         
606         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
607         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
608         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
609         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
610         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
611         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
612         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
613         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
614     }
615     else
616     {
617         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
618         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
619         
620         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
621         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
622         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
623         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
624         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
625         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
626         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
627         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
628     }
629     
630     if( b_playing )
631         [o_btn_play setAlternateImage: o_img_play_pressed];
632     else
633         [o_btn_play setAlternateImage: o_img_pause_pressed];
634 }
635
636 - (void)initStrings
637 {
638     [o_window setTitle: _NS("VLC - Controller")];
639     [self setScrollField:_NS("VLC media player") stopAfter:-1];
640
641     /* button controls */
642     [o_btn_prev setToolTip: _NS("Previous")];
643     [o_btn_rewind setToolTip: _NS("Rewind")];
644     [o_btn_play setToolTip: _NS("Play")];
645     [o_btn_stop setToolTip: _NS("Stop")];
646     [o_btn_ff setToolTip: _NS("Fast Forward")];
647     [o_btn_next setToolTip: _NS("Next")];
648     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
649     [o_volumeslider setToolTip: _NS("Volume")];
650     [o_timeslider setToolTip: _NS("Position")];
651     [o_btn_playlist setToolTip: _NS("Playlist")];
652
653     /* messages panel */
654     [o_msgs_panel setTitle: _NS("Messages")];
655     [o_msgs_btn_crashlog setTitle: _NS("Open CrashLog...")];
656
657     /* main menu */
658     [o_mi_about setTitle: [_NS("About VLC media player") \
659         stringByAppendingString: @"..."]];
660     [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
661     [o_mi_prefs setTitle: _NS("Preferences...")];
662     [o_mi_add_intf setTitle: _NS("Add Interface")];
663     [o_mu_add_intf setTitle: _NS("Add Interface")];
664     [o_mi_services setTitle: _NS("Services")];
665     [o_mi_hide setTitle: _NS("Hide VLC")];
666     [o_mi_hide_others setTitle: _NS("Hide Others")];
667     [o_mi_show_all setTitle: _NS("Show All")];
668     [o_mi_quit setTitle: _NS("Quit VLC")];
669
670     [o_mu_file setTitle: _ANS("1:File")];
671     [o_mi_open_generic setTitle: _NS("Open File...")];
672     [o_mi_open_file setTitle: _NS("Quick Open File...")];
673     [o_mi_open_disc setTitle: _NS("Open Disc...")];
674     [o_mi_open_net setTitle: _NS("Open Network...")];
675     [o_mi_open_recent setTitle: _NS("Open Recent")];
676     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
677     [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
678
679     [o_mu_edit setTitle: _NS("Edit")];
680     [o_mi_cut setTitle: _NS("Cut")];
681     [o_mi_copy setTitle: _NS("Copy")];
682     [o_mi_paste setTitle: _NS("Paste")];
683     [o_mi_clear setTitle: _NS("Clear")];
684     [o_mi_select_all setTitle: _NS("Select All")];
685
686     [o_mu_controls setTitle: _NS("Playback")];
687     [o_mi_play setTitle: _NS("Play")];
688     [o_mi_stop setTitle: _NS("Stop")];
689     [o_mi_faster setTitle: _NS("Faster")];
690     [o_mi_slower setTitle: _NS("Slower")];
691     [o_mi_previous setTitle: _NS("Previous")];
692     [o_mi_next setTitle: _NS("Next")];
693     [o_mi_random setTitle: _NS("Random")];
694     [o_mi_repeat setTitle: _NS("Repeat One")];
695     [o_mi_loop setTitle: _NS("Repeat All")];
696     [o_mi_fwd setTitle: _NS("Step Forward")];
697     [o_mi_bwd setTitle: _NS("Step Backward")];
698
699     [o_mi_program setTitle: _NS("Program")];
700     [o_mu_program setTitle: _NS("Program")];
701     [o_mi_title setTitle: _NS("Title")];
702     [o_mu_title setTitle: _NS("Title")];
703     [o_mi_chapter setTitle: _NS("Chapter")];
704     [o_mu_chapter setTitle: _NS("Chapter")];
705
706     [o_mu_audio setTitle: _NS("Audio")];
707     [o_mi_vol_up setTitle: _NS("Volume Up")];
708     [o_mi_vol_down setTitle: _NS("Volume Down")];
709     [o_mi_mute setTitle: _NS("Mute")];
710     [o_mi_audiotrack setTitle: _NS("Audio Track")];
711     [o_mu_audiotrack setTitle: _NS("Audio Track")];
712     [o_mi_channels setTitle: _NS("Audio Channels")];
713     [o_mu_channels setTitle: _NS("Audio Channels")];
714     [o_mi_device setTitle: _NS("Audio Device")];
715     [o_mu_device setTitle: _NS("Audio Device")];
716     [o_mi_visual setTitle: _NS("Visualizations")];
717     [o_mu_visual setTitle: _NS("Visualizations")];
718
719     [o_mu_video setTitle: _NS("Video")];
720     [o_mi_half_window setTitle: _NS("Half Size")];
721     [o_mi_normal_window setTitle: _NS("Normal Size")];
722     [o_mi_double_window setTitle: _NS("Double Size")];
723     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
724     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
725     [o_mi_floatontop setTitle: _NS("Float on Top")];
726     [o_mi_snapshot setTitle: _NS("Snapshot")];
727     [o_mi_videotrack setTitle: _NS("Video Track")];
728     [o_mu_videotrack setTitle: _NS("Video Track")];
729     [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
730     [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
731     [o_mi_crop setTitle: _NS("Crop")];
732     [o_mu_crop setTitle: _NS("Crop")];
733     [o_mi_screen setTitle: _NS("Video Device")];
734     [o_mu_screen setTitle: _NS("Video Device")];
735     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
736     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
737     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
738     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
739     [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
740     [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
741
742     [o_mu_window setTitle: _NS("Window")];
743     [o_mi_minimize setTitle: _NS("Minimize Window")];
744     [o_mi_close_window setTitle: _NS("Close Window")];
745     [o_mi_controller setTitle: _NS("Controller...")];
746     [o_mi_equalizer setTitle: _NS("Equalizer...")];
747     [o_mi_extended setTitle: _NS("Extended Controls...")];
748     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
749     [o_mi_playlist setTitle: _NS("Playlist...")];
750     [o_mi_info setTitle: _NS("Media Information...")];
751     [o_mi_messages setTitle: _NS("Messages...")];
752     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
753
754     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
755
756     [o_mu_help setTitle: _NS("Help")];
757     [o_mi_help setTitle: _NS("VLC media player Help...")];
758     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
759     [o_mi_license setTitle: _NS("License")];
760     [o_mi_documentation setTitle: _NS("Online Documentation...")];
761     [o_mi_website setTitle: _NS("VideoLAN Website...")];
762     [o_mi_donation setTitle: _NS("Make a donation...")];
763     [o_mi_forum setTitle: _NS("Online Forum...")];
764
765     /* dock menu */
766     [o_dmi_play setTitle: _NS("Play")];
767     [o_dmi_stop setTitle: _NS("Stop")];
768     [o_dmi_next setTitle: _NS("Next")];
769     [o_dmi_previous setTitle: _NS("Previous")];
770     [o_dmi_mute setTitle: _NS("Mute")];
771  
772     /* vout menu */
773     [o_vmi_play setTitle: _NS("Play")];
774     [o_vmi_stop setTitle: _NS("Stop")];
775     [o_vmi_prev setTitle: _NS("Previous")];
776     [o_vmi_next setTitle: _NS("Next")];
777     [o_vmi_volup setTitle: _NS("Volume Up")];
778     [o_vmi_voldown setTitle: _NS("Volume Down")];
779     [o_vmi_mute setTitle: _NS("Mute")];
780     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
781     [o_vmi_snapshot setTitle: _NS("Snapshot")];
782
783     [o_info_window setTitle: _NS("Media Information")];
784 }
785
786 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
787 {
788     o_msg_lock = [[NSLock alloc] init];
789     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
790
791     [p_intf->p_sys->o_sendport setDelegate: self];
792     [[NSRunLoop currentRunLoop]
793         addPort: p_intf->p_sys->o_sendport
794         forMode: NSDefaultRunLoopMode];
795
796     [NSTimer scheduledTimerWithTimeInterval: 0.5
797         target: self selector: @selector(manageIntf:)
798         userInfo: nil repeats: FALSE];
799
800     [NSThread detachNewThreadSelector: @selector(manage)
801         toTarget: self withObject: nil];
802
803     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
804         var: "intf-add" selector: @selector(toggleVar:)];
805
806     /* check whether the user runs a valid version of OSX; alert is auto-released */
807     if( MACOS_VERSION < 10.4f )
808     {
809         NSAlert *ourAlert;
810         int i_returnValue;
811         ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is not supported")
812                         defaultButton: _NS("Quit")
813                       alternateButton: NULL
814                           otherButton: NULL
815             informativeTextWithFormat: _NS("VLC media player requires Mac OS X 10.4 or higher.")];
816         [ourAlert setAlertStyle: NSCriticalAlertStyle];
817         i_returnValue = [ourAlert runModal];
818         [NSApp terminate: self];
819     }
820
821     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
822 }
823
824 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
825 {
826     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
827     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
828     if( b_autoplay )
829         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
830     else
831         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
832
833     return( TRUE );
834 }
835
836 - (NSString *)localizedString:(const char *)psz
837 {
838     NSString * o_str = nil;
839
840     if( psz != NULL )
841     {
842         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
843
844         if( o_str == NULL )
845         {
846             msg_Err( VLCIntf, "could not translate: %s", psz );
847             return( @"" );
848         }
849     }
850     else
851     {
852         msg_Warn( VLCIntf, "can't translate empty strings" );
853         return( @"" );
854     }
855
856     return( o_str );
857 }
858
859 /* When user click in the Dock icon our double click in the finder */
860 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
861 {    
862     if(!hasVisibleWindows)
863         [o_window makeKeyAndOrderFront:self];
864
865     return YES;
866 }
867
868 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
869 {
870 #ifdef UPDATE_CHECK
871     /* Check for update silently on startup */
872     if( !nib_update_loaded )
873         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
874
875     if([o_update shouldCheckForUpdate])
876         [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:NULL];
877 #endif
878
879     /* Handle sleep notification */
880     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
881            name:NSWorkspaceWillSleepNotification object:nil];
882 }
883
884 /* Listen to the remote in exclusive mode, only when VLC is the active
885    application */
886 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
887 {
888     [o_remote startListening: self];
889 }
890 - (void)applicationDidResignActive:(NSNotification *)aNotification
891 {
892     [o_remote stopListening: self];
893 }
894
895 /* Triggered when the computer goes to sleep */
896 - (void)computerWillSleep: (NSNotification *)notification
897 {
898     /* Pause */
899     if( p_intf->p_sys->i_play_status == PLAYING_S )
900     {
901         vlc_value_t val;
902         val.i_int = config_GetInt( p_intf, "key-play-pause" );
903         var_Set( p_intf->p_libvlc, "key-pressed", val );
904     }
905 }
906
907 /* Helper method for the remote control interface in order to trigger forward/backward and volume
908    increase/decrease as long as the user holds the left/right, plus/minus button */
909 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
910 {
911     if(b_remote_button_hold)
912     {
913         switch([buttonIdentifierNumber intValue])
914         {
915             case kRemoteButtonRight_Hold:
916                   [o_controls forward: self];
917             break;
918             case kRemoteButtonLeft_Hold:
919                   [o_controls backward: self];
920             break;
921             case kRemoteButtonVolume_Plus_Hold:
922                 [o_controls volumeUp: self];
923             break;
924             case kRemoteButtonVolume_Minus_Hold:
925                 [o_controls volumeDown: self];
926             break;
927         }
928         if(b_remote_button_hold)
929         {
930             /* trigger event */
931             [self performSelector:@selector(executeHoldActionForRemoteButton:)
932                          withObject:buttonIdentifierNumber
933                          afterDelay:0.25];
934         }
935     }
936 }
937
938 /* Apple Remote callback */
939 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
940                pressedDown: (BOOL) pressedDown
941                 clickCount: (unsigned int) count
942 {
943     switch( buttonIdentifier )
944     {
945         case kRemoteButtonPlay:
946             if(count >= 2) {
947                 [o_controls toogleFullscreen:self];
948             } else {
949                 [o_controls play: self];
950             }
951             break;
952         case kRemoteButtonVolume_Plus:
953             [o_controls volumeUp: self];
954             break;
955         case kRemoteButtonVolume_Minus:
956             [o_controls volumeDown: self];
957             break;
958         case kRemoteButtonRight:
959             [o_controls next: self];
960             break;
961         case kRemoteButtonLeft:
962             [o_controls prev: self];
963             break;
964         case kRemoteButtonRight_Hold:
965         case kRemoteButtonLeft_Hold:
966         case kRemoteButtonVolume_Plus_Hold:
967         case kRemoteButtonVolume_Minus_Hold:
968             /* simulate an event as long as the user holds the button */
969             b_remote_button_hold = pressedDown;
970             if( pressedDown )
971             {
972                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
973                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
974                            withObject:buttonIdentifierNumber];
975             }
976             break;
977         case kRemoteButtonMenu:
978             [o_controls showPosition: self];
979             break;
980         default:
981             /* Add here whatever you want other buttons to do */
982             break;
983     }
984 }
985
986 - (char *)delocalizeString:(NSString *)id
987 {
988     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
989                           allowLossyConversion: NO];
990     char * psz_string;
991
992     if( o_data == nil )
993     {
994         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
995                      allowLossyConversion: YES];
996         psz_string = malloc( [o_data length] + 1 );
997         [o_data getBytes: psz_string];
998         psz_string[ [o_data length] ] = '\0';
999         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1000                  psz_string );
1001     }
1002     else
1003     {
1004         psz_string = malloc( [o_data length] + 1 );
1005         [o_data getBytes: psz_string];
1006         psz_string[ [o_data length] ] = '\0';
1007     }
1008
1009     return psz_string;
1010 }
1011
1012 /* i_width is in pixels */
1013 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1014 {
1015     NSMutableString *o_wrapped;
1016     NSString *o_out_string;
1017     NSRange glyphRange, effectiveRange, charRange;
1018     NSRect lineFragmentRect;
1019     unsigned glyphIndex, breaksInserted = 0;
1020
1021     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1022         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1023         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1024     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1025     NSTextContainer *o_container = [[NSTextContainer alloc]
1026         initWithContainerSize: NSMakeSize(i_width, 2000)];
1027
1028     [o_layout_manager addTextContainer: o_container];
1029     [o_container release];
1030     [o_storage addLayoutManager: o_layout_manager];
1031     [o_layout_manager release];
1032
1033     o_wrapped = [o_in_string mutableCopy];
1034     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1035
1036     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1037             glyphIndex += effectiveRange.length) {
1038         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1039                                             effectiveRange: &effectiveRange];
1040         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1041                                     actualGlyphRange: &effectiveRange];
1042         if([o_wrapped lineRangeForRange:
1043                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1044             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1045             breaksInserted++;
1046         }
1047     }
1048     o_out_string = [NSString stringWithString: o_wrapped];
1049     [o_wrapped release];
1050     [o_storage release];
1051
1052     return o_out_string;
1053 }
1054
1055
1056 /*****************************************************************************
1057  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1058  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1059  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1060  *****************************************************************************/
1061 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1062 {
1063     unichar key = 0;
1064     vlc_value_t val;
1065     unsigned int i_pressed_modifiers = 0;
1066     struct hotkey *p_hotkeys;
1067     int i;
1068
1069     val.i_int = 0;
1070     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1071
1072     i_pressed_modifiers = [o_event modifierFlags];
1073
1074     if( i_pressed_modifiers & NSShiftKeyMask )
1075         val.i_int |= KEY_MODIFIER_SHIFT;
1076     if( i_pressed_modifiers & NSControlKeyMask )
1077         val.i_int |= KEY_MODIFIER_CTRL;
1078     if( i_pressed_modifiers & NSAlternateKeyMask )
1079         val.i_int |= KEY_MODIFIER_ALT;
1080     if( i_pressed_modifiers & NSCommandKeyMask )
1081         val.i_int |= KEY_MODIFIER_COMMAND;
1082
1083     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1084
1085     switch( key )
1086     {
1087         case NSDeleteCharacter:
1088         case NSDeleteFunctionKey:
1089         case NSDeleteCharFunctionKey:
1090         case NSBackspaceCharacter:
1091         case NSUpArrowFunctionKey:
1092         case NSDownArrowFunctionKey:
1093         case NSRightArrowFunctionKey:
1094         case NSLeftArrowFunctionKey:
1095         case NSEnterCharacter:
1096         case NSCarriageReturnCharacter:
1097             return NO;
1098     }
1099
1100     val.i_int |= CocoaKeyToVLC( key );
1101
1102     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1103     {
1104         if( p_hotkeys[i].i_key == val.i_int )
1105         {
1106             var_Set( p_intf->p_libvlc, "key-pressed", val );
1107             return YES;
1108         }
1109     }
1110
1111     return NO;
1112 }
1113
1114 - (id)getControls
1115 {
1116     if( o_controls )
1117         return o_controls;
1118
1119     return nil;
1120 }
1121
1122 - (id)getSimplePreferences
1123 {
1124     if( !o_sprefs )
1125         return nil;
1126
1127     if( !nib_prefs_loaded )
1128         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1129
1130     return o_sprefs;
1131 }
1132
1133 - (id)getPreferences
1134 {
1135     if( !o_prefs )
1136         return nil;
1137
1138     if( !nib_prefs_loaded )
1139         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1140
1141     return o_prefs;
1142 }
1143
1144 - (id)getPlaylist
1145 {
1146     if( o_playlist )
1147         return o_playlist;
1148
1149     return nil;
1150 }
1151
1152 - (id)getInfo
1153 {
1154     if( o_info )
1155         return o_info;
1156
1157     return nil;
1158 }
1159
1160 - (id)getWizard
1161 {
1162     if( o_wizard )
1163         return o_wizard;
1164
1165     return nil;
1166 }
1167
1168 - (id)getBookmarks
1169 {
1170     if( o_bookmarks )
1171         return o_bookmarks;
1172
1173     return nil;
1174 }
1175
1176 - (id)getEmbeddedList
1177 {
1178     if( o_embedded_list )
1179         return o_embedded_list;
1180
1181     return nil;
1182 }
1183
1184 - (id)getInteractionList
1185 {
1186     if( o_interaction_list )
1187         return o_interaction_list;
1188
1189     return nil;
1190 }
1191
1192 - (id)getMainIntfPgbar
1193 {
1194     if( o_main_pgbar )
1195         return o_main_pgbar;
1196
1197     return nil;
1198 }
1199
1200 - (id)getControllerWindow
1201 {
1202     if( o_window )
1203         return o_window;
1204     return nil;
1205 }
1206
1207 - (id)getVoutMenu
1208 {
1209     return o_vout_menu;
1210 }
1211
1212 - (id)getEyeTVController
1213 {
1214     if( o_eyetv )
1215         return o_eyetv;
1216
1217     return nil;
1218 }
1219
1220 - (void)manage
1221 {
1222     playlist_t * p_playlist;
1223
1224     /* new thread requires a new pool */
1225     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
1226
1227     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1228
1229     p_playlist = pl_Yield( p_intf );
1230
1231     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1232     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1233     var_AddCallback( p_playlist, "item-append", PlaylistChanged, self );
1234     var_AddCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1235     var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1236
1237     vlc_object_release( p_playlist );
1238
1239     while( !intf_ShouldDie( p_intf ) )
1240     {
1241         vlc_mutex_lock( &p_intf->change_lock );
1242
1243
1244         if( p_intf->p_sys->p_input == NULL )
1245         {
1246             p_intf->p_sys->p_input = p_playlist->p_input;
1247
1248                 /* Refresh the interface */
1249             if( p_intf->p_sys->p_input )
1250             {
1251                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1252                 p_intf->p_sys->b_input_update = VLC_TRUE;
1253             }
1254         }
1255         else if( p_intf->p_sys->p_input->b_die || p_intf->p_sys->p_input->b_dead )
1256         {
1257             /* input stopped */
1258             p_intf->p_sys->b_intf_update = VLC_TRUE;
1259             p_intf->p_sys->i_play_status = END_S;
1260             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1261             p_intf->p_sys->p_input = NULL;
1262         }
1263
1264         /* Manage volume status */
1265         [self manageVolumeSlider];
1266
1267         vlc_mutex_unlock( &p_intf->change_lock );
1268         msleep( 100000 );
1269     }
1270     [o_pool release];
1271 }
1272
1273 - (void)manageIntf:(NSTimer *)o_timer
1274 {
1275     vlc_value_t val;
1276     playlist_t * p_playlist;
1277     input_thread_t * p_input;
1278
1279     if( p_intf->p_libvlc->b_die == VLC_TRUE )
1280     {
1281         [o_timer invalidate];
1282         return;
1283     }
1284
1285     if( p_intf->p_sys->b_input_update )
1286     {
1287         /* Called when new input is opened */
1288         p_intf->p_sys->b_current_title_update = VLC_TRUE;
1289         p_intf->p_sys->b_intf_update = VLC_TRUE;
1290         p_intf->p_sys->b_input_update = VLC_FALSE;
1291     }
1292     if( p_intf->p_sys->b_intf_update )
1293     {
1294         vlc_bool_t b_input = VLC_FALSE;
1295         vlc_bool_t b_plmul = VLC_FALSE;
1296         vlc_bool_t b_control = VLC_FALSE;
1297         vlc_bool_t b_seekable = VLC_FALSE;
1298         vlc_bool_t b_chapters = VLC_FALSE;
1299
1300         playlist_t * p_playlist = pl_Yield( p_intf );
1301     /* TODO: fix i_size use */
1302         b_plmul = p_playlist->items.i_size > 1;
1303         p_input = p_playlist->p_input;
1304
1305         if( ( b_input = ( p_input != NULL ) ) )
1306         {
1307             /* seekable streams */
1308             vlc_object_yield( p_input );
1309             b_seekable = var_GetBool( p_input, "seekable" );
1310
1311             /* check whether slow/fast motion is possible */
1312             b_control = p_input->b_can_pace_control;
1313
1314             /* chapters & titles */
1315             //b_chapters = p_input->stream.i_area_nb > 1;
1316             vlc_object_release( p_input );
1317         }
1318         vlc_object_release( p_playlist );
1319
1320         [o_btn_stop setEnabled: b_input];
1321         [o_btn_ff setEnabled: b_seekable];
1322         [o_btn_rewind setEnabled: b_seekable];
1323         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1324         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1325
1326         [o_timeslider setFloatValue: 0.0];
1327         [o_timeslider setEnabled: b_seekable];
1328         [o_timefield setStringValue: @"00:00"];
1329         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1330         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1331
1332         [o_embedded_window setSeekable: b_seekable];
1333
1334         p_intf->p_sys->b_current_title_update = VLC_TRUE;
1335         
1336         p_intf->p_sys->b_intf_update = VLC_FALSE;
1337     }
1338
1339     if( p_intf->p_sys->b_playmode_update )
1340     {
1341         [o_playlist playModeUpdated];
1342         p_intf->p_sys->b_playmode_update = VLC_FALSE;
1343     }
1344     if( p_intf->p_sys->b_playlist_update )
1345     {
1346         [o_playlist playlistUpdated];
1347         p_intf->p_sys->b_playlist_update = VLC_FALSE;
1348     }
1349
1350     if( p_intf->p_sys->b_fullscreen_update )
1351     {
1352         p_intf->p_sys->b_fullscreen_update = VLC_FALSE;
1353     }
1354
1355     if( p_intf->p_sys->b_intf_show )
1356     {
1357         [o_window makeKeyAndOrderFront: self];
1358
1359         p_intf->p_sys->b_intf_show = VLC_FALSE;
1360     }
1361
1362     p_playlist = pl_Yield( p_intf );
1363     p_input = p_playlist->p_input;
1364
1365     if( p_input && !p_input->b_die )
1366     {
1367         vlc_value_t val;
1368         vlc_object_yield( p_input );
1369
1370         if( p_intf->p_sys->b_current_title_update )
1371         {
1372             NSString *o_temp;
1373
1374             if( p_playlist->status.p_item == NULL )
1375             {
1376                 vlc_object_release( p_input );
1377                 vlc_object_release( p_playlist );
1378                 return;
1379             }
1380             if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1381                 o_temp = [NSString stringWithUTF8String: 
1382                     input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1383             else
1384                 o_temp = [NSString stringWithUTF8String:
1385                     p_playlist->status.p_item->p_input->psz_name];
1386             [self setScrollField: o_temp stopAfter:-1];
1387             [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1388
1389             [[o_controls getVoutView] updateTitle];
1390  
1391             [o_playlist updateRowSelection];
1392             p_intf->p_sys->b_current_title_update = FALSE;
1393         }
1394
1395         if( [o_timeslider isEnabled] )
1396         {
1397             /* Update the slider */
1398             vlc_value_t time;
1399             NSString * o_time;
1400             vlc_value_t pos;
1401             char psz_time[MSTRTIME_MAX_SIZE];
1402             float f_updated;
1403
1404             var_Get( p_input, "position", &pos );
1405             f_updated = 10000. * pos.f_float;
1406             [o_timeslider setFloatValue: f_updated];
1407
1408             var_Get( p_input, "time", &time );
1409
1410             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1411
1412             [o_timefield setStringValue: o_time];
1413             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1414             [o_embedded_window setTime: o_time position: f_updated];
1415         }
1416
1417         if( p_intf->p_sys->b_volume_update )
1418         {
1419             NSString *o_text;
1420             int i_volume_step = 0;
1421             o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1422             if( i_lastShownVolume != -1 )
1423             [self setScrollField:o_text stopAfter:1000000];
1424             i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1425             [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1426             [o_volumeslider setEnabled: TRUE];
1427             [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1428             p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1429             p_intf->p_sys->b_volume_update = FALSE;
1430         }
1431
1432         /* Manage Playing status */
1433         var_Get( p_input, "state", &val );
1434         if( p_intf->p_sys->i_play_status != val.i_int )
1435         {
1436             p_intf->p_sys->i_play_status = val.i_int;
1437             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1438             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1439         }
1440         vlc_object_release( p_input );
1441     }
1442     else
1443     {
1444         p_intf->p_sys->i_play_status = END_S;
1445         p_intf->p_sys->b_intf_update = VLC_TRUE;
1446         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1447         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1448         [self setSubmenusEnabled: FALSE];
1449     }
1450     vlc_object_release( p_playlist );
1451
1452     [self updateMessageArray];
1453
1454     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1455         [self resetScrollField];
1456
1457     [NSTimer scheduledTimerWithTimeInterval: 0.3
1458         target: self selector: @selector(manageIntf:)
1459         userInfo: nil repeats: FALSE];
1460 }
1461
1462 - (void)setupMenus
1463 {
1464     playlist_t * p_playlist = pl_Yield( p_intf );
1465     input_thread_t * p_input = p_playlist->p_input;
1466     if( p_input != NULL )
1467     {
1468         vlc_object_yield( p_input );
1469         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1470             var: "program" selector: @selector(toggleVar:)];
1471
1472         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1473             var: "title" selector: @selector(toggleVar:)];
1474
1475         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1476             var: "chapter" selector: @selector(toggleVar:)];
1477
1478         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1479             var: "audio-es" selector: @selector(toggleVar:)];
1480
1481         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1482             var: "video-es" selector: @selector(toggleVar:)];
1483
1484         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1485             var: "spu-es" selector: @selector(toggleVar:)];
1486
1487         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1488                                                     FIND_ANYWHERE );
1489         if( p_aout != NULL )
1490         {
1491             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1492                 var: "audio-channels" selector: @selector(toggleVar:)];
1493
1494             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1495                 var: "audio-device" selector: @selector(toggleVar:)];
1496
1497             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1498                 var: "visual" selector: @selector(toggleVar:)];
1499             vlc_object_release( (vlc_object_t *)p_aout );
1500         }
1501
1502         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1503                                                             FIND_ANYWHERE );
1504
1505         if( p_vout != NULL )
1506         {
1507             vlc_object_t * p_dec_obj;
1508
1509             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1510                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1511
1512             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1513                 var: "crop" selector: @selector(toggleVar:)];
1514
1515             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1516                 var: "video-device" selector: @selector(toggleVar:)];
1517
1518             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1519                 var: "deinterlace" selector: @selector(toggleVar:)];
1520
1521             p_dec_obj = (vlc_object_t *)vlc_object_find(
1522                                                  (vlc_object_t *)p_vout,
1523                                                  VLC_OBJECT_DECODER,
1524                                                  FIND_PARENT );
1525             if( p_dec_obj != NULL )
1526             {
1527                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1528                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1529                     @selector(toggleVar:)];
1530
1531                 vlc_object_release(p_dec_obj);
1532             }
1533             vlc_object_release( (vlc_object_t *)p_vout );
1534         }
1535         vlc_object_release( p_input );
1536     }
1537     vlc_object_release( p_playlist );
1538 }
1539
1540 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1541 {
1542     int x,y = 0;
1543     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1544                                               FIND_ANYWHERE );
1545  
1546     if(! p_vout )
1547         return;
1548  
1549     /* clean the menu before adding new entries */
1550     if( [o_mi_screen hasSubmenu] )
1551     {
1552         y = [[o_mi_screen submenu] numberOfItems] - 1;
1553         msg_Dbg( VLCIntf, "%i items in submenu", y );
1554         while( x != y )
1555         {
1556             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1557             [[o_mi_screen submenu] removeItemAtIndex: x];
1558             x++;
1559         }
1560     }
1561
1562     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1563                              var: "video-device" selector: @selector(toggleVar:)];
1564     vlc_object_release( (vlc_object_t *)p_vout );
1565 }
1566
1567 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1568 {
1569     if( timeout != -1 )
1570         i_end_scroll = mdate() + timeout;
1571     else
1572         i_end_scroll = -1;
1573     [o_scrollfield setStringValue: o_string];
1574 }
1575
1576 - (void)resetScrollField
1577 {
1578     playlist_t * p_playlist = pl_Yield( p_intf );
1579     input_thread_t * p_input = p_playlist->p_input;
1580
1581     i_end_scroll = -1;
1582     if( p_input && !p_input->b_die )
1583     {
1584         NSString *o_temp;
1585         vlc_object_yield( p_input );
1586         if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1587             o_temp = [NSString stringWithUTF8String: 
1588                 input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1589         else
1590             o_temp = [NSString stringWithUTF8String:
1591                 p_playlist->status.p_item->p_input->psz_name];
1592         [self setScrollField: o_temp stopAfter:-1];
1593         vlc_object_release( p_input );
1594         vlc_object_release( p_playlist );
1595         return;
1596     }
1597     vlc_object_release( p_playlist );
1598     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1599 }
1600
1601 - (void)updateMessageArray
1602 {
1603     int i_start, i_stop;
1604
1605     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1606     i_stop = *p_intf->p_sys->p_sub->pi_stop;
1607     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1608
1609     if( p_intf->p_sys->p_sub->i_start != i_stop )
1610     {
1611         NSColor *o_white = [NSColor whiteColor];
1612         NSColor *o_red = [NSColor redColor];
1613         NSColor *o_yellow = [NSColor yellowColor];
1614         NSColor *o_gray = [NSColor grayColor];
1615
1616         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1617         static const char * ppsz_type[4] = { ": ", " error: ",
1618                                              " warning: ", " debug: " };
1619
1620         for( i_start = p_intf->p_sys->p_sub->i_start;
1621              i_start != i_stop;
1622              i_start = (i_start+1) % VLC_MSG_QSIZE )
1623         {
1624             NSString *o_msg;
1625             NSDictionary *o_attr;
1626             NSAttributedString *o_msg_color;
1627
1628             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
1629
1630             [o_msg_lock lock];
1631
1632             if( [o_msg_arr count] + 2 > 400 )
1633             {
1634                 unsigned rid[] = { 0, 1 };
1635                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
1636                            numIndices: sizeof(rid)/sizeof(rid[0])];
1637             }
1638
1639             o_attr = [NSDictionary dictionaryWithObject: o_gray
1640                 forKey: NSForegroundColorAttributeName];
1641             o_msg = [NSString stringWithFormat: @"%s%s",
1642                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1643                 ppsz_type[i_type]];
1644             o_msg_color = [[NSAttributedString alloc]
1645                 initWithString: o_msg attributes: o_attr];
1646             [o_msg_arr addObject: [o_msg_color autorelease]];
1647
1648             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1649                 forKey: NSForegroundColorAttributeName];
1650             o_msg = [NSString stringWithFormat: @"%s\n",
1651                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1652             o_msg_color = [[NSAttributedString alloc]
1653                 initWithString: o_msg attributes: o_attr];
1654             [o_msg_arr addObject: [o_msg_color autorelease]];
1655
1656             [o_msg_lock unlock];
1657         }
1658
1659         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1660         p_intf->p_sys->p_sub->i_start = i_start;
1661         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1662     }
1663 }
1664
1665 - (void)playStatusUpdated:(int)i_status
1666 {
1667     if( i_status == PLAYING_S )
1668     {
1669         [[[self getControls] getFSPanel] setPause];
1670         [o_btn_play setImage: o_img_pause];
1671         [o_btn_play setAlternateImage: o_img_pause_pressed];
1672         [o_btn_play setToolTip: _NS("Pause")];
1673         [o_mi_play setTitle: _NS("Pause")];
1674         [o_dmi_play setTitle: _NS("Pause")];
1675         [o_vmi_play setTitle: _NS("Pause")];
1676     }
1677     else
1678     {
1679         [[[self getControls] getFSPanel] setPlay];
1680         [o_btn_play setImage: o_img_play];
1681         [o_btn_play setAlternateImage: o_img_play_pressed];
1682         [o_btn_play setToolTip: _NS("Play")];
1683         [o_mi_play setTitle: _NS("Play")];
1684         [o_dmi_play setTitle: _NS("Play")];
1685         [o_vmi_play setTitle: _NS("Play")];
1686     }
1687 }
1688
1689 - (void)setSubmenusEnabled:(BOOL)b_enabled
1690 {
1691     [o_mi_program setEnabled: b_enabled];
1692     [o_mi_title setEnabled: b_enabled];
1693     [o_mi_chapter setEnabled: b_enabled];
1694     [o_mi_audiotrack setEnabled: b_enabled];
1695     [o_mi_visual setEnabled: b_enabled];
1696     [o_mi_videotrack setEnabled: b_enabled];
1697     [o_mi_subtitle setEnabled: b_enabled];
1698     [o_mi_channels setEnabled: b_enabled];
1699     [o_mi_deinterlace setEnabled: b_enabled];
1700     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1701     [o_mi_device setEnabled: b_enabled];
1702     [o_mi_screen setEnabled: b_enabled];
1703     [o_mi_aspect_ratio setEnabled: b_enabled];
1704     [o_mi_crop setEnabled: b_enabled];
1705 }
1706
1707 - (void)manageVolumeSlider
1708 {
1709     audio_volume_t i_volume;
1710     aout_VolumeGet( p_intf, &i_volume );
1711
1712     if( i_volume != i_lastShownVolume )
1713     {
1714         i_lastShownVolume = i_volume;
1715         p_intf->p_sys->b_volume_update = TRUE;
1716     }
1717 }
1718
1719 - (IBAction)timesliderUpdate:(id)sender
1720 {
1721     float f_updated;
1722     playlist_t * p_playlist;
1723     input_thread_t * p_input;
1724
1725     switch( [[NSApp currentEvent] type] )
1726     {
1727         case NSLeftMouseUp:
1728         case NSLeftMouseDown:
1729         case NSLeftMouseDragged:
1730             f_updated = [sender floatValue];
1731             break;
1732
1733         default:
1734             return;
1735     }
1736     p_playlist = pl_Yield( p_intf );
1737     p_input = p_playlist->p_input;
1738     if( p_input != NULL )
1739     {
1740         vlc_value_t time;
1741         vlc_value_t pos;
1742         NSString * o_time;
1743         char psz_time[MSTRTIME_MAX_SIZE];
1744         vlc_object_yield( p_input );
1745
1746         pos.f_float = f_updated / 10000.;
1747         var_Set( p_input, "position", pos );
1748         [o_timeslider setFloatValue: f_updated];
1749
1750         var_Get( p_input, "time", &time );
1751
1752         o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1753         [o_timefield setStringValue: o_time];
1754         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1755         [o_embedded_window setTime: o_time position: f_updated];
1756         vlc_object_release( p_input );
1757     }
1758     vlc_object_release( p_playlist );
1759 }
1760
1761 - (void)applicationWillTerminate:(NSNotification *)notification
1762 {
1763     playlist_t * p_playlist;
1764     vout_thread_t * p_vout;
1765     int returnedValue = 0;
1766  
1767     /* Stop playback */
1768     p_playlist = pl_Yield( p_intf );
1769     playlist_Stop( p_playlist );
1770     vlc_object_release( p_playlist );
1771
1772     /* make sure that the current volume is saved */
1773     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
1774     returnedValue = config_SaveConfigFile( p_intf->p_libvlc, "main" );
1775     if( returnedValue != 0 )
1776         msg_Err( p_intf,
1777                  "error while saving volume in osx's terminate method (%i)",
1778                  returnedValue );
1779
1780     /* save the prefs if they were changed in the extended panel */
1781     if(o_extended && [o_extended getConfigChanged])
1782     {
1783         [o_extended savePrefs];
1784     }
1785  
1786     p_intf->b_interaction = VLC_FALSE;
1787     var_DelCallback( p_intf, "interaction", InteractCallback, self );
1788
1789     /* remove global observer watching for vout device changes correctly */
1790     [[NSNotificationCenter defaultCenter] removeObserver: self];
1791
1792     /* release some other objects here, because it isn't sure whether dealloc
1793      * will be called later on */
1794     
1795     if( nib_about_loaded && o_about )
1796         [o_about release];
1797     
1798     if( nib_prefs_loaded && o_prefs )
1799         [o_prefs release];
1800     
1801     if( nib_open_loaded && o_open )
1802         [o_open release];
1803  
1804     if( nib_extended_loaded && o_extended )
1805     {
1806         [o_extended collapsAll];
1807         [o_extended release];
1808     }
1809  
1810     if( nib_bookmarks_loaded && o_bookmarks )
1811         [o_bookmarks release];
1812
1813     if( nib_wizard_loaded && o_wizard )
1814         [o_wizard release];
1815  
1816     if( o_embedded_list != nil )
1817         [o_embedded_list release];
1818
1819     if( o_interaction_list != nil )
1820         [o_interaction_list release];
1821
1822     if( o_eyetv != nil )
1823         [o_eyetv release];
1824
1825     if( o_img_pause_pressed != nil )
1826     {
1827         [o_img_pause_pressed release];
1828         o_img_pause_pressed = nil;
1829     }
1830
1831     if( o_img_play_pressed != nil )
1832     {
1833         [o_img_pause_pressed release];
1834         o_img_pause_pressed = nil;
1835     }
1836
1837     if( o_img_pause != nil )
1838     {
1839         [o_img_pause release];
1840         o_img_pause = nil;
1841     }
1842
1843     if( o_img_play != nil )
1844     {
1845         [o_img_play release];
1846         o_img_play = nil;
1847     }
1848
1849     if( o_msg_arr != nil )
1850     {
1851         [o_msg_arr removeAllObjects];
1852         [o_msg_arr release];
1853         o_msg_arr = nil;
1854     }
1855
1856     if( o_msg_lock != nil )
1857     {
1858         [o_msg_lock release];
1859         o_msg_lock = nil;
1860     }
1861
1862     /* write cached user defaults to disk */
1863     [[NSUserDefaults standardUserDefaults] synchronize];
1864
1865     vlc_object_kill( p_intf );
1866
1867     /* Go back to Run() and make libvlc exit properly */
1868     longjmp( jmpbuffer, 1 );
1869     /* not reached */
1870 }
1871
1872
1873 - (IBAction)clearRecentItems:(id)sender
1874 {
1875     [[NSDocumentController sharedDocumentController]
1876                           clearRecentDocuments: nil];
1877 }
1878
1879 - (void)openRecentItem:(id)sender
1880 {
1881     [self application: nil openFile: [sender title]];
1882 }
1883
1884 - (IBAction)intfOpenFile:(id)sender
1885 {
1886     if( !nib_open_loaded )
1887     {
1888         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1889         [o_open awakeFromNib];
1890         [o_open openFile];
1891     } else {
1892         [o_open openFile];
1893     }
1894 }
1895
1896 - (IBAction)intfOpenFileGeneric:(id)sender
1897 {
1898     if( !nib_open_loaded )
1899     {
1900         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1901         [o_open awakeFromNib];
1902         [o_open openFileGeneric];
1903     } else {
1904         [o_open openFileGeneric];
1905     }
1906 }
1907
1908 - (IBAction)intfOpenDisc:(id)sender
1909 {
1910     if( !nib_open_loaded )
1911     {
1912         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1913         [o_open awakeFromNib];
1914         [o_open openDisc];
1915     } else {
1916         [o_open openDisc];
1917     }
1918 }
1919
1920 - (IBAction)intfOpenNet:(id)sender
1921 {
1922     if( !nib_open_loaded )
1923     {
1924         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1925         [o_open awakeFromNib];
1926         [o_open openNet];
1927     } else {
1928         [o_open openNet];
1929     }
1930 }
1931
1932 - (IBAction)showWizard:(id)sender
1933 {
1934     if( !nib_wizard_loaded )
1935     {
1936         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1937         [o_wizard initStrings];
1938         [o_wizard resetWizard];
1939         [o_wizard showWizard];
1940     } else {
1941         [o_wizard resetWizard];
1942         [o_wizard showWizard];
1943     }
1944 }
1945
1946 - (IBAction)showExtended:(id)sender
1947 {
1948     if( o_extended == nil )
1949     {
1950         o_extended = [[VLCExtended alloc] init];
1951     }
1952     if( !nib_extended_loaded )
1953     {
1954         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner:self];
1955         [o_extended initStrings];
1956         [o_extended showPanel];
1957     } else {
1958         [o_extended showPanel];
1959     }
1960 }
1961
1962 - (IBAction)showSFilters:(id)sender
1963 {
1964     if( o_sfilters == nil )
1965     {
1966         o_sfilters = [[VLCsFilters alloc] init];
1967     }
1968     if( !nib_sfilters_loaded )
1969     {
1970         nib_sfilters_loaded = [NSBundle loadNibNamed:@"SFilters" owner:self];
1971         [o_sfilters initStrings];
1972         [o_sfilters showAsPanel];
1973     } else {
1974         [o_sfilters showAsPanel];
1975     }
1976 }
1977
1978 - (IBAction)showBookmarks:(id)sender
1979 {
1980     /* we need the wizard-nib for the bookmarks's extract functionality */
1981     if( !nib_wizard_loaded )
1982     {
1983         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1984         [o_wizard initStrings];
1985     }
1986  
1987     if( !nib_bookmarks_loaded )
1988         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner:self];
1989
1990     [o_bookmarks showBookmarks];
1991 }
1992
1993 - (IBAction)viewAbout:(id)sender
1994 {
1995     if( !nib_about_loaded )
1996         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1997
1998     [o_about showAbout];
1999 }
2000
2001 - (IBAction)showLicense:(id)sender
2002 {
2003     if( !nib_about_loaded )
2004         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2005
2006     [o_about showGPL: sender];
2007 }
2008     
2009 - (IBAction)viewPreferences:(id)sender
2010 {
2011     if( !nib_prefs_loaded )
2012         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
2013
2014     if( sender == o_mi_sprefs )
2015     {
2016         o_sprefs = [[VLCSimplePrefs alloc] init];
2017         [o_sprefs showSimplePrefs];
2018     }
2019     else
2020         [o_prefs showPrefs];
2021 }
2022
2023 - (IBAction)checkForUpdate:(id)sender
2024 {
2025 #ifdef UPDATE_CHECK
2026     if( !nib_update_loaded )
2027         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
2028     [o_update showUpdateWindow];
2029 #else
2030     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2031     intf_UserFatal( VLCIntf, VLC_FALSE, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2032 #endif
2033 }
2034
2035 - (IBAction)viewHelp:(id)sender
2036 {
2037     if( !nib_about_loaded )
2038     {
2039         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2040         [o_about showHelp];
2041     }
2042     else
2043         [o_about showHelp];
2044 }
2045
2046 - (IBAction)openReadMe:(id)sender
2047 {
2048     NSString * o_path = [[NSBundle mainBundle]
2049         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2050
2051     [[NSWorkspace sharedWorkspace] openFile: o_path
2052                                    withApplication: @"TextEdit"];
2053 }
2054
2055 - (IBAction)openDocumentation:(id)sender
2056 {
2057     NSURL * o_url = [NSURL URLWithString:
2058         @"http://www.videolan.org/doc/"];
2059
2060     [[NSWorkspace sharedWorkspace] openURL: o_url];
2061 }
2062
2063 - (IBAction)openWebsite:(id)sender
2064 {
2065     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2066
2067     [[NSWorkspace sharedWorkspace] openURL: o_url];
2068 }
2069
2070 - (IBAction)openForum:(id)sender
2071 {
2072     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2073
2074     [[NSWorkspace sharedWorkspace] openURL: o_url];
2075 }
2076
2077 - (IBAction)openDonate:(id)sender
2078 {
2079     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2080
2081     [[NSWorkspace sharedWorkspace] openURL: o_url];
2082 }
2083
2084 - (IBAction)openCrashLog:(id)sender
2085 {
2086     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
2087                                     stringByExpandingTildeInPath];
2088
2089
2090     if( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
2091     {
2092         [[NSWorkspace sharedWorkspace] openFile: o_path
2093                                     withApplication: @"Console"];
2094     }
2095     else
2096     {
2097         NSBeginInformationalAlertSheet(_NS("No CrashLog found"), @"Continue", nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("Couldn't find any trace of a previous crash.") );
2098
2099     }
2100 }
2101
2102 - (IBAction)viewErrorsAndWarnings:(id)sender
2103 {
2104     [[[self getInteractionList] getErrorPanel] showPanel];
2105 }
2106
2107 - (IBAction)showMessagesPanel:(id)sender
2108 {
2109     [o_msgs_panel makeKeyAndOrderFront: sender];
2110 }
2111
2112 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2113 {
2114     if( [o_notification object] == o_msgs_panel )
2115     {
2116         id o_msg;
2117         NSEnumerator * o_enum;
2118
2119         [o_messages setString: @""];
2120
2121         [o_msg_lock lock];
2122
2123         o_enum = [o_msg_arr objectEnumerator];
2124
2125         while( ( o_msg = [o_enum nextObject] ) != nil )
2126         {
2127             [o_messages insertText: o_msg];
2128         }
2129
2130         [o_msg_lock unlock];
2131     }
2132 }
2133
2134 - (IBAction)togglePlaylist:(id)sender
2135 {
2136     NSRect o_rect = [o_window frame];
2137     /*First, check if the playlist is visible*/
2138     if( o_rect.size.height <= 200 )
2139     {
2140         o_restore_rect = o_rect;
2141         b_restore_size = true;
2142         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2143         /* make large */
2144         if( o_size_with_playlist.height > 200 )
2145         {
2146             o_rect.size.height = o_size_with_playlist.height;
2147         } else {
2148             o_rect.size.height = 500;
2149         }
2150  
2151         if( o_size_with_playlist.width > [o_window minSize].width )
2152         {
2153             o_rect.size.width = o_size_with_playlist.width;
2154         } else {
2155             o_rect.size.width = 500;
2156         }
2157  
2158         o_rect.size.height = (o_size_with_playlist.height > 200) ?
2159             o_size_with_playlist.height : 500;
2160         o_rect.origin.x = [o_window frame].origin.x;
2161         o_rect.origin.y = [o_window frame].origin.y - o_rect.size.height +
2162                                                 [o_window minSize].height;
2163
2164         NSRect screenRect = [[o_window screen] visibleFrame];
2165         if( !NSContainsRect( screenRect, o_rect ) ) {
2166             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2167                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2168             if( NSMinY(o_rect) < NSMinY(screenRect) )
2169                 o_rect.origin.y = ( NSMinY(screenRect) );
2170         }
2171
2172         [o_btn_playlist setState: YES];
2173     }
2174     else
2175     {
2176         NSSize curSize = o_rect.size;
2177         /* make small */
2178         o_rect.size.height = [o_window minSize].height;
2179         o_rect.size.width = [o_window minSize].width;
2180         o_rect.origin.x = [o_window frame].origin.x;
2181         /* Calculate the position of the lower right corner after resize */
2182         o_rect.origin.y = [o_window frame].origin.y +
2183             [o_window frame].size.height - [o_window minSize].height;
2184
2185         if( b_restore_size )
2186             o_rect = o_restore_rect;
2187
2188         [o_playlist_view setAutoresizesSubviews: NO];
2189         [o_playlist_view removeFromSuperview];
2190         [o_btn_playlist setState: NO];
2191         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2192     }
2193
2194     [o_window setFrame: o_rect display:YES animate: YES];
2195 }
2196
2197 - (void)updateTogglePlaylistState
2198 {
2199     if( [o_window frame].size.height <= 200 )
2200     {
2201         [o_btn_playlist setState: NO];
2202     }
2203     else
2204     {
2205         [o_btn_playlist setState: YES];
2206     }
2207 }
2208
2209 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2210 {
2211     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2212
2213    /*Stores the size the controller one resize, to be able to restore it when
2214      toggling the playlist*/
2215     o_size_with_playlist = proposedFrameSize;
2216
2217     if( proposedFrameSize.height <= 200 )
2218     {
2219         if( b_small_window == NO )
2220         {
2221             /* if large and going to small then hide */
2222             b_small_window = YES;
2223             [o_playlist_view setAutoresizesSubviews: NO];
2224             [o_playlist_view removeFromSuperview];
2225         }
2226         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2227     }
2228     return proposedFrameSize;
2229 }
2230
2231 - (void)windowDidMove:(NSNotification *)notif
2232 {
2233     b_restore_size = false;
2234 }
2235
2236 - (void)windowDidResize:(NSNotification *)notif
2237 {
2238     if( [o_window frame].size.height > 200 && b_small_window )
2239     {
2240         /* If large and coming from small then show */
2241         [o_playlist_view setAutoresizesSubviews: YES];
2242         [o_playlist_view setFrame: NSMakeRect( 10, 10, [o_window frame].size.width - 20, [o_window frame].size.height - [o_window minSize].height - 10 )];
2243         [o_playlist_view setNeedsDisplay:YES];
2244         [[o_window contentView] addSubview: o_playlist_view];
2245         b_small_window = NO;
2246     }
2247     [self updateTogglePlaylistState];
2248 }
2249
2250 @end
2251
2252 @implementation VLCMain (NSMenuValidation)
2253
2254 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2255 {
2256     NSString *o_title = [o_mi title];
2257     BOOL bEnabled = TRUE;
2258
2259     /* Recent Items Menu */
2260     if( [o_title isEqualToString: _NS("Clear Menu")] )
2261     {
2262         NSMenu * o_menu = [o_mi_open_recent submenu];
2263         int i_nb_items = [o_menu numberOfItems];
2264         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2265                                                        recentDocumentURLs];
2266         UInt32 i_nb_docs = [o_docs count];
2267
2268         if( i_nb_items > 1 )
2269         {
2270             while( --i_nb_items )
2271             {
2272                 [o_menu removeItemAtIndex: 0];
2273             }
2274         }
2275
2276         if( i_nb_docs > 0 )
2277         {
2278             NSURL * o_url;
2279             NSString * o_doc;
2280
2281             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2282
2283             while( TRUE )
2284             {
2285                 i_nb_docs--;
2286
2287                 o_url = [o_docs objectAtIndex: i_nb_docs];
2288
2289                 if( [o_url isFileURL] )
2290                 {
2291                     o_doc = [o_url path];
2292                 }
2293                 else
2294                 {
2295                     o_doc = [o_url absoluteString];
2296                 }
2297
2298                 [o_menu insertItemWithTitle: o_doc
2299                     action: @selector(openRecentItem:)
2300                     keyEquivalent: @"" atIndex: 0];
2301
2302                 if( i_nb_docs == 0 )
2303                 {
2304                     break;
2305                 }
2306             }
2307         }
2308         else
2309         {
2310             bEnabled = FALSE;
2311         }
2312     }
2313     return( bEnabled );
2314 }
2315
2316 @end
2317
2318 @implementation VLCMain (Internal)
2319
2320 - (void)handlePortMessage:(NSPortMessage *)o_msg
2321 {
2322     id ** val;
2323     NSData * o_data;
2324     NSValue * o_value;
2325     NSInvocation * o_inv;
2326     NSConditionLock * o_lock;
2327
2328     o_data = [[o_msg components] lastObject];
2329     o_inv = *((NSInvocation **)[o_data bytes]);
2330     [o_inv getArgument: &o_value atIndex: 2];
2331     val = (id **)[o_value pointerValue];
2332     [o_inv setArgument: val[1] atIndex: 2];
2333     o_lock = *(val[0]);
2334
2335     [o_lock lock];
2336     [o_inv invoke];
2337     [o_lock unlockWithCondition: 1];
2338 }
2339
2340 @end