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