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