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