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