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