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