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