]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
Merge branch '1.0'
[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_player setTitle: _NS("Player...")];
700     [o_mi_controller setTitle: _NS("Controller...")];
701     [o_mi_equalizer setTitle: _NS("Equalizer...")];
702     [o_mi_extended setTitle: _NS("Extended Controls...")];
703     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
704     [o_mi_playlist setTitle: _NS("Playlist...")];
705     [o_mi_info setTitle: _NS("Media Information...")];
706     [o_mi_messages setTitle: _NS("Messages...")];
707     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
708
709     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
710
711     [o_mu_help setTitle: _NS("Help")];
712     [o_mi_help setTitle: _NS("VLC media player Help...")];
713     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
714     [o_mi_license setTitle: _NS("License")];
715     [o_mi_documentation setTitle: _NS("Online Documentation...")];
716     [o_mi_website setTitle: _NS("VideoLAN Website...")];
717     [o_mi_donation setTitle: _NS("Make a donation...")];
718     [o_mi_forum setTitle: _NS("Online Forum...")];
719
720     /* dock menu */
721     [o_dmi_play setTitle: _NS("Play")];
722     [o_dmi_stop setTitle: _NS("Stop")];
723     [o_dmi_next setTitle: _NS("Next")];
724     [o_dmi_previous setTitle: _NS("Previous")];
725     [o_dmi_mute setTitle: _NS("Mute")];
726  
727     /* vout menu */
728     [o_vmi_play setTitle: _NS("Play")];
729     [o_vmi_stop setTitle: _NS("Stop")];
730     [o_vmi_prev setTitle: _NS("Previous")];
731     [o_vmi_next setTitle: _NS("Next")];
732     [o_vmi_volup setTitle: _NS("Volume Up")];
733     [o_vmi_voldown setTitle: _NS("Volume Down")];
734     [o_vmi_mute setTitle: _NS("Mute")];
735     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
736     [o_vmi_snapshot setTitle: _NS("Snapshot")];
737
738     /* crash reporter panel */
739     [o_crashrep_send_btn setTitle: _NS("Send")];
740     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
741     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
742     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
743     [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, ...")];
744     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
745     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
746 }
747
748 #pragma mark -
749 #pragma mark Termination
750
751 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
752 {
753     NSArray *menuitems_array = [the_menu itemArray];
754     for( int i=0; i<[menuitems_array count]; i++ )
755     {
756         NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
757         if( [one_item hasSubmenu] )
758             [self releaseRepresentedObjects: [one_item submenu]];
759
760         [one_item setRepresentedObject:NULL];
761     }
762 }
763
764 - (void)applicationWillTerminate:(NSNotification *)notification
765 {
766     playlist_t * p_playlist;
767     vout_thread_t * p_vout;
768     int returnedValue = 0;
769  
770     msg_Dbg( p_intf, "Terminating" );
771
772     /* Make sure the manage_thread won't call -terminate: again */
773     pthread_cancel( manage_thread );
774
775     /* Make sure the intf object is getting killed */
776     vlc_object_kill( p_intf );
777
778     /* Make sure our manage_thread ends */
779     pthread_join( manage_thread, NULL );
780
781     /* Make sure the interfaceTimer is destroyed */
782     [interfaceTimer invalidate];
783     [interfaceTimer release];
784     interfaceTimer = nil;
785
786     /* make sure that the current volume is saved */
787     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
788
789     /* save the prefs if they were changed in the extended panel */
790     if(o_extended && [o_extended configChanged])
791     {
792         [o_extended savePrefs];
793     }
794
795     /* unsubscribe from the interactive dialogues */
796     dialog_Unregister( p_intf );
797     var_DelCallback( p_intf, "dialog-fatal", DialogCallback, self );
798     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
799     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
800     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
801
802     /* remove global observer watching for vout device changes correctly */
803     [[NSNotificationCenter defaultCenter] removeObserver: self];
804
805 #ifdef UPDATE_CHECK
806     [o_update end];
807 #endif
808
809     /* release some other objects here, because it isn't sure whether dealloc
810      * will be called later on */
811     if( nib_about_loaded )
812         [o_about release];
813
814     if( nib_prefs_loaded )
815     {
816         [o_sprefs release];
817         [o_prefs release];
818     }
819
820     if( nib_open_loaded )
821         [o_open release];
822
823     if( nib_extended_loaded )
824     {
825         [o_extended release];
826     }
827
828     if( nib_bookmarks_loaded )
829         [o_bookmarks release];
830
831     if( o_info )
832     {
833         [o_info stopTimers];
834         [o_info release];
835     }
836
837     if( nib_wizard_loaded )
838         [o_wizard release];
839
840     [crashLogURLConnection cancel];
841     [crashLogURLConnection release];
842  
843     [o_embedded_list release];
844     [o_coredialogs release];
845     [o_eyetv release];
846
847     [o_img_pause_pressed release];
848     [o_img_play_pressed release];
849     [o_img_pause release];
850     [o_img_play release];
851
852     /* unsubscribe from libvlc's debug messages */
853     msg_Unsubscribe( p_intf->p_sys->p_sub );
854
855     [o_msg_arr removeAllObjects];
856     [o_msg_arr release];
857
858     [o_msg_lock release];
859
860     /* write cached user defaults to disk */
861     [[NSUserDefaults standardUserDefaults] synchronize];
862
863     /* Make sure the Menu doesn't have any references to vlc objects anymore */
864     [self releaseRepresentedObjects:[NSApp mainMenu]];
865
866     /* Kill the playlist, so that it doesn't accept new request
867      * such as the play request from vlc.c (we are a blocking interface). */
868     p_playlist = pl_Hold( p_intf );
869     vlc_object_kill( p_playlist );
870     pl_Release( p_intf );
871
872     libvlc_Quit( p_intf->p_libvlc );
873
874     [self setIntf:nil];
875
876     /* Go back to Run() and make libvlc exit properly */
877     if( jmpbuffer )
878         longjmp( jmpbuffer, 1 );
879     /* not reached */
880 }
881
882 #pragma mark -
883 #pragma mark Toolbar delegate
884
885 /* Our item identifiers */
886 static NSString * VLCToolbarMediaControl     = @"VLCToolbarMediaControl";
887
888 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
889 {
890     return [NSArray arrayWithObjects:
891 //                        NSToolbarCustomizeToolbarItemIdentifier,
892 //                        NSToolbarFlexibleSpaceItemIdentifier,
893 //                        NSToolbarSpaceItemIdentifier,
894 //                        NSToolbarSeparatorItemIdentifier,
895                         VLCToolbarMediaControl,
896                         nil ];
897 }
898
899 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
900 {
901     return [NSArray arrayWithObjects:
902                         VLCToolbarMediaControl,
903                         nil ];
904 }
905
906 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
907 {
908     NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
909
910  
911     if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
912     {
913         [toolbarItem setLabel:@"Media Controls"];
914         [toolbarItem setPaletteLabel:@"Media Controls"];
915
916         NSSize size = toolbarMediaControl.frame.size;
917         [toolbarItem setView:toolbarMediaControl];
918         [toolbarItem setMinSize:size];
919         size.width += 1000.;
920         [toolbarItem setMaxSize:size];
921
922         // Hack: For some reason we need to make sure
923         // that the those element are on top
924         // Add them again will put them frontmost
925         [toolbarMediaControl addSubview:o_scrollfield];
926         [toolbarMediaControl addSubview:o_timeslider];
927         [toolbarMediaControl addSubview:o_timefield];
928         [toolbarMediaControl addSubview:o_main_pgbar];
929
930         /* TODO: setup a menu */
931     }
932     else
933     {
934         /* itemIdentifier referred to a toolbar item that is not
935          * provided or supported by us or Cocoa
936          * Returning nil will inform the toolbar
937          * that this kind of item is not supported */
938         toolbarItem = nil;
939     }
940     return toolbarItem;
941 }
942
943 #pragma mark -
944 #pragma mark Other notification
945
946 - (void)controlTintChanged
947 {
948     BOOL b_playing = NO;
949     
950     if( [o_btn_play alternateImage] == o_img_play_pressed )
951         b_playing = YES;
952     
953     if( [NSColor currentControlTint] == NSGraphiteControlTint )
954     {
955         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
956         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
957         
958         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
959         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
960         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
961         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
962         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
963         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
964         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
965         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
966     }
967     else
968     {
969         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
970         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
971         
972         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
973         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
974         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
975         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
976         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
977         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
978         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
979         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
980     }
981     
982     if( b_playing )
983         [o_btn_play setAlternateImage: o_img_play_pressed];
984     else
985         [o_btn_play setAlternateImage: o_img_pause_pressed];
986 }
987
988 /* Listen to the remote in exclusive mode, only when VLC is the active
989    application */
990 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
991 {
992 #ifndef __x86_64__
993     [o_remote startListening: self];
994 #endif
995 }
996 - (void)applicationDidResignActive:(NSNotification *)aNotification
997 {
998 #ifndef __x86_64__
999     [o_remote stopListening: self];
1000 #endif
1001 }
1002
1003 /* Triggered when the computer goes to sleep */
1004 - (void)computerWillSleep: (NSNotification *)notification
1005 {
1006     /* Pause */
1007     if( p_intf->p_sys->i_play_status == PLAYING_S )
1008     {
1009         vlc_value_t val;
1010         val.i_int = config_GetInt( p_intf, "key-play-pause" );
1011         var_Set( p_intf->p_libvlc, "key-pressed", val );
1012     }
1013 }
1014
1015 #pragma mark -
1016 #pragma mark File opening
1017
1018 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
1019 {
1020     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
1021     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
1022     if( b_autoplay )
1023         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
1024     else
1025         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
1026
1027     return( TRUE );
1028 }
1029
1030 /* When user click in the Dock icon our double click in the finder */
1031 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1032 {    
1033     if(!hasVisibleWindows)
1034         [o_window makeKeyAndOrderFront:self];
1035
1036     return YES;
1037 }
1038
1039 #pragma mark -
1040 #pragma mark Apple Remote Control
1041
1042 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1043    increase/decrease as long as the user holds the left/right, plus/minus button */
1044 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1045 {
1046     if(b_remote_button_hold)
1047     {
1048         switch([buttonIdentifierNumber intValue])
1049         {
1050             case kRemoteButtonRight_Hold:
1051                   [o_controls forward: self];
1052             break;
1053             case kRemoteButtonLeft_Hold:
1054                   [o_controls backward: self];
1055             break;
1056             case kRemoteButtonVolume_Plus_Hold:
1057                 [o_controls volumeUp: self];
1058             break;
1059             case kRemoteButtonVolume_Minus_Hold:
1060                 [o_controls volumeDown: self];
1061             break;
1062         }
1063         if(b_remote_button_hold)
1064         {
1065             /* trigger event */
1066             [self performSelector:@selector(executeHoldActionForRemoteButton:)
1067                          withObject:buttonIdentifierNumber
1068                          afterDelay:0.25];
1069         }
1070     }
1071 }
1072
1073 /* Apple Remote callback */
1074 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1075                pressedDown: (BOOL) pressedDown
1076                 clickCount: (unsigned int) count
1077 {
1078     switch( buttonIdentifier )
1079     {
1080         case kRemoteButtonPlay:
1081             if(count >= 2) {
1082                 [o_controls toogleFullscreen:self];
1083             } else {
1084                 [o_controls play: self];
1085             }
1086             break;
1087         case kRemoteButtonVolume_Plus:
1088             [o_controls volumeUp: self];
1089             break;
1090         case kRemoteButtonVolume_Minus:
1091             [o_controls volumeDown: self];
1092             break;
1093         case kRemoteButtonRight:
1094             [o_controls next: self];
1095             break;
1096         case kRemoteButtonLeft:
1097             [o_controls prev: self];
1098             break;
1099         case kRemoteButtonRight_Hold:
1100         case kRemoteButtonLeft_Hold:
1101         case kRemoteButtonVolume_Plus_Hold:
1102         case kRemoteButtonVolume_Minus_Hold:
1103             /* simulate an event as long as the user holds the button */
1104             b_remote_button_hold = pressedDown;
1105             if( pressedDown )
1106             {
1107                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1108                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1109                            withObject:buttonIdentifierNumber];
1110             }
1111             break;
1112         case kRemoteButtonMenu:
1113             [o_controls showPosition: self];
1114             break;
1115         default:
1116             /* Add here whatever you want other buttons to do */
1117             break;
1118     }
1119 }
1120
1121 #pragma mark -
1122 #pragma mark String utility
1123 // FIXME: this has nothing to do here
1124
1125 - (NSString *)localizedString:(const char *)psz
1126 {
1127     NSString * o_str = nil;
1128
1129     if( psz != NULL )
1130     {
1131         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1132
1133         if( o_str == NULL )
1134         {
1135             msg_Err( VLCIntf, "could not translate: %s", psz );
1136             return( @"" );
1137         }
1138     }
1139     else
1140     {
1141         msg_Warn( VLCIntf, "can't translate empty strings" );
1142         return( @"" );
1143     }
1144
1145     return( o_str );
1146 }
1147
1148
1149
1150 - (char *)delocalizeString:(NSString *)id
1151 {
1152     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1153                           allowLossyConversion: NO];
1154     char * psz_string;
1155
1156     if( o_data == nil )
1157     {
1158         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1159                      allowLossyConversion: YES];
1160         psz_string = malloc( [o_data length] + 1 );
1161         [o_data getBytes: psz_string];
1162         psz_string[ [o_data length] ] = '\0';
1163         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1164                  psz_string );
1165     }
1166     else
1167     {
1168         psz_string = malloc( [o_data length] + 1 );
1169         [o_data getBytes: psz_string];
1170         psz_string[ [o_data length] ] = '\0';
1171     }
1172
1173     return psz_string;
1174 }
1175
1176 /* i_width is in pixels */
1177 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1178 {
1179     NSMutableString *o_wrapped;
1180     NSString *o_out_string;
1181     NSRange glyphRange, effectiveRange, charRange;
1182     NSRect lineFragmentRect;
1183     unsigned glyphIndex, breaksInserted = 0;
1184
1185     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1186         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1187         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1188     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1189     NSTextContainer *o_container = [[NSTextContainer alloc]
1190         initWithContainerSize: NSMakeSize(i_width, 2000)];
1191
1192     [o_layout_manager addTextContainer: o_container];
1193     [o_container release];
1194     [o_storage addLayoutManager: o_layout_manager];
1195     [o_layout_manager release];
1196
1197     o_wrapped = [o_in_string mutableCopy];
1198     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1199
1200     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1201             glyphIndex += effectiveRange.length) {
1202         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1203                                             effectiveRange: &effectiveRange];
1204         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1205                                     actualGlyphRange: &effectiveRange];
1206         if([o_wrapped lineRangeForRange:
1207                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1208             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1209             breaksInserted++;
1210         }
1211     }
1212     o_out_string = [NSString stringWithString: o_wrapped];
1213     [o_wrapped release];
1214     [o_storage release];
1215
1216     return o_out_string;
1217 }
1218
1219
1220 #pragma mark -
1221 #pragma mark Key Shortcuts
1222
1223 static struct
1224 {
1225     unichar i_nskey;
1226     unsigned int i_vlckey;
1227 } nskeys_to_vlckeys[] =
1228 {
1229     { NSUpArrowFunctionKey, KEY_UP },
1230     { NSDownArrowFunctionKey, KEY_DOWN },
1231     { NSLeftArrowFunctionKey, KEY_LEFT },
1232     { NSRightArrowFunctionKey, KEY_RIGHT },
1233     { NSF1FunctionKey, KEY_F1 },
1234     { NSF2FunctionKey, KEY_F2 },
1235     { NSF3FunctionKey, KEY_F3 },
1236     { NSF4FunctionKey, KEY_F4 },
1237     { NSF5FunctionKey, KEY_F5 },
1238     { NSF6FunctionKey, KEY_F6 },
1239     { NSF7FunctionKey, KEY_F7 },
1240     { NSF8FunctionKey, KEY_F8 },
1241     { NSF9FunctionKey, KEY_F9 },
1242     { NSF10FunctionKey, KEY_F10 },
1243     { NSF11FunctionKey, KEY_F11 },
1244     { NSF12FunctionKey, KEY_F12 },
1245     { NSInsertFunctionKey, KEY_INSERT },
1246     { NSHomeFunctionKey, KEY_HOME },
1247     { NSEndFunctionKey, KEY_END },
1248     { NSPageUpFunctionKey, KEY_PAGEUP },
1249     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1250     { NSMenuFunctionKey, KEY_MENU },
1251     { NSTabCharacter, KEY_TAB },
1252     { NSCarriageReturnCharacter, KEY_ENTER },
1253     { NSEnterCharacter, KEY_ENTER },
1254     { NSBackspaceCharacter, KEY_BACKSPACE },
1255     { (unichar) ' ', KEY_SPACE },
1256     { (unichar) 0x1b, KEY_ESC },
1257     {0,0}
1258 };
1259
1260 static unichar VLCKeyToCocoa( unsigned int i_key )
1261 {
1262     unsigned int i;
1263
1264     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1265     {
1266         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1267         {
1268             return nskeys_to_vlckeys[i].i_nskey;
1269         }
1270     }
1271     return (unichar)(i_key & ~KEY_MODIFIER);
1272 }
1273
1274 unsigned int CocoaKeyToVLC( unichar i_key )
1275 {
1276     unsigned int i;
1277
1278     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1279     {
1280         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1281         {
1282             return nskeys_to_vlckeys[i].i_vlckey;
1283         }
1284     }
1285     return (unsigned int)i_key;
1286 }
1287
1288 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1289 {
1290     unsigned int new = 0;
1291     if( i_key & KEY_MODIFIER_COMMAND )
1292         new |= NSCommandKeyMask;
1293     if( i_key & KEY_MODIFIER_ALT )
1294         new |= NSAlternateKeyMask;
1295     if( i_key & KEY_MODIFIER_SHIFT )
1296         new |= NSShiftKeyMask;
1297     if( i_key & KEY_MODIFIER_CTRL )
1298         new |= NSControlKeyMask;
1299     return new;
1300 }
1301
1302 /*****************************************************************************
1303  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1304  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1305  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1306  *****************************************************************************/
1307 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1308 {
1309     unichar key = 0;
1310     vlc_value_t val;
1311     unsigned int i_pressed_modifiers = 0;
1312     const struct hotkey *p_hotkeys;
1313     int i;
1314
1315     val.i_int = 0;
1316     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1317
1318     i_pressed_modifiers = [o_event modifierFlags];
1319
1320     if( i_pressed_modifiers & NSShiftKeyMask )
1321         val.i_int |= KEY_MODIFIER_SHIFT;
1322     if( i_pressed_modifiers & NSControlKeyMask )
1323         val.i_int |= KEY_MODIFIER_CTRL;
1324     if( i_pressed_modifiers & NSAlternateKeyMask )
1325         val.i_int |= KEY_MODIFIER_ALT;
1326     if( i_pressed_modifiers & NSCommandKeyMask )
1327         val.i_int |= KEY_MODIFIER_COMMAND;
1328
1329     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1330
1331     switch( key )
1332     {
1333         case NSDeleteCharacter:
1334         case NSDeleteFunctionKey:
1335         case NSDeleteCharFunctionKey:
1336         case NSBackspaceCharacter:
1337         case NSUpArrowFunctionKey:
1338         case NSDownArrowFunctionKey:
1339         case NSRightArrowFunctionKey:
1340         case NSLeftArrowFunctionKey:
1341         case NSEnterCharacter:
1342         case NSCarriageReturnCharacter:
1343             return NO;
1344     }
1345
1346     val.i_int |= CocoaKeyToVLC( key );
1347
1348     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1349     {
1350         if( p_hotkeys[i].i_key == val.i_int )
1351         {
1352             var_Set( p_intf->p_libvlc, "key-pressed", val );
1353             return YES;
1354         }
1355     }
1356
1357     return NO;
1358 }
1359
1360 #pragma mark -
1361 #pragma mark Other objects getters
1362
1363 - (id)controls
1364 {
1365     if( o_controls )
1366         return o_controls;
1367
1368     return nil;
1369 }
1370
1371 - (id)simplePreferences
1372 {
1373     if( !o_sprefs )
1374         return nil;
1375
1376     if( !nib_prefs_loaded )
1377         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1378
1379     return o_sprefs;
1380 }
1381
1382 - (id)preferences
1383 {
1384     if( !o_prefs )
1385         return nil;
1386
1387     if( !nib_prefs_loaded )
1388         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1389
1390     return o_prefs;
1391 }
1392
1393 - (id)playlist
1394 {
1395     if( o_playlist )
1396         return o_playlist;
1397
1398     return nil;
1399 }
1400
1401 - (BOOL)isPlaylistCollapsed
1402 {
1403     return ![o_btn_playlist state];
1404 }
1405
1406 - (id)info
1407 {
1408     if( o_info )
1409         return o_info;
1410
1411     return nil;
1412 }
1413
1414 - (id)wizard
1415 {
1416     if( o_wizard )
1417         return o_wizard;
1418
1419     return nil;
1420 }
1421
1422 - (id)bookmarks
1423 {
1424     if( o_bookmarks )
1425         return o_bookmarks;
1426
1427     return nil;
1428 }
1429
1430 - (id)embeddedList
1431 {
1432     if( o_embedded_list )
1433         return o_embedded_list;
1434
1435     return nil;
1436 }
1437
1438 - (id)coreDialogProvider
1439 {
1440     if( o_coredialogs )
1441         return o_coredialogs;
1442
1443     return nil;
1444 }
1445
1446 - (id)mainIntfPgbar
1447 {
1448     if( o_main_pgbar )
1449         return o_main_pgbar;
1450
1451     return nil;
1452 }
1453
1454 - (id)controllerWindow
1455 {
1456     if( o_window )
1457         return o_window;
1458     return nil;
1459 }
1460
1461 - (id)voutMenu
1462 {
1463     return o_vout_menu;
1464 }
1465
1466 - (id)eyeTVController
1467 {
1468     if( o_eyetv )
1469         return o_eyetv;
1470
1471     return nil;
1472 }
1473
1474 #pragma mark -
1475 #pragma mark Polling
1476
1477 /*****************************************************************************
1478  * ManageThread: An ugly thread that polls
1479  *****************************************************************************/
1480 static void * ManageThread( void *user_data )
1481 {
1482     id self = user_data;
1483
1484     [self manage];
1485
1486     return NULL;
1487 }
1488
1489 struct manage_cleanup_stack {
1490     intf_thread_t * p_intf;
1491     input_thread_t ** p_input;
1492     playlist_t * p_playlist;
1493     id self;
1494 };
1495
1496 static void manage_cleanup( void * args )
1497 {
1498     struct manage_cleanup_stack * manage_cleanup_stack = args;
1499     intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1500     input_thread_t * p_input = *manage_cleanup_stack->p_input;
1501     id self = manage_cleanup_stack->self;
1502     playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1503
1504     var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1505     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1506     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1507     var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1508     var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1509
1510     pl_Release( p_intf );
1511
1512     if( p_input ) vlc_object_release( p_input );
1513 }
1514
1515 - (void)manage
1516 {
1517     playlist_t * p_playlist;
1518     input_thread_t * p_input = NULL;
1519
1520     /* new thread requires a new pool */
1521
1522     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1523
1524     p_playlist = pl_Hold( p_intf );
1525
1526     var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1527     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1528     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1529     var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1530     var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1531
1532     struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1533     pthread_cleanup_push(manage_cleanup, &stack);
1534
1535     while( true )
1536     {
1537         NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1538
1539         if( !p_input )
1540         {
1541             p_input = playlist_CurrentInput( p_playlist );
1542
1543             /* Refresh the interface */
1544             if( p_input )
1545             {
1546                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1547                 p_intf->p_sys->b_input_update = true;
1548             }
1549         }
1550         else if( !vlc_object_alive (p_input) || p_input->b_dead )
1551         {
1552             /* input stopped */
1553             p_intf->p_sys->b_intf_update = true;
1554             p_intf->p_sys->i_play_status = END_S;
1555             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1556             vlc_object_release( p_input );
1557             p_input = NULL;
1558         }
1559         else if( cachedInputState != input_GetState( p_input ) )
1560         {
1561             p_intf->p_sys->b_intf_update = true;
1562         }
1563
1564         /* Manage volume status */
1565         [self manageVolumeSlider];
1566
1567         msleep( INTF_IDLE_SLEEP );
1568
1569         [pool release];
1570     }
1571
1572     pthread_cleanup_pop(1);
1573
1574     msg_Dbg( p_intf, "Killing the Mac OS X module" );
1575
1576     /* We are dead, terminate */
1577     [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1578 }
1579
1580 - (void)manageVolumeSlider
1581 {
1582     audio_volume_t i_volume;
1583     aout_VolumeGet( p_intf, &i_volume );
1584
1585     if( i_volume != i_lastShownVolume )
1586     {
1587         i_lastShownVolume = i_volume;
1588         p_intf->p_sys->b_volume_update = TRUE;
1589     }
1590 }
1591
1592 - (void)manageIntf:(NSTimer *)o_timer
1593 {
1594     vlc_value_t val;
1595     playlist_t * p_playlist;
1596     input_thread_t * p_input;
1597
1598     if( p_intf->p_sys->b_input_update )
1599     {
1600         /* Called when new input is opened */
1601         p_intf->p_sys->b_current_title_update = true;
1602         p_intf->p_sys->b_intf_update = true;
1603         p_intf->p_sys->b_input_update = false;
1604         [self setupMenus]; /* Make sure input menu is up to date */
1605
1606         /* update our info-panel to reflect the new item, if we don't show
1607          * the playlist or the selection is empty */
1608         if( [self isPlaylistCollapsed] == YES )
1609         {
1610             playlist_t * p_playlist = pl_Hold( p_intf );
1611             PL_LOCK;
1612             playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1613             PL_UNLOCK;
1614             if( p_item )
1615                 [[self info] updatePanelWithItem: p_item->p_input];
1616             pl_Release( p_intf );
1617         }
1618     }
1619     if( p_intf->p_sys->b_intf_update )
1620     {
1621         bool b_input = false;
1622         bool b_plmul = false;
1623         bool b_control = false;
1624         bool b_seekable = false;
1625         bool b_chapters = false;
1626
1627         playlist_t * p_playlist = pl_Hold( p_intf );
1628
1629         PL_LOCK;
1630         b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1631         PL_UNLOCK;
1632
1633         p_input = playlist_CurrentInput( p_playlist );
1634
1635         bool b_buffering = NO;
1636     
1637         if( ( b_input = ( p_input != NULL ) ) )
1638         {
1639             /* seekable streams */
1640             cachedInputState = input_GetState( p_input );
1641             if ( cachedInputState == INIT_S ||
1642                  cachedInputState == OPENING_S )
1643             {
1644                 b_buffering = YES;
1645             }
1646
1647             /* seekable streams */
1648             b_seekable = var_GetBool( p_input, "can-seek" );
1649
1650             /* check whether slow/fast motion is possible */
1651             b_control = var_GetBool( p_input, "can-rate" );
1652
1653             /* chapters & titles */
1654             //b_chapters = p_input->stream.i_area_nb > 1;
1655             vlc_object_release( p_input );
1656         }
1657         pl_Release( p_intf );
1658
1659         if( b_buffering )
1660         {
1661             [o_main_pgbar startAnimation:self];
1662             [o_main_pgbar setIndeterminate:YES];
1663             [o_main_pgbar setHidden:NO];
1664         }
1665         else
1666         {
1667             [o_main_pgbar stopAnimation:self];
1668             [o_main_pgbar setHidden:YES];
1669         }
1670
1671         [o_btn_stop setEnabled: b_input];
1672         [o_embedded_window setStop: b_input];
1673         [o_btn_ff setEnabled: b_seekable];
1674         [o_btn_rewind setEnabled: b_seekable];
1675         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1676         [o_embedded_window setPrev: (b_plmul || b_chapters)];
1677         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1678         [o_embedded_window setNext: (b_plmul || b_chapters)];
1679
1680         [o_timeslider setFloatValue: 0.0];
1681         [o_timeslider setEnabled: b_seekable];
1682         [o_timefield setStringValue: @"00:00"];
1683         [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1684         [[[self controls] fspanel] setSeekable: b_seekable];
1685
1686         [o_embedded_window setSeekable: b_seekable];
1687         [o_embedded_window setTime:@"00:00" position:0.0];
1688
1689         p_intf->p_sys->b_current_title_update = true;
1690         
1691         p_intf->p_sys->b_intf_update = false;
1692     }
1693
1694     if( p_intf->p_sys->b_playmode_update )
1695     {
1696         [o_playlist playModeUpdated];
1697         p_intf->p_sys->b_playmode_update = false;
1698     }
1699     if( p_intf->p_sys->b_playlist_update )
1700     {
1701         [o_playlist playlistUpdated];
1702         p_intf->p_sys->b_playlist_update = false;
1703     }
1704
1705     if( p_intf->p_sys->b_fullscreen_update )
1706     {
1707         p_intf->p_sys->b_fullscreen_update = false;
1708     }
1709
1710     if( p_intf->p_sys->b_intf_show )
1711     {
1712         if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1713             [[o_controls fspanel] fadeIn];
1714         else
1715             [o_window makeKeyAndOrderFront: self];
1716
1717         p_intf->p_sys->b_intf_show = false;
1718     }
1719
1720     p_input = pl_CurrentInput( p_intf );
1721     if( p_input && vlc_object_alive (p_input) )
1722     {
1723         vlc_value_t val;
1724
1725         if( p_intf->p_sys->b_current_title_update )
1726         {
1727             NSString *aString;
1728             input_item_t * p_item = input_GetItem( p_input );
1729             char * name = input_item_GetNowPlaying( p_item );
1730
1731             if( !name )
1732                 name = input_item_GetName( p_item );
1733
1734             aString = [NSString stringWithUTF8String:name];
1735
1736             free(name);
1737
1738             [self setScrollField: aString stopAfter:-1];
1739             [[[self controls] fspanel] setStreamTitle: aString];
1740
1741             [[o_controls voutView] updateTitle];
1742  
1743             [o_playlist updateRowSelection];
1744
1745             p_intf->p_sys->b_current_title_update = FALSE;
1746         }
1747
1748         if( [o_timeslider isEnabled] )
1749         {
1750             /* Update the slider */
1751             vlc_value_t time;
1752             NSString * o_time;
1753             vlc_value_t pos;
1754             char psz_time[MSTRTIME_MAX_SIZE];
1755             float f_updated;
1756
1757             var_Get( p_input, "position", &pos );
1758             f_updated = 10000. * pos.f_float;
1759             [o_timeslider setFloatValue: f_updated];
1760
1761             var_Get( p_input, "time", &time );
1762
1763             mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1764             if( b_time_remaining && dur != -1 )
1765             {
1766                 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1767             }
1768             else
1769                 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1770
1771             [o_timefield setStringValue: o_time];
1772             [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1773             [o_embedded_window setTime: o_time position: f_updated];
1774         }
1775
1776         /* Manage Playing status */
1777         var_Get( p_input, "state", &val );
1778         if( p_intf->p_sys->i_play_status != val.i_int )
1779         {
1780             p_intf->p_sys->i_play_status = val.i_int;
1781             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1782             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1783         }
1784         vlc_object_release( p_input );
1785     }
1786     else if( p_input )
1787     {
1788         vlc_object_release( p_input );
1789     }
1790     else
1791     {
1792         p_intf->p_sys->i_play_status = END_S;
1793         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1794         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1795         [self setSubmenusEnabled: FALSE];
1796     }
1797
1798     if( p_intf->p_sys->b_volume_update )
1799     {
1800         NSString *o_text;
1801         int i_volume_step = 0;
1802         o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1803         if( i_lastShownVolume != -1 )
1804         [self setScrollField:o_text stopAfter:1000000];
1805         i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1806         [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1807         [o_volumeslider setEnabled: TRUE];
1808         [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1809         [o_embedded_window setVolumeEnabled: TRUE];
1810         [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1811         p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1812         p_intf->p_sys->b_volume_update = FALSE;
1813     }
1814
1815 end:
1816     [self updateMessageDisplay];
1817
1818     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1819         [self resetScrollField];
1820
1821     [interfaceTimer autorelease];
1822
1823     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1824         target: self selector: @selector(manageIntf:)
1825         userInfo: nil repeats: FALSE] retain];
1826 }
1827
1828 #pragma mark -
1829 #pragma mark Interface update
1830
1831 - (void)setupMenus
1832 {
1833     playlist_t * p_playlist = pl_Hold( p_intf );
1834     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1835     if( p_input != NULL )
1836     {
1837         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1838             var: "program" selector: @selector(toggleVar:)];
1839
1840         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1841             var: "title" selector: @selector(toggleVar:)];
1842
1843         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1844             var: "chapter" selector: @selector(toggleVar:)];
1845
1846         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1847             var: "audio-es" selector: @selector(toggleVar:)];
1848
1849         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1850             var: "video-es" selector: @selector(toggleVar:)];
1851
1852         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1853             var: "spu-es" selector: @selector(toggleVar:)];
1854
1855         /* special case for "Open File" inside the subtitles menu item */
1856         if( [o_mi_videotrack isEnabled] == YES )
1857             [o_mi_subtitle setEnabled: YES];
1858
1859         aout_instance_t * p_aout = input_GetAout( p_input );
1860         if( p_aout != NULL )
1861         {
1862             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1863                 var: "audio-channels" selector: @selector(toggleVar:)];
1864
1865             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1866                 var: "audio-device" selector: @selector(toggleVar:)];
1867
1868             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1869                 var: "visual" selector: @selector(toggleVar:)];
1870             vlc_object_release( (vlc_object_t *)p_aout );
1871         }
1872
1873         vout_thread_t * p_vout = input_GetVout( p_input );
1874
1875         if( p_vout != NULL )
1876         {
1877             vlc_object_t * p_dec_obj;
1878
1879             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1880                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1881
1882             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1883                 var: "crop" selector: @selector(toggleVar:)];
1884
1885             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1886                 var: "video-device" selector: @selector(toggleVar:)];
1887
1888             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1889                 var: "deinterlace" selector: @selector(toggleVar:)];
1890
1891 #if 0
1892 /* FIXME Post processing. */
1893             p_dec_obj = (vlc_object_t *)vlc_object_find(
1894                                                  (vlc_object_t *)p_vout,
1895                                                  VLC_OBJECT_DECODER,
1896                                                  FIND_PARENT );
1897             if( p_dec_obj != NULL )
1898             {
1899                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1900                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1901                     @selector(toggleVar:)];
1902
1903                 vlc_object_release(p_dec_obj);
1904             }
1905 #endif
1906             vlc_object_release( (vlc_object_t *)p_vout );
1907         }
1908         vlc_object_release( p_input );
1909     }
1910     pl_Release( p_intf );
1911 }
1912
1913 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1914 {
1915     int x,y = 0;
1916     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1917                                               FIND_ANYWHERE );
1918  
1919     if(! p_vout )
1920         return;
1921  
1922     /* clean the menu before adding new entries */
1923     if( [o_mi_screen hasSubmenu] )
1924     {
1925         y = [[o_mi_screen submenu] numberOfItems] - 1;
1926         msg_Dbg( VLCIntf, "%i items in submenu", y );
1927         while( x != y )
1928         {
1929             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1930             [[o_mi_screen submenu] removeItemAtIndex: x];
1931             x++;
1932         }
1933     }
1934
1935     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1936                              var: "video-device" selector: @selector(toggleVar:)];
1937     vlc_object_release( (vlc_object_t *)p_vout );
1938 }
1939
1940 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1941 {
1942     if( timeout != -1 )
1943         i_end_scroll = mdate() + timeout;
1944     else
1945         i_end_scroll = -1;
1946     [o_scrollfield setStringValue: o_string];
1947     [o_embedded_window setScrollString: o_string];
1948 }
1949
1950 - (void)resetScrollField
1951 {
1952     playlist_t * p_playlist = pl_Hold( p_intf );
1953     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1954
1955     i_end_scroll = -1;
1956     if( p_input && vlc_object_alive (p_input) )
1957     {
1958         NSString *o_temp;
1959         PL_LOCK;
1960         playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1961         if( input_item_GetNowPlaying( p_item->p_input ) )
1962             o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1963         else
1964             o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1965         PL_UNLOCK;
1966         [self setScrollField: o_temp stopAfter:-1];
1967         [[[self controls] fspanel] setStreamTitle: o_temp];
1968         vlc_object_release( p_input );
1969         pl_Release( p_intf );
1970         return;
1971     }
1972     pl_Release( p_intf );
1973     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1974 }
1975
1976 - (void)playStatusUpdated:(int)i_status
1977 {
1978     if( i_status == PLAYING_S )
1979     {
1980         [[[self controls] fspanel] setPause];
1981         [o_btn_play setImage: o_img_pause];
1982         [o_btn_play setAlternateImage: o_img_pause_pressed];
1983         [o_btn_play setToolTip: _NS("Pause")];
1984         [o_mi_play setTitle: _NS("Pause")];
1985         [o_dmi_play setTitle: _NS("Pause")];
1986         [o_vmi_play setTitle: _NS("Pause")];
1987     }
1988     else
1989     {
1990         [[[self controls] fspanel] setPlay];
1991         [o_btn_play setImage: o_img_play];
1992         [o_btn_play setAlternateImage: o_img_play_pressed];
1993         [o_btn_play setToolTip: _NS("Play")];
1994         [o_mi_play setTitle: _NS("Play")];
1995         [o_dmi_play setTitle: _NS("Play")];
1996         [o_vmi_play setTitle: _NS("Play")];
1997     }
1998 }
1999
2000 - (void)setSubmenusEnabled:(BOOL)b_enabled
2001 {
2002     [o_mi_program setEnabled: b_enabled];
2003     [o_mi_title setEnabled: b_enabled];
2004     [o_mi_chapter setEnabled: b_enabled];
2005     [o_mi_audiotrack setEnabled: b_enabled];
2006     [o_mi_visual setEnabled: b_enabled];
2007     [o_mi_videotrack setEnabled: b_enabled];
2008     [o_mi_subtitle setEnabled: b_enabled];
2009     [o_mi_channels setEnabled: b_enabled];
2010     [o_mi_deinterlace setEnabled: b_enabled];
2011     [o_mi_ffmpeg_pp setEnabled: b_enabled];
2012     [o_mi_device setEnabled: b_enabled];
2013     [o_mi_screen setEnabled: b_enabled];
2014     [o_mi_aspect_ratio setEnabled: b_enabled];
2015     [o_mi_crop setEnabled: b_enabled];
2016     [o_mi_teletext setEnabled: b_enabled];
2017 }
2018
2019 - (IBAction)timesliderUpdate:(id)sender
2020 {
2021     float f_updated;
2022     playlist_t * p_playlist;
2023     input_thread_t * p_input;
2024
2025     switch( [[NSApp currentEvent] type] )
2026     {
2027         case NSLeftMouseUp:
2028         case NSLeftMouseDown:
2029         case NSLeftMouseDragged:
2030             f_updated = [sender floatValue];
2031             break;
2032
2033         default:
2034             return;
2035     }
2036     p_playlist = pl_Hold( p_intf );
2037     p_input = playlist_CurrentInput( p_playlist );
2038     if( p_input != NULL )
2039     {
2040         vlc_value_t time;
2041         vlc_value_t pos;
2042         NSString * o_time;
2043         char psz_time[MSTRTIME_MAX_SIZE];
2044
2045         pos.f_float = f_updated / 10000.;
2046         var_Set( p_input, "position", pos );
2047         [o_timeslider setFloatValue: f_updated];
2048
2049         var_Get( p_input, "time", &time );
2050
2051         mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2052         if( b_time_remaining && dur != -1 )
2053         {
2054             o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2055         }
2056         else
2057             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2058
2059         [o_timefield setStringValue: o_time];
2060         [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2061         [o_embedded_window setTime: o_time position: f_updated];
2062         vlc_object_release( p_input );
2063     }
2064     pl_Release( p_intf );
2065 }
2066
2067 - (IBAction)timeFieldWasClicked:(id)sender
2068 {
2069     b_time_remaining = !b_time_remaining;
2070 }
2071     
2072
2073 #pragma mark -
2074 #pragma mark Recent Items
2075
2076 - (IBAction)clearRecentItems:(id)sender
2077 {
2078     [[NSDocumentController sharedDocumentController]
2079                           clearRecentDocuments: nil];
2080 }
2081
2082 - (void)openRecentItem:(id)sender
2083 {
2084     [self application: nil openFile: [sender title]];
2085 }
2086
2087 #pragma mark -
2088 #pragma mark Panels
2089
2090 - (IBAction)intfOpenFile:(id)sender
2091 {
2092     if( !nib_open_loaded )
2093     {
2094         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2095         [o_open awakeFromNib];
2096         [o_open openFile];
2097     } else {
2098         [o_open openFile];
2099     }
2100 }
2101
2102 - (IBAction)intfOpenFileGeneric:(id)sender
2103 {
2104     if( !nib_open_loaded )
2105     {
2106         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2107         [o_open awakeFromNib];
2108         [o_open openFileGeneric];
2109     } else {
2110         [o_open openFileGeneric];
2111     }
2112 }
2113
2114 - (IBAction)intfOpenDisc:(id)sender
2115 {
2116     if( !nib_open_loaded )
2117     {
2118         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2119         [o_open awakeFromNib];
2120         [o_open openDisc];
2121     } else {
2122         [o_open openDisc];
2123     }
2124 }
2125
2126 - (IBAction)intfOpenNet:(id)sender
2127 {
2128     if( !nib_open_loaded )
2129     {
2130         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2131         [o_open awakeFromNib];
2132         [o_open openNet];
2133     } else {
2134         [o_open openNet];
2135     }
2136 }
2137
2138 - (IBAction)intfOpenCapture:(id)sender
2139 {
2140     if( !nib_open_loaded )
2141     {
2142         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2143         [o_open awakeFromNib];
2144         [o_open openCapture];
2145     } else {
2146         [o_open openCapture];
2147     }
2148 }
2149
2150 - (IBAction)showWizard:(id)sender
2151 {
2152     if( !nib_wizard_loaded )
2153     {
2154         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2155         [o_wizard initStrings];
2156         [o_wizard resetWizard];
2157         [o_wizard showWizard];
2158     } else {
2159         [o_wizard resetWizard];
2160         [o_wizard showWizard];
2161     }
2162 }
2163
2164 - (IBAction)showExtended:(id)sender
2165 {
2166     if( o_extended == nil )
2167         o_extended = [[VLCExtended alloc] init];
2168
2169     if( !nib_extended_loaded )
2170         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2171
2172     [o_extended showPanel];
2173 }
2174
2175 - (IBAction)showBookmarks:(id)sender
2176 {
2177     /* we need the wizard-nib for the bookmarks's extract functionality */
2178     if( !nib_wizard_loaded )
2179     {
2180         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2181         [o_wizard initStrings];
2182     }
2183  
2184     if( !nib_bookmarks_loaded )
2185         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2186
2187     [o_bookmarks showBookmarks];
2188 }
2189
2190 - (IBAction)viewPreferences:(id)sender
2191 {
2192     if( !nib_prefs_loaded )
2193     {
2194         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2195         o_sprefs = [[VLCSimplePrefs alloc] init];
2196         o_prefs= [[VLCPrefs alloc] init];
2197     }
2198
2199     [o_sprefs showSimplePrefs];
2200 }
2201
2202 #pragma mark -
2203 #pragma mark Update
2204
2205 - (IBAction)checkForUpdate:(id)sender
2206 {
2207 #ifdef UPDATE_CHECK
2208     if( !nib_update_loaded )
2209         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
2210     [o_update showUpdateWindow];
2211 #else
2212     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2213     dialog_FatalWait( VLCIntf, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2214 #endif
2215 }
2216
2217 #pragma mark -
2218 #pragma mark Help and Docs
2219
2220 - (IBAction)viewAbout:(id)sender
2221 {
2222     if( !nib_about_loaded )
2223         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2224
2225     [o_about showAbout];
2226 }
2227
2228 - (IBAction)showLicense:(id)sender
2229 {
2230     if( !nib_about_loaded )
2231         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2232
2233     [o_about showGPL: sender];
2234 }
2235     
2236 - (IBAction)viewHelp:(id)sender
2237 {
2238     if( !nib_about_loaded )
2239     {
2240         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2241         [o_about showHelp];
2242     }
2243     else
2244         [o_about showHelp];
2245 }
2246
2247 - (IBAction)openReadMe:(id)sender
2248 {
2249     NSString * o_path = [[NSBundle mainBundle]
2250         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2251
2252     [[NSWorkspace sharedWorkspace] openFile: o_path
2253                                    withApplication: @"TextEdit"];
2254 }
2255
2256 - (IBAction)openDocumentation:(id)sender
2257 {
2258     NSURL * o_url = [NSURL URLWithString:
2259         @"http://www.videolan.org/doc/"];
2260
2261     [[NSWorkspace sharedWorkspace] openURL: o_url];
2262 }
2263
2264 - (IBAction)openWebsite:(id)sender
2265 {
2266     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2267
2268     [[NSWorkspace sharedWorkspace] openURL: o_url];
2269 }
2270
2271 - (IBAction)openForum:(id)sender
2272 {
2273     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2274
2275     [[NSWorkspace sharedWorkspace] openURL: o_url];
2276 }
2277
2278 - (IBAction)openDonate:(id)sender
2279 {
2280     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2281
2282     [[NSWorkspace sharedWorkspace] openURL: o_url];
2283 }
2284
2285 #pragma mark -
2286 #pragma mark Crash Log
2287 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2288 {
2289     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2290     NSURL *url = [NSURL URLWithString:urlStr];
2291
2292     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2293     [req setHTTPMethod:@"POST"];
2294
2295     NSString * email;
2296     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2297     {
2298         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2299         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2300         email = [emails valueAtIndex:[emails indexForIdentifier:
2301                     [emails primaryIdentifier]]];
2302     }
2303     else
2304         email = [NSString string];
2305
2306     NSString *postBody;
2307     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2308             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2309             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2310             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2311
2312     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2313
2314     /* Released from delegate */
2315     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2316 }
2317
2318 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2319 {
2320     NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2321                 _NS("Thanks for your report!"),
2322                 _NS("OK"), nil, nil, nil);
2323     [crashLogURLConnection release];
2324     crashLogURLConnection = nil;
2325 }
2326
2327 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2328 {
2329     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2330     [crashLogURLConnection release];
2331     crashLogURLConnection = nil;
2332 }
2333
2334 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2335 {
2336     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2337     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2338     NSString *fname;
2339     NSString * latestLog = nil;
2340     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2341     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2342     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
2343     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2344
2345     while (fname = [direnum nextObject])
2346     {
2347         [direnum skipDescendents];
2348         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2349         {
2350             NSArray * compo = [fname componentsSeparatedByString:@"_"];
2351             if( [compo count] < 3 ) continue;
2352             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2353             if( [compo count] < 4 ) continue;
2354
2355             // Dooh. ugly.
2356             if( year < [[compo objectAtIndex:0] intValue] ||
2357                 (year ==[[compo objectAtIndex:0] intValue] && 
2358                  (month < [[compo objectAtIndex:1] intValue] ||
2359                   (month ==[[compo objectAtIndex:1] intValue] &&
2360                    (day   < [[compo objectAtIndex:2] intValue] ||
2361                     (day   ==[[compo objectAtIndex:2] intValue] &&
2362                       hours < [[compo objectAtIndex:3] intValue] ))))))
2363             {
2364                 year  = [[compo objectAtIndex:0] intValue];
2365                 month = [[compo objectAtIndex:1] intValue];
2366                 day   = [[compo objectAtIndex:2] intValue];
2367                 hours = [[compo objectAtIndex:3] intValue];
2368                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2369             }
2370         }
2371     }
2372
2373     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2374         return nil;
2375
2376     if( !previouslySeen )
2377     {
2378         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
2379         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2380         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
2381         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2382     }
2383     return latestLog;
2384 }
2385
2386 - (NSString *)latestCrashLogPath
2387 {
2388     return [self latestCrashLogPathPreviouslySeen:YES];
2389 }
2390
2391 - (void)lookForCrashLog
2392 {
2393     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2394     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2395     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2396     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2397     if( latestLog && !areCrashLogsTooOld )
2398         [NSApp runModalForWindow: o_crashrep_win];
2399     [o_pool release];
2400 }
2401
2402 - (IBAction)crashReporterAction:(id)sender
2403 {
2404     if( sender == o_crashrep_send_btn )
2405         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2406
2407     [NSApp stopModal];
2408     [o_crashrep_win orderOut: sender];
2409 }
2410
2411 - (IBAction)openCrashLog:(id)sender
2412 {
2413     NSString * latestLog = [self latestCrashLogPath];
2414     if( latestLog )
2415     {
2416         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2417     }
2418     else
2419     {
2420         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.") );
2421     }
2422 }
2423
2424 #pragma mark -
2425 #pragma mark Remove old prefs
2426
2427 - (void)_removeOldPreferences
2428 {
2429     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2430     static const int kCurrentPreferencesVersion = 1;
2431     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2432     if( version >= kCurrentPreferencesVersion ) return;
2433
2434     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
2435         NSUserDomainMask, YES);
2436     if( !libraries || [libraries count] == 0) return;
2437     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2438
2439     /* File not found, don't attempt anything */
2440     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2441        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2442     {
2443         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2444         return;
2445     }
2446
2447     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2448                 _NS("We just found an older version of VLC's preferences files."),
2449                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2450     if( res != NSOKButton )
2451     {
2452         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2453         return;
2454     }
2455
2456     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2457
2458     /* Move the file to trash so that user can find them later */
2459     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2460
2461     /* really reset the defaults from now on */
2462     [NSUserDefaults resetStandardUserDefaults];
2463
2464     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2465     [[NSUserDefaults standardUserDefaults] synchronize];
2466
2467     /* Relaunch now */
2468     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2469
2470     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2471     if(fork() != 0)
2472     {
2473         exit(0);
2474         return;
2475     }
2476     execl(path, path, NULL);
2477 }
2478
2479 #pragma mark -
2480 #pragma mark Errors, warnings and messages
2481
2482 - (IBAction)viewErrorsAndWarnings:(id)sender
2483 {
2484     [[[self coreDialogProvider] errorPanel] showPanel];
2485 }
2486
2487 - (IBAction)showMessagesPanel:(id)sender
2488 {
2489     [o_msgs_panel makeKeyAndOrderFront: sender];
2490 }
2491
2492 - (IBAction)showInformationPanel:(id)sender
2493 {
2494     if(! nib_info_loaded )
2495         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2496     
2497     [o_info initPanel];
2498 }
2499
2500 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2501 {
2502     if( [o_notification object] == o_msgs_panel )
2503         [self updateMessageDisplay];
2504 }
2505
2506 - (void)updateMessageDisplay
2507 {
2508     if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2509     {
2510         id o_msg;
2511         NSEnumerator * o_enum;
2512
2513         [o_messages setString: @""];
2514
2515         [o_msg_lock lock];
2516
2517         o_enum = [o_msg_arr objectEnumerator];
2518
2519         while( ( o_msg = [o_enum nextObject] ) != nil )
2520         {
2521             [o_messages insertText: o_msg];
2522         }
2523
2524         b_msg_arr_changed = NO;
2525         [o_msg_lock unlock];
2526     }
2527 }
2528
2529 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2530 {
2531     NSColor *o_white = [NSColor whiteColor];
2532     NSColor *o_red = [NSColor redColor];
2533     NSColor *o_yellow = [NSColor yellowColor];
2534     NSColor *o_gray = [NSColor grayColor];
2535
2536     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2537     static const char * ppsz_type[4] = { ": ", " error: ",
2538     " warning: ", " debug: " };
2539
2540     NSString *o_msg;
2541     NSDictionary *o_attr;
2542     NSAttributedString *o_msg_color;
2543
2544     int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2545
2546     [o_msg_lock lock];
2547
2548     if( [o_msg_arr count] + 2 > 600 )
2549     {
2550                 [o_msg_arr removeObjectAtIndex: 0];
2551         [o_msg_arr removeObjectAtIndex: 1];
2552    }
2553
2554     o_attr = [NSDictionary dictionaryWithObject: o_gray
2555                                          forKey: NSForegroundColorAttributeName];
2556     o_msg = [NSString stringWithFormat: @"%@%s",
2557              [[o_notification userInfo] objectForKey: @"Module"],
2558              ppsz_type[i_type]];
2559     o_msg_color = [[NSAttributedString alloc]
2560                    initWithString: o_msg attributes: o_attr];
2561     [o_msg_arr addObject: [o_msg_color autorelease]];
2562
2563     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2564                                          forKey: NSForegroundColorAttributeName];
2565     o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2566     o_msg_color = [[NSAttributedString alloc]
2567                    initWithString: o_msg attributes: o_attr];
2568     [o_msg_arr addObject: [o_msg_color autorelease]];
2569
2570     b_msg_arr_changed = YES;
2571     [o_msg_lock unlock];
2572 }
2573
2574 - (IBAction)saveDebugLog:(id)sender
2575 {
2576     NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2577     
2578     [saveFolderPanel setCanChooseDirectories: NO];
2579     [saveFolderPanel setCanChooseFiles: YES];
2580     [saveFolderPanel setCanSelectHiddenExtension: NO];
2581     [saveFolderPanel setCanCreateDirectories: YES];
2582     [saveFolderPanel setRequiredFileType: @"rtfd"];
2583     [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];
2584 }
2585
2586 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2587 {
2588     BOOL b_returned;
2589     if( returnCode == NSOKButton )
2590     {
2591         b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2592         if(! b_returned )
2593             msg_Warn( p_intf, "Error while saving the debug log" );
2594     }
2595 }
2596
2597 #pragma mark -
2598 #pragma mark Playlist toggling
2599
2600 - (IBAction)togglePlaylist:(id)sender
2601 {
2602     NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2603     NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2604     /*First, check if the playlist is visible*/
2605     if( contentRect.size.height <= 169. )
2606     {
2607         o_restore_rect = contentRect;
2608         b_restore_size = true;
2609         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2610
2611         /* make large */
2612         if( o_size_with_playlist.height > 169. )
2613             o_rect.size.height = o_size_with_playlist.height;
2614         else
2615             o_rect.size.height = 500.;
2616  
2617         if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2618             o_rect.size.width = o_size_with_playlist.width;
2619         else
2620             o_rect.size.width = [o_window contentMinSize].width;
2621
2622         o_rect.origin.x = contentRect.origin.x;
2623         o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2624             [o_window contentMinSize].height;
2625
2626         o_rect = [o_window frameRectForContentRect:o_rect];
2627
2628         NSRect screenRect = [[o_window screen] visibleFrame];
2629         if( !NSContainsRect( screenRect, o_rect ) ) {
2630             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2631                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2632             if( NSMinY(o_rect) < NSMinY(screenRect) )
2633                 o_rect.origin.y = ( NSMinY(screenRect) );
2634         }
2635
2636         [o_btn_playlist setState: YES];
2637     }
2638     else
2639     {
2640         NSSize curSize = o_rect.size;
2641         if( b_restore_size )
2642         {
2643             o_rect = o_restore_rect;
2644             if( o_rect.size.height < [o_window contentMinSize].height )
2645                 o_rect.size.height = [o_window contentMinSize].height;
2646             if( o_rect.size.width < [o_window contentMinSize].width )
2647                 o_rect.size.width = [o_window contentMinSize].width;
2648         }
2649         else
2650         {
2651             NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2652             /* make small */
2653             o_rect.size.height = [o_window contentMinSize].height;
2654             o_rect.size.width = [o_window contentMinSize].width;
2655             o_rect.origin.x = contentRect.origin.x;
2656             /* Calculate the position of the lower right corner after resize */
2657             o_rect.origin.y = contentRect.origin.y +
2658                 contentRect.size.height - [o_window contentMinSize].height;
2659         }
2660
2661         [o_playlist_view setAutoresizesSubviews: NO];
2662         [o_playlist_view removeFromSuperview];
2663         [o_btn_playlist setState: NO];
2664         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2665         o_rect = [o_window frameRectForContentRect:o_rect];
2666     }
2667
2668     [o_window setFrame: o_rect display:YES animate: YES];
2669 }
2670
2671 - (void)updateTogglePlaylistState
2672 {
2673     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2674         [o_btn_playlist setState: NO];
2675     else
2676         [o_btn_playlist setState: YES];
2677
2678     [[self playlist] outlineViewSelectionDidChange: NULL];
2679 }
2680
2681 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2682 {
2683
2684     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2685
2686    /*Stores the size the controller one resize, to be able to restore it when
2687      toggling the playlist*/
2688     o_size_with_playlist = proposedFrameSize;
2689
2690     NSRect rect;
2691     rect.size = proposedFrameSize;
2692     if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2693     {
2694         if( b_small_window == NO )
2695         {
2696             /* if large and going to small then hide */
2697             b_small_window = YES;
2698             [o_playlist_view setAutoresizesSubviews: NO];
2699             [o_playlist_view removeFromSuperview];
2700         }
2701         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2702     }
2703     return proposedFrameSize;
2704 }
2705
2706 - (void)windowDidMove:(NSNotification *)notif
2707 {
2708     b_restore_size = false;
2709 }
2710
2711 - (void)windowDidResize:(NSNotification *)notif
2712 {
2713     if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2714     {
2715         /* If large and coming from small then show */
2716         [o_playlist_view setAutoresizesSubviews: YES];
2717         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2718         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2719         [o_playlist_view setNeedsDisplay:YES];
2720         [[o_window contentView] addSubview: o_playlist_view];
2721         b_small_window = NO;
2722     }
2723     [self updateTogglePlaylistState];
2724 }
2725
2726 #pragma mark -
2727
2728 @end
2729
2730 @implementation VLCMain (NSMenuValidation)
2731
2732 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2733 {
2734     NSString *o_title = [o_mi title];
2735     BOOL bEnabled = TRUE;
2736
2737     /* Recent Items Menu */
2738     if( [o_title isEqualToString: _NS("Clear Menu")] )
2739     {
2740         NSMenu * o_menu = [o_mi_open_recent submenu];
2741         int i_nb_items = [o_menu numberOfItems];
2742         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2743                                                        recentDocumentURLs];
2744         UInt32 i_nb_docs = [o_docs count];
2745
2746         if( i_nb_items > 1 )
2747         {
2748             while( --i_nb_items )
2749             {
2750                 [o_menu removeItemAtIndex: 0];
2751             }
2752         }
2753
2754         if( i_nb_docs > 0 )
2755         {
2756             NSURL * o_url;
2757             NSString * o_doc;
2758
2759             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2760
2761             while( TRUE )
2762             {
2763                 i_nb_docs--;
2764
2765                 o_url = [o_docs objectAtIndex: i_nb_docs];
2766
2767                 if( [o_url isFileURL] )
2768                 {
2769                     o_doc = [o_url path];
2770                 }
2771                 else
2772                 {
2773                     o_doc = [o_url absoluteString];
2774                 }
2775
2776                 [o_menu insertItemWithTitle: o_doc
2777                     action: @selector(openRecentItem:)
2778                     keyEquivalent: @"" atIndex: 0];
2779
2780                 if( i_nb_docs == 0 )
2781                 {
2782                     break;
2783                 }
2784             }
2785         }
2786         else
2787         {
2788             bEnabled = FALSE;
2789         }
2790     }
2791     return( bEnabled );
2792 }
2793
2794 @end
2795
2796 @implementation VLCMain (Internal)
2797
2798 - (void)handlePortMessage:(NSPortMessage *)o_msg
2799 {
2800     id ** val;
2801     NSData * o_data;
2802     NSValue * o_value;
2803     NSInvocation * o_inv;
2804     NSConditionLock * o_lock;
2805
2806     o_data = [[o_msg components] lastObject];
2807     o_inv = *((NSInvocation **)[o_data bytes]);
2808     [o_inv getArgument: &o_value atIndex: 2];
2809     val = (id **)[o_value pointerValue];
2810     [o_inv setArgument: val[1] atIndex: 2];
2811     o_lock = *(val[0]);
2812
2813     [o_lock lock];
2814     [o_inv invoke];
2815     [o_lock unlockWithCondition: 1];
2816 }
2817
2818 @end
2819
2820 /*****************************************************************************
2821  * VLCApplication interface
2822  * exclusively used to implement media key support on Al Apple keyboards
2823  *   b_justJumped is required as the keyboard send its events faster than
2824  *    the user can actually jump through his media
2825  *****************************************************************************/
2826
2827 @implementation VLCApplication
2828
2829 - (void)sendEvent: (NSEvent*)event
2830 {
2831     if( [event type] == NSSystemDefined && [event subtype] == 8 )
2832         {
2833                 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
2834                 int keyFlags = ([event data1] & 0x0000FFFF);
2835                 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
2836         int keyRepeat = (keyFlags & 0x1);
2837
2838         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
2839             var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
2840
2841         if( keyCode == NX_KEYTYPE_FAST && !b_justJumped )
2842         {
2843             if( keyState == 0 && keyRepeat == 0 )
2844             {
2845                     var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_NEXT );
2846             }
2847             else if( keyRepeat == 1 )
2848             {
2849                 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
2850                 b_justJumped = YES;
2851                 [self performSelector:@selector(resetJump)
2852                            withObject: NULL
2853                            afterDelay:0.25];
2854             }
2855         }
2856
2857         if( keyCode == NX_KEYTYPE_REWIND && !b_justJumped )
2858         {
2859             if( keyState == 0 && keyRepeat == 0 )
2860             {
2861                 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PREV );
2862             }
2863             else if( keyRepeat == 1 )
2864             {
2865                 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
2866                 b_justJumped = YES;
2867                 [self performSelector:@selector(resetJump)
2868                            withObject: NULL
2869                            afterDelay:0.25];
2870             }
2871         }
2872         }
2873         [super sendEvent: event];
2874 }
2875
2876 - (void)resetJump
2877 {
2878     b_justJumped = NO;
2879 }
2880
2881 @end