]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
qt4: Fix PLSelector when a discovery service fails to be created.
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2012 VLC authors and VideoLAN
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 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <stdlib.h>                                      /* malloc(), free() */
35 #include <sys/param.h>                                    /* for MAXPATHLEN */
36 #include <string.h>
37 #include <vlc_common.h>
38 #include <vlc_keys.h>
39 #include <vlc_dialog.h>
40 #include <vlc_url.h>
41 #include <vlc_modules.h>
42 #include <vlc_aout_intf.h>
43 #include <vlc_vout_window.h>
44 #include <unistd.h> /* execl() */
45
46 #import "CompatibilityFixes.h"
47 #import "intf.h"
48 #import "MainMenu.h"
49 #import "VideoView.h"
50 #import "prefs.h"
51 #import "playlist.h"
52 #import "playlistinfo.h"
53 #import "controls.h"
54 #import "open.h"
55 #import "wizard.h"
56 #import "bookmarks.h"
57 #import "coredialogs.h"
58 #import "AppleRemote.h"
59 #import "eyetv.h"
60 #import "simple_prefs.h"
61 #import "CoreInteraction.h"
62 #import "TrackSynchronization.h"
63
64 #import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
65 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
66
67 /*****************************************************************************
68  * Local prototypes.
69  *****************************************************************************/
70 static void Run ( intf_thread_t *p_intf );
71
72 static void updateProgressPanel (void *, const char *, float);
73 static bool checkProgressPanel (void *);
74 static void destroyProgressPanel (void *);
75
76 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
77
78 static int InputEvent( vlc_object_t *, const char *,
79                       vlc_value_t, vlc_value_t, void * );
80 static int PLItemChanged( vlc_object_t *, const char *,
81                          vlc_value_t, vlc_value_t, void * );
82 static int PlaylistUpdated( vlc_object_t *, const char *,
83                            vlc_value_t, vlc_value_t, void * );
84 static int PlaybackModeUpdated( vlc_object_t *, const char *,
85                                vlc_value_t, vlc_value_t, void * );
86 static int VolumeUpdated( vlc_object_t *, const char *,
87                          vlc_value_t, vlc_value_t, void * );
88
89 #pragma mark -
90 #pragma mark VLC Interface Object Callbacks
91
92 /*****************************************************************************
93  * OpenIntf: initialize interface
94  *****************************************************************************/
95 int OpenIntf ( vlc_object_t *p_this )
96 {
97     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
98     [VLCApplication sharedApplication];
99     intf_thread_t *p_intf = (intf_thread_t*) p_this;
100
101     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
102     if( p_intf->p_sys == NULL )
103         return VLC_ENOMEM;
104
105     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
106
107     /* subscribe to LibVLCCore's messages */
108     p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
109     p_intf->pf_run = Run;
110     p_intf->b_should_run_on_first_thread = true;
111
112     [o_pool release];
113     return VLC_SUCCESS;
114 }
115
116 /*****************************************************************************
117  * CloseIntf: destroy interface
118  *****************************************************************************/
119 void CloseIntf ( vlc_object_t *p_this )
120 {
121     intf_thread_t *p_intf = (intf_thread_t*) p_this;
122
123     free( p_intf->p_sys );
124 }
125
126 static int WindowControl( vout_window_t *, int i_query, va_list );
127
128 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
129 {
130     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
131     intf_thread_t *p_intf = VLCIntf;
132     if (!p_intf) {
133         msg_Err( p_wnd, "Mac OS X interface not found" );
134         return VLC_EGENERIC;
135     }
136
137     int i_x = cfg->x;
138     int i_y = cfg->y;
139     unsigned i_width = cfg->width;
140     unsigned i_height = cfg->height;
141     p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
142
143     if ( !p_wnd->handle.nsobject ) {
144         msg_Err( p_wnd, "got no video view from the interface" );
145         [o_pool release];
146         return VLC_EGENERIC;
147     }
148
149     [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
150     [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
151     p_wnd->control = WindowControl;
152     p_wnd->sys = (vout_window_sys_t *)VLCIntf;
153     [o_pool release];
154     return VLC_SUCCESS;
155 }
156
157 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
158 {
159     /* TODO */
160     if( i_query == VOUT_WINDOW_SET_STATE )
161         msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
162     else if( i_query == VOUT_WINDOW_SET_SIZE )
163     {
164         unsigned int i_width  = va_arg( args, unsigned int );
165         unsigned int i_height = va_arg( args, unsigned int );
166         [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
167     }
168     else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
169     {
170         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
171         [[VLCMain sharedInstance] fullscreenChanged];
172         [o_pool release];
173     }
174     else
175         msg_Dbg( p_wnd, "WindowControl: unknown query" );
176     return VLC_SUCCESS;
177 }
178
179 void WindowClose( vout_window_t *p_wnd )
180 {
181     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
182     [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
183
184     [o_pool release];
185 }
186
187 /*****************************************************************************
188  * Run: main loop
189  *****************************************************************************/
190 static NSLock * o_appLock = nil;    // controls access to f_appExit
191
192 static void Run( intf_thread_t *p_intf )
193 {
194     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
195     [VLCApplication sharedApplication];
196
197     o_appLock = [[NSLock alloc] init];
198
199     [[VLCMain sharedInstance] setIntf: p_intf];
200     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
201
202     [NSApp run];
203     [[VLCMain sharedInstance] applicationWillTerminate:nil];
204     [o_appLock release];
205     [o_pool release];
206 }
207
208 #pragma mark -
209 #pragma mark Variables Callback
210
211 /*****************************************************************************
212  * MsgCallback: Callback triggered by the core once a new debug message is
213  * ready to be displayed. We store everything in a NSArray in our Cocoa part
214  * of this file.
215  *****************************************************************************/
216 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
217 {
218     int canc = vlc_savecancel();
219     char *str;
220
221     if (vasprintf( &str, format, ap ) == -1)
222     {
223         vlc_restorecancel( canc );
224         return;
225     }
226
227     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
228     [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
229     [o_pool release];
230
231     vlc_restorecancel( canc );
232     free( str );
233 }
234
235 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
236                        vlc_value_t oldval, vlc_value_t new_val, void *param )
237 {
238     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
239     switch (new_val.i_int) {
240         case INPUT_EVENT_STATE:
241             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
242             break;
243         case INPUT_EVENT_RATE:
244             [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
245             break;
246         case INPUT_EVENT_POSITION:
247             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
248             break;
249         case INPUT_EVENT_TITLE:
250         case INPUT_EVENT_CHAPTER:
251             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
252             break;
253         case INPUT_EVENT_CACHE:
254             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
255             break;
256         case INPUT_EVENT_STATISTICS:
257             [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
258             break;
259         case INPUT_EVENT_ES:
260             break;
261         case INPUT_EVENT_TELETEXT:
262             break;
263         case INPUT_EVENT_AOUT:
264             break;
265         case INPUT_EVENT_VOUT:
266             break;
267         case INPUT_EVENT_ITEM_META:
268         case INPUT_EVENT_ITEM_INFO:
269             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
270             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
271             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
272             break;
273         case INPUT_EVENT_BOOKMARK:
274             break;
275         case INPUT_EVENT_RECORD:
276             [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
277             break;
278         case INPUT_EVENT_PROGRAM:
279             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
280             break;
281         case INPUT_EVENT_ITEM_EPG:
282             break;
283         case INPUT_EVENT_SIGNAL:
284             break;
285
286         case INPUT_EVENT_ITEM_NAME:
287             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
288             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
289             break;
290
291         case INPUT_EVENT_AUDIO_DELAY:
292         case INPUT_EVENT_SUBTITLE_DELAY:
293             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
294             break;
295
296         case INPUT_EVENT_DEAD:
297             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
298             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
299             break;
300
301         case INPUT_EVENT_ABORT:
302             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
303             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
304             break;
305
306         default:
307             //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
308             break;
309     }
310
311     [o_pool release];
312     return VLC_SUCCESS;
313 }
314
315 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
316                          vlc_value_t oldval, vlc_value_t new_val, void *param )
317 {
318     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
319     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
320
321     [o_pool release];
322     return VLC_SUCCESS;
323 }
324
325 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
326                          vlc_value_t oldval, vlc_value_t new_val, void *param )
327 {
328     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
329     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
330
331     [o_pool release];
332     return VLC_SUCCESS;
333 }
334
335 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
336                          vlc_value_t oldval, vlc_value_t new_val, void *param )
337 {
338     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
339     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
340
341     [o_pool release];
342     return VLC_SUCCESS;
343 }
344
345 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
346                          vlc_value_t oldval, vlc_value_t new_val, void *param )
347 {
348     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
349     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
350
351     [o_pool release];
352     return VLC_SUCCESS;
353 }
354
355 /*****************************************************************************
356  * ShowController: Callback triggered by the show-intf playlist variable
357  * through the ShowIntf-control-intf, to let us show the controller-win;
358  * usually when in fullscreen-mode
359  *****************************************************************************/
360 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
361                      vlc_value_t old_val, vlc_value_t new_val, void *param )
362 {
363     intf_thread_t * p_intf = VLCIntf;
364     if( p_intf && p_intf->p_sys )
365     {
366         playlist_t * p_playlist = pl_Get( p_intf );
367         BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
368         if( strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen )
369         {
370             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
371         }
372         else
373         {
374             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
375         }
376     }
377     return VLC_SUCCESS;
378 }
379
380 /*****************************************************************************
381  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
382  * variable, to let the intf update the controller.
383  *****************************************************************************/
384 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
385                      vlc_value_t old_val, vlc_value_t new_val, void *param )
386 {
387     intf_thread_t * p_intf = VLCIntf;
388     if (p_intf)
389     {
390         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
391         [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject:nil waitUntilDone:NO];
392         [o_pool release];
393     }
394     return VLC_SUCCESS;
395 }
396
397 /*****************************************************************************
398  * DialogCallback: Callback triggered by the "dialog-*" variables
399  * to let the intf display error and interaction dialogs
400  *****************************************************************************/
401 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
402 {
403     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
404     VLCMain *interface = (VLCMain *)data;
405
406     if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
407     {
408         /* the progress panel needs to update itself and therefore wants special treatment within this context */
409         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
410
411         p_dialog->pf_update = updateProgressPanel;
412         p_dialog->pf_check = checkProgressPanel;
413         p_dialog->pf_destroy = destroyProgressPanel;
414         p_dialog->p_sys = VLCIntf->p_libvlc;
415     }
416
417     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
418     [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
419
420     [o_pool release];
421     return VLC_SUCCESS;
422 }
423
424 void updateProgressPanel (void *priv, const char *text, float value)
425 {
426     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
427
428     NSString *o_txt;
429     if( text != NULL )
430         o_txt = [NSString stringWithUTF8String: text];
431     else
432         o_txt = @"";
433
434     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
435
436     [o_pool release];
437 }
438
439 void destroyProgressPanel (void *priv)
440 {
441     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
442     [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:NO];
443     [o_pool release];
444 }
445
446 bool checkProgressPanel (void *priv)
447 {
448     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
449     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
450     [o_pool release];
451 }
452
453 #pragma mark -
454 #pragma mark Helpers
455
456 input_thread_t *getInput(void)
457 {
458     intf_thread_t *p_intf = VLCIntf;
459     if (!p_intf)
460         return NULL;
461     return pl_CurrentInput(p_intf);
462 }
463
464 vout_thread_t *getVout(void)
465 {
466     input_thread_t *p_input = getInput();
467     if (!p_input)
468         return NULL;
469     vout_thread_t *p_vout = input_GetVout(p_input);
470     vlc_object_release(p_input);
471     return p_vout;
472 }
473
474 audio_output_t *getAout(void)
475 {
476     input_thread_t *p_input = getInput();
477     if (!p_input)
478         return NULL;
479     audio_output_t *p_aout = input_GetAout(p_input);
480     vlc_object_release(p_input);
481     return p_aout;
482 }
483
484 #pragma mark -
485 #pragma mark Private
486
487 @interface VLCMain ()
488 - (void)_removeOldPreferences;
489 @end
490
491 /*****************************************************************************
492  * VLCMain implementation
493  *****************************************************************************/
494 @implementation VLCMain
495
496 #pragma mark -
497 #pragma mark Initialization
498
499 static VLCMain *_o_sharedMainInstance = nil;
500
501 + (VLCMain *)sharedInstance
502 {
503     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
504 }
505
506 - (id)init
507 {
508     if( _o_sharedMainInstance)
509     {
510         [self dealloc];
511         return _o_sharedMainInstance;
512     }
513     else
514         _o_sharedMainInstance = [super init];
515
516     p_intf = NULL;
517     p_current_input = NULL;
518
519     o_msg_lock = [[NSLock alloc] init];
520     o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
521
522     o_open = [[VLCOpen alloc] init];
523     //o_embedded_list = [[VLCEmbeddedList alloc] init];
524     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
525     o_info = [[VLCInfo alloc] init];
526     o_mainmenu = [[VLCMainMenu alloc] init];
527     o_coreinteraction = [[VLCCoreInteraction alloc] init];
528     o_eyetv = [[VLCEyeTVController alloc] init];
529     o_mainwindow = [[VLCMainWindow alloc] init];
530
531     /* announce our launch to a potential eyetv plugin */
532     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
533                                                                    object: @"VLCEyeTVSupport"
534                                                                  userInfo: NULL
535                                                        deliverImmediately: YES];
536
537     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
538     NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
539     [defaults registerDefaults:appDefaults];
540
541     return _o_sharedMainInstance;
542 }
543
544 - (void)setIntf: (intf_thread_t *)p_mainintf {
545     p_intf = p_mainintf;
546 }
547
548 - (intf_thread_t *)intf {
549     return p_intf;
550 }
551
552 - (void)awakeFromNib
553 {
554     playlist_t *p_playlist;
555     vlc_value_t val;
556     if( !p_intf ) return;
557     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
558
559     /* Check if we already did this once. Opening the other nibs calls it too,
560      because VLCMain is the owner */
561     if( nib_main_loaded ) return;
562
563     [o_msgs_panel setExcludedFromWindowsMenu: YES];
564     [o_msgs_panel setDelegate: self];
565
566     p_playlist = pl_Get( p_intf );
567
568     val.b_bool = false;
569
570     var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
571     var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
572     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
573     //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
574     var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
575     var_AddCallback(p_playlist, "activity", PLItemChanged, self);
576     var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
577     var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
578     var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
579     var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
580     var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
581     var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
582     var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
583     var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
584
585     if (OSX_LION)
586     {
587         if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
588             var_SetBool( p_playlist, "fullscreen", YES );
589     }
590
591     /* load our Core Dialogs nib */
592     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
593
594     /* subscribe to various interactive dialogues */
595     var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
596     var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
597     var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
598     var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
599     var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
600     var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
601     var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
602     var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
603     var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
604     var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
605     dialog_Register( p_intf );
606
607     /* init Apple Remote support */
608     o_remote = [[AppleRemote alloc] init];
609     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
610     [o_remote setDelegate: _o_sharedMainInstance];
611
612     [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
613
614     /* yeah, we are done */
615     b_nativeFullscreenMode = NO;
616 #ifdef MAC_OS_X_VERSION_10_7
617     if( config_GetInt( VLCIntf, "embedded-video" ))
618         b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
619 #endif
620     nib_main_loaded = TRUE;
621 }
622
623 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
624 {
625     if( !p_intf ) return;
626
627     [o_mainwindow updateWindow];
628     [o_mainwindow updateTimeSlider];
629     [o_mainwindow updateVolumeSlider];
630     [o_mainwindow makeKeyAndOrderFront: self];
631
632     /* init media key support */
633     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
634     if( b_mediaKeySupport )
635     {
636         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
637         [o_mediaKeyController startWatchingMediaKeys];
638         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
639                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
640                                                                  nil]];
641     }
642     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
643
644     [self _removeOldPreferences];
645
646     /* Handle sleep notification */
647     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
648            name:NSWorkspaceWillSleepNotification object:nil];
649
650     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
651
652     /* we will need this, so let's load it here so the interface appears to be more responsive */
653     nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
654     [self initStrings];
655 }
656
657 - (void)initStrings
658 {
659     if( !p_intf ) return;
660
661     /* messages panel */
662     [o_msgs_panel setTitle: _NS("Messages")];
663     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
664     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
665
666     /* crash reporter panel */
667     [o_crashrep_send_btn setTitle: _NS("Send")];
668     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
669     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
670     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
671     [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, ...")];
672     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
673     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
674 }
675
676 #pragma mark -
677 #pragma mark Termination
678
679 - (void)applicationWillTerminate:(NSNotification *)notification
680 {
681     /* don't allow a double termination call. If the user has
682      * already invoked the quit then simply return this time. */
683     static bool f_appExit = false;
684     bool isTerminating;
685
686     [o_appLock lock];
687     isTerminating = f_appExit;
688     f_appExit = true;
689     [o_appLock unlock];
690
691     if (isTerminating)
692         return;
693
694     if (notification == nil)
695         [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
696
697     playlist_t * p_playlist = pl_Get( p_intf );
698     int returnedValue = 0;
699
700     /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
701     if (OSX_LION && b_nativeFullscreenMode)
702     {
703         [o_mainwindow toggleFullScreen: self];
704         [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
705     }
706
707     /* Save some interface state in configuration, at module quit */
708     config_PutInt( p_intf, "random", var_GetBool( p_playlist, "random" ) );
709     config_PutInt( p_intf, "loop", var_GetBool( p_playlist, "loop" ) );
710     config_PutInt( p_intf, "repeat", var_GetBool( p_playlist, "repeat" ) );
711
712     msg_Dbg( p_intf, "Terminating" );
713
714     /* unsubscribe from the interactive dialogues */
715     dialog_Unregister( p_intf );
716     var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
717     var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
718     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
719     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
720     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
721     //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
722     var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
723     var_DelCallback(p_playlist, "activity", PLItemChanged, self);
724     var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
725     var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
726     var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
727     var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
728     var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
729     var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
730     var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
731     var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
732     var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
733     var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
734     var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
735
736     if( p_current_input )
737     {
738         var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
739         vlc_object_release( p_current_input );
740         p_current_input = NULL;
741     }
742
743     /* remove global observer watching for vout device changes correctly */
744     [[NSNotificationCenter defaultCenter] removeObserver: self];
745
746     /* release some other objects here, because it isn't sure whether dealloc
747      * will be called later on */
748     if( o_sprefs )
749         [o_sprefs release];
750
751     if( o_prefs )
752         [o_prefs release];
753
754     [o_open release];
755
756     if( o_info )
757         [o_info release];
758
759     if( o_wizard )
760         [o_wizard release];
761
762     [crashLogURLConnection cancel];
763     [crashLogURLConnection release];
764
765     [o_embedded_list release];
766     [o_coredialogs release];
767     [o_eyetv release];
768     [o_mainwindow release];
769
770     /* unsubscribe from libvlc's debug messages */
771     vlc_Unsubscribe( p_intf->p_sys->p_sub );
772
773     [o_msg_arr removeAllObjects];
774     [o_msg_arr release];
775
776     [o_msg_lock release];
777
778     /* write cached user defaults to disk */
779     [[NSUserDefaults standardUserDefaults] synchronize];
780
781     /* Make sure the Menu doesn't have any references to vlc objects anymore */
782     //FIXME: this should be moved to VLCMainMenu
783     [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
784     [o_mainmenu release];
785
786     libvlc_Quit( p_intf->p_libvlc );
787
788     [self setIntf:nil];
789 }
790
791 #pragma mark -
792 #pragma mark Sparkle delegate
793 /* received directly before the update gets installed, so let's shut down a bit */
794 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
795 {
796     [NSApp activateIgnoringOtherApps:YES];
797     [o_remote stopListening: self];
798     [[VLCCoreInteraction sharedInstance] stop];
799 }
800
801 #pragma mark -
802 #pragma mark Media Key support
803
804 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
805 {
806     if( b_mediaKeySupport )
807        {
808         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
809
810         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
811         int keyFlags = ([event data1] & 0x0000FFFF);
812         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
813         int keyRepeat = (keyFlags & 0x1);
814
815         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
816             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
817
818         if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
819         {
820             if( keyState == 0 && keyRepeat == 0 )
821                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
822             else if( keyRepeat == 1 )
823             {
824                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
825                 b_mediakeyJustJumped = YES;
826                 [self performSelector:@selector(resetMediaKeyJump)
827                            withObject: NULL
828                            afterDelay:0.25];
829             }
830         }
831
832         if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
833         {
834             if( keyState == 0 && keyRepeat == 0 )
835                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
836             else if( keyRepeat == 1 )
837             {
838                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
839                 b_mediakeyJustJumped = YES;
840                 [self performSelector:@selector(resetMediaKeyJump)
841                            withObject: NULL
842                            afterDelay:0.25];
843             }
844         }
845     }
846 }
847
848 #pragma mark -
849 #pragma mark Other notification
850
851 /* Listen to the remote in exclusive mode, only when VLC is the active
852    application */
853 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
854 {
855     if( !p_intf ) return;
856     if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
857         [o_remote startListening: self];
858 }
859 - (void)applicationDidResignActive:(NSNotification *)aNotification
860 {
861     if( !p_intf ) return;
862     [o_remote stopListening: self];
863 }
864
865 /* Triggered when the computer goes to sleep */
866 - (void)computerWillSleep: (NSNotification *)notification
867 {
868     [[VLCCoreInteraction sharedInstance] pause];
869 }
870
871 #pragma mark -
872 #pragma mark File opening
873
874 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
875 {
876     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
877     char *psz_uri = make_URI([o_filename UTF8String], "file" );
878     if( !psz_uri )
879         return( FALSE );
880
881     input_thread_t * p_input = pl_CurrentInput( VLCIntf );
882     BOOL b_returned = NO;
883
884     if (p_input)
885     {
886         b_returned = input_AddSubtitle( p_input, psz_uri, true );
887         vlc_object_release( p_input );
888         if(!b_returned)
889         {
890             free( psz_uri );
891             return YES;
892         }
893     }
894     else if( p_input )
895         vlc_object_release( p_input );
896
897     NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
898
899     free( psz_uri );
900
901     if( b_autoplay )
902         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
903     else
904         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
905
906     return( TRUE );
907 }
908
909 /* When user click in the Dock icon our double click in the finder */
910 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
911 {
912     if(!hasVisibleWindows)
913         [o_mainwindow makeKeyAndOrderFront:self];
914
915     return YES;
916 }
917
918 #pragma mark -
919 #pragma mark Apple Remote Control
920
921 /* Helper method for the remote control interface in order to trigger forward/backward and volume
922    increase/decrease as long as the user holds the left/right, plus/minus button */
923 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
924 {
925     if(b_remote_button_hold)
926     {
927         switch([buttonIdentifierNumber intValue])
928         {
929             case kRemoteButtonRight_Hold:
930                 [[VLCCoreInteraction sharedInstance] forward];
931             break;
932             case kRemoteButtonLeft_Hold:
933                 [[VLCCoreInteraction sharedInstance] backward];
934             break;
935             case kRemoteButtonVolume_Plus_Hold:
936                 [[VLCCoreInteraction sharedInstance] volumeUp];
937             break;
938             case kRemoteButtonVolume_Minus_Hold:
939                 [[VLCCoreInteraction sharedInstance] volumeDown];
940             break;
941         }
942         if(b_remote_button_hold)
943         {
944             /* trigger event */
945             [self performSelector:@selector(executeHoldActionForRemoteButton:)
946                          withObject:buttonIdentifierNumber
947                          afterDelay:0.25];
948         }
949     }
950 }
951
952 /* Apple Remote callback */
953 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
954                pressedDown: (BOOL) pressedDown
955                 clickCount: (unsigned int) count
956 {
957     switch( buttonIdentifier )
958     {
959         case k2009RemoteButtonFullscreen:
960             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
961             break;
962         case k2009RemoteButtonPlay:
963             [[VLCCoreInteraction sharedInstance] play];
964             break;
965         case kRemoteButtonPlay:
966             if(count >= 2) {
967                 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
968             } else {
969                 [[VLCCoreInteraction sharedInstance] play];
970             }
971             break;
972         case kRemoteButtonVolume_Plus:
973             [[VLCCoreInteraction sharedInstance] volumeUp];
974             break;
975         case kRemoteButtonVolume_Minus:
976             [[VLCCoreInteraction sharedInstance] volumeDown];
977             break;
978         case kRemoteButtonRight:
979             [[VLCCoreInteraction sharedInstance] next];
980             break;
981         case kRemoteButtonLeft:
982             [[VLCCoreInteraction sharedInstance] previous];
983             break;
984         case kRemoteButtonRight_Hold:
985         case kRemoteButtonLeft_Hold:
986         case kRemoteButtonVolume_Plus_Hold:
987         case kRemoteButtonVolume_Minus_Hold:
988             /* simulate an event as long as the user holds the button */
989             b_remote_button_hold = pressedDown;
990             if( pressedDown )
991             {
992                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
993                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
994                            withObject:buttonIdentifierNumber];
995             }
996             break;
997         case kRemoteButtonMenu:
998             [o_controls showPosition: self]; //FIXME
999             break;
1000         default:
1001             /* Add here whatever you want other buttons to do */
1002             break;
1003     }
1004 }
1005
1006 #pragma mark -
1007 #pragma mark String utility
1008 // FIXME: this has nothing to do here
1009
1010 - (NSString *)localizedString:(const char *)psz
1011 {
1012     NSString * o_str = nil;
1013
1014     if( psz != NULL )
1015     {
1016         o_str = [NSString stringWithCString: _(psz) encoding:NSUTF8StringEncoding];
1017
1018         if( o_str == NULL )
1019         {
1020             msg_Err( VLCIntf, "could not translate: %s", psz );
1021             return( @"" );
1022         }
1023     }
1024     else
1025     {
1026         msg_Warn( VLCIntf, "can't translate empty strings" );
1027         return( @"" );
1028     }
1029
1030     return( o_str );
1031 }
1032
1033
1034
1035 - (char *)delocalizeString:(NSString *)id
1036 {
1037     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1038                           allowLossyConversion: NO];
1039     char * psz_string;
1040
1041     if( o_data == nil )
1042     {
1043         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1044                      allowLossyConversion: YES];
1045         psz_string = malloc( [o_data length] + 1 );
1046         [o_data getBytes: psz_string];
1047         psz_string[ [o_data length] ] = '\0';
1048         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1049                  psz_string );
1050     }
1051     else
1052     {
1053         psz_string = malloc( [o_data length] + 1 );
1054         [o_data getBytes: psz_string];
1055         psz_string[ [o_data length] ] = '\0';
1056     }
1057
1058     return psz_string;
1059 }
1060
1061 /* i_width is in pixels */
1062 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1063 {
1064     NSMutableString *o_wrapped;
1065     NSString *o_out_string;
1066     NSRange glyphRange, effectiveRange, charRange;
1067     NSRect lineFragmentRect;
1068     unsigned glyphIndex, breaksInserted = 0;
1069
1070     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1071         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1072         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1073     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1074     NSTextContainer *o_container = [[NSTextContainer alloc]
1075         initWithContainerSize: NSMakeSize(i_width, 2000)];
1076
1077     [o_layout_manager addTextContainer: o_container];
1078     [o_container release];
1079     [o_storage addLayoutManager: o_layout_manager];
1080     [o_layout_manager release];
1081
1082     o_wrapped = [o_in_string mutableCopy];
1083     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1084
1085     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1086             glyphIndex += effectiveRange.length) {
1087         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1088                                             effectiveRange: &effectiveRange];
1089         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1090                                     actualGlyphRange: &effectiveRange];
1091         if([o_wrapped lineRangeForRange:
1092                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1093             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1094             breaksInserted++;
1095         }
1096     }
1097     o_out_string = [NSString stringWithString: o_wrapped];
1098     [o_wrapped release];
1099     [o_storage release];
1100
1101     return o_out_string;
1102 }
1103
1104
1105 #pragma mark -
1106 #pragma mark Key Shortcuts
1107
1108 static struct
1109 {
1110     unichar i_nskey;
1111     unsigned int i_vlckey;
1112 } nskeys_to_vlckeys[] =
1113 {
1114     { NSUpArrowFunctionKey, KEY_UP },
1115     { NSDownArrowFunctionKey, KEY_DOWN },
1116     { NSLeftArrowFunctionKey, KEY_LEFT },
1117     { NSRightArrowFunctionKey, KEY_RIGHT },
1118     { NSF1FunctionKey, KEY_F1 },
1119     { NSF2FunctionKey, KEY_F2 },
1120     { NSF3FunctionKey, KEY_F3 },
1121     { NSF4FunctionKey, KEY_F4 },
1122     { NSF5FunctionKey, KEY_F5 },
1123     { NSF6FunctionKey, KEY_F6 },
1124     { NSF7FunctionKey, KEY_F7 },
1125     { NSF8FunctionKey, KEY_F8 },
1126     { NSF9FunctionKey, KEY_F9 },
1127     { NSF10FunctionKey, KEY_F10 },
1128     { NSF11FunctionKey, KEY_F11 },
1129     { NSF12FunctionKey, KEY_F12 },
1130     { NSInsertFunctionKey, KEY_INSERT },
1131     { NSHomeFunctionKey, KEY_HOME },
1132     { NSEndFunctionKey, KEY_END },
1133     { NSPageUpFunctionKey, KEY_PAGEUP },
1134     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1135     { NSMenuFunctionKey, KEY_MENU },
1136     { NSTabCharacter, KEY_TAB },
1137     { NSCarriageReturnCharacter, KEY_ENTER },
1138     { NSEnterCharacter, KEY_ENTER },
1139     { NSBackspaceCharacter, KEY_BACKSPACE },
1140     { NSDeleteCharacter, KEY_DELETE },
1141     {0,0}
1142 };
1143
1144 unsigned int CocoaKeyToVLC( unichar i_key )
1145 {
1146     unsigned int i;
1147
1148     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1149     {
1150         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1151         {
1152             return nskeys_to_vlckeys[i].i_vlckey;
1153         }
1154     }
1155     return (unsigned int)i_key;
1156 }
1157
1158 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1159 {
1160     unsigned int new = 0;
1161
1162     if([theString rangeOfString:@"Command"].location != NSNotFound)
1163         new |= NSCommandKeyMask;
1164     if([theString rangeOfString:@"Alt"].location != NSNotFound)
1165         new |= NSAlternateKeyMask;
1166     if([theString rangeOfString:@"Shift"].location != NSNotFound)
1167         new |= NSShiftKeyMask;
1168     if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1169         new |= NSControlKeyMask;
1170     return new;
1171 }
1172
1173 - (NSString *)VLCKeyToString:(NSString *)theString
1174 {
1175     if (![theString isEqualToString:@""]) {
1176         if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1177             theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1178         else
1179         {
1180             theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1181             theString = [NSString stringWithFormat:@"%@+", theString];
1182         }
1183         if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1184             theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1185         else
1186         {
1187             theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1188             theString = [NSString stringWithFormat:@"%@-", theString];
1189         }
1190         theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1191         theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1192         theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1193         theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1194     }
1195     if ([theString length] > 1)
1196     {
1197         if([theString rangeOfString:@"Up"].location != NSNotFound)
1198             return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1199         else if([theString rangeOfString:@"Down"].location != NSNotFound)
1200             return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1201         else if([theString rangeOfString:@"Right"].location != NSNotFound)
1202             return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1203         else if([theString rangeOfString:@"Left"].location != NSNotFound)
1204             return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1205         else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1206             return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1207         else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1208             return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1209         else if([theString rangeOfString:@"Home"].location != NSNotFound)
1210             return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1211         else if([theString rangeOfString:@"End"].location != NSNotFound)
1212             return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1213         else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1214             return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1215         else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1216             return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1217         else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1218             return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1219         else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1220             return [NSString stringWithFormat:@"%C", NSTabCharacter];
1221         else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1222             return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1223         else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1224             return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1225         else if([theString rangeOfString:@"F12"].location != NSNotFound)
1226             return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1227         else if([theString rangeOfString:@"F11"].location != NSNotFound)
1228             return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1229         else if([theString rangeOfString:@"F10"].location != NSNotFound)
1230             return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1231         else if([theString rangeOfString:@"F9"].location != NSNotFound)
1232             return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1233         else if([theString rangeOfString:@"F8"].location != NSNotFound)
1234             return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1235         else if([theString rangeOfString:@"F7"].location != NSNotFound)
1236             return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1237         else if([theString rangeOfString:@"F6"].location != NSNotFound)
1238             return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1239         else if([theString rangeOfString:@"F5"].location != NSNotFound)
1240             return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1241         else if([theString rangeOfString:@"F4"].location != NSNotFound)
1242             return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1243         else if([theString rangeOfString:@"F3"].location != NSNotFound)
1244             return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1245         else if([theString rangeOfString:@"F2"].location != NSNotFound)
1246             return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1247         else if([theString rangeOfString:@"F1"].location != NSNotFound)
1248             return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1249         /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1250     }
1251
1252     return theString;
1253 }
1254
1255
1256 /*****************************************************************************
1257  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1258  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1259  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1260  *****************************************************************************/
1261 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1262 {
1263     unichar key = 0;
1264     vlc_value_t val;
1265     unsigned int i_pressed_modifiers = 0;
1266     const struct hotkey *p_hotkeys;
1267     int i;
1268     NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1269     NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1270
1271     val.i_int = 0;
1272     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1273
1274     i_pressed_modifiers = [o_event modifierFlags];
1275
1276     if( i_pressed_modifiers & NSShiftKeyMask ) {
1277         val.i_int |= KEY_MODIFIER_SHIFT;
1278         [tempString appendString:@"Shift-"];
1279         [tempStringPlus appendString:@"Shift+"];
1280     }
1281     if( i_pressed_modifiers & NSControlKeyMask ) {
1282         val.i_int |= KEY_MODIFIER_CTRL;
1283         [tempString appendString:@"Ctrl-"];
1284         [tempStringPlus appendString:@"Ctrl+"];
1285     }
1286     if( i_pressed_modifiers & NSAlternateKeyMask ) {
1287         val.i_int |= KEY_MODIFIER_ALT;
1288         [tempString appendString:@"Alt-"];
1289         [tempStringPlus appendString:@"Alt+"];
1290     }
1291     if( i_pressed_modifiers & NSCommandKeyMask ) {
1292         val.i_int |= KEY_MODIFIER_COMMAND;
1293         [tempString appendString:@"Command-"];
1294         [tempStringPlus appendString:@"Command+"];
1295     }
1296
1297     [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1298     [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1299
1300     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1301
1302     /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1303     if( key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask )
1304     {
1305         [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1306         return YES;
1307     }
1308
1309     switch( key )
1310     {
1311         case NSDeleteCharacter:
1312         case NSDeleteFunctionKey:
1313         case NSDeleteCharFunctionKey:
1314         case NSBackspaceCharacter:
1315         case NSUpArrowFunctionKey:
1316         case NSDownArrowFunctionKey:
1317         case NSRightArrowFunctionKey:
1318         case NSLeftArrowFunctionKey:
1319         case NSEnterCharacter:
1320         case NSCarriageReturnCharacter:
1321             return NO;
1322     }
1323
1324     if( key == 0x0020 ) // space key
1325     {
1326         [[VLCCoreInteraction sharedInstance] play];
1327         return YES;
1328     }
1329
1330     val.i_int |= CocoaKeyToVLC( key );
1331
1332     if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1333     {
1334         var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1335         return YES;
1336     }
1337
1338     return NO;
1339 }
1340
1341 - (void)updateCurrentlyUsedHotkeys
1342 {
1343     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1344     /* Get the main Module */
1345     module_t *p_main = module_get_main();
1346     assert( p_main );
1347     unsigned confsize;
1348     module_config_t *p_config;
1349
1350     p_config = module_config_get (p_main, &confsize);
1351
1352     for (size_t i = 0; i < confsize; i++)
1353     {
1354         module_config_t *p_item = p_config + i;
1355
1356         if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1357            && !strncmp( p_item->psz_name , "key-", 4 )
1358            && !EMPTY_STR( p_item->psz_text ) )
1359         {
1360             if (p_item->value.psz)
1361                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1362         }
1363     }
1364     module_config_free (p_config);
1365     o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1366 }
1367
1368 #pragma mark -
1369 #pragma mark Interface updaters
1370 - (void)fullscreenChanged
1371 {
1372     playlist_t * p_playlist = pl_Get( VLCIntf );
1373     BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1374
1375     if (OSX_LION && b_nativeFullscreenMode)
1376     {
1377         [o_mainwindow toggleFullScreen: self];
1378         if(b_fullscreen)
1379             [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1380         else
1381             [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1382     }
1383     else
1384     {
1385         if( b_fullscreen )
1386         {
1387             input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1388             if( p_input != NULL && [self activeVideoPlayback] )
1389             {
1390                 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1391             }
1392             if (p_input)
1393                 vlc_object_release( p_input );
1394         }
1395         else
1396         {
1397             // leaving fullscreen is always allowed
1398             [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1399         }
1400     }
1401 }
1402
1403 - (void)PlaylistItemChanged
1404 {
1405     if( p_current_input && ( p_current_input->b_dead || !vlc_object_alive( p_current_input ) ))
1406     {
1407         var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1408         vlc_object_release( p_current_input );
1409         p_current_input = NULL;
1410
1411         [o_mainmenu setRateControlsEnabled: NO];
1412     }
1413     else if( !p_current_input )
1414     {
1415         // object is hold here and released then it is dead
1416         p_current_input = playlist_CurrentInput( pl_Get( VLCIntf ));
1417         if( p_current_input )
1418         {
1419             var_AddCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1420
1421             [o_mainmenu setRateControlsEnabled: YES];
1422             if ( [self activeVideoPlayback] && [[o_mainwindow videoView] isHidden] )
1423                 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1424         }
1425     }
1426
1427     [o_playlist updateRowSelection];
1428     [o_mainwindow updateWindow];
1429     [self updateDelays];
1430     [self updateMainMenu];
1431 }
1432
1433 - (void)updateMainMenu
1434 {
1435     [o_mainmenu setupMenus];
1436     [o_mainmenu updatePlaybackRate];
1437 }
1438
1439 - (void)updateMainWindow
1440 {
1441     [o_mainwindow updateWindow];
1442 }
1443
1444 - (void)showMainWindow
1445 {
1446     [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1447 }
1448
1449 - (void)showFullscreenController
1450 {
1451     [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1452 }
1453
1454 - (void)updateDelays
1455 {
1456     [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1457 }
1458
1459 - (void)updateName
1460 {
1461     [o_mainwindow updateName];
1462 }
1463
1464 - (void)updatePlaybackPosition
1465 {
1466     [o_mainwindow updateTimeSlider];
1467
1468     input_thread_t * p_input;
1469     p_input = pl_CurrentInput( p_intf );
1470     if( p_input )
1471     {
1472         if( var_GetInteger( p_input, "state" ) == PLAYING_S && [self activeVideoPlayback] )
1473             UpdateSystemActivity( UsrActivity );
1474         vlc_object_release( p_input );
1475     }
1476 }
1477
1478 - (void)updateVolume
1479 {
1480     [o_mainwindow updateVolumeSlider];
1481 }
1482
1483 - (void)playlistUpdated
1484 {
1485     [self playbackStatusUpdated];
1486     [o_playlist playlistUpdated];
1487     [o_mainwindow updateWindow];
1488     [o_mainwindow updateName];
1489 }
1490
1491 - (void)updateRecordState: (BOOL)b_value
1492 {
1493     [o_mainmenu updateRecordState:b_value];
1494 }
1495
1496 - (void)updateInfoandMetaPanel
1497 {
1498     [o_playlist outlineViewSelectionDidChange:nil];
1499 }
1500
1501 - (void)playbackStatusUpdated
1502 {
1503     input_thread_t * p_input;
1504
1505     p_input = pl_CurrentInput( p_intf );
1506     if( p_input )
1507     {
1508         int state = var_GetInteger( p_input, "state" );
1509         if( state == PLAYING_S )
1510         {
1511             [[self mainMenu] setPause];
1512             [o_mainwindow setPause];
1513         }
1514         else
1515         {
1516             if (state == END_S)
1517                 [o_mainmenu setSubmenusEnabled: FALSE];
1518             [[self mainMenu] setPlay];
1519             [o_mainwindow setPlay];
1520         }
1521         vlc_object_release( p_input );
1522     }
1523
1524     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1525     [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1526 }
1527
1528 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1529 {
1530     [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1531                                                                    object:nil
1532                                                                  userInfo:nil
1533                                                        deliverImmediately:YES];
1534 }
1535
1536 - (void)playbackModeUpdated
1537 {
1538     vlc_value_t looping,repeating;
1539     playlist_t * p_playlist = pl_Get( VLCIntf );
1540
1541     bool loop = var_GetBool( p_playlist, "loop" );
1542     bool repeat = var_GetBool( p_playlist, "repeat" );
1543     if( repeat ) {
1544         [o_mainwindow setRepeatOne];
1545         [o_mainmenu setRepeatOne];
1546     } else if( loop ) {
1547         [o_mainwindow setRepeatAll];
1548         [o_mainmenu setRepeatAll];
1549     } else {
1550         [o_mainwindow setRepeatOff];
1551         [o_mainmenu setRepeatOff];
1552     }
1553
1554     [o_mainwindow setShuffle];
1555     [o_mainmenu setShuffle];
1556 }
1557
1558 #pragma mark -
1559 #pragma mark Other objects getters
1560
1561 - (id)mainMenu
1562 {
1563     return o_mainmenu;
1564 }
1565
1566 - (id)mainWindow
1567 {
1568     return o_mainwindow;
1569 }
1570
1571 - (id)controls
1572 {
1573     if( o_controls )
1574         return o_controls;
1575
1576     return nil;
1577 }
1578
1579 - (id)bookmarks
1580 {
1581     if (!o_bookmarks )
1582         o_bookmarks = [[VLCBookmarks alloc] init];
1583
1584     if( !nib_bookmarks_loaded )
1585         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1586
1587     return o_bookmarks;
1588 }
1589
1590 - (id)open
1591 {
1592     if (!o_open)
1593         return nil;
1594
1595     if (!nib_open_loaded)
1596         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1597
1598     return o_open;
1599 }
1600
1601 - (id)simplePreferences
1602 {
1603     if (!o_sprefs)
1604         o_sprefs = [[VLCSimplePrefs alloc] init];
1605
1606     if (!nib_prefs_loaded)
1607         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1608
1609     return o_sprefs;
1610 }
1611
1612 - (id)preferences
1613 {
1614     if( !o_prefs )
1615         o_prefs = [[VLCPrefs alloc] init];
1616
1617     if( !nib_prefs_loaded )
1618         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1619
1620     return o_prefs;
1621 }
1622
1623 - (id)playlist
1624 {
1625     if( o_playlist )
1626         return o_playlist;
1627
1628     return nil;
1629 }
1630
1631 - (id)info
1632 {
1633     if(! nib_info_loaded )
1634         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1635
1636     if( o_info )
1637         return o_info;
1638
1639     return nil;
1640 }
1641
1642 - (id)wizard
1643 {
1644     if( !o_wizard )
1645         o_wizard = [[VLCWizard alloc] init];
1646
1647     if( !nib_wizard_loaded )
1648     {
1649         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1650         [o_wizard initStrings];
1651     }
1652     return o_wizard;
1653 }
1654
1655 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1656 {
1657     id videoView = [o_mainwindow setupVideoView];
1658     NSRect videoRect = [videoView frame];
1659     int i_x = (int)videoRect.origin.x;
1660     int i_y = (int)videoRect.origin.y;
1661     unsigned int i_width = (int)videoRect.size.width;
1662     unsigned int i_height = (int)videoRect.size.height;
1663     pi_x = &i_x;
1664     pi_y = &i_y;
1665     pi_width = &i_width;
1666     pi_height = &i_height;
1667     msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1668     return videoView;
1669 }
1670
1671 - (void)setNativeVideoSize:(NSSize)size
1672 {
1673     [o_mainwindow setNativeVideoSize:size];
1674 }
1675
1676 - (id)embeddedList
1677 {
1678     if( o_embedded_list )
1679         return o_embedded_list;
1680
1681     return nil;
1682 }
1683
1684 - (id)coreDialogProvider
1685 {
1686     if( o_coredialogs )
1687         return o_coredialogs;
1688
1689     return nil;
1690 }
1691
1692 - (id)eyeTVController
1693 {
1694     if( o_eyetv )
1695         return o_eyetv;
1696
1697     return nil;
1698 }
1699
1700 - (id)appleRemoteController
1701 {
1702     return o_remote;
1703 }
1704
1705 - (void)setActiveVideoPlayback:(BOOL)b_value
1706 {
1707     b_active_videoplayback = b_value;
1708     [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject: nil waitUntilDone:NO];
1709     [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1710 }
1711
1712 - (BOOL)activeVideoPlayback
1713 {
1714     return b_active_videoplayback;
1715 }
1716
1717 #pragma mark -
1718 #pragma mark Crash Log
1719 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1720 {
1721     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1722     NSURL *url = [NSURL URLWithString:urlStr];
1723
1724     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1725     [req setHTTPMethod:@"POST"];
1726
1727     NSString * email;
1728     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1729     {
1730         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1731         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1732         email = [emails valueAtIndex:[emails indexForIdentifier:
1733                     [emails primaryIdentifier]]];
1734     }
1735     else
1736         email = [NSString string];
1737
1738     NSString *postBody;
1739     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1740             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1741             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1742             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1743
1744     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1745
1746     /* Released from delegate */
1747     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1748 }
1749
1750 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1751 {
1752     [crashLogURLConnection release];
1753     crashLogURLConnection = nil;
1754 }
1755
1756 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1757 {
1758     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1759     [crashLogURLConnection release];
1760     crashLogURLConnection = nil;
1761 }
1762
1763 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1764 {
1765     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1766     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1767     NSString *fname;
1768     NSString * latestLog = nil;
1769     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1770     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1771     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
1772     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1773
1774     while (fname = [direnum nextObject])
1775     {
1776         [direnum skipDescendents];
1777         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1778         {
1779             NSArray * compo = [fname componentsSeparatedByString:@"_"];
1780             if( [compo count] < 3 ) continue;
1781             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1782             if( [compo count] < 4 ) continue;
1783
1784             // Dooh. ugly.
1785             if( year < [[compo objectAtIndex:0] intValue] ||
1786                 (year ==[[compo objectAtIndex:0] intValue] &&
1787                  (month < [[compo objectAtIndex:1] intValue] ||
1788                   (month ==[[compo objectAtIndex:1] intValue] &&
1789                    (day   < [[compo objectAtIndex:2] intValue] ||
1790                     (day   ==[[compo objectAtIndex:2] intValue] &&
1791                       hours < [[compo objectAtIndex:3] intValue] ))))))
1792             {
1793                 year  = [[compo objectAtIndex:0] intValue];
1794                 month = [[compo objectAtIndex:1] intValue];
1795                 day   = [[compo objectAtIndex:2] intValue];
1796                 hours = [[compo objectAtIndex:3] intValue];
1797                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1798             }
1799         }
1800     }
1801
1802     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1803         return nil;
1804
1805     if( !previouslySeen )
1806     {
1807         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
1808         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1809         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
1810         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1811     }
1812     return latestLog;
1813 }
1814
1815 - (NSString *)latestCrashLogPath
1816 {
1817     return [self latestCrashLogPathPreviouslySeen:YES];
1818 }
1819
1820 - (void)lookForCrashLog
1821 {
1822     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1823     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1824     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1825     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1826     if( latestLog && !areCrashLogsTooOld )
1827         [NSApp runModalForWindow: o_crashrep_win];
1828     [o_pool release];
1829 }
1830
1831 - (IBAction)crashReporterAction:(id)sender
1832 {
1833     if( sender == o_crashrep_send_btn )
1834         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1835
1836     [NSApp stopModal];
1837     [o_crashrep_win orderOut: sender];
1838 }
1839
1840 - (IBAction)openCrashLog:(id)sender
1841 {
1842     NSString * latestLog = [self latestCrashLogPath];
1843     if( latestLog )
1844     {
1845         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1846     }
1847     else
1848     {
1849         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.") );
1850     }
1851 }
1852
1853 #pragma mark -
1854 #pragma mark Remove old prefs
1855
1856 - (void)_removeOldPreferences
1857 {
1858     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1859     static const int kCurrentPreferencesVersion = 1;
1860     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1861     if( version >= kCurrentPreferencesVersion ) return;
1862
1863     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1864         NSUserDomainMask, YES);
1865     if( !libraries || [libraries count] == 0) return;
1866     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1867
1868     /* File not found, don't attempt anything */
1869     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1870        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1871     {
1872         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1873         return;
1874     }
1875
1876     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1877                 _NS("We just found an older version of VLC's preferences files."),
1878                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1879     if( res != NSOKButton )
1880     {
1881         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1882         return;
1883     }
1884
1885     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1886
1887     /* Move the file to trash so that user can find them later */
1888     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1889
1890     /* really reset the defaults from now on */
1891     [NSUserDefaults resetStandardUserDefaults];
1892
1893     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1894     [[NSUserDefaults standardUserDefaults] synchronize];
1895
1896     /* Relaunch now */
1897     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1898
1899     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1900     if(fork() != 0)
1901     {
1902         exit(0);
1903         return;
1904     }
1905     execl(path, path, NULL);
1906 }
1907
1908 #pragma mark -
1909 #pragma mark Errors, warnings and messages
1910 - (IBAction)updateMessagesPanel:(id)sender
1911 {
1912     [self windowDidBecomeKey:nil];
1913 }
1914
1915 - (IBAction)showMessagesPanel:(id)sender
1916 {
1917     [o_msgs_panel makeKeyAndOrderFront: sender];
1918 }
1919
1920 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1921 {
1922     [o_msgs_table reloadData];
1923     [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1924 }
1925
1926 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1927 {
1928     if (aTableView == o_msgs_table)
1929         return [o_msg_arr count];
1930     return 0; 
1931 }
1932
1933 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1934 {
1935     NSMutableAttributedString *result = NULL;
1936
1937     [o_msg_lock lock];
1938     if( rowIndex < [o_msg_arr count] )
1939         result = [o_msg_arr objectAtIndex: rowIndex];
1940     [o_msg_lock unlock];
1941
1942     if( result != NULL )
1943         return result;
1944     else
1945         return @"";
1946 }
1947
1948 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1949 {
1950     NSColor *o_white = [NSColor whiteColor];
1951     NSColor *o_red = [NSColor redColor];
1952     NSColor *o_yellow = [NSColor yellowColor];
1953     NSColor *o_gray = [NSColor grayColor];
1954     NSString * firstString, * secondString;
1955
1956     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1957     static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1958
1959     NSDictionary *o_attr;
1960     NSMutableAttributedString *o_msg_color;
1961
1962     [o_msg_lock lock];
1963
1964     if( [o_msg_arr count] + 2 > 600 )
1965     {
1966         [o_msg_arr removeObjectAtIndex: 0];
1967         [o_msg_arr removeObjectAtIndex: 1];
1968     }
1969     firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1970     secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1971
1972     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]  forKey: NSForegroundColorAttributeName];
1973     o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1974     o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1975     [o_msg_color setAttributes: o_attr range: NSMakeRange( 0, [firstString length] )];
1976     [o_msg_arr addObject: [o_msg_color autorelease]];
1977
1978     b_msg_arr_changed = YES;
1979     [o_msg_lock unlock];
1980 }
1981
1982 - (IBAction)saveDebugLog:(id)sender
1983 {
1984     NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1985
1986     [saveFolderPanel setCanSelectHiddenExtension: NO];
1987     [saveFolderPanel setCanCreateDirectories: YES];
1988     [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1989     [saveFolderPanel beginSheetForDirectory:nil file: [NSString stringWithFormat: _NS("VLC Debug Log (%s).rtfd"), VERSION_MESSAGE] modalForWindow: o_msgs_panel modalDelegate:self didEndSelector:@selector(saveDebugLogAsRTF:returnCode:contextInfo:) contextInfo:nil];
1990 }
1991
1992 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1993 {
1994     BOOL b_returned;
1995     if( returnCode == NSOKButton )
1996     {
1997         NSUInteger count = [o_msg_arr count];
1998         NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1999         for (NSUInteger i = 0; i < count; i++)
2000         {
2001             [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
2002         }
2003         b_returned = [[string RTFDFileWrapperFromRange:NSMakeRange( 0, [string length] ) documentAttributes:[NSDictionary dictionaryWithObject: NSRTFDTextDocumentType forKey: NSDocumentTypeDocumentAttribute]] writeToFile:[[sheet URL] path] atomically:YES updateFilenames:NO];
2004         [string release];
2005
2006         if(! b_returned )
2007             msg_Warn( p_intf, "Error while saving the debug log" );
2008     }
2009 }
2010
2011 #pragma mark -
2012 #pragma mark Playlist toggling
2013
2014 - (void)updateTogglePlaylistState
2015 {
2016     [[self playlist] outlineViewSelectionDidChange: NULL];
2017 }
2018
2019 #pragma mark -
2020
2021 @end
2022
2023 @implementation VLCMain (Internal)
2024
2025 - (void)handlePortMessage:(NSPortMessage *)o_msg
2026 {
2027     id ** val;
2028     NSData * o_data;
2029     NSValue * o_value;
2030     NSInvocation * o_inv;
2031     NSConditionLock * o_lock;
2032
2033     o_data = [[o_msg components] lastObject];
2034     o_inv = *((NSInvocation **)[o_data bytes]);
2035     [o_inv getArgument: &o_value atIndex: 2];
2036     val = (id **)[o_value pointerValue];
2037     [o_inv setArgument: val[1] atIndex: 2];
2038     o_lock = *(val[0]);
2039
2040     [o_lock lock];
2041     [o_inv invoke];
2042     [o_lock unlockWithCondition: 1];
2043 }
2044 - (void)resetMediaKeyJump
2045 {
2046     b_mediakeyJustJumped = NO;
2047 }
2048 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2049 {
2050     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2051     if (b_mediaKeySupport) {
2052         if (!o_mediaKeyController)
2053             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2054         [o_mediaKeyController startWatchingMediaKeys];
2055     }
2056     else if (!b_mediaKeySupport && o_mediaKeyController)
2057     {
2058         int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
2059                                                _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
2060                                                _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
2061         if( returnedValue == NSOKButton )
2062         {
2063             /* Relaunch now */
2064             const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2065
2066             /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2067             if(fork() != 0)
2068             {
2069                 exit(0);
2070                 return;
2071             }
2072             execl(path, path, NULL);
2073         }
2074     }
2075 }
2076
2077 @end
2078
2079 /*****************************************************************************
2080  * VLCApplication interface
2081  *****************************************************************************/
2082
2083 @implementation VLCApplication
2084 // when user selects the quit menu from dock it sends a terminate:
2085 // but we need to send a stop: to properly exits libvlc.
2086 // However, we are not able to change the action-method sent by this standard menu item.
2087 // thus we override terminat: to send a stop:
2088 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2089 - (void)terminate:(id)sender
2090 {
2091     [self activateIgnoringOtherApps:YES];
2092     [self stop:sender];
2093 }
2094
2095 @end