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