]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: fixed crash in case either psz_module or psz_msg are NULL when received from...
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2009 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_common.h>
34 #include <vlc_keys.h>
35 #include <vlc_dialog.h>
36 #include <unistd.h> /* execl() */
37 #import <vlc_dialog.h>
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 "coredialogs.h"
52 #import "embeddedwindow.h"
53 #import "update.h"
54 #import "AppleRemote.h"
55 #import "eyetv.h"
56 #import "simple_prefs.h"
57 #import "vlm.h"
58
59 #import <AddressBook/AddressBook.h>
60
61 /*****************************************************************************
62  * Local prototypes.
63  *****************************************************************************/
64 static void Run ( intf_thread_t *p_intf );
65
66 static void * ManageThread( void *user_data );
67
68 static unichar VLCKeyToCocoa( unsigned int i_key );
69 static unsigned int VLCModifiersToCocoa( unsigned int i_key );
70
71 #pragma mark -
72 #pragma mark VLC Interface Object Callbacks
73
74 /*****************************************************************************
75  * OpenIntf: initialize interface
76  *****************************************************************************/
77 int OpenIntf ( vlc_object_t *p_this )
78 {
79     intf_thread_t *p_intf = (intf_thread_t*) p_this;
80
81     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
82     if( p_intf->p_sys == NULL )
83         return VLC_ENOMEM;
84
85     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
86
87     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
88
89     /* subscribe to LibVLCCore's messages */
90     p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
91     p_intf->pf_run = Run;
92     p_intf->b_should_run_on_first_thread = true;
93
94     return VLC_SUCCESS;
95 }
96
97 /*****************************************************************************
98  * CloseIntf: destroy interface
99  *****************************************************************************/
100 void CloseIntf ( vlc_object_t *p_this )
101 {
102     intf_thread_t *p_intf = (intf_thread_t*) p_this;
103
104     [p_intf->p_sys->o_pool release];
105
106     free( p_intf->p_sys );
107 }
108
109 /*****************************************************************************
110  * Run: main loop
111  *****************************************************************************/
112 jmp_buf jmpbuffer;
113
114 static void Run( intf_thread_t *p_intf )
115 {
116     sigset_t set;
117
118     /* Do it again - for some unknown reason, vlc_thread_create() often
119      * fails to go to real-time priority with the first launched thread
120      * (???) --Meuuh */
121     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
122
123     /* Make sure the "force quit" menu item does quit instantly.
124      * VLC overrides SIGTERM which is sent by the "force quit"
125      * menu item to make sure deamon mode quits gracefully, so
126      * we un-override SIGTERM here. */
127     sigemptyset( &set );
128     sigaddset( &set, SIGTERM );
129     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
130
131     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
132
133     /* Install a jmpbuffer to where we can go back before the NSApp exit
134      * see applicationWillTerminate: */
135     [NSApplication sharedApplication];
136
137     [[VLCMain sharedInstance] setIntf: p_intf];
138     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
139
140     /* Install a jmpbuffer to where we can go back before the NSApp exit
141      * see applicationWillTerminate: */
142     if(setjmp(jmpbuffer) == 0)
143         [NSApp run];
144     
145     [o_pool release];
146 }
147
148 #pragma mark -
149 #pragma mark Variables Callback
150
151 /*****************************************************************************
152  * MsgCallback: Callback triggered by the core once a new debug message is
153  * ready to be displayed. We store everything in a NSArray in our Cocoa part
154  * of this file, so we are forwarding everything through notifications.
155  *****************************************************************************/
156 static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned int i )
157 {
158     int canc = vlc_savecancel();
159     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
160
161     /* this may happen from time to time, let's bail out as info would be useless anyway */ 
162     if( !item->psz_module || !item->psz_msg )
163         return;
164
165     NSDictionary *o_dict = [NSDictionary dictionaryWithObjectsAndKeys:
166                                 [NSString stringWithUTF8String: item->psz_module], @"Module",
167                                 [NSString stringWithUTF8String: item->psz_msg], @"Message",
168                                 [NSNumber numberWithInt: item->i_type], @"Type", nil];
169
170     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived" 
171                                                         object: nil 
172                                                       userInfo: o_dict];
173
174     [o_pool release];
175     vlc_restorecancel( canc );
176 }
177
178
179 /*****************************************************************************
180  * playlistChanged: Callback triggered by the intf-change playlist
181  * variable, to let the intf update the playlist.
182  *****************************************************************************/
183 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
184                      vlc_value_t old_val, vlc_value_t new_val, void *param )
185 {
186     intf_thread_t * p_intf = VLCIntf;
187     if( p_intf && p_intf->p_sys )
188     {
189         p_intf->p_sys->b_intf_update = true;
190         p_intf->p_sys->b_playlist_update = true;
191         p_intf->p_sys->b_playmode_update = true;
192         p_intf->p_sys->b_current_title_update = true;
193     }
194     return VLC_SUCCESS;
195 }
196
197 /*****************************************************************************
198  * ShowController: Callback triggered by the show-intf playlist variable
199  * through the ShowIntf-control-intf, to let us show the controller-win;
200  * usually when in fullscreen-mode
201  *****************************************************************************/
202 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
203                      vlc_value_t old_val, vlc_value_t new_val, void *param )
204 {
205     intf_thread_t * p_intf = VLCIntf;
206     if( p_intf && p_intf->p_sys )
207         p_intf->p_sys->b_intf_show = true;
208     return VLC_SUCCESS;
209 }
210
211 /*****************************************************************************
212  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
213  * variable, to let the intf update the controller.
214  *****************************************************************************/
215 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
216                      vlc_value_t old_val, vlc_value_t new_val, void *param )
217 {
218     intf_thread_t * p_intf = VLCIntf;
219     if( p_intf && p_intf->p_sys )
220         p_intf->p_sys->b_fullscreen_update = true;
221     return VLC_SUCCESS;
222 }
223
224 /*****************************************************************************
225  * DialogCallback: Callback triggered by the "dialog-*" variables 
226  * to let the intf display error and interaction dialogs
227  *****************************************************************************/
228 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
229 {
230     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
231     VLCMain *interface = (VLCMain *)data;
232
233     const dialog_fatal_t *p_dialog = (const dialog_fatal_t *)value.p_address;
234
235     NSValue *o_value = [NSValue valueWithPointer:p_dialog];
236     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface getCoreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
237
238     [o_pool release];
239     return VLC_SUCCESS;
240 }
241
242 #pragma mark -
243 #pragma mark Private
244
245 @interface VLCMain ()
246 - (void)_removeOldPreferences;
247 @end
248
249 /*****************************************************************************
250  * VLCMain implementation
251  *****************************************************************************/
252 @implementation VLCMain
253
254 #pragma mark -
255 #pragma mark Initialization
256
257 static VLCMain *_o_sharedMainInstance = nil;
258
259 + (VLCMain *)sharedInstance
260 {
261     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
262 }
263
264 - (id)init
265 {
266     if( _o_sharedMainInstance) 
267     {
268         [self dealloc];
269         return _o_sharedMainInstance;
270     } 
271     else
272         _o_sharedMainInstance = [super init];
273
274     o_msg_lock = [[NSLock alloc] init];
275     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
276     /* subscribe to LibVLC's debug messages as early as possible (for us) */
277     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
278     
279     o_about = [[VLAboutBox alloc] init];
280     o_prefs = nil;
281     o_open = [[VLCOpen alloc] init];
282     o_wizard = [[VLCWizard alloc] init];
283     o_vlm = [[VLCVLMController alloc] init];
284     o_extended = nil;
285     o_bookmarks = [[VLCBookmarks alloc] init];
286     o_embedded_list = [[VLCEmbeddedList alloc] init];
287     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
288     o_info = [[VLCInfo alloc] init];
289 #ifdef UPDATE_CHECK
290     o_update = [[VLCUpdate alloc] init];
291 #endif
292
293     i_lastShownVolume = -1;
294
295     o_remote = [[AppleRemote alloc] init];
296     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
297     [o_remote setDelegate: _o_sharedMainInstance];
298
299     o_eyetv = [[VLCEyeTVController alloc] init];
300
301     /* announce our launch to a potential eyetv plugin */
302     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
303                                                                    object: @"VLCEyeTVSupport"
304                                                                  userInfo: NULL
305                                                        deliverImmediately: YES];
306
307     return _o_sharedMainInstance;
308 }
309
310 - (void)setIntf: (intf_thread_t *)p_mainintf {
311     p_intf = p_mainintf;
312 }
313
314 - (intf_thread_t *)getIntf {
315     return p_intf;
316 }
317
318 - (void)awakeFromNib
319 {
320     unsigned int i_key = 0;
321     playlist_t *p_playlist;
322     vlc_value_t val;
323
324     /* Check if we already did this once. Opening the other nibs calls it too, because VLCMain is the owner */
325     if( nib_main_loaded ) return;
326
327     /* check whether the user runs a valid version of OS X */
328     if( MACOS_VERSION < 10.5f )
329     {
330         NSAlert *ourAlert;
331         int i_returnValue;
332         NSString *o_blabla;
333         if( MACOS_VERSION == 10.4f )
334             o_blabla = _NS("VLC's last release for your OS is the 0.9 series." );
335         else if( MACOS_VERSION == 10.3f )
336             o_blabla = _NS("VLC's last release for your OS is VLC 0.8.6i, which is prone to known security issues." );
337         else // 10.2 and 10.1, still 3% of the OS X market share
338             o_blabla = _NS("VLC's last release for your OS is VLC 0.7.2, which is highly out of date and prone to " \
339                          "known security issues. We recommend you to update your Mac to a modern version of Mac OS X.");
340         ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is no longer supported")
341                                    defaultButton: _NS("Quit")
342                                  alternateButton: NULL
343                                      otherButton: NULL
344                        informativeTextWithFormat: _NS("VLC media player %s requires Mac OS X 10.5 or higher.\n\n%@"), VLC_Version(), o_blabla];
345         [ourAlert setAlertStyle: NSCriticalAlertStyle];
346         i_returnValue = [ourAlert runModal];
347         [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
348         return;
349     }
350
351     [self initStrings];
352
353     [o_window setExcludedFromWindowsMenu: YES];
354     [o_msgs_panel setExcludedFromWindowsMenu: YES];
355     [o_msgs_panel setDelegate: self];
356
357     /* In code and not in Nib for 10.4 compat */
358     NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
359     [toolbar setDelegate:self];
360     [toolbar setShowsBaselineSeparator:NO];
361     [toolbar setAllowsUserCustomization:NO];
362     [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
363     [toolbar setAutosavesConfiguration:YES];
364     [o_window setToolbar:toolbar];
365
366     i_key = config_GetInt( p_intf, "key-quit" );
367     [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
368     [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
369     i_key = config_GetInt( p_intf, "key-play-pause" );
370     [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
371     [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
372     i_key = config_GetInt( p_intf, "key-stop" );
373     [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
374     [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
375     i_key = config_GetInt( p_intf, "key-faster" );
376     [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
377     [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
378     i_key = config_GetInt( p_intf, "key-slower" );
379     [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
380     [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
381     i_key = config_GetInt( p_intf, "key-prev" );
382     [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
383     [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
384     i_key = config_GetInt( p_intf, "key-next" );
385     [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
386     [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
387     i_key = config_GetInt( p_intf, "key-jump+short" );
388     [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
389     [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
390     i_key = config_GetInt( p_intf, "key-jump-short" );
391     [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
392     [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
393     i_key = config_GetInt( p_intf, "key-jump+medium" );
394     [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
395     [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
396     i_key = config_GetInt( p_intf, "key-jump-medium" );
397     [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
398     [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
399     i_key = config_GetInt( p_intf, "key-jump+long" );
400     [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
401     [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
402     i_key = config_GetInt( p_intf, "key-jump-long" );
403     [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
404     [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
405     i_key = config_GetInt( p_intf, "key-vol-up" );
406     [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
407     [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
408     i_key = config_GetInt( p_intf, "key-vol-down" );
409     [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
410     [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
411     i_key = config_GetInt( p_intf, "key-vol-mute" );
412     [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
413     [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
414     i_key = config_GetInt( p_intf, "key-fullscreen" );
415     [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
416     [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
417     i_key = config_GetInt( p_intf, "key-snapshot" );
418     [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
419     [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
420
421     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
422
423     [self setSubmenusEnabled: FALSE];
424     [o_volumeslider setEnabled: YES];
425     [self manageVolumeSlider];
426     [o_window setDelegate: self];
427  
428     b_restore_size = false;
429
430     // Set that here as IB seems to be buggy
431     [o_window setContentMinSize:NSMakeSize(338., 30.)];
432
433     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
434     {
435         b_small_window = YES;
436         [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
437             [o_window frame].origin.y, [o_window frame].size.width,
438             [o_window minSize].height ) display: YES animate:YES];
439         [o_playlist_view setAutoresizesSubviews: NO];
440     }
441     else
442     {
443         b_small_window = NO;
444         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
445         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
446         [o_playlist_view setNeedsDisplay:YES];
447         [o_playlist_view setAutoresizesSubviews: YES];
448         [[o_window contentView] addSubview: o_playlist_view];
449     }
450
451     [self updateTogglePlaylistState];
452
453     o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
454
455     p_playlist = pl_Hold( p_intf );
456
457     var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
458     val.b_bool = false;
459
460     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
461     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
462
463     pl_Release( p_intf );
464
465     /* load our Core Dialogs nib */
466     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
467     
468     /* subscribe to various interactive dialogues */
469     var_Create( p_intf, "dialog-fatal", VLC_VAR_ADDRESS );
470     var_AddCallback( p_intf, "dialog-fatal", DialogCallback, self );
471     var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
472     var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
473     var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
474     var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
475     var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
476     var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
477     dialog_Register( p_intf );
478
479     /* update the playmode stuff */
480     p_intf->p_sys->b_playmode_update = true;
481
482     [[NSNotificationCenter defaultCenter] addObserver: self
483                                              selector: @selector(refreshVoutDeviceMenu:)
484                                                  name: NSApplicationDidChangeScreenParametersNotification
485                                                object: nil];
486
487     /* take care of tint changes during runtime */
488     o_img_play = [NSImage imageNamed: @"play"];
489     o_img_pause = [NSImage imageNamed: @"pause"];    
490     [self controlTintChanged];
491     [[NSNotificationCenter defaultCenter] addObserver: self
492                                              selector: @selector( controlTintChanged )
493                                                  name: NSControlTintDidChangeNotification
494                                                object: nil];
495
496     /* yeah, we are done */
497     nib_main_loaded = TRUE;
498 }
499
500 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
501 {
502     /* FIXME: don't poll */
503     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
504                                      target: self selector: @selector(manageIntf:)
505                                    userInfo: nil repeats: FALSE] retain];
506
507     /* Note: we use the pthread API to support pre-10.5 */
508     pthread_create( &manage_thread, NULL, ManageThread, self );
509
510     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
511         var: "intf-add" selector: @selector(toggleVar:)];
512
513     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
514 }
515
516 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
517 {
518     [self _removeOldPreferences];
519
520 #ifdef UPDATE_CHECK
521     /* Check for update silently on startup */
522     if( !nib_update_loaded )
523         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
524
525     if([o_update shouldCheckForUpdate])
526         [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:nil];
527 #endif
528
529     /* Handle sleep notification */
530     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
531            name:NSWorkspaceWillSleepNotification object:nil];
532
533     [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
534 }
535
536 - (void)initStrings
537 {
538     [o_window setTitle: _NS("VLC media player")];
539     [self setScrollField:_NS("VLC media player") stopAfter:-1];
540
541     /* button controls */
542     [o_btn_prev setToolTip: _NS("Previous")];
543     [o_btn_rewind setToolTip: _NS("Rewind")];
544     [o_btn_play setToolTip: _NS("Play")];
545     [o_btn_stop setToolTip: _NS("Stop")];
546     [o_btn_ff setToolTip: _NS("Fast Forward")];
547     [o_btn_next setToolTip: _NS("Next")];
548     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
549     [o_volumeslider setToolTip: _NS("Volume")];
550     [o_timeslider setToolTip: _NS("Position")];
551     [o_btn_playlist setToolTip: _NS("Playlist")];
552
553     /* messages panel */
554     [o_msgs_panel setTitle: _NS("Messages")];
555     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
556     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
557
558     /* main menu */
559     [o_mi_about setTitle: [_NS("About VLC media player") \
560         stringByAppendingString: @"..."]];
561     [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
562     [o_mi_prefs setTitle: _NS("Preferences...")];
563     [o_mi_add_intf setTitle: _NS("Add Interface")];
564     [o_mu_add_intf setTitle: _NS("Add Interface")];
565     [o_mi_services setTitle: _NS("Services")];
566     [o_mi_hide setTitle: _NS("Hide VLC")];
567     [o_mi_hide_others setTitle: _NS("Hide Others")];
568     [o_mi_show_all setTitle: _NS("Show All")];
569     [o_mi_quit setTitle: _NS("Quit VLC")];
570
571     [o_mu_file setTitle: _ANS("1:File")];
572     [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
573     [o_mi_open_file setTitle: _NS("Open File...")];
574     [o_mi_open_disc setTitle: _NS("Open Disc...")];
575     [o_mi_open_net setTitle: _NS("Open Network...")];
576     [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
577     [o_mi_open_recent setTitle: _NS("Open Recent")];
578     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
579     [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
580
581     [o_mu_edit setTitle: _NS("Edit")];
582     [o_mi_cut setTitle: _NS("Cut")];
583     [o_mi_copy setTitle: _NS("Copy")];
584     [o_mi_paste setTitle: _NS("Paste")];
585     [o_mi_clear setTitle: _NS("Clear")];
586     [o_mi_select_all setTitle: _NS("Select All")];
587
588     [o_mu_controls setTitle: _NS("Playback")];
589     [o_mi_play setTitle: _NS("Play")];
590     [o_mi_stop setTitle: _NS("Stop")];
591     [o_mi_faster setTitle: _NS("Faster")];
592     [o_mi_slower setTitle: _NS("Slower")];
593     [o_mi_previous setTitle: _NS("Previous")];
594     [o_mi_next setTitle: _NS("Next")];
595     [o_mi_random setTitle: _NS("Random")];
596     [o_mi_repeat setTitle: _NS("Repeat One")];
597     [o_mi_loop setTitle: _NS("Repeat All")];
598     [o_mi_fwd setTitle: _NS("Step Forward")];
599     [o_mi_bwd setTitle: _NS("Step Backward")];
600
601     [o_mi_program setTitle: _NS("Program")];
602     [o_mu_program setTitle: _NS("Program")];
603     [o_mi_title setTitle: _NS("Title")];
604     [o_mu_title setTitle: _NS("Title")];
605     [o_mi_chapter setTitle: _NS("Chapter")];
606     [o_mu_chapter setTitle: _NS("Chapter")];
607
608     [o_mu_audio setTitle: _NS("Audio")];
609     [o_mi_vol_up setTitle: _NS("Increase Volume")];
610     [o_mi_vol_down setTitle: _NS("Decrease Volume")];
611     [o_mi_mute setTitle: _NS("Mute")];
612     [o_mi_audiotrack setTitle: _NS("Audio Track")];
613     [o_mu_audiotrack setTitle: _NS("Audio Track")];
614     [o_mi_channels setTitle: _NS("Audio Channels")];
615     [o_mu_channels setTitle: _NS("Audio Channels")];
616     [o_mi_device setTitle: _NS("Audio Device")];
617     [o_mu_device setTitle: _NS("Audio Device")];
618     [o_mi_visual setTitle: _NS("Visualizations")];
619     [o_mu_visual setTitle: _NS("Visualizations")];
620
621     [o_mu_video setTitle: _NS("Video")];
622     [o_mi_half_window setTitle: _NS("Half Size")];
623     [o_mi_normal_window setTitle: _NS("Normal Size")];
624     [o_mi_double_window setTitle: _NS("Double Size")];
625     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
626     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
627     [o_mi_floatontop setTitle: _NS("Float on Top")];
628     [o_mi_snapshot setTitle: _NS("Snapshot")];
629     [o_mi_videotrack setTitle: _NS("Video Track")];
630     [o_mu_videotrack setTitle: _NS("Video Track")];
631     [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
632     [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
633     [o_mi_crop setTitle: _NS("Crop")];
634     [o_mu_crop setTitle: _NS("Crop")];
635     [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
636     [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
637     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
638     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
639     [o_mi_addSub setTitle: _NS("Open File...")];
640     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
641     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
642     [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
643     [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
644     [o_mi_teletext setTitle: _NS("Teletext")];
645     [o_mi_teletext_transparent setTitle: _NS("Transparent")];
646     [o_mi_teletext_index setTitle: _NS("Index")];
647     [o_mi_teletext_red setTitle: _NS("Red")];
648     [o_mi_teletext_green setTitle: _NS("Green")];
649     [o_mi_teletext_yellow setTitle: _NS("Yellow")];
650     [o_mi_teletext_blue setTitle: _NS("Blue")];
651
652     [o_mu_window setTitle: _NS("Window")];
653     [o_mi_minimize setTitle: _NS("Minimize Window")];
654     [o_mi_close_window setTitle: _NS("Close Window")];
655     [o_mi_controller setTitle: _NS("Controller...")];
656     [o_mi_equalizer setTitle: _NS("Equalizer...")];
657     [o_mi_extended setTitle: _NS("Extended Controls...")];
658     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
659     [o_mi_playlist setTitle: _NS("Playlist...")];
660     [o_mi_info setTitle: _NS("Media Information...")];
661     [o_mi_messages setTitle: _NS("Messages...")];
662     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
663
664     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
665
666     [o_mu_help setTitle: _NS("Help")];
667     [o_mi_help setTitle: _NS("VLC media player Help...")];
668     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
669     [o_mi_license setTitle: _NS("License")];
670     [o_mi_documentation setTitle: _NS("Online Documentation...")];
671     [o_mi_website setTitle: _NS("VideoLAN Website...")];
672     [o_mi_donation setTitle: _NS("Make a donation...")];
673     [o_mi_forum setTitle: _NS("Online Forum...")];
674
675     /* dock menu */
676     [o_dmi_play setTitle: _NS("Play")];
677     [o_dmi_stop setTitle: _NS("Stop")];
678     [o_dmi_next setTitle: _NS("Next")];
679     [o_dmi_previous setTitle: _NS("Previous")];
680     [o_dmi_mute setTitle: _NS("Mute")];
681  
682     /* vout menu */
683     [o_vmi_play setTitle: _NS("Play")];
684     [o_vmi_stop setTitle: _NS("Stop")];
685     [o_vmi_prev setTitle: _NS("Previous")];
686     [o_vmi_next setTitle: _NS("Next")];
687     [o_vmi_volup setTitle: _NS("Volume Up")];
688     [o_vmi_voldown setTitle: _NS("Volume Down")];
689     [o_vmi_mute setTitle: _NS("Mute")];
690     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
691     [o_vmi_snapshot setTitle: _NS("Snapshot")];
692
693     /* crash reporter panel */
694     [o_crashrep_send_btn setTitle: _NS("Send")];
695     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
696     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
697     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
698     [o_crashrep_desc_txt setStringValue: _NS("Do you want to send details on the crash to VLC's development team?\n\nIf you want, you can enter a few lines on what you did before VLC crashed along with other helpful information: a link to download a sample file, a URL of a network stream, ...")];
699     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
700     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
701 }
702
703 #pragma mark -
704 #pragma mark Termination
705
706 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
707 {
708     NSArray *menuitems_array = [the_menu itemArray];
709     for( int i=0; i<[menuitems_array count]; i++ )
710     {
711         NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
712         if( [one_item hasSubmenu] )
713             [self releaseRepresentedObjects: [one_item submenu]];
714
715         [one_item setRepresentedObject:NULL];
716     }
717 }
718
719 - (void)applicationWillTerminate:(NSNotification *)notification
720 {
721     playlist_t * p_playlist;
722     vout_thread_t * p_vout;
723     int returnedValue = 0;
724  
725     msg_Dbg( p_intf, "Terminating" );
726
727     /* Make sure the manage_thread won't call -terminate: again */
728     pthread_cancel( manage_thread );
729
730     /* Make sure the intf object is getting killed */
731     vlc_object_kill( p_intf );
732
733     /* Make sure our manage_thread ends */
734     pthread_join( manage_thread, NULL );
735
736     /* Make sure the interfaceTimer is destroyed */
737     [interfaceTimer invalidate];
738     [interfaceTimer release];
739     interfaceTimer = nil;
740
741     /* make sure that the current volume is saved */
742     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
743
744     /* save the prefs if they were changed in the extended panel */
745     if(o_extended && [o_extended getConfigChanged])
746     {
747         [o_extended savePrefs];
748     }
749
750     /* unsubscribe from the interactive dialogues */
751     dialog_Unregister( p_intf );
752     var_DelCallback( p_intf, "dialog-fatal", DialogCallback, self );
753     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
754     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
755     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
756
757     /* remove global observer watching for vout device changes correctly */
758     [[NSNotificationCenter defaultCenter] removeObserver: self];
759
760     [o_update end];
761
762     /* release some other objects here, because it isn't sure whether dealloc
763      * will be called later on */
764     if( nib_about_loaded )
765         [o_about release];
766
767     if( nib_prefs_loaded )
768     {
769         [o_sprefs release];
770         [o_prefs release];
771     }
772
773     if( nib_open_loaded )
774         [o_open release];
775
776     if( nib_extended_loaded )
777     {
778         [o_extended release];
779     }
780
781     if( nib_bookmarks_loaded )
782         [o_bookmarks release];
783
784     if( o_info )
785     {
786         [o_info stopTimers];
787         [o_info release];
788     }
789
790     if( nib_wizard_loaded )
791         [o_wizard release];
792
793     [crashLogURLConnection cancel];
794     [crashLogURLConnection release];
795  
796     [o_embedded_list release];
797     [o_coredialogs release];
798     [o_eyetv release];
799
800     [o_img_pause_pressed release];
801     [o_img_play_pressed release];
802     [o_img_pause release];
803     [o_img_play release];
804
805     /* unsubscribe from libvlc's debug messages */
806     msg_Unsubscribe( p_intf->p_sys->p_sub );
807
808     [o_msg_arr removeAllObjects];
809     [o_msg_arr release];
810
811     [o_msg_lock release];
812
813     /* write cached user defaults to disk */
814     [[NSUserDefaults standardUserDefaults] synchronize];
815
816     /* Make sure the Menu doesn't have any references to vlc objects anymore */
817     [self releaseRepresentedObjects:[NSApp mainMenu]];
818
819     /* Kill the playlist, so that it doesn't accept new request
820      * such as the play request from vlc.c (we are a blocking interface). */
821     p_playlist = pl_Hold( p_intf );
822     vlc_object_kill( p_playlist );
823     pl_Release( p_intf );
824
825     libvlc_Quit( p_intf->p_libvlc );
826
827     [self setIntf:nil];
828
829     /* Go back to Run() and make libvlc exit properly */
830     if( jmpbuffer )
831         longjmp( jmpbuffer, 1 );
832     /* not reached */
833 }
834
835 #pragma mark -
836 #pragma mark Toolbar delegate
837
838 /* Our item identifiers */
839 static NSString * VLCToolbarMediaControl     = @"VLCToolbarMediaControl";
840
841 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
842 {
843     return [NSArray arrayWithObjects:
844 //                        NSToolbarCustomizeToolbarItemIdentifier,
845 //                        NSToolbarFlexibleSpaceItemIdentifier,
846 //                        NSToolbarSpaceItemIdentifier,
847 //                        NSToolbarSeparatorItemIdentifier,
848                         VLCToolbarMediaControl,
849                         nil ];
850 }
851
852 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
853 {
854     return [NSArray arrayWithObjects:
855                         VLCToolbarMediaControl,
856                         nil ];
857 }
858
859 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
860 {
861     NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
862
863  
864     if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
865     {
866         [toolbarItem setLabel:@"Media Controls"];
867         [toolbarItem setPaletteLabel:@"Media Controls"];
868
869         NSSize size = toolbarMediaControl.frame.size;
870         [toolbarItem setView:toolbarMediaControl];
871         [toolbarItem setMinSize:size];
872         size.width += 1000.;
873         [toolbarItem setMaxSize:size];
874
875         // Hack: For some reason we need to make sure
876         // that the those element are on top
877         // Add them again will put them frontmost
878         [toolbarMediaControl addSubview:o_scrollfield];
879         [toolbarMediaControl addSubview:o_timeslider];
880         [toolbarMediaControl addSubview:o_timefield];
881         [toolbarMediaControl addSubview:o_main_pgbar];
882
883         /* TODO: setup a menu */
884     }
885     else
886     {
887         /* itemIdentifier referred to a toolbar item that is not
888          * provided or supported by us or Cocoa
889          * Returning nil will inform the toolbar
890          * that this kind of item is not supported */
891         toolbarItem = nil;
892     }
893     return toolbarItem;
894 }
895
896 #pragma mark -
897 #pragma mark Other notification
898
899 - (void)controlTintChanged
900 {
901     BOOL b_playing = NO;
902     
903     if( [o_btn_play alternateImage] == o_img_play_pressed )
904         b_playing = YES;
905     
906     if( [NSColor currentControlTint] == NSGraphiteControlTint )
907     {
908         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
909         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
910         
911         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
912         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
913         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
914         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
915         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
916         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
917         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
918         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
919     }
920     else
921     {
922         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
923         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
924         
925         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
926         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
927         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
928         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
929         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
930         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
931         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
932         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
933     }
934     
935     if( b_playing )
936         [o_btn_play setAlternateImage: o_img_play_pressed];
937     else
938         [o_btn_play setAlternateImage: o_img_pause_pressed];
939 }
940
941 /* Listen to the remote in exclusive mode, only when VLC is the active
942    application */
943 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
944 {
945     [o_remote startListening: self];
946 }
947 - (void)applicationDidResignActive:(NSNotification *)aNotification
948 {
949     [o_remote stopListening: self];
950 }
951
952 /* Triggered when the computer goes to sleep */
953 - (void)computerWillSleep: (NSNotification *)notification
954 {
955     /* Pause */
956     if( p_intf->p_sys->i_play_status == PLAYING_S )
957     {
958         vlc_value_t val;
959         val.i_int = config_GetInt( p_intf, "key-play-pause" );
960         var_Set( p_intf->p_libvlc, "key-pressed", val );
961     }
962 }
963
964 #pragma mark -
965 #pragma mark File opening
966
967 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
968 {
969     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
970     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
971     if( b_autoplay )
972         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
973     else
974         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
975
976     return( TRUE );
977 }
978
979 /* When user click in the Dock icon our double click in the finder */
980 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
981 {    
982     if(!hasVisibleWindows)
983         [o_window makeKeyAndOrderFront:self];
984
985     return YES;
986 }
987
988 #pragma mark -
989 #pragma mark Apple Remote Control
990
991 /* Helper method for the remote control interface in order to trigger forward/backward and volume
992    increase/decrease as long as the user holds the left/right, plus/minus button */
993 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
994 {
995     if(b_remote_button_hold)
996     {
997         switch([buttonIdentifierNumber intValue])
998         {
999             case kRemoteButtonRight_Hold:
1000                   [o_controls forward: self];
1001             break;
1002             case kRemoteButtonLeft_Hold:
1003                   [o_controls backward: self];
1004             break;
1005             case kRemoteButtonVolume_Plus_Hold:
1006                 [o_controls volumeUp: self];
1007             break;
1008             case kRemoteButtonVolume_Minus_Hold:
1009                 [o_controls volumeDown: self];
1010             break;
1011         }
1012         if(b_remote_button_hold)
1013         {
1014             /* trigger event */
1015             [self performSelector:@selector(executeHoldActionForRemoteButton:)
1016                          withObject:buttonIdentifierNumber
1017                          afterDelay:0.25];
1018         }
1019     }
1020 }
1021
1022 /* Apple Remote callback */
1023 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1024                pressedDown: (BOOL) pressedDown
1025                 clickCount: (unsigned int) count
1026 {
1027     switch( buttonIdentifier )
1028     {
1029         case kRemoteButtonPlay:
1030             if(count >= 2) {
1031                 [o_controls toogleFullscreen:self];
1032             } else {
1033                 [o_controls play: self];
1034             }
1035             break;
1036         case kRemoteButtonVolume_Plus:
1037             [o_controls volumeUp: self];
1038             break;
1039         case kRemoteButtonVolume_Minus:
1040             [o_controls volumeDown: self];
1041             break;
1042         case kRemoteButtonRight:
1043             [o_controls next: self];
1044             break;
1045         case kRemoteButtonLeft:
1046             [o_controls prev: self];
1047             break;
1048         case kRemoteButtonRight_Hold:
1049         case kRemoteButtonLeft_Hold:
1050         case kRemoteButtonVolume_Plus_Hold:
1051         case kRemoteButtonVolume_Minus_Hold:
1052             /* simulate an event as long as the user holds the button */
1053             b_remote_button_hold = pressedDown;
1054             if( pressedDown )
1055             {
1056                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1057                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1058                            withObject:buttonIdentifierNumber];
1059             }
1060             break;
1061         case kRemoteButtonMenu:
1062             [o_controls showPosition: self];
1063             break;
1064         default:
1065             /* Add here whatever you want other buttons to do */
1066             break;
1067     }
1068 }
1069
1070 #pragma mark -
1071 #pragma mark String utility
1072 // FIXME: this has nothing to do here
1073
1074 - (NSString *)localizedString:(const char *)psz
1075 {
1076     NSString * o_str = nil;
1077
1078     if( psz != NULL )
1079     {
1080         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1081
1082         if( o_str == NULL )
1083         {
1084             msg_Err( VLCIntf, "could not translate: %s", psz );
1085             return( @"" );
1086         }
1087     }
1088     else
1089     {
1090         msg_Warn( VLCIntf, "can't translate empty strings" );
1091         return( @"" );
1092     }
1093
1094     return( o_str );
1095 }
1096
1097
1098
1099 - (char *)delocalizeString:(NSString *)id
1100 {
1101     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1102                           allowLossyConversion: NO];
1103     char * psz_string;
1104
1105     if( o_data == nil )
1106     {
1107         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1108                      allowLossyConversion: YES];
1109         psz_string = malloc( [o_data length] + 1 );
1110         [o_data getBytes: psz_string];
1111         psz_string[ [o_data length] ] = '\0';
1112         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1113                  psz_string );
1114     }
1115     else
1116     {
1117         psz_string = malloc( [o_data length] + 1 );
1118         [o_data getBytes: psz_string];
1119         psz_string[ [o_data length] ] = '\0';
1120     }
1121
1122     return psz_string;
1123 }
1124
1125 /* i_width is in pixels */
1126 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1127 {
1128     NSMutableString *o_wrapped;
1129     NSString *o_out_string;
1130     NSRange glyphRange, effectiveRange, charRange;
1131     NSRect lineFragmentRect;
1132     unsigned glyphIndex, breaksInserted = 0;
1133
1134     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1135         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1136         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1137     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1138     NSTextContainer *o_container = [[NSTextContainer alloc]
1139         initWithContainerSize: NSMakeSize(i_width, 2000)];
1140
1141     [o_layout_manager addTextContainer: o_container];
1142     [o_container release];
1143     [o_storage addLayoutManager: o_layout_manager];
1144     [o_layout_manager release];
1145
1146     o_wrapped = [o_in_string mutableCopy];
1147     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1148
1149     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1150             glyphIndex += effectiveRange.length) {
1151         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1152                                             effectiveRange: &effectiveRange];
1153         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1154                                     actualGlyphRange: &effectiveRange];
1155         if([o_wrapped lineRangeForRange:
1156                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1157             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1158             breaksInserted++;
1159         }
1160     }
1161     o_out_string = [NSString stringWithString: o_wrapped];
1162     [o_wrapped release];
1163     [o_storage release];
1164
1165     return o_out_string;
1166 }
1167
1168
1169 #pragma mark -
1170 #pragma mark Key Shortcuts
1171
1172 static struct
1173 {
1174     unichar i_nskey;
1175     unsigned int i_vlckey;
1176 } nskeys_to_vlckeys[] =
1177 {
1178     { NSUpArrowFunctionKey, KEY_UP },
1179     { NSDownArrowFunctionKey, KEY_DOWN },
1180     { NSLeftArrowFunctionKey, KEY_LEFT },
1181     { NSRightArrowFunctionKey, KEY_RIGHT },
1182     { NSF1FunctionKey, KEY_F1 },
1183     { NSF2FunctionKey, KEY_F2 },
1184     { NSF3FunctionKey, KEY_F3 },
1185     { NSF4FunctionKey, KEY_F4 },
1186     { NSF5FunctionKey, KEY_F5 },
1187     { NSF6FunctionKey, KEY_F6 },
1188     { NSF7FunctionKey, KEY_F7 },
1189     { NSF8FunctionKey, KEY_F8 },
1190     { NSF9FunctionKey, KEY_F9 },
1191     { NSF10FunctionKey, KEY_F10 },
1192     { NSF11FunctionKey, KEY_F11 },
1193     { NSF12FunctionKey, KEY_F12 },
1194     { NSInsertFunctionKey, KEY_INSERT },
1195     { NSHomeFunctionKey, KEY_HOME },
1196     { NSEndFunctionKey, KEY_END },
1197     { NSPageUpFunctionKey, KEY_PAGEUP },
1198     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1199     { NSMenuFunctionKey, KEY_MENU },
1200     { NSTabCharacter, KEY_TAB },
1201     { NSCarriageReturnCharacter, KEY_ENTER },
1202     { NSEnterCharacter, KEY_ENTER },
1203     { NSBackspaceCharacter, KEY_BACKSPACE },
1204     { (unichar) ' ', KEY_SPACE },
1205     { (unichar) 0x1b, KEY_ESC },
1206     {0,0}
1207 };
1208
1209 static unichar VLCKeyToCocoa( unsigned int i_key )
1210 {
1211     unsigned int i;
1212
1213     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1214     {
1215         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1216         {
1217             return nskeys_to_vlckeys[i].i_nskey;
1218         }
1219     }
1220     return (unichar)(i_key & ~KEY_MODIFIER);
1221 }
1222
1223 unsigned int CocoaKeyToVLC( unichar i_key )
1224 {
1225     unsigned int i;
1226
1227     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1228     {
1229         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1230         {
1231             return nskeys_to_vlckeys[i].i_vlckey;
1232         }
1233     }
1234     return (unsigned int)i_key;
1235 }
1236
1237 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1238 {
1239     unsigned int new = 0;
1240     if( i_key & KEY_MODIFIER_COMMAND )
1241         new |= NSCommandKeyMask;
1242     if( i_key & KEY_MODIFIER_ALT )
1243         new |= NSAlternateKeyMask;
1244     if( i_key & KEY_MODIFIER_SHIFT )
1245         new |= NSShiftKeyMask;
1246     if( i_key & KEY_MODIFIER_CTRL )
1247         new |= NSControlKeyMask;
1248     return new;
1249 }
1250
1251 /*****************************************************************************
1252  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1253  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1254  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1255  *****************************************************************************/
1256 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1257 {
1258     unichar key = 0;
1259     vlc_value_t val;
1260     unsigned int i_pressed_modifiers = 0;
1261     struct hotkey *p_hotkeys;
1262     int i;
1263
1264     val.i_int = 0;
1265     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1266
1267     i_pressed_modifiers = [o_event modifierFlags];
1268
1269     if( i_pressed_modifiers & NSShiftKeyMask )
1270         val.i_int |= KEY_MODIFIER_SHIFT;
1271     if( i_pressed_modifiers & NSControlKeyMask )
1272         val.i_int |= KEY_MODIFIER_CTRL;
1273     if( i_pressed_modifiers & NSAlternateKeyMask )
1274         val.i_int |= KEY_MODIFIER_ALT;
1275     if( i_pressed_modifiers & NSCommandKeyMask )
1276         val.i_int |= KEY_MODIFIER_COMMAND;
1277
1278     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1279
1280     switch( key )
1281     {
1282         case NSDeleteCharacter:
1283         case NSDeleteFunctionKey:
1284         case NSDeleteCharFunctionKey:
1285         case NSBackspaceCharacter:
1286         case NSUpArrowFunctionKey:
1287         case NSDownArrowFunctionKey:
1288         case NSRightArrowFunctionKey:
1289         case NSLeftArrowFunctionKey:
1290         case NSEnterCharacter:
1291         case NSCarriageReturnCharacter:
1292             return NO;
1293     }
1294
1295     val.i_int |= CocoaKeyToVLC( key );
1296
1297     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1298     {
1299         if( p_hotkeys[i].i_key == val.i_int )
1300         {
1301             var_Set( p_intf->p_libvlc, "key-pressed", val );
1302             return YES;
1303         }
1304     }
1305
1306     return NO;
1307 }
1308
1309 #pragma mark -
1310 #pragma mark Other objects getters
1311 // FIXME: this is ugly and does not respect cocoa naming scheme
1312
1313 - (id)getControls
1314 {
1315     if( o_controls )
1316         return o_controls;
1317
1318     return nil;
1319 }
1320
1321 - (id)getSimplePreferences
1322 {
1323     if( !o_sprefs )
1324         return nil;
1325
1326     if( !nib_prefs_loaded )
1327         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1328
1329     return o_sprefs;
1330 }
1331
1332 - (id)getPreferences
1333 {
1334     if( !o_prefs )
1335         return nil;
1336
1337     if( !nib_prefs_loaded )
1338         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1339
1340     return o_prefs;
1341 }
1342
1343 - (id)getPlaylist
1344 {
1345     if( o_playlist )
1346         return o_playlist;
1347
1348     return nil;
1349 }
1350
1351 - (BOOL)isPlaylistCollapsed
1352 {
1353     return ![o_btn_playlist state];
1354 }
1355
1356 - (id)getInfo
1357 {
1358     if( o_info )
1359         return o_info;
1360
1361     return nil;
1362 }
1363
1364 - (id)getWizard
1365 {
1366     if( o_wizard )
1367         return o_wizard;
1368
1369     return nil;
1370 }
1371
1372 - (id)getVLM
1373 {
1374     return o_vlm;
1375 }
1376
1377 - (id)getBookmarks
1378 {
1379     if( o_bookmarks )
1380         return o_bookmarks;
1381
1382     return nil;
1383 }
1384
1385 - (id)getEmbeddedList
1386 {
1387     if( o_embedded_list )
1388         return o_embedded_list;
1389
1390     return nil;
1391 }
1392
1393 - (id)getCoreDialogProvider
1394 {
1395     if( o_coredialogs )
1396         return o_coredialogs;
1397
1398     return nil;
1399 }
1400
1401 - (id)getMainIntfPgbar
1402 {
1403     if( o_main_pgbar )
1404         return o_main_pgbar;
1405
1406     return nil;
1407 }
1408
1409 - (id)getControllerWindow
1410 {
1411     if( o_window )
1412         return o_window;
1413     return nil;
1414 }
1415
1416 - (id)getVoutMenu
1417 {
1418     return o_vout_menu;
1419 }
1420
1421 - (id)getEyeTVController
1422 {
1423     if( o_eyetv )
1424         return o_eyetv;
1425
1426     return nil;
1427 }
1428
1429 #pragma mark -
1430 #pragma mark Polling
1431
1432 /*****************************************************************************
1433  * ManageThread: An ugly thread that polls
1434  *****************************************************************************/
1435 static void * ManageThread( void *user_data )
1436 {
1437     id self = user_data;
1438
1439     [self manage];
1440
1441     return NULL;
1442 }
1443
1444 struct manage_cleanup_stack {
1445     intf_thread_t * p_intf;
1446     input_thread_t ** p_input;
1447     playlist_t * p_playlist;
1448     id self;
1449 };
1450
1451 static void manage_cleanup( void * args )
1452 {
1453     struct manage_cleanup_stack * manage_cleanup_stack = args;
1454     intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1455     input_thread_t * p_input = *manage_cleanup_stack->p_input;
1456     id self = manage_cleanup_stack->self;
1457     playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1458
1459     var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1460     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1461     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1462     var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1463     var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1464
1465     pl_Release( p_intf );
1466
1467     if( p_input ) vlc_object_release( p_input );
1468 }
1469
1470 - (void)manage
1471 {
1472     playlist_t * p_playlist;
1473     input_thread_t * p_input = NULL;
1474
1475     /* new thread requires a new pool */
1476
1477     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1478
1479     p_playlist = pl_Hold( p_intf );
1480
1481     var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1482     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1483     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1484     var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1485     var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1486
1487     struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1488     pthread_cleanup_push(manage_cleanup, &stack);
1489
1490     while( true )
1491     {
1492         NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1493
1494         if( !p_input )
1495         {
1496             p_input = playlist_CurrentInput( p_playlist );
1497
1498             /* Refresh the interface */
1499             if( p_input )
1500             {
1501                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1502                 p_intf->p_sys->b_input_update = true;
1503             }
1504         }
1505         else if( !vlc_object_alive (p_input) || p_input->b_dead )
1506         {
1507             /* input stopped */
1508             p_intf->p_sys->b_intf_update = true;
1509             p_intf->p_sys->i_play_status = END_S;
1510             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1511             vlc_object_release( p_input );
1512             p_input = NULL;
1513         }
1514         else if( cachedInputState != input_GetState( p_input ) )
1515         {
1516             p_intf->p_sys->b_intf_update = true;
1517         }
1518
1519         /* Manage volume status */
1520         [self manageVolumeSlider];
1521
1522         msleep( INTF_IDLE_SLEEP );
1523
1524         [pool release];
1525     }
1526
1527     pthread_cleanup_pop(1);
1528
1529     msg_Dbg( p_intf, "Killing the Mac OS X module" );
1530
1531     /* We are dead, terminate */
1532     [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1533 }
1534
1535 - (void)manageVolumeSlider
1536 {
1537     audio_volume_t i_volume;
1538     aout_VolumeGet( p_intf, &i_volume );
1539
1540     if( i_volume != i_lastShownVolume )
1541     {
1542         i_lastShownVolume = i_volume;
1543         p_intf->p_sys->b_volume_update = TRUE;
1544     }
1545 }
1546
1547 - (void)manageIntf:(NSTimer *)o_timer
1548 {
1549     vlc_value_t val;
1550     playlist_t * p_playlist;
1551     input_thread_t * p_input;
1552
1553     if( p_intf->p_sys->b_input_update )
1554     {
1555         /* Called when new input is opened */
1556         p_intf->p_sys->b_current_title_update = true;
1557         p_intf->p_sys->b_intf_update = true;
1558         p_intf->p_sys->b_input_update = false;
1559         [self setupMenus]; /* Make sure input menu is up to date */
1560     }
1561     if( p_intf->p_sys->b_intf_update )
1562     {
1563         bool b_input = false;
1564         bool b_plmul = false;
1565         bool b_control = false;
1566         bool b_seekable = false;
1567         bool b_chapters = false;
1568
1569         playlist_t * p_playlist = pl_Hold( p_intf );
1570
1571         /* TODO: fix i_size use */
1572         b_plmul = p_playlist->items.i_size > 1;
1573
1574         p_input = playlist_CurrentInput( p_playlist );
1575         bool b_buffering = NO;
1576     
1577         if( ( b_input = ( p_input != NULL ) ) )
1578         {
1579             /* seekable streams */
1580             cachedInputState = input_GetState( p_input );
1581             if ( cachedInputState == INIT_S ||
1582                  cachedInputState == OPENING_S )
1583             {
1584                 b_buffering = YES;
1585             }
1586
1587             /* update our info-panel to reflect the new item, if we don't show
1588              * the playlist or the selection is empty */
1589             if( [self isPlaylistCollapsed] == YES )
1590             {
1591                 PL_LOCK;
1592                 [[self getInfo] updatePanelWithItem: playlist_CurrentPlayingItem( p_playlist )->p_input];
1593                 PL_UNLOCK;
1594             }
1595
1596             /* seekable streams */
1597             b_seekable = var_GetBool( p_input, "can-seek" );
1598
1599             /* check whether slow/fast motion is possible */
1600             b_control = var_GetBool( p_input, "can-rate" );
1601
1602             /* chapters & titles */
1603             //b_chapters = p_input->stream.i_area_nb > 1;
1604             vlc_object_release( p_input );
1605         }
1606         pl_Release( p_intf );
1607
1608         if( b_buffering )
1609         {
1610             [o_main_pgbar startAnimation:self];
1611             [o_main_pgbar setIndeterminate:YES];
1612             [o_main_pgbar setHidden:NO];
1613         }
1614         else
1615         {
1616             [o_main_pgbar stopAnimation:self];
1617             [o_main_pgbar setHidden:YES];
1618         }
1619
1620         [o_btn_stop setEnabled: b_input];
1621         [o_btn_ff setEnabled: b_seekable];
1622         [o_btn_rewind setEnabled: b_seekable];
1623         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1624         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1625
1626         [o_timeslider setFloatValue: 0.0];
1627         [o_timeslider setEnabled: b_seekable];
1628         [o_timefield setStringValue: @"00:00"];
1629         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1630         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1631
1632         [o_embedded_window setSeekable: b_seekable];
1633
1634         p_intf->p_sys->b_current_title_update = true;
1635         
1636         p_intf->p_sys->b_intf_update = false;
1637     }
1638
1639     if( p_intf->p_sys->b_playmode_update )
1640     {
1641         [o_playlist playModeUpdated];
1642         p_intf->p_sys->b_playmode_update = false;
1643     }
1644     if( p_intf->p_sys->b_playlist_update )
1645     {
1646         [o_playlist playlistUpdated];
1647         p_intf->p_sys->b_playlist_update = false;
1648     }
1649
1650     if( p_intf->p_sys->b_fullscreen_update )
1651     {
1652         p_intf->p_sys->b_fullscreen_update = false;
1653     }
1654
1655     if( p_intf->p_sys->b_intf_show )
1656     {
1657         if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1658             [[o_controls getFSPanel] fadeIn];
1659         else
1660             [o_window makeKeyAndOrderFront: self];
1661
1662         p_intf->p_sys->b_intf_show = false;
1663     }
1664
1665     p_input = pl_CurrentInput( p_intf );
1666     if( p_input && vlc_object_alive (p_input) )
1667     {
1668         vlc_value_t val;
1669
1670         if( p_intf->p_sys->b_current_title_update )
1671         {
1672             NSString *aString;
1673             input_item_t * p_item = input_GetItem( p_input );
1674             char * name = input_item_GetNowPlaying( p_item );
1675
1676             if( !name )
1677                 name = input_item_GetName( p_item );
1678
1679             aString = [NSString stringWithUTF8String:name];
1680
1681             free(name);
1682
1683             [self setScrollField: aString stopAfter:-1];
1684             [[[self getControls] getFSPanel] setStreamTitle: aString];
1685
1686             [[o_controls voutView] updateTitle];
1687  
1688             [o_playlist updateRowSelection];
1689             p_intf->p_sys->b_current_title_update = FALSE;
1690         }
1691
1692         if( [o_timeslider isEnabled] )
1693         {
1694             /* Update the slider */
1695             vlc_value_t time;
1696             NSString * o_time;
1697             vlc_value_t pos;
1698             char psz_time[MSTRTIME_MAX_SIZE];
1699             float f_updated;
1700
1701             var_Get( p_input, "position", &pos );
1702             f_updated = 10000. * pos.f_float;
1703             [o_timeslider setFloatValue: f_updated];
1704
1705             var_Get( p_input, "time", &time );
1706
1707             mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1708             if( b_time_remaining && dur != -1 )
1709             {
1710                 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1711             }
1712             else
1713                 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1714
1715             [o_timefield setStringValue: o_time];
1716             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1717             [o_embedded_window setTime: o_time position: f_updated];
1718         }
1719
1720         /* Manage Playing status */
1721         var_Get( p_input, "state", &val );
1722         if( p_intf->p_sys->i_play_status != val.i_int )
1723         {
1724             p_intf->p_sys->i_play_status = val.i_int;
1725             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1726             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1727         }
1728         vlc_object_release( p_input );
1729     }
1730     else if( p_input )
1731     {
1732         vlc_object_release( p_input );
1733     }
1734     else
1735     {
1736         p_intf->p_sys->i_play_status = END_S;
1737         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1738         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1739         [self setSubmenusEnabled: FALSE];
1740     }
1741
1742     if( p_intf->p_sys->b_volume_update )
1743     {
1744         NSString *o_text;
1745         int i_volume_step = 0;
1746         o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1747         if( i_lastShownVolume != -1 )
1748         [self setScrollField:o_text stopAfter:1000000];
1749         i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1750         [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1751         [o_volumeslider setEnabled: TRUE];
1752         [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1753         p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1754         p_intf->p_sys->b_volume_update = FALSE;
1755     }
1756
1757 end:
1758     [self updateMessageDisplay];
1759
1760     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1761         [self resetScrollField];
1762
1763     [interfaceTimer autorelease];
1764
1765     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1766         target: self selector: @selector(manageIntf:)
1767         userInfo: nil repeats: FALSE] retain];
1768 }
1769
1770 #pragma mark -
1771 #pragma mark Interface update
1772
1773 - (void)setupMenus
1774 {
1775     playlist_t * p_playlist = pl_Hold( p_intf );
1776     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1777     if( p_input != NULL )
1778     {
1779         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1780             var: "program" selector: @selector(toggleVar:)];
1781
1782         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1783             var: "title" selector: @selector(toggleVar:)];
1784
1785         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1786             var: "chapter" selector: @selector(toggleVar:)];
1787
1788         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1789             var: "audio-es" selector: @selector(toggleVar:)];
1790
1791         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1792             var: "video-es" selector: @selector(toggleVar:)];
1793
1794         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1795             var: "spu-es" selector: @selector(toggleVar:)];
1796
1797         /* special case for "Open File" inside the subtitles menu item */
1798         if( [o_mi_videotrack isEnabled] == YES )
1799             [o_mi_subtitle setEnabled: YES];
1800
1801         aout_instance_t * p_aout = input_GetAout( p_input );
1802         if( p_aout != NULL )
1803         {
1804             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1805                 var: "audio-channels" selector: @selector(toggleVar:)];
1806
1807             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1808                 var: "audio-device" selector: @selector(toggleVar:)];
1809
1810             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1811                 var: "visual" selector: @selector(toggleVar:)];
1812             vlc_object_release( (vlc_object_t *)p_aout );
1813         }
1814
1815         vout_thread_t * p_vout = input_GetVout( p_input );
1816
1817         if( p_vout != NULL )
1818         {
1819             vlc_object_t * p_dec_obj;
1820
1821             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1822                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1823
1824             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1825                 var: "crop" selector: @selector(toggleVar:)];
1826
1827             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1828                 var: "video-device" selector: @selector(toggleVar:)];
1829
1830             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1831                 var: "deinterlace" selector: @selector(toggleVar:)];
1832
1833 #if 0
1834 /* FIXME Post processing. */
1835             p_dec_obj = (vlc_object_t *)vlc_object_find(
1836                                                  (vlc_object_t *)p_vout,
1837                                                  VLC_OBJECT_DECODER,
1838                                                  FIND_PARENT );
1839             if( p_dec_obj != NULL )
1840             {
1841                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1842                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1843                     @selector(toggleVar:)];
1844
1845                 vlc_object_release(p_dec_obj);
1846             }
1847 #endif
1848             vlc_object_release( (vlc_object_t *)p_vout );
1849         }
1850         vlc_object_release( p_input );
1851     }
1852     pl_Release( p_intf );
1853 }
1854
1855 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1856 {
1857     int x,y = 0;
1858     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1859                                               FIND_ANYWHERE );
1860  
1861     if(! p_vout )
1862         return;
1863  
1864     /* clean the menu before adding new entries */
1865     if( [o_mi_screen hasSubmenu] )
1866     {
1867         y = [[o_mi_screen submenu] numberOfItems] - 1;
1868         msg_Dbg( VLCIntf, "%i items in submenu", y );
1869         while( x != y )
1870         {
1871             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1872             [[o_mi_screen submenu] removeItemAtIndex: x];
1873             x++;
1874         }
1875     }
1876
1877     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1878                              var: "video-device" selector: @selector(toggleVar:)];
1879     vlc_object_release( (vlc_object_t *)p_vout );
1880 }
1881
1882 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1883 {
1884     if( timeout != -1 )
1885         i_end_scroll = mdate() + timeout;
1886     else
1887         i_end_scroll = -1;
1888     [o_scrollfield setStringValue: o_string];
1889 }
1890
1891 - (void)resetScrollField
1892 {
1893     playlist_t * p_playlist = pl_Hold( p_intf );
1894     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1895
1896     i_end_scroll = -1;
1897     if( p_input && vlc_object_alive (p_input) )
1898     {
1899         NSString *o_temp;
1900         PL_LOCK;
1901         playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1902         if( input_item_GetNowPlaying( p_item->p_input ) )
1903             o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1904         else
1905             o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1906         PL_UNLOCK;
1907         [self setScrollField: o_temp stopAfter:-1];
1908         [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1909         vlc_object_release( p_input );
1910         pl_Release( p_intf );
1911         return;
1912     }
1913     pl_Release( p_intf );
1914     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1915 }
1916
1917 - (void)playStatusUpdated:(int)i_status
1918 {
1919     if( i_status == PLAYING_S )
1920     {
1921         [[[self getControls] getFSPanel] setPause];
1922         [o_btn_play setImage: o_img_pause];
1923         [o_btn_play setAlternateImage: o_img_pause_pressed];
1924         [o_btn_play setToolTip: _NS("Pause")];
1925         [o_mi_play setTitle: _NS("Pause")];
1926         [o_dmi_play setTitle: _NS("Pause")];
1927         [o_vmi_play setTitle: _NS("Pause")];
1928     }
1929     else
1930     {
1931         [[[self getControls] getFSPanel] setPlay];
1932         [o_btn_play setImage: o_img_play];
1933         [o_btn_play setAlternateImage: o_img_play_pressed];
1934         [o_btn_play setToolTip: _NS("Play")];
1935         [o_mi_play setTitle: _NS("Play")];
1936         [o_dmi_play setTitle: _NS("Play")];
1937         [o_vmi_play setTitle: _NS("Play")];
1938     }
1939 }
1940
1941 - (void)setSubmenusEnabled:(BOOL)b_enabled
1942 {
1943     [o_mi_program setEnabled: b_enabled];
1944     [o_mi_title setEnabled: b_enabled];
1945     [o_mi_chapter setEnabled: b_enabled];
1946     [o_mi_audiotrack setEnabled: b_enabled];
1947     [o_mi_visual setEnabled: b_enabled];
1948     [o_mi_videotrack setEnabled: b_enabled];
1949     [o_mi_subtitle setEnabled: b_enabled];
1950     [o_mi_channels setEnabled: b_enabled];
1951     [o_mi_deinterlace setEnabled: b_enabled];
1952     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1953     [o_mi_device setEnabled: b_enabled];
1954     [o_mi_screen setEnabled: b_enabled];
1955     [o_mi_aspect_ratio setEnabled: b_enabled];
1956     [o_mi_crop setEnabled: b_enabled];
1957     [o_mi_teletext setEnabled: b_enabled];
1958 }
1959
1960 - (IBAction)timesliderUpdate:(id)sender
1961 {
1962     float f_updated;
1963     playlist_t * p_playlist;
1964     input_thread_t * p_input;
1965
1966     switch( [[NSApp currentEvent] type] )
1967     {
1968         case NSLeftMouseUp:
1969         case NSLeftMouseDown:
1970         case NSLeftMouseDragged:
1971             f_updated = [sender floatValue];
1972             break;
1973
1974         default:
1975             return;
1976     }
1977     p_playlist = pl_Hold( p_intf );
1978     p_input = playlist_CurrentInput( p_playlist );
1979     if( p_input != NULL )
1980     {
1981         vlc_value_t time;
1982         vlc_value_t pos;
1983         NSString * o_time;
1984         char psz_time[MSTRTIME_MAX_SIZE];
1985
1986         pos.f_float = f_updated / 10000.;
1987         var_Set( p_input, "position", pos );
1988         [o_timeslider setFloatValue: f_updated];
1989
1990         var_Get( p_input, "time", &time );
1991
1992         mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1993         if( b_time_remaining && dur != -1 )
1994         {
1995             o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
1996         }
1997         else
1998             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1999
2000         [o_timefield setStringValue: o_time];
2001         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
2002         [o_embedded_window setTime: o_time position: f_updated];
2003         vlc_object_release( p_input );
2004     }
2005     pl_Release( p_intf );
2006 }
2007
2008 - (IBAction)timeFieldWasClicked:(id)sender
2009 {
2010     b_time_remaining = !b_time_remaining;
2011 }
2012     
2013
2014 #pragma mark -
2015 #pragma mark Recent Items
2016
2017 - (IBAction)clearRecentItems:(id)sender
2018 {
2019     [[NSDocumentController sharedDocumentController]
2020                           clearRecentDocuments: nil];
2021 }
2022
2023 - (void)openRecentItem:(id)sender
2024 {
2025     [self application: nil openFile: [sender title]];
2026 }
2027
2028 #pragma mark -
2029 #pragma mark Panels
2030
2031 - (IBAction)intfOpenFile:(id)sender
2032 {
2033     if( !nib_open_loaded )
2034     {
2035         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2036         [o_open awakeFromNib];
2037         [o_open openFile];
2038     } else {
2039         [o_open openFile];
2040     }
2041 }
2042
2043 - (IBAction)intfOpenFileGeneric:(id)sender
2044 {
2045     if( !nib_open_loaded )
2046     {
2047         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2048         [o_open awakeFromNib];
2049         [o_open openFileGeneric];
2050     } else {
2051         [o_open openFileGeneric];
2052     }
2053 }
2054
2055 - (IBAction)intfOpenDisc:(id)sender
2056 {
2057     if( !nib_open_loaded )
2058     {
2059         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2060         [o_open awakeFromNib];
2061         [o_open openDisc];
2062     } else {
2063         [o_open openDisc];
2064     }
2065 }
2066
2067 - (IBAction)intfOpenNet:(id)sender
2068 {
2069     if( !nib_open_loaded )
2070     {
2071         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2072         [o_open awakeFromNib];
2073         [o_open openNet];
2074     } else {
2075         [o_open openNet];
2076     }
2077 }
2078
2079 - (IBAction)intfOpenCapture:(id)sender
2080 {
2081     if( !nib_open_loaded )
2082     {
2083         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2084         [o_open awakeFromNib];
2085         [o_open openCapture];
2086     } else {
2087         [o_open openCapture];
2088     }
2089 }
2090
2091 - (IBAction)showWizard:(id)sender
2092 {
2093     if( !nib_wizard_loaded )
2094     {
2095         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2096         [o_wizard initStrings];
2097         [o_wizard resetWizard];
2098         [o_wizard showWizard];
2099     } else {
2100         [o_wizard resetWizard];
2101         [o_wizard showWizard];
2102     }
2103 }
2104
2105 - (IBAction)showVLM:(id)sender
2106 {
2107     if( !nib_vlm_loaded )
2108         nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2109
2110     [o_vlm showVLMWindow];
2111 }
2112
2113 - (IBAction)showExtended:(id)sender
2114 {
2115     if( o_extended == nil )
2116         o_extended = [[VLCExtended alloc] init];
2117
2118     if( !nib_extended_loaded )
2119         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2120
2121     [o_extended showPanel];
2122 }
2123
2124 - (IBAction)showBookmarks:(id)sender
2125 {
2126     /* we need the wizard-nib for the bookmarks's extract functionality */
2127     if( !nib_wizard_loaded )
2128     {
2129         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2130         [o_wizard initStrings];
2131     }
2132  
2133     if( !nib_bookmarks_loaded )
2134         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2135
2136     [o_bookmarks showBookmarks];
2137 }
2138
2139 - (IBAction)viewPreferences:(id)sender
2140 {
2141     if( !nib_prefs_loaded )
2142     {
2143         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2144         o_sprefs = [[VLCSimplePrefs alloc] init];
2145         o_prefs= [[VLCPrefs alloc] init];
2146     }
2147
2148     [o_sprefs showSimplePrefs];
2149 }
2150
2151 #pragma mark -
2152 #pragma mark Update
2153
2154 - (IBAction)checkForUpdate:(id)sender
2155 {
2156 #ifdef UPDATE_CHECK
2157     if( !nib_update_loaded )
2158         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
2159     [o_update showUpdateWindow];
2160 #else
2161     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2162     dialog_FatalWait( VLCIntf, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2163 #endif
2164 }
2165
2166 #pragma mark -
2167 #pragma mark Help and Docs
2168
2169 - (IBAction)viewAbout:(id)sender
2170 {
2171     if( !nib_about_loaded )
2172         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2173
2174     [o_about showAbout];
2175 }
2176
2177 - (IBAction)showLicense:(id)sender
2178 {
2179     if( !nib_about_loaded )
2180         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2181
2182     [o_about showGPL: sender];
2183 }
2184     
2185 - (IBAction)viewHelp:(id)sender
2186 {
2187     if( !nib_about_loaded )
2188     {
2189         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2190         [o_about showHelp];
2191     }
2192     else
2193         [o_about showHelp];
2194 }
2195
2196 - (IBAction)openReadMe:(id)sender
2197 {
2198     NSString * o_path = [[NSBundle mainBundle]
2199         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2200
2201     [[NSWorkspace sharedWorkspace] openFile: o_path
2202                                    withApplication: @"TextEdit"];
2203 }
2204
2205 - (IBAction)openDocumentation:(id)sender
2206 {
2207     NSURL * o_url = [NSURL URLWithString:
2208         @"http://www.videolan.org/doc/"];
2209
2210     [[NSWorkspace sharedWorkspace] openURL: o_url];
2211 }
2212
2213 - (IBAction)openWebsite:(id)sender
2214 {
2215     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2216
2217     [[NSWorkspace sharedWorkspace] openURL: o_url];
2218 }
2219
2220 - (IBAction)openForum:(id)sender
2221 {
2222     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2223
2224     [[NSWorkspace sharedWorkspace] openURL: o_url];
2225 }
2226
2227 - (IBAction)openDonate:(id)sender
2228 {
2229     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2230
2231     [[NSWorkspace sharedWorkspace] openURL: o_url];
2232 }
2233
2234 #pragma mark -
2235 #pragma mark Crash Log
2236 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2237 {
2238     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2239     NSURL *url = [NSURL URLWithString:urlStr];
2240
2241     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2242     [req setHTTPMethod:@"POST"];
2243
2244     NSString * email;
2245     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2246     {
2247         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2248         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2249         email = [emails valueAtIndex:[emails indexForIdentifier:
2250                     [emails primaryIdentifier]]];
2251     }
2252     else
2253         email = [NSString string];
2254
2255     NSString *postBody;
2256     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2257             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2258             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2259             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2260
2261     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2262
2263     /* Released from delegate */
2264     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2265 }
2266
2267 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2268 {
2269     NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2270                 _NS("Thanks for your report!"),
2271                 _NS("OK"), nil, nil, nil);
2272     [crashLogURLConnection release];
2273     crashLogURLConnection = nil;
2274 }
2275
2276 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2277 {
2278     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2279     [crashLogURLConnection release];
2280     crashLogURLConnection = nil;
2281 }
2282
2283 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2284 {
2285     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2286     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2287     NSString *fname;
2288     NSString * latestLog = nil;
2289     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2290     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2291     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
2292     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2293
2294     while (fname = [direnum nextObject])
2295     {
2296         [direnum skipDescendents];
2297         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2298         {
2299             NSArray * compo = [fname componentsSeparatedByString:@"_"];
2300             if( [compo count] < 3 ) continue;
2301             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2302             if( [compo count] < 4 ) continue;
2303
2304             // Dooh. ugly.
2305             if( year < [[compo objectAtIndex:0] intValue] ||
2306                 (year ==[[compo objectAtIndex:0] intValue] && 
2307                  (month < [[compo objectAtIndex:1] intValue] ||
2308                   (month ==[[compo objectAtIndex:1] intValue] &&
2309                    (day   < [[compo objectAtIndex:2] intValue] ||
2310                     (day   ==[[compo objectAtIndex:2] intValue] &&
2311                       hours < [[compo objectAtIndex:3] intValue] ))))))
2312             {
2313                 year  = [[compo objectAtIndex:0] intValue];
2314                 month = [[compo objectAtIndex:1] intValue];
2315                 day   = [[compo objectAtIndex:2] intValue];
2316                 hours = [[compo objectAtIndex:3] intValue];
2317                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2318             }
2319         }
2320     }
2321
2322     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2323         return nil;
2324
2325     if( !previouslySeen )
2326     {
2327         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
2328         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2329         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
2330         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2331     }
2332     return latestLog;
2333 }
2334
2335 - (NSString *)latestCrashLogPath
2336 {
2337     return [self latestCrashLogPathPreviouslySeen:YES];
2338 }
2339
2340 - (void)lookForCrashLog
2341 {
2342     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2343     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2344     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2345     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2346     if( latestLog && !areCrashLogsTooOld )
2347         [NSApp runModalForWindow: o_crashrep_win];
2348     [o_pool release];
2349 }
2350
2351 - (IBAction)crashReporterAction:(id)sender
2352 {
2353     if( sender == o_crashrep_send_btn )
2354         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2355
2356     [NSApp stopModal];
2357     [o_crashrep_win orderOut: sender];
2358 }
2359
2360 - (IBAction)openCrashLog:(id)sender
2361 {
2362     NSString * latestLog = [self latestCrashLogPath];
2363     if( latestLog )
2364     {
2365         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2366     }
2367     else
2368     {
2369         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.") );
2370     }
2371 }
2372
2373 #pragma mark -
2374 #pragma mark Remove old prefs
2375
2376 - (void)_removeOldPreferences
2377 {
2378     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2379     static const int kCurrentPreferencesVersion = 1;
2380     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2381     if( version >= kCurrentPreferencesVersion ) return;
2382
2383     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
2384         NSUserDomainMask, YES);
2385     if( !libraries || [libraries count] == 0) return;
2386     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2387
2388     /* File not found, don't attempt anything */
2389     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2390        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2391     {
2392         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2393         return;
2394     }
2395
2396     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2397                 _NS("We just found an older version of VLC's preferences files."),
2398                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2399     if( res != NSOKButton )
2400     {
2401         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2402         return;
2403     }
2404
2405     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2406
2407     /* Move the file to trash so that user can find them later */
2408     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2409
2410     /* really reset the defaults from now on */
2411     [NSUserDefaults resetStandardUserDefaults];
2412
2413     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2414     [[NSUserDefaults standardUserDefaults] synchronize];
2415
2416     /* Relaunch now */
2417     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2418
2419     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2420     if(fork() != 0)
2421     {
2422         exit(0);
2423         return;
2424     }
2425     execl(path, path, NULL);
2426 }
2427
2428 #pragma mark -
2429 #pragma mark Errors, warnings and messages
2430
2431 - (IBAction)viewErrorsAndWarnings:(id)sender
2432 {
2433     [[[self getCoreDialogProvider] getErrorPanel] showPanel];
2434 }
2435
2436 - (IBAction)showMessagesPanel:(id)sender
2437 {
2438     [o_msgs_panel makeKeyAndOrderFront: sender];
2439 }
2440
2441 - (IBAction)showInformationPanel:(id)sender
2442 {
2443     if(! nib_info_loaded )
2444         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2445     
2446     [o_info initPanel];
2447 }
2448
2449 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2450 {
2451     if( [o_notification object] == o_msgs_panel )
2452         [self updateMessageDisplay];
2453 }
2454
2455 - (void)updateMessageDisplay
2456 {
2457     if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2458     {
2459         id o_msg;
2460         NSEnumerator * o_enum;
2461
2462         [o_messages setString: @""];
2463
2464         [o_msg_lock lock];
2465
2466         o_enum = [o_msg_arr objectEnumerator];
2467
2468         while( ( o_msg = [o_enum nextObject] ) != nil )
2469         {
2470             [o_messages insertText: o_msg];
2471         }
2472
2473         b_msg_arr_changed = NO;
2474         [o_msg_lock unlock];
2475     }
2476 }
2477
2478 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2479 {
2480     NSColor *o_white = [NSColor whiteColor];
2481     NSColor *o_red = [NSColor redColor];
2482     NSColor *o_yellow = [NSColor yellowColor];
2483     NSColor *o_gray = [NSColor grayColor];
2484
2485     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2486     static const char * ppsz_type[4] = { ": ", " error: ",
2487     " warning: ", " debug: " };
2488
2489     NSString *o_msg;
2490     NSDictionary *o_attr;
2491     NSAttributedString *o_msg_color;
2492
2493     int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2494
2495     [o_msg_lock lock];
2496
2497     if( [o_msg_arr count] + 2 > 400 )
2498     {
2499         unsigned rid[] = { 0, 1 };
2500         [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
2501                                  numIndices: sizeof(rid)/sizeof(rid[0])];
2502     }
2503
2504     o_attr = [NSDictionary dictionaryWithObject: o_gray
2505                                          forKey: NSForegroundColorAttributeName];
2506     o_msg = [NSString stringWithFormat: @"%@%s",
2507              [[o_notification userInfo] objectForKey: @"Module"],
2508              ppsz_type[i_type]];
2509     o_msg_color = [[NSAttributedString alloc]
2510                    initWithString: o_msg attributes: o_attr];
2511     [o_msg_arr addObject: [o_msg_color autorelease]];
2512
2513     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2514                                          forKey: NSForegroundColorAttributeName];
2515     o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2516     o_msg_color = [[NSAttributedString alloc]
2517                    initWithString: o_msg attributes: o_attr];
2518     [o_msg_arr addObject: [o_msg_color autorelease]];
2519
2520     b_msg_arr_changed = YES;
2521     [o_msg_lock unlock];
2522 }
2523
2524 - (IBAction)saveDebugLog:(id)sender
2525 {
2526     NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2527     
2528     [saveFolderPanel setCanChooseDirectories: NO];
2529     [saveFolderPanel setCanChooseFiles: YES];
2530     [saveFolderPanel setCanSelectHiddenExtension: NO];
2531     [saveFolderPanel setCanCreateDirectories: YES];
2532     [saveFolderPanel setRequiredFileType: @"rtfd"];
2533     [saveFolderPanel beginSheetForDirectory:nil file: [NSString stringWithFormat: _NS("VLC Debug Log (%s).rtfd"), VLC_Version()] modalForWindow: o_msgs_panel modalDelegate:self didEndSelector:@selector(saveDebugLogAsRTF:returnCode:contextInfo:) contextInfo:nil];
2534 }
2535
2536 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2537 {
2538     BOOL b_returned;
2539     if( returnCode == NSOKButton )
2540     {
2541         b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2542         if(! b_returned )
2543             msg_Warn( p_intf, "Error while saving the debug log" );
2544     }
2545 }
2546
2547 #pragma mark -
2548 #pragma mark Playlist toggling
2549
2550 - (IBAction)togglePlaylist:(id)sender
2551 {
2552     NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2553     NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2554     /*First, check if the playlist is visible*/
2555     if( contentRect.size.height <= 169. )
2556     {
2557         o_restore_rect = contentRect;
2558         b_restore_size = true;
2559         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2560
2561         /* make large */
2562         if( o_size_with_playlist.height > 169. )
2563             o_rect.size.height = o_size_with_playlist.height;
2564         else
2565             o_rect.size.height = 500.;
2566  
2567         if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2568             o_rect.size.width = o_size_with_playlist.width;
2569         else
2570             o_rect.size.width = [o_window contentMinSize].width;
2571
2572         o_rect.origin.x = contentRect.origin.x;
2573         o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2574             [o_window contentMinSize].height;
2575
2576         o_rect = [o_window frameRectForContentRect:o_rect];
2577
2578         NSRect screenRect = [[o_window screen] visibleFrame];
2579         if( !NSContainsRect( screenRect, o_rect ) ) {
2580             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2581                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2582             if( NSMinY(o_rect) < NSMinY(screenRect) )
2583                 o_rect.origin.y = ( NSMinY(screenRect) );
2584         }
2585
2586         [o_btn_playlist setState: YES];
2587     }
2588     else
2589     {
2590         NSSize curSize = o_rect.size;
2591         if( b_restore_size )
2592         {
2593             o_rect = o_restore_rect;
2594             if( o_rect.size.height < [o_window contentMinSize].height )
2595                 o_rect.size.height = [o_window contentMinSize].height;
2596             if( o_rect.size.width < [o_window contentMinSize].width )
2597                 o_rect.size.width = [o_window contentMinSize].width;
2598         }
2599         else
2600         {
2601             NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2602             /* make small */
2603             o_rect.size.height = [o_window contentMinSize].height;
2604             o_rect.size.width = [o_window contentMinSize].width;
2605             o_rect.origin.x = contentRect.origin.x;
2606             /* Calculate the position of the lower right corner after resize */
2607             o_rect.origin.y = contentRect.origin.y +
2608                 contentRect.size.height - [o_window contentMinSize].height;
2609         }
2610
2611         [o_playlist_view setAutoresizesSubviews: NO];
2612         [o_playlist_view removeFromSuperview];
2613         [o_btn_playlist setState: NO];
2614         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2615         o_rect = [o_window frameRectForContentRect:o_rect];
2616     }
2617
2618     [o_window setFrame: o_rect display:YES animate: YES];
2619 }
2620
2621 - (void)updateTogglePlaylistState
2622 {
2623     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2624         [o_btn_playlist setState: NO];
2625     else
2626         [o_btn_playlist setState: YES];
2627
2628     [[self getPlaylist] outlineViewSelectionDidChange: NULL];
2629 }
2630
2631 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2632 {
2633
2634     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2635
2636    /*Stores the size the controller one resize, to be able to restore it when
2637      toggling the playlist*/
2638     o_size_with_playlist = proposedFrameSize;
2639
2640     NSRect rect;
2641     rect.size = proposedFrameSize;
2642     if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2643     {
2644         if( b_small_window == NO )
2645         {
2646             /* if large and going to small then hide */
2647             b_small_window = YES;
2648             [o_playlist_view setAutoresizesSubviews: NO];
2649             [o_playlist_view removeFromSuperview];
2650         }
2651         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2652     }
2653     return proposedFrameSize;
2654 }
2655
2656 - (void)windowDidMove:(NSNotification *)notif
2657 {
2658     b_restore_size = false;
2659 }
2660
2661 - (void)windowDidResize:(NSNotification *)notif
2662 {
2663     if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2664     {
2665         /* If large and coming from small then show */
2666         [o_playlist_view setAutoresizesSubviews: YES];
2667         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2668         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2669         [o_playlist_view setNeedsDisplay:YES];
2670         [[o_window contentView] addSubview: o_playlist_view];
2671         b_small_window = NO;
2672     }
2673     [self updateTogglePlaylistState];
2674 }
2675
2676 #pragma mark -
2677
2678 @end
2679
2680 @implementation VLCMain (NSMenuValidation)
2681
2682 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2683 {
2684     NSString *o_title = [o_mi title];
2685     BOOL bEnabled = TRUE;
2686
2687     /* Recent Items Menu */
2688     if( [o_title isEqualToString: _NS("Clear Menu")] )
2689     {
2690         NSMenu * o_menu = [o_mi_open_recent submenu];
2691         int i_nb_items = [o_menu numberOfItems];
2692         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2693                                                        recentDocumentURLs];
2694         UInt32 i_nb_docs = [o_docs count];
2695
2696         if( i_nb_items > 1 )
2697         {
2698             while( --i_nb_items )
2699             {
2700                 [o_menu removeItemAtIndex: 0];
2701             }
2702         }
2703
2704         if( i_nb_docs > 0 )
2705         {
2706             NSURL * o_url;
2707             NSString * o_doc;
2708
2709             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2710
2711             while( TRUE )
2712             {
2713                 i_nb_docs--;
2714
2715                 o_url = [o_docs objectAtIndex: i_nb_docs];
2716
2717                 if( [o_url isFileURL] )
2718                 {
2719                     o_doc = [o_url path];
2720                 }
2721                 else
2722                 {
2723                     o_doc = [o_url absoluteString];
2724                 }
2725
2726                 [o_menu insertItemWithTitle: o_doc
2727                     action: @selector(openRecentItem:)
2728                     keyEquivalent: @"" atIndex: 0];
2729
2730                 if( i_nb_docs == 0 )
2731                 {
2732                     break;
2733                 }
2734             }
2735         }
2736         else
2737         {
2738             bEnabled = FALSE;
2739         }
2740     }
2741     return( bEnabled );
2742 }
2743
2744 @end
2745
2746 @implementation VLCMain (Internal)
2747
2748 - (void)handlePortMessage:(NSPortMessage *)o_msg
2749 {
2750     id ** val;
2751     NSData * o_data;
2752     NSValue * o_value;
2753     NSInvocation * o_inv;
2754     NSConditionLock * o_lock;
2755
2756     o_data = [[o_msg components] lastObject];
2757     o_inv = *((NSInvocation **)[o_data bytes]);
2758     [o_inv getArgument: &o_value atIndex: 2];
2759     val = (id **)[o_value pointerValue];
2760     [o_inv setArgument: val[1] atIndex: 2];
2761     o_lock = *(val[0]);
2762
2763     [o_lock lock];
2764     [o_inv invoke];
2765     [o_lock unlockWithCondition: 1];
2766 }
2767
2768 @end