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