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