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