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