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