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