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